Messaging and async

Backpressure

What happens when producers outrun consumers, why unbounded queues fail, and how to push back by blocking, shedding, dropping or scaling.

Lesson13 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A thumbnail service takes uploaded images from a queue and resizes them. Uploads arrive at 1,000 per second and the workers handle 1,000 per second, with a queue between them “for safety”. One afternoon object storage slows down, and the workers drop to 600 per second.

Nothing fails. The upload API is as fast as ever, because all it does is enqueue, and its dashboards are green. But 400 more jobs arrive each second than leave, and an hour later 1.44 million are waiting. A new upload gets its thumbnail 40 minutes late. Users who see no thumbnail upload again, which adds load. In the end the broker’s memory or disk fills, and the failure finally becomes visible: late, large, and in a component that was never the cause.

The first instinct is a bigger buffer. It buys time and changes nothing else. If arrivals exceed departures, any finite buffer fills, and a bigger one only holds staler work when it does. The second instinct is more workers, which helps only when the workers are the bottleneck. Here they were waiting on storage.

What is missing is a signal travelling the other way. When the consumer cannot keep up, the producer has to find out and do something about it: wait, slow down or refuse work. That signal is backpressure.

An unbounded queue hides overload; a bounded one pushes back5 components: Clients, Upload API, Job queue, Resize workers, Object storage. Connections: Clients to Upload API; Upload API to Job queue (enqueue); Job queue to Resize workers (dequeue); Resize workers to Object storage.ClientsUpload APIproducerJob queuedepth near 0Resize workersconsumers1,000 jobs/sObject storageenqueuedequeue

Step 1 of 9

An upload API puts one resize job on a queue for every image. In normal running, 1,000 jobs arrive each second and the workers finish 1,000 each second. The queue stays close to empty, and a job waits a few milliseconds.

Read the steps as text
  1. An upload API puts one resize job on a queue for every image. In normal running, 1,000 jobs arrive each second and the workers finish 1,000 each second. The queue stays close to empty, and a job waits a few milliseconds.
  2. Object storage becomes slow, so each worker takes longer over every image. The workers drop to 600 jobs per second. Uploads have not slowed at all, so 400 more jobs arrive each second than leave.
  3. With an unbounded queue, nothing pushes back. After an hour the backlog is 1.44 million jobs, and a new job waits 40 minutes before a worker touches it. Every dashboard for the API still looks healthy.
  4. The queue keeps growing until something gives. The broker runs out of memory or disk, or the jobs become worthless because users stopped waiting for their thumbnails long ago. The system is busy doing work that nobody wants.
  5. Now run it again with a bound of 10,000 jobs on the queue. It fills in 25 seconds, and the next enqueue fails or blocks. The slowdown is no longer hidden inside the queue. It has travelled upstream to the producer.
  6. The API has to choose. It can block until there is room, which suits a batch job. For a user-facing request it should shed load instead: answer 429 or 503 quickly, so that the client backs off and tries again later.
  7. Arrivals now match what the workers can do. The queue never holds more than 10,000 jobs, so the worst wait is about 17 seconds, not 40 minutes. The users who are accepted get a service that works.
  8. Meanwhile an autoscaler that watches the age of the oldest job adds workers, and the storage problem is fixed. Capacity returns, the queue drains, and the API stops rejecting requests.
  9. Backpressure means a slow consumer makes the producer slow down, by blocking, rejecting or dropping, before buffers grow without limit. A queue can absorb a burst. It cannot absorb sustained overload, so every queue needs a bound and a plan for when it is full.
An unbounded queue hides overload; a bounded one pushes back

Why unbounded queues fail

A queue is good at absorbing a burst: a spike lasting minutes, followed by a quieter period in which the backlog drains. It cannot absorb sustained overload, where the arrival rate stays above the service rate. The backlog then grows in a straight line, and so does the wait.

An unbounded queue turns a throughput problem into three worse ones:

  • Latency without limit. Waiting time is the backlog divided by the service rate. A queue with no bound has no bound on latency.
  • Wasted work. By the time a job is served, its caller may have timed out and retried. The system spends scarce capacity on requests nobody is waiting for, and the retries add more.
  • A later, larger failure. Memory or disk eventually runs out. The crash takes the queued work with it, and recovery begins with a backlog.

“Unbounded” is often an accident: an in-memory list between two threads, a thread pool whose default work queue has no limit, a channel created without a capacity. Every buffer in a system should have a stated size and a stated behaviour when it is full.

What to do when the buffer is full

Strategy What happens Fits when
Block the producer It waits for space Batch pipelines whose upstream can simply go slower
Shed load New work is rejected fast (429 or 503) User-facing requests, where a quick “no” beats a slow timeout
Drop The newest, the oldest or a sample is discarded Data that goes stale: metrics, live positions, video frames
Buffer to disk Work spills to a durable log with a retention limit Work that must not be lost and may be late
Scale consumers Capacity is added as lag grows The consumers are the bottleneck and can scale in time

These combine. A typical design buffers a bounded amount to ride out bursts, scales consumers on lag, and sheds load when both are used up.

Blocking is the purest form, but it only moves the problem one hop upstream. That is fine when the upstream is a file reader that can pause. It is not fine when the upstream is a request thread holding a user’s connection: blocked threads pile up until the service answers nobody. At the edge of a system there is no upstream left to slow down, so backpressure has to become load shedding, usually through rate limiting, with a Retry-After header that tells the client when to come back.

When you shed, choose what to shed. Dropping the oldest queued request is often better than dropping the newest, because its caller has most likely given up already. Low-priority traffic should go before checkout.

Pull versus push

Who controls the pace decides how much backpressure you get for free.

In a pull system the consumer asks for work when it is ready. Kafka consumers call poll() and SQS consumers call ReceiveMessage. A slow consumer asks less often and cannot be overwhelmed. The backlog stays in the broker, on disk, where it is cheap.

In a push system the sender decides. Without a limit, a fast broker floods a slow consumer’s memory, so push systems add explicit credit. RabbitMQ pushes messages to consumers, and its prefetch setting caps how many unacknowledged messages each consumer may hold. With no prefetch limit the broker sends everything it has.

Pull protects the consumer and nothing else. The backlog still grows in the broker, and with time-based retention a consumer that falls further behind than the retention period silently loses data. A large disk is still a bound.

Two classic designs

TCP flow control. Every TCP receiver advertises a receive window, the number of bytes its buffer can still take, and a sender may not have more unacknowledged data in flight than that. If the receiving application stops reading, the buffer fills, the window shrinks to zero and the sender stops. The sender’s own buffer then fills, and the sending application’s write() blocks or reports that it would block. A slow reader has slowed a writer on another machine without any application code. A chain of TCP connections carries backpressure hop by hop, provided each process stops reading its input when it cannot write its output. TCP and UDP covers the protocol.

Reactive Streams. This specification was started in 2013 by engineers from Netflix, Pivotal, Lightbend (then Typesafe) and others, and was adopted into Java 9 as java.util.concurrent.Flow. It standardises backpressure inside a process. A subscriber calls request(n) to say it can take n more items, and a publisher must never send more than has been requested. Demand flows upstream while data flows downstream, so a slow final stage throttles the source. Project Reactor, RxJava and Akka Streams implement it. HTTP/2, and gRPC on top of it, apply the same credit idea with flow-control windows per stream.

Backpressure through a pipeline

Backpressure only works end to end. One unbounded buffer anywhere in a chain absorbs the signal, and everything upstream of it runs at full speed into it. Walk a design stage by stage, and ask at each one what happens when the next stage is slow.

Kafka’s producer client shows the idea done properly. Records wait in a client-side buffer of fixed size (buffer.memory, 32 MB by default). When it is full, send() blocks for up to max.block.ms and then throws. The application then has to decide whether to slow its own input, shed or drop.

Monitoring lag

You cannot push back on what you do not measure. Watch three things:

  • Depth or lag. Queue depth, or in Kafka the log end offset minus the committed offset for each partition.
  • Age. How long the oldest unprocessed message has waited, such as ApproximateAgeOfOldestMessage in SQS. Age maps directly to delay that users see. A count does not: a lag of 100,000 is two seconds at one throughput and an hour at another.
  • Trend. Steady lag means the consumers are keeping pace with a backlog. Lag that rises for ten minutes means arrivals exceed capacity and something must change.

Alert on age and trend, and drive consumer autoscaling from lag, not CPU. A consumer blocked on a slow dependency shows low CPU and a growing backlog.

When to use which, and when not to

Block when the producer can wait. Shed when it cannot. Drop when late data is worthless. Buffer durably when nothing may be lost, and accept the delay.

Not every buffer needs a protocol: one that can only ever hold a small, fixed amount of work is already bounded. And adding consumers is not backpressure when the slow part is a shared dependency, because more workers hitting a struggling database make it slower.

In the interview

Bring up backpressure the moment you draw a queue between a fast producer and a slower consumer. Say that the queue is bounded and what happens when it fills: “The queue absorbs bursts. Consumers autoscale on lag. If lag passes a threshold, the API sheds low-priority traffic with 429s, so latency stays bounded for the requests we accept.” Then name the metric you would alert on, which is the age of the oldest message. An interviewer who asks “what if the consumers are down for an hour?” is checking that you know a queue delays overload and does not remove it.

Key takeaways

  • A queue absorbs a burst. It cannot absorb sustained overload, where arrivals stay above the service rate.
  • An unbounded queue hides overload as growing latency, spends capacity on work nobody is waiting for, and fails later and harder.
  • Every buffer needs a bound and a stated behaviour when full: block the producer, shed load, drop data, spill to disk, or scale consumers.
  • Blocking only moves the problem one hop upstream. At the edge of the system, backpressure has to become load shedding.
  • Pull-based consumers cannot be flooded; push-based delivery needs explicit credit such as a prefetch limit or a request(n) signal.
  • Monitor the age of the oldest message and the trend in lag, and scale consumers on lag, not CPU.

Check yourself

1. Jobs arrive at 5,000 per second and workers complete 4,000 per second. The queue is bounded at 60,000 and starts empty. How long until it is full, and roughly how long does a job at the back then wait?
2. An API hands each request to an unbounded in-memory queue feeding a database writer. The database slows down. What is the likely sequence?
3. A user-facing API finds its work queue full. Which response is usually best?
4. A Kafka topic has 7 days of retention. One consumer group is stopped for 8 days and then restarted. What does it find?
5. Consumer CPU is at 15% and lag has grown steadily for 20 minutes. An autoscaler driven by CPU does nothing. What is the best reading of this?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What is backpressure?

A signal from a slow consumer that makes the producer slow down, wait, or stop sending, so that buffers between them do not grow without limit.

Why is an unbounded queue a failure mode?

Under sustained overload its backlog and latency grow without limit, it processes requests whose callers have given up, and it eventually exhausts memory or disk.

Name five responses to a full buffer.

Block the producer, shed load with a fast rejection, drop data (newest, oldest or a sample), spill to a durable bounded log, and scale out consumers.

How does TCP flow control apply backpressure?

The receiver advertises how much buffer space it has left. When the application stops reading, the window falls to zero, the sender stops, and the sending application's writes block.

How does Reactive Streams apply backpressure?

A subscriber signals demand with request(n), and a publisher may never emit more items than have been requested. Demand flows upstream as data flows downstream.

Which lag metric maps best to user impact?

The age of the oldest unprocessed message. A raw count means different delays at different throughputs.

Review the deck