Sub topic 9
Load Shedding: Protecting Core Functions Under Overload
This chapter assumes you can build a service that calls other services over a network, you understand exceptions and HTTP status codes, and you know what latency and availability mean. It also assumes you have read the earlier chapters on timeouts, retries, circuit breakers, and bulkheads.
Why overload needs its own defense
Timeouts, retries, and circuit breakers protect a service from a failing dependency. Load shedding protects a service from its own callers. When requests arrive faster than the service can finish them, work piles up in queues, latency grows, and eventually every request is slow or fails. Load shedding means deliberately rejecting some work early so the rest can finish.
The key idea is that rejecting a request costs little, while accepting a request you cannot finish costs a lot. A rejected request returns an error in microseconds. An accepted but doomed request holds a thread, memory, and a database connection until the client gives up. During that time, it also pushes other requests further back in the queue.
What happens without shedding
Consider a service that can handle 100 requests per second and receives 150. The extra 50 requests per second go into a queue. The queue grows without bound, so each new request waits longer than the last. After a short time, the wait exceeds the client's timeout. The client abandons the request and, often, retries. The service still processes the abandoned request, because nothing tells it the client has gone.
This leads to a state sometimes called congestion collapse. The service is busy at 100% capacity, but almost all its work is wasted on requests nobody is waiting for. Useful throughput (called goodput) falls toward zero even though the service is running flat out.
The first line shows an unprotected service. The second shows the same service when it rejects the excess. Shedding keeps goodput at capacity, which is the best outcome available when demand exceeds supply.
Load shedding compared with related ideas
Several techniques are easy to confuse. The table separates them by what they protect and where they act.
| Technique | What it limits | Typical trigger | Who is affected |
|---|---|---|---|
| Bulkhead | Resources one part of the system can consume | Pool of a fixed size is full | Only callers of that part |
| Rate limiting | Requests per client over time | A client exceeds its quota | One client or tenant |
| Load shedding | Total work the service accepts | The service itself is overloaded | Whichever requests are least valuable |
| Backpressure | The rate a producer sends | Consumer signals it is full | The producer, which slows down |
Rate limiting is about fairness between clients and is usually based on identity. Load shedding is about survival and is usually based on the service's current health and the importance of each request. A service can need shedding even when every client stays within its quota, for example when a cache is cold, a deploy removed half the instances, or traffic spikes from many clients at once.
Deciding what to shed
Shedding only helps users if you shed the right things. This is where the critical versus optional classification from earlier in the tutorial pays off. A common approach is to assign each request a priority and reject low-priority requests first.
A typical set of tiers for an online store:
- Critical: checkout, payment, and login. These keep the business running.
- Important: product pages and search. Users need these to reach checkout.
- Optional: recommendations, reviews, and analytics events. The product works without them.
- Background: batch exports, reports, and prefetching. These can run later.
When the service is mildly overloaded, it rejects only background work. As load rises, it rejects optional work, then important work. Critical requests are rejected last, and only when nothing else remains to shed.
Where the priority comes from
A request's priority can be derived in several ways. Pick the one that matches how your traffic is structured.
- By endpoint.
/checkoutis critical and/recommendationsis optional. This is simple and needs no client cooperation. - By a header. The caller sets something like
X-Priority: low. This lets one endpoint serve both interactive and batch callers, but callers must be trusted not to mark everything as critical. - By caller identity. Internal batch jobs get low priority and customer-facing frontends get high priority.
- By user. Paying customers or users who already hold items in a cart may be favored. Use this carefully because it can look unfair.
Whatever you choose, propagate the priority through downstream calls. If a low-priority request reaches your service and then calls three dependencies, those calls should also be low priority. Otherwise low-priority work can still consume capacity deeper in the system.
Signals that tell you to shed
A service needs a measurable signal that it is overloaded. Good signals reflect the work waiting, not just the work running.
- Concurrency in flight. The number of requests currently being handled. When it passes a limit, reject new ones. This is the simplest signal and the one shown below.
- Queue length or queue wait time. If requests wait longer than a threshold before a worker picks them up, the service is behind. Queue wait time is more reliable than queue length because it adapts to how fast the work completes.
- CPU or memory use. Useful, but CPU often reaches 100% before a service is actually in trouble, and memory pressure can arrive too late to act on.
- Latency of recent requests. Rising latency at a steady request rate means capacity is shrinking.
Avoid relying on CPU alone. A service doing efficient work at 90% CPU is healthy. A service stalled waiting on a slow database may show 20% CPU while being completely overloaded.
A concurrency-limit load shedder
The following code limits how many requests run at once and gives each priority tier a different ceiling. Lower tiers are rejected first because their ceiling is reached sooner. It uses only the standard library.
import threading
class Overloaded(Exception):
"""Raised when a request is rejected to protect the service."""
class LoadShedder:
# Highest number of in-flight requests at which each tier is still admitted.
DEFAULT_LIMITS = {"critical": 100, "important": 80, "optional": 50, "background": 20}
def __init__(self, limits=None):
self.limits = dict(limits or self.DEFAULT_LIMITS)
self.in_flight = 0
self.shed_counts = {tier: 0 for tier in self.limits}
self._lock = threading.Lock()
def acquire(self, tier):
with self._lock:
if self.in_flight >= self.limits[tier]:
self.shed_counts[tier] += 1
raise Overloaded(f"shedding {tier} request at {self.in_flight} in flight")
self.in_flight += 1
def release(self):
with self._lock:
self.in_flight -= 1
def run(self, tier, handler):
self.acquire(tier)
try:
return handler()
finally:
self.release()
if __name__ == "__main__":
shedder = LoadShedder({"critical": 3, "optional": 1})
shedder.acquire("optional") # one request already running
try:
shedder.run("optional", lambda: "ok")
except Overloaded as error:
print("rejected:", error)
print("critical:", shedder.run("critical", lambda: "ok"))
print("shed counts:", shedder.shed_counts)Running the example prints that the second optional request is rejected, while the critical request still succeeds. The optional tier tops out at one request in flight, but the critical tier is allowed up to three.
Two details matter here. The finally block guarantees the slot is released even if the handler raises an exception. Without it, errors would slowly leak capacity until the service rejected everything. The lock keeps the counter correct under concurrent access.
How to reject well
How you reject a request affects whether shedding helps or hurts.
Reject early and cheaply
Check the shedding condition before doing expensive work such as parsing a large body, opening a database connection, or calling a dependency. The cheapest place to shed is at the edge, such as a load balancer or the first middleware in your framework. Shedding after the work is mostly done saves nothing.
Use the right status code
For HTTP services, return 503 Service Unavailable for server-side overload. Use 429 Too Many Requests for per-client quota violations. Clients and proxies treat these differently, and mixing them up hides the real cause in your dashboards. Include a Retry-After header when you can estimate when capacity will return.
Prevent retry storms
A rejected request that is immediately retried by every client adds more load. Callers should treat 503 as a signal to back off, using the exponential backoff and jitter from the retries chapter. Well-behaved clients also cap retries with a retry budget, for example allowing retries only up to 10% of normal request volume. Without this, shedding on the server can trigger a retry wave that defeats it.
Prefer shedding old work to new work
A request that has already waited close to its deadline will probably time out before it completes. Dropping it frees capacity for fresher requests that still have a chance. Some systems process the newest requests first during overload (last-in, first-out) for this reason. Carrying a deadline with each request lets the service skip work whose caller has already given up.
import time
def should_skip(deadline_monotonic):
"""Return True if the caller's deadline has already passed."""
return time.monotonic() >= deadline_monotonic
def handle(request, deadline_monotonic, do_work):
if should_skip(deadline_monotonic):
return {"status": 503, "reason": "deadline exceeded before processing"}
return {"status": 200, "body": do_work(request)}Edge cases and common mistakes
- Static limits that go stale. A fixed limit of 100 concurrent requests is correct until a dependency becomes slower, at which point 100 may be too many. Review limits after performance changes, or use an adaptive limit that lowers itself as latency rises.
- Health checks that get shed. If your load balancer's health check hits an endpoint that is subject to shedding, an overloaded instance will fail the check and be removed. Its traffic then moves to the remaining instances, which overload in turn. Exempt health checks from shedding, or make them lightweight and separate.
- Shedding the wrong tier first. If priorities are set per endpoint but one critical operation shares an endpoint with batch traffic, critical work gets rejected. Check that tiers match real business value.
- Priority inflation. When every team marks its traffic critical, nothing is low priority. Enforce priority at a gateway based on caller identity rather than trusting headers.
- Shedding hidden from users. Rejected requests that return a bare error look like a bug. Return a fallback where one exists, for example an empty recommendations list with a degraded flag, as shown earlier in this tutorial.
- Autoscaling is not a substitute. New instances take time to start. Shedding covers the minutes before extra capacity arrives, and also covers spikes that scaling can never absorb.
Making shedding visible
Shed requests are intentional failures, so count them separately from errors. Track at least these measurements:
- The number of requests shed, labelled by tier and by reason.
- The current in-flight count compared with its limit.
- Goodput: requests completed successfully within their deadline.
- Latency of admitted requests, which should stay flat when shedding works.
An alert on shed counts for the critical tier is usually worth having. Shed counts for the background tier are normal during load and should not page anyone. Link this to the degraded state signals chapter: the user-facing response should say that the answer is reduced, not wrong.
Testing a load shedder
Shedding logic only runs under stress, so it is easy to ship broken. Test it directly with a simple check on the code above.
from concurrent.futures import ThreadPoolExecutor
import threading
import time
def test_critical_survives_optional_shedding():
shedder = LoadShedder({"critical": 10, "optional": 2})
gate = threading.Event()
def slow():
gate.wait(timeout=2)
return "done"
with ThreadPoolExecutor(max_workers=12) as pool:
optional_futures = [pool.submit(shedder.run, "optional", slow) for _ in range(5)]
time.sleep(0.2) # let the first requests occupy their slots
critical_future = pool.submit(shedder.run, "critical", lambda: "paid")
assert critical_future.result(timeout=1) == "paid"
gate.set()
shed = 0
for future in optional_futures:
try:
future.result(timeout=3)
except Overloaded:
shed += 1
assert shed == 3
assert shedder.shed_counts["optional"] == 3Place this test next to the LoadShedder class. It starts five optional requests against a limit of two, then confirms that three are shed and that a critical request still succeeds while the others are blocked. In a real environment, repeat the idea at larger scale with a load generator, and inject slow dependencies as described in the fault-injection chapter.
Summary
Load shedding keeps a service useful under overload by rejecting low-value work early. It relies on a priority scheme, a signal of overload, and a cheap, fast rejection path. Clients must back off when rejected, and health checks must be exempt. Measure shed requests by tier so that rejected work is visible instead of silent.
Exercise
A service has a fixed limit of 200 concurrent requests. A downstream database slows down, so each request takes five times longer. CPU use is only 25%, but latency has tripled and clients are timing out. Why might a CPU-based shedding rule fail to protect the service here, and what signal would work better?
Show answer
CPU stays low because requests are waiting on the database, not computing, so a CPU threshold never triggers while the service is actually overloaded. A better signal is concurrency in flight, queue wait time, or recent request latency. With slower requests, the same arrival rate keeps more requests in flight, so a concurrency limit or latency rule fires and sheds optional work. The limit of 200 may also now be too high and should be lowered or made adaptive.
Exercise
Your load balancer health check calls /status, which passes through the same load shedder as user traffic. During a traffic spike, instances begin dropping out of the pool one at a time and the remaining instances fail faster. What is happening, and how do you fix it?
Show answer
Overloaded instances shed the health check request, so the load balancer marks them unhealthy and removes them. Their traffic goes to the remaining instances, which then become overloaded and fail the check too, causing a cascade. Fix it by exempting the health check from shedding or serving it from a lightweight path that bypasses the shedder, so instances stay in the pool and keep serving critical requests.