Sub topic 6
Load Shedding: Rejecting Work on Purpose
This chapter assumes you can read short Python examples and know HTTP status codes and request latency. It also assumes you know what a queue is and how Little's law relates arrival rate, latency, and work in flight. Earlier chapters covered bounded queues and back pressure. This one covers what a service does when slowing the producer is not possible or not enough.
What load shedding is
Load shedding means a service refuses some work on purpose, so the work it accepts still finishes in time. The service decides to say no quickly. The alternative is accepting everything and finishing most of it too late to matter.
Shedding is a deliberate trade. You give up some requests to protect the rest. A rejected request costs the client a fast, clear failure. An overloaded service that accepts everything costs every client a slow failure.
Why rejecting beats accepting everything
Suppose a service can finish 100 requests per second, and clients give up after 1 second. Traffic rises to 150 requests per second.
With an unbounded queue, the backlog grows by 50 requests every second. After 2 seconds the oldest queued request has waited more than 1 second. From then on the service works hard, but it mostly finishes requests whose clients have already left. Throughput stays at 100 per second, but useful throughput, called goodput, falls toward zero.
With shedding, the service accepts about 100 requests per second and rejects the other 50 immediately. Accepted requests finish quickly, and their clients get answers. Rejected clients learn at once that they should back off or go elsewhere.
| Strategy at 150 req/s offered, 100 req/s capacity | Completed per second | Completed in time | Typical latency |
|---|---|---|---|
| Accept everything (unbounded queue) | 100 | Near 0 after the backlog builds | Grows without bound |
| Shed excess | 100 | About 100 | Stable and low |
The first row is the failure described in the chapter on unbounded queues. Load shedding is one of the main fixes.
Back pressure versus load shedding
Both techniques limit how much work enters the system. They differ in what happens to the extra work.
| Row | Back pressure | Load shedding |
|---|---|---|
| What the producer experiences | It waits or slows down | It gets a rejection |
| Where the extra work goes | It stays with the producer | It is dropped |
| Requires a producer you control | Yes, or a protocol that carries the signal | No |
| Typical setting | Pipelines, internal streams, batch jobs | Public APIs, many independent clients |
Back pressure works when the producer can actually slow down, such as a worker reading from a file or a service you own. It does not work when thousands of independent clients send requests and each one cannot see the others. Those clients will not coordinate. The server has to protect itself by rejecting some of them.
The two techniques are often combined. Back pressure handles the producers you control, and shedding is the safety net for everyone else.
Shedding at the queue
The simplest shedding mechanism is a bounded queue that rejects when full. Back pressure uses await queue.put(...), which waits. Shedding uses put_nowait, which fails immediately.
import asyncio
class Overloaded(Exception):
pass
def submit(queue: asyncio.Queue, request) -> None:
try:
queue.put_nowait(request)
except asyncio.QueueFull:
raise Overloaded("queue full") from None
async def main() -> None:
queue = asyncio.Queue(maxsize=3)
accepted = 0
rejected = 0
for i in range(5):
try:
submit(queue, i)
accepted += 1
except Overloaded:
rejected += 1
print(f"accepted={accepted} rejected={rejected}")
asyncio.run(main())With no consumer running and room for three items, this prints accepted=3 rejected=2. The caller catches Overloaded and turns it into a response, such as HTTP 503. The queue size sets how much waiting you tolerate. A queue of 3 here is for demonstration. In a real service, size it from Little's law and your latency target.
Shedding on work in flight
A queue limit protects the waiting line. A limit on in-flight work protects the service itself, including work already started. The service counts requests it is processing, and refuses new ones once the count reaches a fixed maximum.
import asyncio
MAX_IN_FLIGHT = 50
in_flight = 0
async def handle(request, process):
global in_flight
if in_flight >= MAX_IN_FLIGHT:
return 503, {"Retry-After": "1"}
in_flight += 1
try:
return 200, await process(request)
finally:
in_flight -= 1
async def process(request):
await asyncio.sleep(0.1) # simulate 100 ms of work
return f"done {request}"
async def main() -> None:
results = await asyncio.gather(*(handle(i, process) for i in range(80)))
ok = sum(1 for status, _ in results if status == 200)
shed = sum(1 for status, _ in results if status == 503)
print(f"ok={ok} shed={shed}")
asyncio.run(main())The 80 requests arrive at once. The first 50 are accepted, and the other 30 receive 503 right away. The output is ok=50 shed=30.
This code is safe in a single asyncio event loop. There is no await between the check and the increment, so no other task can run in between. With threads, the check and increment would race, and you would need a lock or an atomic counter.
Little's law helps you pick the number. In-flight work equals arrival rate times latency. If each request takes 0.1 seconds, a limit of 50 in flight supports about 500 requests per second. If the real capacity is lower, because a database saturates first, the limit should be lower too. A later chapter covers choosing and adapting this limit.
Where to shed
The diagram shows the shape of a shedding decision.
Shed as early as possible. Rejecting costs little only if it happens before the expensive work: before parsing a large body, opening a database connection, or calling other services. A rejection that happens after most of the work is done saves almost nothing. The best place is often the edge of the service, such as a load balancer, a proxy, or the first middleware in your framework.
The rejection path must also be cheap. If building a 503 response needs a database lookup, a log line that blocks on disk, or a lock shared with the slow path, then shedding itself becomes a bottleneck. Return a small static response and increment a counter.
Edge cases and failure modes
- Shedding too late. If you only shed when the service is already out of memory or at 100% CPU, the rejections themselves may be slow. Set limits below the point where the machine saturates.
- Shedding too early. A limit set far below real capacity rejects work the service could have done. Check the rejection rate against your metrics. A steady nonzero rate at normal traffic means the limit is too low.
- Per-instance limits and uneven traffic. Each instance sheds on its own view. If a load balancer sends more traffic to one instance, that instance sheds while others have room. Balance by least-loaded or least-connections where you can.
- Shedding hides the problem. A service that shed 30% of its traffic all day looks healthy on latency graphs. Always alert on the shed rate, not only latency.
- Rejected work comes back. A client that retries immediately turns each rejection into more load. Shedding works only if clients slow down after a rejection. The chapters on client signals and retries cover this.
- Not all work is equal. Dropping a health check or a payment confirmation costs more than dropping a prefetch. A plain counter treats them the same. The next chapters cover choosing what to shed by priority, age, and fairness.
Choosing between waiting and rejecting
Use these questions to decide for a given boundary:
- Can the producer slow down? If yes, prefer back pressure.
- Does a late answer still have value? If not, prefer shedding, because waiting produces useless work.
- Are there many independent clients? If yes, shed. You cannot make all of them wait politely.
- Is losing the request acceptable, or can the client retry safely? If neither, use back pressure or a durable queue instead.
Exercise
A service has 40 requests in flight at steady state and each request takes 0.2 seconds. Using Little's law, what request rate is it handling? If you set a hard limit of 40 in flight, what happens when traffic doubles?
Show answer
Rate = in-flight / latency = 40 / 0.2 = 200 requests per second. If traffic doubles to 400 requests per second and latency stays 0.2 seconds, the service would need 80 in flight. With the limit of 40, it accepts about 200 requests per second and rejects the other 200 immediately, for example with 503 and Retry-After. Accepted requests keep their 0.2 second latency. Without the limit, in-flight work would grow, latency would rise, and clients would time out.
Exercise
In the handle function, why is it safe to check in_flight and then increment it without a lock, and when would it stop being safe?
Show answer
In a single asyncio event loop, tasks switch only at await points, and there is no await between the check and the increment. No other task can run between them. It stops being safe if the code runs in multiple threads, or if an await is added between the check and the increment, because then two tasks could both pass the check before either increments.