Sub topic 9
Load shedding: protecting core functions under overload
This chapter assumes you know how timeouts, retries, and circuit breakers work, and that you have classified your dependencies as critical or optional. Here the problem is your own service. It receives more work than it can finish, and you must decide what to refuse.
Why overload needs its own defense
A service has a fixed capacity: threads, connections, CPU, and memory. When requests arrive faster than it can finish them, a queue builds. Latency rises, callers time out, and many callers retry. The retries add load. Eventually the service spends its time on requests whose callers have already given up. Throughput collapses even though the machine is busy.
Load shedding means rejecting some work early and cheaply so the rest can finish on time. A fast "no" costs less than a slow "yes" that arrives after the caller's timeout.
Shedding is not the same as a bulkhead. A bulkhead limits how far a failure spreads between parts of the system. Shedding decides which requests to drop when total demand exceeds capacity.
Decide what to protect
Use the critical and optional classification from earlier chapters. Rank request types by how much the business needs them:
| Priority | Example requests | Under overload |
|---|---|---|
| Critical | Checkout, login, payment confirmation | Keep serving |
| Important | Order history, search | Serve if capacity allows |
| Optional | Recommendations, analytics beacons | Drop first |
Dropping optional work first is graceful degradation applied to your own capacity.
Choosing a shedding signal
You need a cheap measure of "too busy" that you can check before doing real work. Common choices:
- In-flight requests. Count requests currently being handled. Reject when the count passes a limit.
- Queue length or queue wait time. Reject when requests have waited longer than the caller would tolerate.
- CPU or memory use. Useful, but it reacts slowly.
In-flight count is the simplest and the best starting point. Set the limit from load testing: find the concurrency where latency starts to climb sharply, and set the limit just below it.
A priority-aware shedder
The sketch below admits requests until a limit is reached. Lower-priority requests are rejected earlier, so critical work keeps a reserved share of capacity. It uses a lock because requests run concurrently.
import threading
class Overloaded(Exception):
"""Raised when a request is rejected to protect the service."""
class LoadShedder:
# Fraction of max_in_flight at which each priority starts being rejected.
THRESHOLDS = {"critical": 1.0, "important": 0.8, "optional": 0.5}
def __init__(self, max_in_flight=100):
self.max_in_flight = max_in_flight
self.in_flight = 0
self._lock = threading.Lock()
def acquire(self, priority):
limit = self.max_in_flight * self.THRESHOLDS[priority]
with self._lock:
if self.in_flight >= limit:
raise Overloaded(priority)
self.in_flight += 1
def release(self):
with self._lock:
self.in_flight -= 1
def run(self, priority, fn):
self.acquire(priority)
try:
return fn()
finally:
self.release()With max_in_flight=100, optional requests are rejected once 50 are running, important ones at 80, and critical ones only at 100. The finally block matters. If release is skipped on an exception, the counter leaks and the service eventually rejects everything.
Reject in a way callers can use
How you reject affects whether the system recovers.
- Return HTTP 503 (Service Unavailable) or 429 (Too Many Requests), not a slow timeout.
- Add a
Retry-Afterheader when you can estimate a recovery time. - Reject before expensive work: before parsing large bodies, opening database connections, or calling other services.
- Make sure clients do not retry shed requests immediately. The backoff and jitter from the retries chapter apply here. A client that retries a 503 with no delay turns shedding into a retry storm.
Where the caller has a fallback, a rejection triggers it. A page that cannot get recommendations because they were shed can show cached or default ones.
Common errors
- Shedding too late. If you check the limit after authentication, database lookups, and parsing, the rejected requests have already consumed the capacity you wanted to save.
- One global limit. Without priorities, health checks and checkout get rejected as readily as analytics.
- Shedding health checks. If the load balancer's health check is rejected, it marks the instance dead and moves its traffic to the others, which can overload them in turn. Exempt health checks.
- A limit set by guesswork. A limit that is too low rejects traffic you could have served. One that is too high does nothing. Measure it, and revisit it when the code or hardware changes.
- Invisible shedding. Count every rejection by priority and expose it as a metric. Otherwise a shedder that rejects 20% of traffic looks like a healthy service.
Exercise
A service has maxinflight=200 and the thresholds from the sketch. Currently 120 requests are in flight. Which of an optional, an important, and a critical request are admitted?
Show answer
The optional threshold is 200 × 0.5 = 100, and 120 ≥ 100, so the optional request is rejected. The important threshold is 200 × 0.8 = 160, and 120 < 160, so it is admitted. The critical threshold is 200, so it is admitted.
Exercise
Why can shedding a service's health check endpoint make an overload worse?
Show answer
The load balancer sees failed health checks and removes the instance from rotation. Its traffic moves to the remaining instances, which may then become overloaded and be removed too. Health checks should be exempt from shedding.