Asynchronism: Queues and Back Pressure (System Design #13)
At 9 a.m. Monday, ten thousand users sign in at once. Your API handles it, but every sign-in fires an email, a Slack notification, a search-index update, and a CRM sync — synchronously. The email provider throttles, the calls start timing out, threads pile up waiting on sockets, and the whole service goes down. The requests were fine. The coupling in time killed it.
Asynchronism breaks that coupling. A producer writes a message and moves on; a consumer processes it whenever it can. The queue absorbs the spike, retries the failures, and lets the two sides scale independently. This chapter covers task queues, message queues, event streams, delivery guarantees, ordering, and the discipline that keeps a queue from becoming an unbounded liability: back pressure.
The core pattern
Synchronous: A calls B and waits for the result. If B is slow, A is slow; if B is down, A fails. Asynchronous: A publishes a message and returns; B consumes it later. If B is slow, messages queue; if B is down, messages wait.
\[ \text{sync: } T_A = T_A^{\text{work}} + T_B, \qquad \text{async: } T_A = T_A^{\text{work}} + T_{\text{enqueue}} \]
Many patterns look like “just add a queue”, but there are three distinct shapes with different semantics:
- Task queue. One job is assigned to one worker. Used for work distribution: send this email, resize this image. Work is done once (modulo retries).
- Message queue. Messages flow between services, often with acknowledgements and retries. A superset behaviorally; the terms are used loosely.
- Event stream / log (Kafka-style). An append-only, replayable sequence partitioned by key. Many consumers can read independently, and you can rewind. Used for event sourcing, analytics, and fan-out.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.6cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=green!12] (api) at (-3.6,0) {api};
\node[b, fill=yellow!22] (q) at (-0.9,0) {queue};
\node[b, fill=orange!16] (w1) at (1.8,0.9) {worker};
\node[b, fill=orange!16] (w2) at (1.8,-0.9) {worker};
\draw[a] (api) -- node[above, font=\scriptsize] {publish} (q);
\draw[a] (q) -- node[above, font=\scriptsize] {consume} (w1);
\draw[a] (q) -- (w2);
\node[font=\rmfamily\small, text=black!60] at (-3.6,-0.8) {returns immediately};
\end{tikzpicture}
Topologies: competing consumers vs pub/sub
- Competing consumers. Each message goes to exactly one worker. This is how you parallelize a backlog across N workers. Add workers to increase throughput; the queue distributes.
- Pub/sub (publish–subscribe). Each message is delivered to every subscriber. One
user.createdevent is consumed by the email service, the search indexer, and the analytics pipeline independently. Used for fan-out.
Systems commonly combine them: a topic fans out to consumer groups, and within each group, competing consumers split the load. Kafka models exactly this — partitions distribute across a group, and separate groups each get a full copy.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, rounded corners=3pt, minimum width=1.7cm, minimum height=0.68cm, align=center, font=\rmfamily\small},
a/.style={->, thick}]
\node[b, fill=green!12] (p) at (-3.8,0) {publisher};
\node[b, fill=yellow!22] (t) at (-1.5,0) {topic};
\node[b, fill=orange!16] (s1) at (1.3,1.2) {email group};
\node[b, fill=orange!16] (s2) at (1.3,0) {search group};
\node[b, fill=orange!16] (s3) at (1.3,-1.2) {analytics group};
\draw[a] (p) -- (t);
\draw[a] (t) -- (s1); \draw[a] (t) -- (s2); \draw[a] (t) -- (s3);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-0.9) {one event, many independent consumers};
\end{tikzpicture}
Delivery semantics
You must choose what happens when things go wrong. There is no free “exactly once” across a network.
| Guarantee | Behavior | Risk |
|---|---|---|
| At most once | fire and forget | messages lost |
| At least once | retry until acknowledged | duplicates |
| Exactly once | no loss, no duplicates | expensive; only within one system |
Real systems almost always choose at-least-once, which means duplicates happen and consumers must be idempotent (Chapter 14). True end-to-end exactly-once requires the broker and the consumer to share a transaction — Kafka Streams and some databases offer it within their boundary, but the moment you call an external API, you are back to at-least-once. Design for duplicates; they are not exceptional.
The mechanism is acknowledgement: a consumer removes the message only after successfully processing it. If it crashes before acking, the message is redelivered (a visibility timeout makes it available again). Hence the classic job-id + processed-set pattern from Chapter 6.
Ordering
Queues are not automatically ordered. In a distributed broker, partitions are ordered but the topic is not: two messages with the same key can land on different partitions and be processed out of order. If order matters (a “cancel” after an “order”), you must:
- Route all messages for an entity to the same partition (partition by entity id), so order is preserved per entity, or
- Add sequence numbers and have the consumer buffer/reorder, or
- Make operations commutative so order does not matter.
Per-entity ordering is usually the right answer: partition by user_id or order_id, and accept that different entities may be processed concurrently.
Back pressure: the missing discipline
A queue is a buffer, and buffers fill. If producers are faster than consumers indefinitely, the queue grows without bound — memory, disk, and latency all blow up until something dies. The queue has not solved the problem; it has hidden it until the worst possible moment.
Back pressure is the set of mechanisms that tell producers to slow down when consumers cannot keep up:
- Bounded queues. Cap the depth. When full, the producer blocks, drops, or rejects.
- Load shedding with 429s. Return “too many requests” and let clients back off, rather than accepting work you cannot do.
- Drop / sample low priority. Under stress, discard analytics or non-critical work and keep the critical path moving.
- Flow control / credits. The consumer advertises how much it can take (used in streaming protocols and TCP itself).
- Autoscaling with a ceiling. Add consumers, but cap spending — a queue that drains only with infinite workers is not a design.
The essential point: every queue needs an overflow policy. “Grow forever” is not one. Decide, in advance, whether you drop, shed, block, or scale — and monitor queue depth and consumer lag so you know when the policy is about to matter.
# bounded ceiling: shed load instead of accepting unbounded work
def enqueue(queue, job, max_depth=100_000):
if queue.depth() >= max_depth:
raise TooBusy("429: try later") # back pressure to the producer
queue.push(job)
# consumer lag is the health metric: growing lag = consumers can't keep up
def healthy(lag, capacity): return lag < capacity * 60 # < 60s of backlog
Sizing and monitoring
Little’s Law (Chapter 6) sizes the consumers: with arrival rate \(\lambda\) and processing time \(W\), you need \(L = \lambda W\) workers to break even, plus headroom. Then monitor the two metrics that reveal trouble:
- Queue depth / consumer lag — a steadily growing value is a slow-motion outage.
- Age of oldest message — tells you the latency a job actually experiences, which depth alone does not.
Set alerts on both. A queue with a stable depth is fine; a queue whose oldest message is two hours old is already failing its users.
Pitfalls
- Unbounded queues. They convert a load problem into an out-of-memory problem. Always cap depth.
- No overflow policy. When the cap is hit, the behavior must be defined: block, shed, drop, or scale.
- Assuming ordering. Only per-partition order is guaranteed. Partition by entity if order matters.
- Non-idempotent consumers with at-least-once. Duplicates are guaranteed; make every consumer safe to repeat.
- Ignoring consumer lag. The queue hides the outage until the backlog is unrecoverable. Alert on lag and age.
- Using a queue to avoid fixing capacity. Async decouples and buffers; it does not create throughput. If consumers are too slow, the queue merely postpones the failure.
Why is at-least-once the usual delivery guarantee, and what must consumers do? What is back pressure and why does every queue need an overflow policy?
ASolution
Exactly-once is expensive and generally impossible once you cross a network or call an external service, so systems deliver at least once and tolerate duplicates; consumers must therefore be idempotent. Back pressure slows or rejects producers when consumers cannot keep up, and without an overflow policy (drop, shed, block, or scale) a queue grows unbounded until it takes down the system.
Next: Communication, APIs and Idempotency (System Design #14) — how components talk, and how to retry safely.