Production architecture review — JobWizard (Cloudflare)
Status: REVISE. Read-only audit; no code changed.
Date: 2026-11-19. Scope: backend/ (Workers/D1/Queues, B1–B3 + B6-lite),
scrapers/MiniWzrd (Go), scrapers/jobindie (Rust), app/ contract expectations.
server/ (Convex) is reference only and was not modified.
Evidence labels used throughout: [IMPL] confirmed by reading the implementation · [TEST] proven by an executed test · [DOC] confirmed by current official Cloudflare documentation · [INFERRED] follows from the design but was not executed · [UNPROVEN] assumption without measurement · [OWNER] requires a product/architecture decision.
1. What actually runs today
Browser ──POST /api/v1/searches──▶ Worker ──► D1 (searches row, cap ledger)
└────► Queue: ONE message per search (ref + HMAC)
Queue ──► consumer invocation (max_batch_size=1) ──► claimSearch: queued→running
│
├─ pool(4) over the search's sources
│ reserveCap(source_fetch, keyed)
│ scrape() → MiniWzrd | jobindie
│ adaptBatch() → ingestCanonical()
│ recordExecutive() (ops_scraper_executions)
└─ settleSearch: one status for the whole searchVerified facts:
- One message per search, not per source.
searches.tscallsenqueueScrape(ref)once after the row exists [IMPL]. - Fan-out is in-process:
pool(..., DEFAULT_CONCURRENCY = 4, ...)over sources [IMPL] (features/jobs/scrapeRun.ts:229). max_batch_size: 1,max_batch_timeout: 10,max_retries: 2, DLQ configured,max_concurrencyNOT set inwrangler.jsonc[IMPL]. Per Cloudflare, an unsetmax_concurrencyscales to the platform maximum of 250 concurrent invocations [DOC].- No consumer for the DLQ —
jobwzrd-scrape-dlqhas no[[queues.consumers]]entry [IMPL]. Messages there are invisible until retention deletes them (default 4 days, max 14) [DOC]. - 8
log()calls exist in the entire backend (HTTP 1, features 5, platform 1) [IMPL] — versus ~40 modules and 19 routes. - No D1 rows-read/rows-written/duration capture anywhere [IMPL].
- Tenant rate buckets and daily budgets are process-local in both scrapers: Go
TenantRegistryin-memory maps [IMPL], RustArc<Mutex<RegistryInner>>withutc_day()reset in memory [IMPL]. A second replica doubles the effective quota and loses counters on restart. MAX_INGEST_PER_SEARCHis not concurrency-safe.remainingis read by up to four parallel source workers before any of them decrements it, so 10 sources × 50 can store 500 rows against a 300 bound [IMPL] (line 253 read, line 312 decrement). The B6-lite acceptance used a single source and did not expose it.- A crashed invocation strands a search in
runningforever.claimSearchonly matchesstatus='queued'; the reset lives inside thecatchofconsumeScrapeMessage. If the invocation is killed (15-minute wall clock, isolate eviction), the catch never runs, the redelivery findsrunning, andconsumeScrapeMessageacks it asnoop[IMPL]. F-MZ-13 taught us a silent zero is a defect; this is the queue analogue: a silent "running". - Partial success is reported as
complete.executeSearchsetscompletewhen any source isok/empty;/searches/listreturns status +result_countand no per-source breakdown [IMPL]. A search where 4 of 5 sources failed reads as a success. - No per-search detail route and no progressive read; only
GET /searches/list[IMPL]./jobs(B4) does not exist yet. - Caps are server-owned and charged before dispatch, keyed per
(search, source)[IMPL] — this part is sound and worth keeping.
2. Requirement-by-requirement verdict (the 10 queue requirements)
| # | Requirement | As built | Why |
|---|---|---|---|
| 1 | One slow scraper must not block unrelated scraper requests | partial | Different searches are different invocations, so cross-user isolation holds only while concurrency > 1. Inside one search, pool(4) means one slow source occupies a slot and delays that search's settlement; it does not block other searches. |
| 2 | Messages for one search independently executable | fail | There is exactly one message per search. A source cannot be retried, delayed or dead-lettered on its own. |
| 3 | Different users' operations execute concurrently | pass | Separate messages → separate invocations → up to 250 concurrent [DOC]. |
| 4 | Results persisted as each source completes | pass (data) / fail (visibility) | ingestCanonical commits per source [IMPL], but no API surface exposes per-source progress. |
| 5 | One source's failure must not discard others' results | pass | Each source's ingest commits before the next; the failure path only records an execution row [IMPL]. |
| 6 | Status must distinguish running / complete / partial / failed | fail | Any success → complete. No partial. |
| 7 | User can see finished sources while others run | fail | No /searches/{id} and no per-source endpoint. |
| 8 | A failed message must not prevent unrelated messages being processed | pass | Batch size is 1; a thrown message retries alone. |
| 9 | One user's volume must not starve others | fail (by design of caps) | Per-user caps exist (20 searches/day, 200 source fetches/day) [IMPL], but Queue delivery is FIFO-ish per queue with no per-tenant fairness; 20 searches × 10 sources = 200 messages from one user can sit ahead of everyone else. Global max_concurrency is unbounded today, which hides it locally and amplifies it remotely. |
| 10 | A slow source must not hold a global lock | pass | No lock exists. remaining is mutated without one — which is the opposite bug (§1). |
3. Architecture verdict
Confirmed sound
- Caps charged atomically before dispatch, keyed by
op_keyso a redelivery is free. - Ingest idempotent by schema (
canonical_url,(source_id, source_job_id)),fetch_count,content_hashvsfingerprintseparation. - Fail-closed egress: gateway 502, scrapers 502, never a fabricated empty board.
- Contract preservation: 58 frozen paths; B6-lite added only
/sources,/searches,/searches/listas additive routes. - HMAC-signed queue messages; forged messages ack without retry.
Revise before production (ranked)
- SEV-1 — Fan-out granularity. One message per search makes per-source retry,
isolation and progress impossible. Split to one message per
(search, source)and settle the search from source-level outcomes. (This is the single change that satisfies requirements 1, 2, 4, 6, 7 and 8 simultaneously.) - SEV-1 — Unbounded consumer concurrency.
max_concurrencyunset = 250 invocations × 4 in-flight sources = ~1,000 simultaneous scrape calls, which would hammer two single-replica scraper services with in-memory quotas, and flood D1 writes. Set an explicit, measured limit. - SEV-1 — Process-local scraper quotas. Daily budgets and rate buckets must be shared (or the scraper must stay single-replica with a documented cap), or horizontal scaling silently multiplies quota and resets budgets on restart.
- SEV-1 — Stranded
runningsearches. Add a lease (running_at,lease_expires_at) and a reclaim path in the consumer/sweep. Without it, a killed invocation is a permanent "running" for the user and a leak against the one-active-search rule. - SEV-2 — Partial success reported as complete. Add
partial(or explicitsources_failedcounts) and publish per-source outcomes. - SEV-2 — Ingest bound race. Make
remaininga single reservation (atomic decrement before dispatch) or enforce the bound in the ingest statement, not in two places. - SEV-2 — No DLQ consumer, no alerting. A DLQ nobody reads is a silent failure store.
- SEV-2 — Observability is 8 log lines. Cannot answer 18 of the 25 incident questions in §6 of the request.
- SEV-3 — No dispatch-attempt ledger for scraper POSTs: an ambiguous timeout cannot be distinguished from "never left", so retries risk a second real scrape.
- SEV-3 — No per-source daily budget (only per-service); a chatty source can consume the whole tenant budget.
Explicitly not recommended
- No Redis in this phase (
§11trade-off below). - No separate queue per source and no per-source consumer architecture.
- No WebSocket/DO for progress; bounded polling on a per-search endpoint is sufficient.
- No rewrite of Go/Rust engines; the fixes they need are quota-sharing and an idempotency key, not a redesign.
4. Owner decisions required
| # | Decision | Options | Recommendation |
|---|---|---|---|
| D1 | Keep one-active-search-per-user? | keep / allow N | Keep for now. It bounds the fan-out a single user can create, keeps cap math explainable, and hides the missing fairness scheduler. Revisit when per-source messages land and a user can see progress. |
| D2 | Partial status in the API contract | new partial status / keep complete + counts | Add partial — the alternative is an API that claims a success it did not have. Additive to a status enum, not a frozen path change. |
| D3 | Job store: D1 vs Redis | D1 24 h TTL / Redis cache / both | D1 only for now. Expected volume (below) fits; Redis would duplicate rows and introduce a second expiry truth. See PRODUCTION-ARCHITECTURE-REVIEW.md §6. |
| D4 | Concurrency ceiling | 5 / 10 / 25 / unset | 10 initial, ramp on measurement. Never leave it unset. |
| D5 | DLQ handling | ignore / inspect manually / automated requeue | Inspect + alert now, automated requeue only after the attempt ledger exists. Blind requeue can double-charge a scraper budget. |
| D6 | Scraper quota store | single replica / shared KV or D1 / gateway-enforced | Short term single replica with documented cap; medium term gateway-enforced per-tenant limits (the gateway already sees every request). |
5. Cost / retention implications (order of magnitude, [UNPROVEN])
- Queue ops: 20 searches × 10 sources = 200 messages/user/day worst case; 1,000 daily-active users ≈ 200k messages/day → within per-queue 5,000 msg/s [DOC] by three orders of magnitude.
- D1 storage (24 h window): 300 rows/search × 20 searches × ~1.5 KB ≈ 9 MB per heavy user-day; 1,000 heavy users ≈ 9 GB, at the paid-plan ceiling. This is the one number that could force a shorter TTL or Redis; it must be measured, not assumed.
- Logpush→R2: dominated by request logs; sampling 10 % of success events keeps archival under a few GB/month at the above volume [UNPROVEN].
6. Files that must change in the follow-up implementation (no change made now)
| Area | File(s) | Change |
|---|---|---|
| Fan-out | src/features/jobs/searches.ts, src/platform/queue.ts, src/features/jobs/scrapeQueue.ts | enqueue one message per (search, source); consumer runs one source; settle counts |
| Lease | migrations/0012_search_leases.sql, scrapeRun.ts | running_at, lease_expires_at, reclaim in sweepExpired |
| Status | scrapeRun.ts, features/jobs/searches.ts, src/http/routes/searches.ts | partial, per-source array, GET /searches/{id} |
| Concurrency | wrangler.jsonc | explicit max_concurrency, retry_delay, DLQ consumer |
| Ingest bound | scrapeRun.ts, features/jobs/ingest.ts | atomic reservation |
| Dispatch ledger | ops_scraper_executions migration, scraperClient.ts | attempt id, dispatched_at, uncertain state |
| Scraper quotas | scrapers/MiniWzrd/internal/api/tenancy.go, scrapers/jobindie/src/tenants.rs | shared budget source or documented single-replica constraint |
| Observability | src/platform/log.ts + every route/feature | envelope, trace propagation, request logging |
| Error/event catalog | backend/contract/error-catalog.json | new artifact, tested for uniqueness |
7. Recommendation
REVISE. The data path is honest and the caps are right, but the execution model is search-shaped where it needs to be source-shaped, the concurrency ceiling is unset, the scrapers' quotas are replica-local, and the system cannot yet explain an incident. None of these requires a rewrite: five contained changes (fan-out, lease, status, concurrency, observability envelope) take it to production shape.
Do not go to remote staging before items 1–4 and 7–8 are closed, because remote staging is exactly where each of them becomes visible (concurrency spikes, replica duplication, stranded searches, and logs you cannot find).