Skip to content

Background jobs ​

Two entry points on the server Worker (apps/server/src/index.ts):

EntryTriggerHandler
scheduledCron */15 * * * * (crons in alchemy.run.ts)runSweeps(now) runs every registered sweep
queueMessages on the jobs queuehandleJob(message.body) dispatches by type

Failed messages retry up to 3 times and then land in the jobs-dlq dead-letter queue. A DLQ message is a bug to look at, not noise: Cloudflare does not alert on it.

Envelope ​

Defined in packages/api/src/jobs.ts:

ts
{ type: "email.send", v: 1, key: "email:call-booked:lead_123", enqueuedAt: 1760000000000, payload: { ... } }
  • type is stable. v is the payload version for that type.
  • key is the idempotency key. Handling the same key twice must change nothing (check a processed-keys record, or make the effect naturally idempotent: upsert, "set status if not already set").
  • Messages outlive deploys: version N may enqueue what N+1 consumes. A consumer accepts the current v and the previous one for one release, then drops the old one.
  • Unknown type or v is acknowledged and logged, never retried forever.

Adding a job ​

  1. Add a Zod schema for the payload next to the feature, versioned by v.
  2. Register a handler in jobHandlers["thing.do"].
  3. Enqueue with env.JOBS.send({ type, v, key, enqueuedAt, payload }).
  4. Write the handler so a retry is harmless. Record what you did in audit_log when the owner might ask.

Adding a sweep ​

A sweep runs every tick and finds work by looking at data ("scripts whose deadline passed and are not locked"), never by remembering it already ran. Register it in sweeps in packages/api/src/jobs.ts. Because it runs every 15 minutes, lock/auto-approve actions can lag a deadline by up to 15 minutes; if that matters, raise the cron frequency, nothing else changes.

Things that must not run in a request ​

Research/scraping and video processing. Enqueue a job; if heavy, the job calls an external service (Stack).

Internal documentation. Not for clients.