Load shedding
Read first: Retries, backoff, and circuit breakers, Latency numbers that matter
Past a concurrency or queue limit, reject the extra work while rejecting is still cheap. An uncapped queue stores that work in memory and turns a spike into a leak. Bulkheads keep one stuck dependency from spending the threads the rest of the request needed.
Every service has a rate at which it finishes work, and the world does not have to respect it. When more arrives than you can finish, the difference accumulates somewhere. If you let it accumulate in a queue with no bound, the somewhere is memory, and the queue is a leak that happens to be shaped like a list of requests. Load shedding is the decision to refuse the surplus on purpose, early, and cheaply, so the work you did accept can still finish inside the time the caller has left.
Core concepts
A bound, then a refusal. Pick a maximum number of requests in flight, and a maximum number waiting. When a new request would pass either number, do not enqueue it. Return a fast failure, conventionally a 503, or return a degraded response that you can build without the saturated dependency. The refusal should happen before the expensive work: before the database transaction, before the fanout, before you have allocated the large object the request would have held. A rejection that runs after that work has already paid the cost and then thrown away the result.
Reject early because late rejection is just latency. A request sitting in a queue is a request whose latency has already started. Latency numbers that matter gives you the budget the user is actually on. If the budget for this hop is a few hundred milliseconds and the queue is deep enough that the tail will wait seconds, you are not buffering. You are making the user stare at a spinner until their client times out, and then, unless that client was written carefully, they come back. Retries, backoff, and circuit breakers is that return trip. Shedding and retry policy are one design. A 503 that the client retries immediately is not shedding. It is a brief delay before the same load.
Little’s law tells you the bound is about time, not about RAM. Average concurrency equals arrival rate times average latency. Rearranged, the wait in a queue is the depth of that queue times the service time of whatever is draining it. Memory will let you hold millions of queued requests. The caller’s timeout will not let those requests succeed. Set the depth so that a request at the tail can still start and finish before the client gives up. Anything deeper is work you already know is wasted.
An uncapped queue is a memory leak with extra steps. Each queued request holds a body, some parsed state, and a slot in a list. Arrivals that exceed the completion rate add one of those per extra request, every second, until the process is killed. The leak is linear in the overload. It does not level off, because nothing in an unbounded queue ever says no. The operating system may eventually refuse connections, which is a bound you did not choose, applied after your process is already sick. Choose the bound yourself, in the application, where you can still return a deliberate 503.
Shed the cheap traffic first, if you can tell it apart. A browse request that can be served from a cache, or skipped, should die before a checkout that already reserved stock. The signal is something you know at the door: the route, a priority the edge marked, a tenant. If you cannot tell the classes apart, shed uniformly and say so. A random 503 is fair. A 503 that always hits the paying path because you ranked by “which route has the most requests” is how you save the cheap traffic and lose the product.
A degraded response is a shed you decided was still useful. Recommendations empty, and the cart still renders. Search results from the cache, without the personalization call that is timing out. That is a product decision. Checkout with no payment result is not a degraded success. It is a failure you should report as a failure, or the dashboard will show a healthy success rate while users see a broken button.
A bulkhead is a separate pool. Threads, connections, or in-flight slots for one dependency are not allowed to be spent by another. Payment gets a pool. The home page gets a pool. When payment stalls, payment’s pool fills and further payment calls shed. The home page keeps its pool and stays up. Without the wall, the stall consumes every thread the process has, and the symptom is “the site is down” when the truth is “one client is stuck.” The name comes from the walls in a ship: one flooded compartment does not flood the hull. The implementation is boring on purpose. It is a semaphore per dependency, sized from how many concurrent calls that dependency is allowed to have.
A rate limit and a shed meet in the middle. The limiter says “this key has had its share.” The shedder says “this process has had all the concurrency it can hold.” You want both. A limiter will not save you from a shift in latency that ties up the workers you still allowed. A shedder will not stop one tenant from being the entire offered load unless you also cap that tenant.
flowchart LR
client[Client]
admit[Admission check]
paypool[Payment pool]
homepool[Home page pool]
payment[Payment dependency]
reject[Fast 503]
client --> admit
admit -->|payment under cap| paypool
admit -->|home under cap| homepool
admit -->|pool is full| reject
paypool --> payment
Health checks sit next to this and are easy to wire wrong. Load balancing should stop sending traffic to a process that cannot do work. A process that is shedding is doing exactly the work it can, and refusing the rest. If the balancer treats every 503 as “this instance is dead” and drains it, the leftover instances take the full arrival rate, shed, get drained, and the fleet unwraps from the outside. The health check should fail when admitted requests are not finishing, not when the admission check is successfully saying no.
A worked example
Two pictures, both assumptions, and they are not the same completion rate. First, a process that finishes 1,000 requests per second when the database is healthy and 200 per second when it is not, while arrivals hold at 1,000. A queued request retains about 20 KB, and the heap you are willing to spend is 2 GB. That picture is the memory leak. Second, the same kind of handler with 8 workers, a healthy service time of 50 ms, and a client that gives up at 1 second. That picture is how a pool turns service time into a queue cap. Eight workers at 50 ms finish 160 per second, not 1,000. None of these are measurements of a named system.
The uncapped queue. Completions fall to 200 while arrivals stay at 1,000. The queue grows by 800 requests every second.
growth = 1,000 - 200 = 800 requests per second
bytes = 800 * 20 KB = 16,000 KB/s = 16 MB/s
heap assumed = 2 GB = 2,048 MB
time to fill = 2,048 / 16 = 128 seconds
About two minutes from “the database got slow” to “the process is out of memory,” with no bug in the allocator. The queue did what a leak does. It retained an object per extra arrival and never released it, because the requests at the front were still waiting on the database. A bound of 50 queued requests changes the memory term and the product.
queue bound = 50
memory = 50 * 20 KB = 1,000 KB, about 1 MB
admitted completions = 200 rps
rejected at the door = 800 rps
Memory is no longer the failure mode. Whether 50 is the right bound is a latency question, not a memory question. The wait depends on how many workers drain the queue, not on how small each object is.
The bound that matches the timeout. With W workers, each busy for service time S, the pool finishes about W / S requests per second. A request behind Q others waits about Q / (W / S) seconds before a worker starts it, then pays S as well. One worker would make that wait Q times S. Eight workers divide it by eight. Leave the eight out and the cap is wrong in both directions.
workers W = 8
healthy S = 0.05 s
healthy completion = 8 / 0.05 = 160 per second
queue of 50, healthy wait = 50 / 160 = 0.31 s
plus service ≈ 0.36 s, which still fits in a 1 s client timeout
incident S = 1 s, the database you are protecting against
incident completion = 8 / 1 = 8 per second
queue of 50, incident wait = 50 / 8 = 6.25 s
Fifty was cheap in memory and fine while the database was healthy. The same fifty, once service time is a second, holds the tail for six seconds and then does the work for a client who left at one. Size the cap from the timeout and from the completion rate you will actually have. While you still believe service stays near 50 ms, the useful wait is about 0.95 s and the cap is about 0.95 times 160, roughly 150. If the incident you fear is a 1 s service time, the timeout is already the service time, useful wait is about zero, and the cap on queued work is zero: when all eight workers are busy, return 503 and do not enqueue. A static small queue is the first design. Drop the cap further as latency climbs, or the number you picked on a healthy afternoon becomes the pile.
The bulkhead. Same process, 32 threads, two kinds of work. Payment calls start taking 2 seconds. The home page does not use payment.
no bulkhead
all 32 threads block in payment
home page throughput = 0
with a bulkhead
payment pool = 8, home pool = 24
payment throughput while stuck = 8 / 2 s = 4 rps
home page keeps 24 threads
Little’s law again, aimed at one pool. Eight threads divided by a 2-second hold is four payment calls per second of throughput, which matches “the pool is full and each call occupies a slot for 2 seconds.” The other 24 threads never enter that wait. Users can still load the home page. Payment sheds, quickly, instead of taking the site down. Four payment completions per second is bad, and it is much less bad than zero of everything.
What you keep. Assume you can see the route at admission. Checkout is the scarce, valuable path and it shares the sick database. Anonymous browsing is most of the requests and can be served from cache or refused. Shed browsing first, keep checkout up to the concurrency the database can still finish, and 503 the checkout overflow rather than timing it out. If checkout itself has a class that is optional, such as a fraud-enrichment call, that call gets its own small pool and a degraded “review later” path. Do not degrade the capture of money into a fake success.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Unbounded queue | No request is refused by your code | Memory grows without a limit, and latency grows with it |
| Bound set from the heap | You will not run out of memory first | The tail still waits longer than the client, so you store doomed work |
| Bound set from the timeout | Admitted requests can still finish | You 503 traffic a bigger queue would have accepted and then failed |
| 503 at the door | The refusal is cheap and visible | Clients that retry at once put the load back |
| Degraded response | The page still does something useful | A fake success hides the shed from the success rate |
| Shed cheap routes first | The valuable path keeps the capacity | You need a classification you can make before the expensive work |
| Shed uniformly | No classification to get wrong | The cheap flood and the checkout die together |
| One shared thread pool | Simple, and full use of every thread | One stuck dependency spends all of them |
| Bulkhead per dependency | The stuck call stays in its pool | Idle threads in one pool cannot help another, so you size them on purpose |
| Health check that treats 503 as death | Traffic leaves a process that is erroring | Shedding instances get drained and the rest tip over in turn |
Pitfalls
- A queue with no maximum. Memory climbs in a straight line, the process dies, and the postmortem calls it an OOM bug. It was an admission bug.
- A maximum chosen because the objects were small. A million queued requests at 20 KB is 20 GB. A thousand ahead of one worker at 50 ms is 50 seconds of wait. A pool divides that wait by the worker count, and it is still far past a one-second client.
- Shedding after the database call. You paid for the scarce work and then discarded it. The database is just as overloaded as if you had returned the result.
- One pool for every outbound call. Payment latency goes to seconds and the thread dump is nothing but payment. The home page had no bug.
- A client that retries 503 immediately. Your shed graph looks active and the arrival graph never drops. The limiter and the client did not agree.
- A load balancer that removes any instance returning 503. The fleet shrinks, the surviving instances shed harder, and the outage accelerates.
- Counting a degraded empty page as success. The SLO stays green through the incident you most needed it to see.
- Protecting the high-QPS browse path because it is most of the errors, and shedding checkout. You optimized the count and dropped the product.
In the interview
Say it early. “I bound in-flight work and the queue. Past the bound I return 503 before the database. The bound comes from the timeout, not from memory. Payment has its own pool so a 2-second payment stall cannot take the home page’s threads.”
Give one number out loud. Either the memory line, 800 extra requests a second at 20 KB is 16 MB a second, or the queue line, a 1-second timeout and a 50 ms service time cannot justify a deep queue. The bottleneck is the dependency whose latency ate the pool. The tradeoff is that some callers get a fast no instead of a slow yes. You prefer that because the slow yes was not going to arrive anyway, and the queue would have taken down the yeses you could still have served.
Skip kernel backlog tuning and skip a particular limiter product. If they ask what you shed first, answer with a classification you can make at admission, and say what you do when you cannot tell requests apart. The question that usually follows is “what does the client do with the 503?” The answer is backoff, inside a retry budget, or the shed does not hold.
Check yourself
Arrivals are 2,000 per second, completions drop to 500 per second, and each queued request holds 10 KB. How fast does an unbounded queue grow in memory?
The queue gains 1,500 requests per second. Times 10 KB that is 15,000 KB per second, about 15 MB per second. A minute is about 900 MB. Nothing in the queue’s design stops the line. A bound stops it, and the bound has to be chosen from how long a queued request can wait before the client is gone.
Healthy service time is 25 milliseconds and the client timeout is 200 milliseconds. Why is a queue depth of 100 the wrong bound even if the objects are tiny?
If one worker runs them one after another, a hundred requests at 25 milliseconds each is 2.5 seconds before the tail starts. A pool of W workers divides that wait by W, and you still have to do the division before you trust the depth. The client left after 200 milliseconds. On one worker the requests that fit are 200 / 25 = 8, including service. A depth of 100 stores work that cannot succeed. Small objects keep the process alive while it does that useless work. They do not make the work useful.
Thirty-two threads share one pool. A dependency slows to 4 seconds. What happens to the routes that do not call it, and what does a bulkhead of 8 threads change?
Without a wall, all 32 threads block in the slow call and every other route’s throughput goes to zero. With 8 threads reserved for that dependency, it can complete 8 / 4 = 2 requests per second while it is stuck, and the other 24 threads keep serving routes that do not need it. The slow dependency is still degraded. It is no longer allowed to be the whole process.
Your load balancer marks an instance unhealthy when it returns any 503. You add shedding. What failure should you expect under overload?
The overloaded instances start shedding and immediately look unhealthy, so the balancer drains them. The same load lands on fewer instances, which shed and get drained too. The fleet collapses by trying to avoid the instances that were protecting themselves. Health should reflect whether admitted work is finishing. A deliberate refusal of overflow is the protection working.
Based on: Marc Brooker, AWS Builders' Library; Google SRE book.