Bỏ qua, tới nội dung chính

Kiến trúc · ADR 0005

BullMQ worker on Redis, with Zod job contracts

Trạng thái
accepted
Ngày
2026-09-21
Người quyết định
Alex

Context

Parsing a PDF, embedding its chunks and drafting quiz questions take seconds to minutes and call paid APIs. AGENTS.md rule 5 says none of that may run on a request path: a student taking a quiz must never wait on a model. The work needs a queue with retries, and it must survive an API restart.

Decision

  • BullMQ on Redis 7, consumed by a separate process, apps/worker. The API only enqueues.
  • Queue names are constants in packages/shared (QUEUES: ingest, embed, quiz).
  • Payloads are Zod schemas in packages/shared/src/schemas/jobs.ts (ingestJobDataSchema → IngestJobData). jobDataSchemas is keyed by QueueName, so adding a queue without a payload schema fails to compile.
  • The worker parses job.data before any work. It is untrusted JSON from Redis. A payload that fails the schema would fail every retry too, so the worker throws UnrecoverableError and BullMQ does not retry it.
  • Processors take plain data, not a BullMQ Job, so they are unit-tested without Redis.
  • One Redis connection per worker process, with maxRetriesPerRequest: null as BullMQ requires. Workers log failed, error and stalled events; an unhandled error event would crash the process.
  • On SIGTERM the worker closes every Worker (in-flight jobs finish) and then exits. Compose gives it stop_grace_period: 30s.

Alternatives considered

  • Postgres-backed queue (pg-boss). One fewer service, but Redis is needed for caching anyway, and BullMQ has better tooling and documentation.
  • Running jobs inside the API process. One process fewer, but an ingest spike would slow every request, and a deploy would drop in-flight jobs.

Consequences

  • The producer and the consumer share one contract and cannot drift silently.
  • The API will need its own BullMQ connection for producers. Its RedisService connection has a 2-second ping timeout for the readiness probe, which BullMQ must not inherit.
  • Two services to run locally. pnpm dev starts both.