Appearance
Background jobs
Two entry points on the server Worker (apps/server/src/index.ts):
| Entry | Trigger | Handler |
|---|---|---|
scheduled | Cron */15 * * * * (crons in alchemy.run.ts) | runSweeps(now) runs every registered sweep |
queue | Messages on the jobs queue | handleJob(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: { ... } }typeis stable.vis the payload version for that type.keyis 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
vand the previous one for one release, then drops the old one. - Unknown
typeorvis acknowledged and logged, never retried forever.
Adding a job
- Add a Zod schema for the payload next to the feature, versioned by
v. - Register a handler in
jobHandlers["thing.do"]. - Enqueue with
env.JOBS.send({ type, v, key, enqueuedAt, payload }). - Write the handler so a retry is harmless. Record what you did in
audit_logwhen 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).