Background work: queues, schedulers and cron at scale
When the customer stops waiting, the work still has to happen exactly once in effect, on time and visibly: queues, retries, poison messages and scheduled jobs for Dabba’s notifications, refunds and payouts.
This chapter lets you move work out of the request without losing it, doing it twice in a way that hurts, or letting it pile up unseen. The tools are a queue, a worker, a retry policy and a scheduler. Most of the design is about what happens when each of them fails.
Here is the situation in Dabba. When a customer taps “Place order”, the first version of the handler did everything in line: it wrote the order, confirmed the payment, pushed a notification to the restaurant tablet, sent the customer an SMS, emailed a receipt and updated the loyalty points. On a quiet afternoon that took about 400 ms. At dinner, the SMS provider began answering in two seconds, and checkout became a two-second operation for reasons the customer could not see or care about. On one bad evening the email provider returned errors, the handler raised, and orders that had been paid for were reported to the customer as failed.
The fix is to answer the customer once the order is safely recorded, and to do the rest afterwards. That sentence is easy. The rest of this chapter is about making “afterwards” as dependable as the request it replaced, because nobody is watching it.
Decide what the customer must wait for
Start with a question per step: does the customer’s next screen depend on its result? The order row must exist before we say “order placed”, or a crash leaves the customer with a confirmation for nothing. The payment authorisation must have an answer, because the next screen is either “paid” or “try another method”. Everything else on the list changes no decision the customer makes in the next second. The restaurant notification matters a great deal, but it matters within seconds, not within the request.
So the handler keeps two things and hands off the rest: writing the order and obtaining the payment result. Restaurant notification, customer SMS, receipt email and loyalty points become jobs: units of work described by a small message (“notify restaurant 4471 about order 9182”) and executed by a separate fleet of workers.
This moves latency, not work. A queue does not create processing capacity. If the SMS provider can only accept 300 messages a second and we produce 400, the queue grows by 100 a second until dinner ends. What the queue buys is that the customer no longer pays for that backlog with a spinning button, and that a slow provider slows only the work that depends on it.
It is worth sizing the work before building for it. The brief from the first chapter gives about a million orders a day, and about six notifications per order (placed, accepted, rider assigned, picked up, nearby, delivered): some 6 million notification jobs a day. The dinner hour carries 15% of orders, so it carries about 900,000 notifications, 250 a second, and spikes within the hour run two to three times that, so plan for around 600 a second. Refunds are rarer: if 2% of orders end in a full or partial refund, that is 20,000 refund jobs a day. Rider payouts are a nightly batch for every rider who worked that day, tens of thousands of them. Three very different shapes of work, which will matter when we decide whether they share a queue.
Write the order and the job together, or lose one of them
The first bug in almost every hand-off is in the hand-off itself. Commit the order, then publish “notify restaurant” to the queue, and a crash between the two lines leaves an order the restaurant never hears about. Swap the lines and the restaurant hears about an order that then rolled back. The writes chapter met exactly this problem when a paid order had to reach the kitchen, and its answer applies unchanged: the outbox table.
As a short recap, the job is written as an outbox row in the same transaction as the order, so both commit or neither does, and a relay ships unsent rows afterwards. The only difference here is the destination. The streams chapter extended the relay to append to the order-events log for many readers; here it feeds a work queue, where each job should be done once by one worker. The relay can still crash after sending and before marking a row sent, so a job can be enqueued twice. That is a duplicate, not a loss, and the rest of this chapter exists to make duplicates harmless.
BEGIN;
INSERT INTO orders (id, customer_id, restaurant_id, status, ...) VALUES (...);
INSERT INTO outbox (event_id, aggregate_id, type, payload)
VALUES (gen_id(), :order_id, 'notify.restaurant', '{"order_id": ...}');
COMMIT;
-- the relay sends unsent rows to the work queue, then marks them sentThe cost is small next to the order itself: a few extra rows per order, at a design target of 150 orders a second. The relay is one more process that can lag, so the age of the oldest unsent row gets a dashboard and an alert, as it did for the event log. Many teams run one relay for both destinations, routing each row by its type.
A queue hands out leases, not messages
It helps to be exact about what a queue promises. When a worker receives a job, the queue does not delete it. It hides it for a period called the visibility timeout (or lease) and waits. If the worker acknowledges the job before the lease ends, the job is deleted. If the lease ends without an acknowledgement, the job becomes visible again and another worker can take it. That is the whole mechanism, and it is how a queue survives a worker that crashes, hangs or loses its network.
Look at what the queue cannot know. It sees “acked” or “not acked”. It does not see whether the refund call reached the payment provider. A worker that called the provider, received success, and then crashed before acking looks identical, from the queue’s side, to a worker that crashed before calling. Both get redelivered. This is why every queue you will use offers at-least-once delivery: the alternative would be to delete the job before the work, and then a crash loses it.
Dabba’s refund worker has a 30-second visibility timeout. At dinner the payment provider’s refund API slows to around 40 seconds per call. Workers are healthy and nobody crashes. What happens to refund #8812, and what does the customer see?
Show the worked answer
Worker A takes the job and calls the provider. At 30 seconds the lease expires while A is still waiting, so the job becomes visible and worker B takes it and calls the provider too. At 40 seconds A’s call succeeds and A tries to ack, but the ack is for a lease it no longer holds; depending on the queue it is rejected or ignored. At about 70 seconds B’s call returns. Without protection the provider has now processed two refunds, and the customer receives ₹800 back on a ₹400 order.
Nothing failed. Slowness alone produced the duplicate. Two fixes are needed together: a lease comfortably longer than the slowest normal call (and a worker that extends its lease while it waits, which most queues support), and a refund call that the provider will only execute once however many times it arrives. The second is the subject of the next section, and it is the one that actually makes the system correct.
Exactly-once is a property of the effect, not the delivery
Vendors and blog posts sometimes promise “exactly-once delivery”. Read those claims carefully. A queue can guarantee that, within its own storage, a message is processed and its result recorded once (Kafka’s transactions do this for work that reads and writes only Kafka). Nothing the queue does can stop a worker from calling an external API, crashing, and calling it again. What we can build is exactly-once effect: deliveries may repeat, but the second one changes nothing. The term for a handler with that property is idempotent.
Each of Dabba’s jobs gets idempotency in the way that suits its effect.
Refunds go to the payment provider with an idempotency key. The key must name the logical refund, not the attempt: refund-8812, created when the refund was decided and stored in the job payload. A key generated inside the worker (uuid() at call time) is useless, because the retry generates a different key. Payment providers keep idempotency keys for a limited window, often a day or so, which is another reason retries should not stretch for days.
Payouts are made idempotent by the database. A payout ledger has a unique constraint on (rider_id, period). The worker inserts the ledger row first, inside a transaction, and only the transaction that wins the insert proceeds to call the bank. A second delivery hits the constraint and stops. The bank transfer itself also carries the payout ID as its reference, so a crash after the insert and during the transfer can be reconciled by asking the bank whether that reference was paid.
def handle_payout(job):
with db.transaction():
inserted = db.execute("""
INSERT INTO payouts (rider_id, period, amount, status)
VALUES (%s, %s, %s, 'PENDING')
ON CONFLICT (rider_id, period) DO NOTHING
""", job.rider_id, job.period, job.amount).rowcount
row = db.get_payout(job.rider_id, job.period)
if row.status == 'PAID':
return ack(job) # an earlier delivery finished
bank.transfer(ref=row.id, amount=row.amount) # bank dedupes on ref
db.mark_paid(row.id)
ack(job)Notifications are the awkward case, because an SMS cannot be un-sent and most SMS gateways do not deduplicate. Here we keep a small record of what has been sent, keyed by (order_id, event), and check it before sending. That narrows the duplicate window to the moment between sending and recording, which is acceptable for “your rider is nearby” and is the honest limit of what can be done with a provider that offers no key. Writing down which jobs are only “nearly once” is part of the design.
Some effects are idempotent without help. Setting status = 'NOTIFIED' is the same however many times it runs. Overwriting a resized dish photo at a fixed path is the same. Incrementing loyalty points is not: “add 20 points” twice adds 40. Rewriting it as “record that order 9182 earned 20 points” (an insert keyed by order) and computing the balance as a sum turns an unsafe increment into a safe insert. That rewrite, from “change the value” to “record the fact”, is the move to reach for first.
Retries, and the message that will never succeed
Jobs fail for two very different reasons, and the retry policy has to tell them apart.
| Failure | Dabba example | What the worker should do |
|---|---|---|
| Transient | SMS gateway timeout, provider 503, database failover | retry later with growing delay and jitter |
| Rate limited | provider returns 429 with Retry-After | wait at least as long as asked; slow the whole queue, not one job |
| Permanent | refund for an order with no captured payment; malformed payload | stop retrying, record why, send to the dead-letter queue |
| Unknown outcome | bank transfer timed out after sending | reconcile first (ask the bank by reference), then decide |
Now walk through what happens without that distinction. A bug in an older app version produces refund requests whose amount field is a string. The refund worker raises an exception on parse, the job is not acked, and the lease expires. The job is redelivered, raises again, and is redelivered again. One such job is a nuisance. Two thousand of them, produced over an evening, behave like a capacity leak: each one occupies a worker for a parse attempt every lease period, forever. If the queue preserves order within a partition, as Kafka does, it is worse: the bad message sits at the head of its partition and every refund behind it waits. This is a poison message.
The fix has three parts. First, a maximum attempt count (five is common), after which the job moves to a dead-letter queue with its last error attached. Second, an alert on the first arrival in the dead-letter queue, not on its size, because a refund that will never process is a customer who has not been paid back. Third, a tool to replay dead-lettered jobs once the bug is fixed. Without the replay tool, a dead-letter queue is a place where work goes to be forgotten. The cost is real: someone owns that queue, reads its errors, and decides for each class of failure whether to fix and replay or to discard.
Retry timing matters as much as the count. Retrying immediately turns a provider’s brief hiccup into a burst of our own traffic exactly when it is weakest. The usual schedule is exponential backoff (1 s, 2 s, 4 s, 8 s…) with random jitter so that a thousand jobs that failed at the same moment do not all return at the same moment. The chapter on failure works through why jitter matters with numbers. For now, note that a queue gives us backoff almost for free: a job can be re-enqueued with a delay rather than retried in a loop inside the worker, which keeps the worker free for other jobs.
Work that must happen at a particular time
Some of Dabba’s jobs are triggered by the clock rather than by an event. The writes chapter already has one: the sweeper that releases stock reservations still unpaid after 10 minutes. It is the simplest form, a periodic job that finds everything overdue and handles it. Two more show the harder cases.
The first is the acceptance timeout. If a restaurant has not accepted an order within five minutes, we cancel it and refund the customer. The natural implementation is a delayed job: when the order is placed, enqueue “check acceptance of 9182” to become visible in five minutes. Most managed queues support delays directly; otherwise a table of due times, polled every second for rows that are due, does the same. The trap is in what the job does when it runs. By then the restaurant has usually accepted. The job must not cancel blindly; it must cancel only if the order is still waiting, in one conditional statement:
UPDATE orders SET status = 'CANCELLED_NO_ACCEPT'
WHERE id = 9182 AND status = 'PLACED';
-- 0 rows updated: the restaurant got there first, do nothingA check-then-act version (read status, see PLACED, then update) loses the race when the restaurant taps “accept” between the read and the write. The conditional update makes the database decide which of the two transitions happened first, and the other one finds nothing to do. We will use the same shape again for rider offers in the worked design.
The second is the nightly payout at 02:00. Run the scheduler on one machine and the payout does not happen on the night that machine is being replaced. Run it on three for availability and, unless they coordinate, the payout is triggered three times. The usual design is to elect one scheduler as leader using a lease in a coordination service (the Distributed Systems pathway covers leases and fencing), have the leader enqueue one job per rider rather than doing the payouts itself, and record that the 02:00 run for a given date has been triggered. If the leader dies halfway through, the new leader sees the run is incomplete and enqueues again. Because each payout is idempotent on (rider_id, period), enqueuing some riders twice is harmless. This is the general pattern: make the scheduler’s job small (decide what is due, emit jobs) and let the idempotency of the jobs absorb the scheduler’s mistakes.
Time zones are mostly simple for Dabba, since India uses one, but the design should still store due times in UTC and convert at the edges. The day Dabba opens in Dubai or Singapore, “02:00” stops being one moment.
Give urgent work its own lane
Suppose all jobs share one queue and one pool of workers. At 20:10 the marketing team sends a promotional push to 2 million customers, which enters the queue as 2 million jobs ahead of the “rider assigned” and “your order is nearby” notifications for every order in the country. At 600 jobs a second the promotion takes almost an hour to drain, and every order notification behind it is up to an hour late, which for “your rider is at the door” means useless. The bulk work did not fail; it simply stood in front.
Separate queues by urgency and by kind of work: one for time-sensitive order notifications, one for refunds, one for payouts, one for low-value work such as receipts and analytics. Each gets its own workers, sized independently. Little’s law sizes them: the number of jobs in progress equals arrival rate times time per job. At 600 notifications a second and about 150 ms per provider call, we need around 90 calls in flight; with headroom for a slow provider (say calls stretch to 500 ms), around 300. Those can be threads in a few processes, but the number should come from this arithmetic, not from a default.
Within a queue, one tenant can still crowd out the rest. If a chain’s kitchen outage triggers a few thousand refunds in minutes, a per-chain concurrency cap stops it from occupying every refund worker while a single customer elsewhere waits for theirs. The cost of lanes and caps is more moving parts: more queues to monitor, more pools to size, and capacity that sits idle in one lane while another is busy. That is the trade, and for a system where some messages expire in usefulness within a minute it is usually worth making.
The metric that tells you a lane is in trouble is the age of its oldest job, not its depth. A depth of 10,000 is fine if workers clear it in five seconds and alarming if they clear it in ten minutes. Age says “late” directly, and it maps onto a promise you can state: order notifications leave within 10 seconds, refunds start within 5 minutes, payouts finish by 06:00. Each promise gets an alert on its own lane.
When a queue is the wrong tool
A queue is wrong when the caller needs the answer. Payment authorisation stays in the request: putting it behind a queue would mean telling the customer “order placed” before knowing whether they can pay, and then chasing them afterwards. Some products choose that trade deliberately (accept the order, collect payment later), but it is a product decision, not a performance trick.
A queue is also the wrong shape when many consumers need the same events in order. If the search index, the analytics pipeline and the fraud model all need every order event, three work queues fed by three outbox rows is a poor copy of the replayable log from the streams chapter. Use a work queue for chores that one worker should do once; use a log for facts that several readers consume at their own pace. And when the work is small, fast and reliable, such as writing an audit row to the same database, keep it in the transaction. Every hop to a queue adds an outbox row, a relay, a worker and a dashboard.
Revisit this design if the shape of the jobs changes. Workflows with many steps and compensations (“place order, reserve rider, charge, and undo each if a later step fails”) outgrow hand-written queue jobs, and a workflow engine that persists each step’s state starts paying for itself.
Background work protected the order request from slow dependencies behind it. The next chapter, on rate limiting, protects the API from callers in front of it: scripts that request login OTPs for thousands of phone numbers, scrapers walking every menu, and our own app retrying in a tight loop.