22. Message Queues
22.2 Why go async?
At the bank: Without tokens, everyone stands in one line at one counter. One slow customer holds up everyone behind them. With tokens, you're free to sit, the bank can add counters, and a slow case doesn't stop the room.
In the system: Doing everything synchronously inside the "place order" request means the customer waits for every step, and any step failing fails the whole order:
Figure: the customer only waits for what must happen now; the rest happens in the background.
What a queue buys you:
- Faster responses. Save the order, enqueue the follow-up jobs, reply. With the illustrative timings above, about 60 ms instead of 1.8 seconds.
- Failure isolation. If the SMS gateway is down, orders still go through; SMS messages wait in the queue and go out when it recovers.
- Smoothing spikes. At a Big Sale, orders arrive faster than the SMS gateway allows. The queue absorbs the burst and workers drain it at a steady pace (22.8).
- Independent scaling. Add more SMS workers without touching checkout.
What it costs:
- Eventual, not immediate. The SMS arrives seconds later, not before the "order placed" screen. Show "we'll text you shortly", not "SMS sent".
- More moving parts: the broker to run and monitor, retries, duplicates (22.3) and ordering (22.7) to think about.
- Harder debugging: one request now spans several processes. Pass a correlation ID in each message (Chapter 30).
Rule of thumb: do synchronously what the user needs to see now (save the order, take the payment); queue what can happen a moment later (emails, SMS, thumbnails, analytics, search indexing).
Memory code: "Do now what they must see; queue what can wait a moment."