Backpressure and Load Shedding - Complete Deep Dive
Prerequisites: Performance Metrics, Message Queues Used in: Message Queue, Notification System, Rate Limiter
What is Backpressure?
Backpressure is the signal that travels from a slow consumer back to a fast producer, telling it to slow down. A consumer is whatever does the work — a service, a worker, a database. A producer is whatever hands it work — a client, an upstream service, a queue publisher. When the consumer cannot keep up and has a way to say so, the producer slows down or the request is rejected cleanly. When it has no way to say so, the excess work piles up somewhere.
That is the whole point. A system with backpressure converts overload into a clean rejection: “no, try later.” A system without backpressure converts overload into unbounded latency: every request is accepted, nothing is refused, and the time to serve any one of them grows until the whole thing is useless. The second outcome looks healthier on a dashboard — no errors! — and is far worse for users.
Real-world analogy: A restaurant kitchen can plate 60 covers an hour. On a busy night 120 parties arrive. A restaurant with backpressure has a host at the door who says “the wait is 40 minutes, or we can call you” — some people leave, the ones who stay get food while it is hot, and the kitchen works at its real capacity. A restaurant without backpressure seats all 120, takes every order, and the kitchen tries. Nobody is turned away, which feels generous, but orders sit for 90 minutes, food goes out cold, diners who have already given up walk out leaving dishes the kitchen still cooked, and the staff waste capacity on meals nobody will eat. The second restaurant served fewer happy customers while doing more work.
Why an Unbounded Queue Is a Bug
The instinct when a consumer falls behind is to add a buffer. “Put a queue in front of it so nothing is lost.” This instinct is correct for one case and catastrophically wrong for the other, and the distinction is the single most important idea on this page.
A queue absorbs a burst. A queue cannot absorb a mismatch.
Service rate = 1,000 requests/sec
Case A - a BURST. Arrivals 5,000/sec for 2 seconds, then 500/sec.
Backlog peaks near 8,000 items, then drains. The queue did its job.
Case B - a sustained MISMATCH. Arrivals 1,200/sec, indefinitely.
Backlog grows by 200 items every second, forever.
After 1 hour 720,000 items. After 2 hours 1,440,000.
No queue size and no amount of memory fixes this.
In Case B the arrival rate exceeds the service rate on average, so the queue grows without bound. And the items in it are not just waiting — they are ageing past the point of being useful. The user who submitted the request at the back of a 720,000-item backlog closed the tab 20 minutes ago. You will still spend CPU on their request, produce a perfect response, and send it nowhere.
An unbounded queue — new LinkedBlockingQueue<>() with no capacity argument, an unbounded thread pool work queue, a channel with no size, a list you keep appending to — is therefore a bug, not a design. It does not prevent failure. It delays failure, turns a fast clear failure into a slow confusing one, and converts a capacity problem into a memory problem. The things it breaks:
- Memory growth. Each queued item holds its request body, headers, buffers, and whatever context the framework attached. A million queued items is gigabytes.
- Garbage collection pressure. In a managed runtime, a heap full of live queued objects means the GC — garbage collector, the component that reclaims unused memory — scans more and reclaims less. GC pauses lengthen, which slows the consumer, which grows the queue further. This loop is self-reinforcing.
- Timeouts firing while work is still queued. The client gave up after 2 seconds. The item is still number 40,000 in line. Nobody told the queue.
- Wasted work. Every item processed after its client gave up is capacity spent on a response with no recipient.
Little’s Law, and Why a Deep Queue IS High Latency
Little’s Law is the one piece of queueing theory worth memorising. Stated plainly:
L = λ × W
L = items in the system (queue length plus items being worked on)
λ = arrival rate (items per second)
W = time an item spends in the system (latency)
Rearranged, W = L / λ, which is the number you want:
a backlog of 50,000 items draining at 1,000 items/sec
W = 50,000 / 1,000 = 50 seconds of wait for the item at the back
This is not an approximation or a model to argue with — it is an accounting identity, true for any stable system regardless of how arrivals are distributed. The consequence is blunt: queue depth and latency are the same quantity in different units. A team that says “latency is fine, we just have a deep queue” has misread their own dashboard. If the queue is deep, latency is high by definition; they are measuring latency somewhere that excludes the wait.
It also tells you what “more capacity” does and does not do. Doubling the service rate halves the wait for a given backlog. It does nothing at all for Case B above unless the new rate exceeds the arrival rate — and the moment arrivals exceed service again, the backlog resumes growing from wherever it had got to.
Measure p99 latency — the value below which 99% of requests complete, so the experience of the unluckiest one in a hundred — including queue wait, or you are measuring the kitchen and ignoring the queue at the door. See performance metrics.
The Retry Storm and Metastable Failure
Here is how a brief overload becomes a multi-hour outage. Every step is something a reasonable engineer built on purpose.
flowchart LR
LOAD["Load rises above<br/>service capacity"] --> Q["Queue grows"]
Q --> LAT["Latency grows<br/>per queueing math"]
LAT --> TO["Client timeouts fire"]
TO --> RETRY["Clients retry"]
RETRY --> MORE["Arrival rate increases"]
MORE --> Q
LAT --> WASTE["Server still processing<br/>abandoned requests"]
WASTE --> CAP["Effective capacity drops"]
CAP --> Q
What the loop does: latency rises past the client timeout, so clients retry. A retry is a new arrival. If every client retries twice, your arrival rate triples at the exact moment you had too much load. Meanwhile the server is burning capacity on requests whose clients have already given up, so useful throughput falls while offered load rises. Both feedback arrows push the same way.
The dangerous property is what happens when the original surge ends. In a well-behaved system, removing the cause removes the effect. Here, the retries are now generated by the latency, and the latency is now generated by the retries. The system sits in a metastable failure state — a state it can stay in indefinitely, under normal load, because the load it is now serving is its own retry traffic. The only exits are to cut the load off entirely (shed or block traffic at the edge until the backlog drains) or to restart and drop the backlog.
Retrying into an overloaded system is the single most common amplifier in production incidents. The mitigations are not optional: exponential backoff with jitter so retries spread out instead of synchronising, a retry budget capping retries as a fraction of total traffic, and a circuit breaker that stops sending to a dependency that is clearly unwell. See retry and backoff for the detail. The headline rule: a retry must be cheaper for the server than the original request, or it must not happen.
Layer 1 - Bounded Queues With an Explicit Rejection Policy
Give every queue a capacity, and decide in writing what happens when it is full. The choice is the design; the capacity is a tuning knob.
| Policy | Behaviour when full | Use when |
|---|---|---|
| Reject | Caller gets an immediate error | Request-response work with a waiting client |
| Block the producer | Producer thread waits for space | In-process pipelines where the producer can usefully slow down |
| Drop oldest | Evict the head, accept the new item | Freshness matters more than completeness, such as metrics or location pings |
| Drop newest | Discard the arriving item | Order matters and the backlog is still useful |
Blocking the producer is real backpressure — the signal propagates. Rejecting is load shedding. Dropping is sampling. All three are legitimate; silently buffering is not.
How to size the capacity: work backwards from the latency you will tolerate, using Little’s Law. If you serve 1,000 items per second and your deadline is 2 seconds, a queue deeper than 2,000 items contains only items that will miss their deadline. So cap it near 2,000. A queue sized “big enough that it never fills” is an unbounded queue with extra steps.
Layer 2 - Load Shedding and Admission Control at the Edge
Load shedding is deliberately refusing work you cannot do in time. Do it as early as possible — at the gateway or edge, before the request has consumed a connection, a thread, a database handle or a cache lookup. A request rejected at the edge costs microseconds; the same request rejected after it has walked through five services has already spent most of the capacity it was going to spend. Return 503 Service Unavailable with a Retry-After header so a well-behaved client waits instead of hammering, and keep the reject path free of database calls and expensive logging — a shed path that costs 20 ms cannot save you at 50,000 requests per second.
Two status codes, two different mechanisms, and you want both. 429 Too Many Requests means you, specific caller, exceeded your share — that is rate limiting, a fairness policy enforced whether or not the system is busy. 503 means the system is out of capacity right now, applied regardless of who you are.
Admission control goes one step further and decides which requests to accept, not just how many. Classify traffic into a few tiers and shed from the bottom:
| Tier | Example traffic | Under overload |
|---|---|---|
| Critical | Checkout, payment, login, writes in flight | Never shed; protect with reserved capacity |
| Interactive | Product page, search, feed | Shed last, after cheap tiers are gone |
| Retryable background | Async jobs, recommendation refresh, prefetch | Shed first; it will come back |
| Opportunistic | Analytics beacons, bulk crawlers, speculative reads | Shed immediately and permanently |
The guidance that follows: shed the cheap and retryable work, and protect the checkout. A dropped recommendation refresh costs a slightly staler carousel; a dropped checkout costs revenue and a support ticket. Shedding 40% of traffic while keeping 100% of payments is a good afternoon. Two implementation notes: the tier must be knowable at the edge from a header or route rather than a lookup, and critical traffic needs reserved capacity rather than a fair fight — under overload, fair sharing gives analytics beacons the same odds as payments.
Layer 3 - Queue Wait Time Is a Better Signal Than Queue Depth
Teams instinctively alarm and autoscale on queue depth, the number of items waiting. It is the wrong signal, for a simple reason: 10,000 items is a catastrophe for a service that handles 100 per second and a rounding error for one that handles 50,000. Depth has no meaning without the service rate, and the service rate moves — a slow dependency, a GC pause or a deploy changes it without the queue changing at all.
Queue wait time — how long the item you just dequeued actually sat there — is the signal you want, because it is already in the unit the user feels. Stamp each item on enqueue, subtract on dequeue, and emit the distribution.
item.enqueued_at = now_ms()
queue.put(item) # bounded; rejects when full
# ... later, on the consumer side ...
item = queue.get()
wait_ms = now_ms() - item.enqueued_at
metrics.observe("queue_wait_ms", wait_ms)
if wait_ms > DEADLINE_MS:
metrics.increment("shed_expired")
continue # drop it; nobody is waiting for this any more
That last branch is the important one and it is three lines. If an item has already waited longer than anyone will wait for it, processing it is pure waste — drop it and move to the next. This is the core idea behind CoDel, Controlled Delay, an algorithm from network queue management: do not watch how long the queue is, watch how long the minimum wait stays above a target, and shed when it does. Use wait time for all three decisions — alarm, autoscale and shed — and export the distribution rather than the average. See observability.
Layer 4 - Deadlines, Not Just Timeouts
A timeout is local and selfish: “I will wait 2 seconds.” The server never learns about it, so it keeps working after the caller leaves. A deadline is a wall-clock instant, passed down the call chain, so every service in the path knows when the work stops being worth doing.
flowchart LR
C["Client sets deadline<br/>now plus 2000 ms"] --> GW["Gateway<br/>1950 ms remaining"]
GW --> A["Service A<br/>1700 ms remaining"]
A --> B["Service B<br/>900 ms remaining"]
B --> DB["Database query<br/>budget 900 ms"]
A --> CH["Service C<br/>deadline already passed"]
CH --> DROP["Return immediately<br/>do not start work"]
New behaviour in this picture: the deadline travels as request metadata — a gRPC deadline, or a header carrying remaining milliseconds. Each hop subtracts the time it used and passes the remainder on. Any hop that finds the remaining budget too small to finish its own work returns immediately without starting, which is the whole value: a request nobody is waiting for any more is dropped rather than processed.
This is one of the highest-leverage changes you can make to an overloaded system, because it removes the wasted work that was dragging effective capacity down in the retry-storm loop. It also makes database protection natural — pass the remaining budget as the statement timeout, so a query with 50 ms of budget left does not run for 30 seconds holding a connection.
Layer 5 - Concurrency Limits, Bulkheads and Adaptive Tuning
Rate limits cap requests per second. Concurrency limits cap requests in flight, which is what actually maps to resources — threads, connections, memory. Little’s Law again: with a concurrency limit of 50 and a service time of 20 ms, throughput is capped at 2,500 per second and, crucially, the queue cannot grow inside the dependency.
A bulkhead is a per-dependency concurrency limit, named after the compartments in a ship’s hull that stop one flooded section sinking the whole vessel. Give each downstream dependency its own pool:
One shared pool of 200 threads, recommendations slows to 5s:
all 200 threads block on recommendations, checkout cannot get a
thread, and the whole service is down because an optional feature
got slow.
Bulkheaded pools, same failure:
recommendations max 20 in flight -> 20 block, the rest reject fast
catalog max 60 in flight -> unaffected
payments max 40 in flight -> unaffected
Checkout keeps working and the carousel shows a fallback.
Pick the limit from measured service time and target throughput, and pair it with a circuit breaker so a dependency that is failing outright stops receiving traffic at all. Note that connection pool size is already a concurrency limit — a pool of 20 database connections is a bulkhead of 20 whether you designed it or not. The only question is whether exhausting it produces a fast rejection or an unbounded wait.
Every number so far is static, and static numbers go stale the moment the environment changes — a new instance type, a slower dependency, a noisy neighbour. Three adaptive approaches measure the system and set the limit themselves:
- TCP congestion control is the original. TCP, the Transmission Control Protocol, keeps a congestion window — how much data may be in flight unacknowledged — growing it while things go well and cutting it sharply on loss or delay. The network never says “slow down”; TCP infers it. Decades of the internet working is the proof it scales.
- Netflix concurrency-limits applies that idea to remote calls. It watches latency, infers the concurrency at which latency starts climbing — the point where a queue begins forming — and parks the limit just below it. Nobody tunes a number.
- CoDel, from Layer 3, watches the minimum queue wait over a sliding window, which distinguishes a harmless burst from a real standing queue.
All three share one principle: latency rising is the signal that a queue is forming, and reacting early is cheaper than reacting to a full queue late. Start static because it is easy to reason about; go adaptive when you find yourself retuning.
Protocol-Level Backpressure, and Why Pull Models Win
You often do not have to build backpressure — some protocols have it, and the ones that do share a shape.
| Mechanism | How the signal travels | What it bounds |
|---|---|---|
| TCP receive window | Receiver advertises free buffer space; sender cannot exceed it | Bytes in flight per connection |
| HTTP/2 flow control | Per-stream and per-connection window updates | Bytes in flight per stream |
Reactive streams request(n) |
Subscriber asks for exactly n items; publisher may send no more |
Items in flight in a pipeline |
| Kafka consumer poll | Consumer calls poll when ready; broker never pushes |
Nothing buffers in the consumer |
| Plain fire-and-forget push | No signal exists | Nothing. This is the problem case |
The pattern: a pull model has backpressure built in, and a push model has to add it. When the consumer asks for work, it asks at exactly the rate it can handle, and a consumer that stops asking has already applied perfect backpressure without sending a single message. When the producer pushes, the consumer’s only options are to buffer (unbounded queue, see above), drop, or shout back over a side channel you had to design.
This is the real argument for putting a broker between two services. A Kafka or SQS consumer pulling at its own pace cannot be overwhelmed by a producer spike — the backlog sits durably in the broker, visible as consumer lag, instead of in a consumer’s heap. See message queues. Two caveats: the broker bounds memory, not time, so a sustained mismatch still means items age past usefulness and you must alarm on consumer lag and set message TTLs; and work that fails repeatedly needs somewhere to go, which is a dead letter queue rather than infinite redelivery that is itself a form of self-inflicted load.
Which Mechanism Protects What
| Mechanism | Protects against | Signal it uses |
|---|---|---|
| Bounded queue | Memory exhaustion, unbounded latency | Queue capacity |
| Load shedding at the edge | Wasted work deep in the stack | Overload detection, wait time |
| Rate limiting | One noisy caller starving the rest | Requests per caller per window |
| Admission control and priority | Losing valuable work alongside cheap work | Request class |
| Deadline propagation | Processing abandoned requests | Remaining time budget |
| Concurrency limit and bulkhead | One slow dependency taking everything down | In-flight count per dependency |
| Circuit breaker | Hammering a dependency that is already failing | Error rate, latency |
| Adaptive limit | Static tuning going stale | Latency gradient |
| Pull-based transport | Producer spikes overwhelming consumers | Consumer demand |
No single row is sufficient. A realistic service has a bounded queue, a deadline, a concurrency limit per dependency, a shed path at the edge, and an alarm on queue wait time.
Shedding Load Is a Feature
The hardest part of this topic is not technical. It is accepting that refusing work is correct behaviour, and that a dashboard with a steady band of 503s during a spike is a system working as designed, not a system failing.
Three statements worth saying out loud in a design review:
- A fast failure beats a slow one. A client that gets a 503 in 5 ms can retry elsewhere, serve a cached version, show a fallback, or tell the user honestly. A client that waits 30 seconds and then fails has burned 30 seconds of the user’s patience and 30 seconds of your capacity, and has probably timed out a request further up the chain too.
- Partial availability beats total collapse. Serving 70% of traffic well is a better outcome than serving 100% of traffic so badly that nobody completes anything. Without shedding, overload does not degrade — it collapses, and the collapse is metastable.
- An error rate is a capacity measurement. Shed counters tell you exactly how much capacity you are short of, in the unit you need for the scaling decision. Unbounded queues hide that number inside a latency graph.
The design question is never “how do we avoid rejecting requests.” It is “when we must reject, which requests, how fast, and how clearly do we say so.”
Common Interview Questions
Q1: What is backpressure, and what happens in a system that has none?
Backpressure is a signal from a slow consumer back to a fast producer telling it to slow down. Without it, excess work has nowhere to go but a buffer, so overload shows up as unbounded latency rather than a clean rejection — queues grow, memory grows, clients time out while their work is still queued, and the server keeps spending capacity on requests nobody is waiting for. The failure mode is worse than a rejection because it is slow, it looks error-free on a dashboard, and it feeds a retry loop that keeps the system down after the original load has gone.
Q2: Why not just add a bigger queue?
Because a queue absorbs a burst, not a mismatch. If arrivals exceed service rate on average, the backlog grows without bound and no capacity fixes it. And by Little’s Law — items in the system equals arrival rate times time in the system — a deep queue is high latency: 50,000 items draining at 1,000 per second means 50 seconds of wait for the item at the back, by which time its client has gone. Size queues backwards from the deadline you will tolerate, not forwards from the memory you happen to have.
Q3: How do you decide what to shed?
By class, not at random. Classify traffic at the edge into critical, interactive, retryable background and opportunistic, reserve capacity for the critical tier, and shed from the bottom. Drop the recommendation refresh and the analytics beacons; protect checkout and login. Shed as early as possible so the rejection costs microseconds instead of a journey through five services, return 503 with a
Retry-Afterheader, and keep the reject path free of database calls so it stays cheap at the rate where you need it.
Q4: What metric do you alarm on for overload?
Queue wait time, not queue depth. Depth is meaningless without the service rate, and the service rate moves when a dependency slows or a garbage collection pause lands. Wait time is already in the unit the user feels, so the same threshold works as an alarm, an autoscaling trigger and a shed decision — and if an item has already waited past its deadline when you dequeue it, drop it instead of processing it. Alarm on the distribution, p99 especially, rather than the average.
Q5: Clients are retrying and making an outage worse. What do you do?
Short term, break the loop: shed at the edge so the backlog can drain, and if the system is metastable — sustaining itself on its own retry traffic — cut traffic off hard rather than hoping it recovers under load. Structurally, make retries cheap and rare: exponential backoff with jitter so they do not synchronise, a retry budget capping retries at a small fraction of total traffic, a circuit breaker so a failing dependency stops receiving calls, and deadline propagation so a retried request that has no budget left is never started. A retry must cost the server less than the original request, or it must not happen.
Navigation
| ← QPS vs TPS vs RPS | Back-of-Envelope Estimation → |
| All Concepts | HLD Designs |