System Design · 04. Communication · 10 min · Intermediate
Message Queues
Put slow work in a line and let workers handle it later.
In short
A queue lets the API answer in 52 ms instead of 850 ms, and lets workers do the slow part later. A pool of 4 workers does 5 jobs a second and the line absorbs spikes.
Ack after the work, make jobs idempotent, send poison messages to a dead-letter queue, partition by key when order matters, and watch the depth.
Key ideas
- Work the user does not need right now should leave the request path. (step 1)
- The queue is a buffer between a fast producer and a slower consumer. (step 3)
- Ack after the work is done, never before. An early ack loses the job if the worker dies. (step 6)
- A queue hides a slow consumer; it does not fix it. Capacity must still match the average load. (step 10)
Good to know
- A queue turns "do it now and wait" into "promise to do it soon". The HTTP answer is often 202 Accepted. (step 2)
- Need more speed? Add workers. They are stateless, so any number can read the same queue. (step 4)
- Idempotent jobs are safe to retry. This one habit makes queues, retries and crashes much less scary. (step 7)
Watch out
- Users do not wait, but the last email is sent minutes late. Watch the queue depth and the age of the oldest message. (step 5)
- Put an alert on the DLQ. A DLQ nobody looks at is only a quiet place to lose work. (step 8)
- Strict order costs parallelism. Keep it only where the business needs it. (step 9)
Key numbers
- Queue depth
- ~0
- Workers
- 4
- Signup p99
- 52 ms
Terms
- Message queue
- A line where producers leave messages and consumers take them later, so slow work leaves the request.
- Producer
- The code that puts messages into the queue.
- Consumer
- The code (a worker) that takes messages from the queue and does the job.
- Worker pool
- Several workers reading one queue; each message goes to one of them.
- Acknowledgement (ack)
- A worker's note that a message is done, after which the queue deletes it.
- Visibility timeout
- How long a taken message stays hidden before the queue offers it to another worker.
- At-least-once delivery
- The queue may deliver a message more than once, but not lose it.
- Idempotency
- Doing a job twice gives the same result as doing it once.
- Dead-letter queue
- A side queue that keeps messages which failed too many times.
- Partition key
- A value such as user id that sends related messages to the same partition so they stay in order.
- Backpressure
- Slowing or rejecting producers when consumers cannot keep up.