Queues: accept now, work later
Move slow work off the request and keep a queue from falling behind.
Why a queue
Some work is slow (sending email, resizing video) or comes in bursts (a flash sale). Doing it inside the request makes users wait and lets a spike knock servers over.
With a queue, the server writes a small message and replies at once. Workers take messages off the queue and do the work at their own pace.
POST /order:
queue.publish({ orderId, items }) // ~2 ms
return 202 Accepted // user isn't kept waiting
worker loop:
msg = queue.take()
process(msg) // slow work, off the request
The one rule: drain faster than you fill
If 2,000 messages arrive each second and workers finish 1,500, the queue grows by 500 every second, forever. Messages wait longer and longer.
Capacity = workers × messages per worker per second. Add workers (or make each faster) until capacity beats the arrival rate, with headroom for peaks.
Retries and duplicates
A worker can crash after doing the work but before confirming it, so the message is delivered again. Workers must be safe to run twice (idempotent), which the money stage covers.
Key takeaways
- Queues turn a burst into steady work.
- Worker capacity must exceed the arrival rate, or the backlog grows forever.
- Messages can arrive twice; make workers idempotent.
Try it in the simulator: Absorb a spike with a queue
Put this concept into practice on Flash Sale Inventory Gate:
- Build Client → Load balancer → API servers → PostgreSQL and run the sale. Watch requests fail at the peak.
- Add Kafka and connect the API servers to it as well as to PostgreSQL, then connect Kafka → Workers → PostgreSQL. Reads still go straight to the database; writes now go through the queue.
- Start with one Worker, then add Workers until none of them is near full.
What to watch: Through the queue, the burst stops hitting the database all at once. With too few Workers they run near 100% and the backlog grows; with enough, they drain it as fast as orders arrive.
Check your understanding
Answer these questions interactively to test what you learned and track progress on your skill map:
- 3,000 jobs arrive per second. Each worker does 200 per second. How many workers keep up, with no headroom?
- What does a queue mainly protect during a sudden spike?