Background Work Without a Server
Queues: Work That Must Not Get Lost
Answer Now, Work Later
Someone checks out. You need to send an email, make a PDF and tell three other systems. Don't make them watch a spinner, and don't lose the order because an email service hiccuped. Put a job in a queue and answer right away. This goes inside wrangler.jsonc:
"queues": {
"producers": [{ "binding": "JOBS", "queue": "jobs" }],
"consumers": [
{ "queue": "jobs", "max_retries": 3, "dead_letter_queue": "jobs-dead" }
]
}
Cloudflare hands the jobs to your Worker in batches:
async queue(batch, env) {
for (const msg of batch.messages) {
try {
const seen = await env.DB
.prepare("SELECT 1 FROM processed_events WHERE event_id = ?")
.bind(msg.body.id)
.first();
if (!seen) await handleEvent(env, msg.body);
msg.ack();
} catch (err) {
console.error("job failed", { id: msg.body.id, error: String(err) });
msg.retry({ delaySeconds: 60 });
}
}
},
Four things to check in any queue code AI writes:
- Each message gets its own
ackorretry. Otherwise one bad job sends the whole batch around again, including the ones that worked. - A dead letter queue is set. Without one, a job that runs out of retries is deleted. Gone. With one, it waits there so you can look at it: 4 days by default on paid, 24 hours on free.
- Doing it twice is harmless. Queues promise at least once. Sometimes that's twice.
- Somebody looks at the dead letter queue. A dead letter queue nobody reads is a slower way to lose things.
Making Twice Harmless
async function handleEvent(env, event) {
// One transaction: the work and the receipt land together or not at all
await env.DB.batch([
env.DB.prepare("INSERT INTO processed_events (event_id) VALUES (?)").bind(event.id),
env.DB.prepare("UPDATE orders SET paid = 1 WHERE id = ?").bind(event.orderId),
]);
}
event_id is the primary key. If two copies race, the second insert fails and the whole batch rolls back with it. For outside calls like a payment or email, pass the same ID as the provider's idempotency key if it has one, so they drop the duplicate.
A delivered message is usually 3 operations: write, read, delete. On paid, 1 million operations a month are included, then $0.40 per million. A million messages a month is 3 million operations, so 80 cents.
A job fails all its retries and there is no dead letter queue. What happens to it?