22. Message Queues
The picture to keep in your head
Every question below is answered twice: first at the bank, so you can picture it, then in the system, so you know exactly how it works. Each answer ends with a memory code to lock it in.
The picture to keep in your head
Walk into a busy bank. You don't stand at a counter waiting for a clerk to be free. You press a button, take a token, number 47, and go sit down. Your token goes on the board. When a clerk at any counter is free, the board calls the next number. When your work is done, the clerk clears your token. If the bank gets busy, the manager opens more counters. And if one customer's problem can't be solved at the counter, after a few tries they're sent to the manager's desk, so the queue keeps moving.
You didn't have to wait at the counter. The clerks didn't have to rush. Nobody was forgotten, even when the bank was packed.
That's a message queue: one part of a system leaves a job, another part picks it up when it's free, and the queue holds everything in between.
Our running example: the grocery app's checkout. When a customer places an order, three slower jobs need to happen: send the SMS confirmation, print the packing slip at the store, and add loyalty points. At a Big Sale, orders peak at around 1,200 a second (an assumption for practice).
| At the bank | In the system |
|---|---|
| Taking a token and sitting down | The producer sends a message and moves on |
| The token board | The queue (or log) |
| Clerks at the counters | Consumers (workers) |
| "Done, next!" and the token is cleared | Acknowledging (acking) a message |
| A clerk who walks off mid-job: the token is called again | Visibility timeout and redelivery |
| The manager's desk for the stuck cases | The dead-letter queue (DLQ) |
| A token called twice: don't pay out twice | Idempotent consumers |
| Opening more counters at rush hour | Scaling consumers |
| "Come back at 3 pm" | Delayed and scheduled jobs |
Figure: take a token and sit down; the work gets done, just not while you stand at the counter.