Backpressure and flow control
When the consumer is slower than the producer, you must buffer, drop or slow the sender. Learn to slow the sender, so your queues stay small.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
On 25 March 2026, voice and video on Discord were badly degraded from 12:13 to 15:30 PDT. Most users could not start or join calls. They saw "Awaiting Endpoint". 1
It began with a routine config change. Kubernetes stopped pods before their sessions could hand off cleanly. About 17% of sessions across Discord stopped without warning. 1
Those users all tried to reconnect. Discord has a start-session rate limit that "provides backpressure when we have a flood of requests". But that limit had not been re-tuned after a recent migration. Too many session starts got through, and gateway nodes in one zone began to run out of memory. 1
The voice service had a second problem. Its Elixir processes read one message at a time from a mailbox, "a queue of incoming messages". 1 Each new outbound connection went through a single supervisor process. To start a process, that supervisor scanned its mailbox for one message. With about 100,000 messages waiting, each start took about 1 ms longer. 1
So the longer the queue got, the slower it drained. In total, the mailboxes on 15 voice syncers grew to nearly 1 million messages and kept rising. The connection that sends health reports to etcd also went through those supervisors. After the 60-second TTL, instances dropped out of service discovery. 1
Early restarts helped only briefly, because the queues filled again. Recovery came after the team set lower spawn limits and doubled the instances. 1
The idea in simple words
A producer sends work. A consumer does it. Sometimes the producer is faster for a while. What then?
You have three choices, and only three:
- Buffer. Store the extra work and do it later.
- Drop. Throw some work away, on purpose.
- Slow the producer. Make the sender wait until the consumer is ready.
The third one is backpressure. The slow part pushes back on the fast part. A buffer only buys time. If the producer stays faster on average, the buffer fills, and then you are back to choosing between dropping and slowing.
Load shedding is choice 2: drop work early and cheaply. Backpressure is choice 3. You often need both. You can slow your own services, but you cannot slow a user who is tapping a button.
The key idea. A queue does not add capacity. It only moves the wait. Give every queue a limit, and decide what happens when it is full: the sender waits, or the sender gets an error.
How it works
Unbounded queues hide the problem
Many queues have no limit by default. In Python, asyncio.Queue() has maxsize=0, and that means "the queue size is infinite". 5 Java's Executors.newFixedThreadPool uses "a shared unbounded queue". 3
The Java docs say what this means. An unbounded queue smooths out short bursts. But it allows "unbounded work queue growth" when tasks keep arriving faster than they finish. 2 As the Tail latency and queueing lesson showed, a long queue also means a long wait for every item in it.
Node.js measured the cost. It compressed a file of about 9 GB with streams, once with backpressure and once without. With backpressure, the process used about 87.81 MB of memory. Without it, about 1.52 GB. 4
A bounded queue has a fixed size. Java's docs say it "helps prevent resource exhaustion". 2 The hard part is the next question: what happens when it is full?
Wait or reject
When a bounded queue is full, the producer either waits or gets an error. Pick one on purpose.
In asyncio, await queue.put(item) waits for a free slot. put_nowait(item) raises QueueFull at once. 5 Here is both, in a small sketch:
import asyncio
queue = asyncio.Queue(maxsize=100) # at most 100 jobs wait (Python 3.10+)
async def producer(jobs):
for job in jobs:
await queue.put(job) # waits while the queue is full
async def worker():
while True:
job = await queue.get()
try:
await handle(job)
finally:
queue.task_done()
def enqueue_from_request(job): # a handler that must not wait
try:
queue.put_nowait(job)
return 202
except asyncio.QueueFull:
return 503 # caller should back off and retry laterWaiting is real backpressure: the producer slows to the consumer's speed. Use it inside your own system, such as a batch job.
Rejecting turns the decision into load shedding. Use it at the edge, where callers are users or other teams. Return 503 with Retry-After, as in the load shedding lesson.
Java gives you both choices too. The default policy, AbortPolicy, throws RejectedExecutionException. CallerRunsPolicy runs the task on the thread that submitted it. The docs call this "a simple feedback control mechanism" that slows down new submissions. 2
Pull and credits instead of push
In a push system, the sender decides the rate. Kafka's docs say a push consumer "tends to be overwhelmed" when it is slower than the producer. 9 So Kafka consumers pull. A slow consumer "simply falls behind and catches up when it can". 9
A more general form is credit-based flow control. The receiver says how much it can take. The sender sends no more than that.
- Reactive Streams. The subscriber calls
request(n)to ask for n more items. 6 The publisher must never send more items in total than were requested. 6 The goal is that the receiver "is not forced to buffer arbitrary amounts of data". 6 - HTTP/2. Each stream and each connection has a flow-control window. The receiver opens it with
WINDOW_UPDATEframes. The RFC calls it "a credit-based scheme". 7 Both windows start at 65,535 octets, and only DATA frames count. 7 - TCP. Every segment carries a window: how many more bytes the receiver will accept. 8 If the window drops to zero, the sender stops and sends small probes, with growing gaps, until it opens. 8
This is flow control: one receiver protecting itself from one sender. It is different from congestion control, which protects the network. The TCP/IP lesson covers both.
How backpressure travels, and where it stops
Backpressure works best when it travels back, hop by hop, to whoever started the work. Step through it. Use Next and Back, or the ← and → keys.
- A client sends jobs through an API to a queue with room for 4 jobs. 150 jobs a second arrive, but the worker finishes only 100. The queue is full almost at once.
- The queue is full, so each API handler's put() call waits for a free slot. A waiting handler does not take the next request.
- Requests now wait in the API's connections, so the client waits too. A client with a fixed number of requests in flight now sends only as fast as the worker finishes. The slow-down travelled back, hop by hop.
- Now the queue has no limit. The API adds every job and answers at once, so the client never slows down. The queue grows by 50 jobs every second, and so does memory, until something crashes.
- The fix: give every queue a limit. When it is full, either wait, which slows the sender, or reject with 503 and Retry-After, which is load shedding.
The chain is only as good as its weakest link. Three things break it:
- An unbounded buffer anywhere. The signal stops there. That part just grows. In Discord's outage, the mailboxes kept growing until the team lowered rate limits upstream. 1
- An async boundary that answers early. "202 Accepted" ends the caller's wait before the work is done. From then on, only the queue's limit protects you. Reactive Streams exists to carry the signal across exactly these boundaries. 6
- Fire-and-forget calls. A call nobody waits for can never slow anybody down.
A durable log is a special case. A Kafka producer does not slow down when a consumer falls behind. The log on disk is the buffer, and the cost shows up as consumer lag. 9 Inside the consumer, you can still apply backpressure. max.poll.records limits how many records one poll returns. pause() stops fetching from chosen partitions until you call resume(). 10 But keep calling poll(). If you wait longer than max.poll.interval.ms, the consumer leaves its group. 10
At the very front, users will not slow down. So the last hop of backpressure becomes a choice: make them wait a little, or reject with a clear error.
Trade-offs
| Option | Memory safe? | What the producer sees | Use it when |
|---|---|---|---|
| Unbounded buffer | No It grows until something crashes. | Nothing. Every send succeeds. | Never on purpose. Find these and add limits. |
| Bounded queue, producer waits | Yes | Slower sends. | Inside your own system: pipelines, batch jobs, workers. |
| Bounded queue, reject when full | Yes | Fast errors, such as 503. | At the edge, where callers can retry later. |
| Drop oldest or newest item | Yes | Nothing. Data is lost quietly. | Only the latest value matters, like metrics or presence. |
| Pull or credit-based flow | Yes | The receiver sets the pace. | Streams, brokers, protocols you control on both sides. |
| Durable log (Kafka) | Yes , on disk, until retention. | Nothing. Lag grows instead. | Consumers may fall behind and catch up later. |
Simple rule: every queue gets a limit. Inside your system, let the producer wait. At the edge, reject fast.
At work: how a senior uses this
- Draw the path of one request and mark every buffer: thread pools, channels, mailboxes, connection pools, broker queues. Ask: "What is its limit, and what happens when it is full?"
- Search for default constructors that hide unbounded queues, such as
newFixedThreadPoolorasyncio.Queue(). Give each a size from Little's law and your latency target. - Size a queue from time, not memory. If you can wait 2 seconds and do 100 jobs a second, 200 is the limit.
- Alert on queue length and the age of the oldest item. Also track time spent blocked in
put(). - After a migration or a resize, retune every limit that provides backpressure. Discord's limit had not been re-tuned after a migration. 1
- Never let health checks or heartbeats wait behind normal work. Give them their own path.
- When you add an async API that returns 202, write down who protects the queue behind it.
With AI
What to ask the agent
"List every queue, channel, thread pool and buffer in this service. For each, give its size limit, or say 'unbounded', and what happens when it is full."
"Replace this unbounded asyncio.Queue with a bounded one. Producers inside the batch job should wait. The HTTP handler should return 503 with Retry-After when the queue is full."
"Write a load test where the consumer is 50% slower than the producer for 10 minutes. Record queue length, memory and p99 latency every second."
What to check yourself
- No queue uses a default that means "no limit". Read the docs of each constructor the agent used.
- The handler that must stay fast uses a non-waiting call, like
put_nowaitoroffer, not a blockingput. - A blocking
putnever runs on an event loop thread or while holding a lock. - The load test runs long enough for the queue to fill. Memory flattens out instead of climbing.
- Rejected work is counted in a metric, so you can see shedding happen.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 10 sources and related lessons
- Bo Ingram and Stephen Birarda, “You’ve Got (Too Much) Mail: Behind the Scenes of the 3/25/26 Voice Outage”, Discord Blog, 29 April 2026 (opens in a new tab)
The official postmortem. Read how a reconnect flood filled process mailboxes, and how the team got the queues to drain again. - Java SE 21 API documentation: ThreadPoolExecutor (opens in a new tab)
The "Queuing" and "Rejected tasks" sections compare unbounded and bounded work queues, and list what happens when a pool is full. - Java SE 21 API documentation: Executors (opens in a new tab)
newFixedThreadPool uses a shared unbounded queue. Worth knowing before you use it in a server. - Node.js Learn: Backpressuring in Streams (opens in a new tab)
What write() returning false means, the 'drain' event, and a measured memory test with and without backpressure. - Python documentation: asyncio Queues (opens in a new tab)
maxsize, put() that waits, put_nowait() that raises QueueFull, and task_done(). - Reactive Streams: reactive-streams-jvm README (specification for the JVM) (opens in a new tab)
The goals of the spec, and the rules for Subscription.request(n) and how many onNext signals a Publisher may send. - Thomson and Benfield (eds.), RFC 9113: HTTP/2 (IETF, 2022), section 5.2 (opens in a new tab)
HTTP/2 flow control per stream and per connection, the credit-based scheme, and the 65,535-octet starting window. - Eddy (ed.), RFC 9293: Transmission Control Protocol (TCP) (IETF, 2022) (opens in a new tab)
The window field in section 3.1, and zero-window probing in section 3.8.6.1. - Apache Kafka documentation: Design (Kafka 4.3) (opens in a new tab)
The "Push vs. pull" section explains why Kafka consumers pull, and what a slow consumer does in each model. - Apache Kafka 4.3 API documentation: KafkaConsumer (opens in a new tab)
The "Consumption Flow Control" section on pause() and resume(), and max.poll.records and max.poll.interval.ms.
Real incident: Discord, 25 Mar 2026: Discord voice and video outage: message queues grew faster than they drained
Case studies: Amazon: Why queue backlogs can turn a short outage into a long one · Netflix: Adaptive concurrency limits instead of hand-tuned limits
Related: Queues vs logs and delivery guarantees · Tail latency and queueing · Load shedding and graceful degradation · Rate limiting · TCP/IP and the network stack · HTTP/1.1, HTTP/2 and HTTP/3 · Stream processing · Circuit breakers, bulkheads and fallbacks
Before this: Queues vs logs and Tail latency and queueing. Next to it: Load shedding and Rate limiting. For flow control in protocols, see TCP/IP and HTTP/1.1, HTTP/2, HTTP/3 and QUIC.