Notes
All notes

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:

\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

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:

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:

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:

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

QQuestionSelf-check

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.