Skip to Content
JobWzrd Docs

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 search

Verified facts:

  • One message per search, not per source. searches.ts calls enqueueScrape(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_concurrency NOT set in wrangler.jsonc [IMPL]. Per Cloudflare, an unset max_concurrency scales to the platform maximum of 250 concurrent invocations [DOC].
  • No consumer for the DLQ — jobwzrd-scrape-dlq has 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 TenantRegistry in-memory maps [IMPL], Rust Arc<Mutex<RegistryInner>> with utc_day() reset in memory [IMPL]. A second replica doubles the effective quota and loses counters on restart.
  • MAX_INGEST_PER_SEARCH is not concurrency-safe. remaining is 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 running forever. claimSearch only matches status='queued'; the reset lives inside the catch of consumeScrapeMessage. If the invocation is killed (15-minute wall clock, isolate eviction), the catch never runs, the redelivery finds running, and consumeScrapeMessage acks it as noop [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. executeSearch sets complete when any source is ok/empty; /searches/list returns status + result_count and 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)

#RequirementAs builtWhy
1One slow scraper must not block unrelated scraper requestspartialDifferent 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.
2Messages for one search independently executablefailThere is exactly one message per search. A source cannot be retried, delayed or dead-lettered on its own.
3Different users' operations execute concurrentlypassSeparate messages → separate invocations → up to 250 concurrent [DOC].
4Results persisted as each source completespass (data) / fail (visibility)ingestCanonical commits per source [IMPL], but no API surface exposes per-source progress.
5One source's failure must not discard others' resultspassEach source's ingest commits before the next; the failure path only records an execution row [IMPL].
6Status must distinguish running / complete / partial / failedfailAny success → complete. No partial.
7User can see finished sources while others runfailNo /searches/{id} and no per-source endpoint.
8A failed message must not prevent unrelated messages being processedpassBatch size is 1; a thrown message retries alone.
9One user's volume must not starve othersfail (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.
10A slow source must not hold a global lockpassNo 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_key so a redelivery is free.
  • Ingest idempotent by schema (canonical_url, (source_id, source_job_id)), fetch_count, content_hash vs fingerprint separation.
  • Fail-closed egress: gateway 502, scrapers 502, never a fabricated empty board.
  • Contract preservation: 58 frozen paths; B6-lite added only /sources, /searches, /searches/list as additive routes.
  • HMAC-signed queue messages; forged messages ack without retry.

Revise before production (ranked)

  1. 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.)
  2. SEV-1 — Unbounded consumer concurrency. max_concurrency unset = 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.
  3. 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.
  4. SEV-1 — Stranded running searches. 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.
  5. SEV-2 — Partial success reported as complete. Add partial (or explicit sources_failed counts) and publish per-source outcomes.
  6. SEV-2 — Ingest bound race. Make remaining a single reservation (atomic decrement before dispatch) or enforce the bound in the ingest statement, not in two places.
  7. SEV-2 — No DLQ consumer, no alerting. A DLQ nobody reads is a silent failure store.
  8. SEV-2 — Observability is 8 log lines. Cannot answer 18 of the 25 incident questions in §6 of the request.
  9. 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.
  10. SEV-3 — No per-source daily budget (only per-service); a chatty source can consume the whole tenant budget.
  • No Redis in this phase (§11 trade-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

#DecisionOptionsRecommendation
D1Keep one-active-search-per-user?keep / allow NKeep 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.
D2Partial status in the API contractnew partial status / keep complete + countsAdd partial — the alternative is an API that claims a success it did not have. Additive to a status enum, not a frozen path change.
D3Job store: D1 vs RedisD1 24 h TTL / Redis cache / bothD1 only for now. Expected volume (below) fits; Redis would duplicate rows and introduce a second expiry truth. See PRODUCTION-ARCHITECTURE-REVIEW.md §6.
D4Concurrency ceiling5 / 10 / 25 / unset10 initial, ramp on measurement. Never leave it unset.
D5DLQ handlingignore / inspect manually / automated requeueInspect + alert now, automated requeue only after the attempt ledger exists. Blind requeue can double-charge a scraper budget.
D6Scraper quota storesingle replica / shared KV or D1 / gateway-enforcedShort 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)

AreaFile(s)Change
Fan-outsrc/features/jobs/searches.ts, src/platform/queue.ts, src/features/jobs/scrapeQueue.tsenqueue one message per (search, source); consumer runs one source; settle counts
Leasemigrations/0012_search_leases.sql, scrapeRun.tsrunning_at, lease_expires_at, reclaim in sweepExpired
StatusscrapeRun.ts, features/jobs/searches.ts, src/http/routes/searches.tspartial, per-source array, GET /searches/{id}
Concurrencywrangler.jsoncexplicit max_concurrency, retry_delay, DLQ consumer
Ingest boundscrapeRun.ts, features/jobs/ingest.tsatomic reservation
Dispatch ledgerops_scraper_executions migration, scraperClient.tsattempt id, dispatched_at, uncertain state
Scraper quotasscrapers/MiniWzrd/internal/api/tenancy.go, scrapers/jobindie/src/tenants.rsshared budget source or documented single-replica constraint
Observabilitysrc/platform/log.ts + every route/featureenvelope, trace propagation, request logging
Error/event catalogbackend/contract/error-catalog.jsonnew 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).

On this page