Distributed systems · L2Backpressure and flow control

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.

L2 SeniorDistributed systems19 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 9 Nov 2026 · How we check content
Section 1 of 8

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

Section 2 of 8

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:

  1. Buffer. Store the extra work and do it later.
  2. Drop. Throw some work away, on purpose.
  3. 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.

Section 3 of 8

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 later

Waiting 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_UPDATE frames. 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 full bounded queue slows every hop back to the client; an unbounded queue hides the problem until memory runs outA · Bounded queue (limit: 4 jobs) example numbers · the worker does 100 jobs/s Client API Queue Worker 150 jobs/s arrive · 100 jobs/s leavethe queue holds 4/4 in a moment full → API's put() waitsAPI handlers stop taking new requests its connections fill · the client waits✓ the client slows to 100 jobs/s B · Same, but the queue has no limitClientAPINo limitWorkerAPI says "OK" at once · client never slows+50 jobs every second · memory grows ✓ fix: set a limit · when full, wait or rejectreject = 503 + Retry-After, as in load shedding SeniorPath
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
Step 1 of 5

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.

Section 4 of 8

Trade-offs

OptionMemory safe?What the producer seesUse it when
Unbounded bufferNo It grows until something crashes.Nothing. Every send succeeds.Never on purpose. Find these and add limits.
Bounded queue, producer waitsYes Slower sends.Inside your own system: pipelines, batch jobs, workers.
Bounded queue, reject when fullYes Fast errors, such as 503.At the edge, where callers can retry later.
Drop oldest or newest itemYes Nothing. Data is lost quietly.Only the latest value matters, like metrics or presence.
Pull or credit-based flowYes 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.

Section 5 of 8

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 newFixedThreadPool or asyncio.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.
Section 6 of 8

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_nowait or offer, not a blocking put.
  • A blocking put never 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.
Section 7 of 8

Check yourself

1. A service creates its worker pool with Java's Executors.newFixedThreadPool(8). Jobs arrive faster than 8 threads can finish them, for an hour. What happens?

Show answer

New jobs wait in a queue with no size limit, which keeps growing and uses more and more memory. newFixedThreadPool uses a shared unbounded queue. A running pool rejects jobs only when both its threads and its queue have finite limits and are full.

2. In Reactive Streams, a subscriber has called request(10) and has received 10 items. What may the publisher do next?

Show answer

Wait. It may not send more items until the subscriber requests more. The total number of items sent must never be more than the total requested. Demand is a credit, and the subscriber gives more credit with another request(n).

3. An API puts each request on a queue and returns 202 Accepted at once. A worker reads the queue. The worker slows down. Which statement is true?

Show answer

The client does not slow down. The queue absorbs the difference, so you must give it a limit and decide what happens when it is full. The 202 ends the client's wait before the work is done. That async boundary stops backpressure. Only a limit on the queue, with a wait or a reject, brings it back.

4. Your request handler must not wait. Which asyncio call fits a bounded queue there?

Show answer

queue.put_nowait(job), and turn QueueFull into 503 with Retry-After. put_nowait raises QueueFull at once when the queue is at maxsize. The default maxsize of 0 means the queue has no limit.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 10 sources and related lessons
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. Python documentation: asyncio Queues (opens in a new tab)
    maxsize, put() that waits, put_nowait() that raises QueueFull, and task_done().
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. 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.

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper