Skip to content

Load shedding

Under overload, queueing degrades latency for every request equally. Load shedding proactively rejects lower-priority requests with a cheap 503 Service Unavailable so critical traffic stays responsive.

Priority classes and thresholds

from paceapi import LoadShedder
from paceapi.integrations.starlette import LoadSheddingMiddleware
# This process can do about 200 requests at once, and is in trouble when its event loop
# runs a quarter of a second late. At half of either, requests with no API key are
# answered 503 and told when to come back. At four fifths, so are those on the free
# plan. Paying customers are not named, and are never turned away by this.
shedder = LoadShedder({"anonymous": 0.5, "free": 0.8}, max_in_flight=200, max_lag=0.25)

LoadShedder maps sheddable priority classes to load thresholds in (0, 1]. Any class not listed (and None) is never shed.

Classify each request with a synchronous priority callable receiving HTTPConnection:

def plan(connection: HTTPConnection) -> str | None:
    """What class a request is: read from the request alone, before any work is done."""
    if connection.url.path == "/healthz":
        # Of no class, and so never turned away: a load balancer that was told 503
        # would take this instance out just when the others need it most.
        return None
    return PLANS.get(connection.headers.get("x-api-key", ""), "anonymous")

Register both with the middleware:

app.add_middleware(LoadSheddingMiddleware, shedder=shedder, priority=plan)
  • priority runs on every request before routing or FastAPI dependencies, so it must be fast and non-blocking (read headers, in-memory lookups, or AuthenticationMiddleware state).
  • Return None for health checks (/healthz) so load balancers do not remove busy instances from rotation.
  • Do not pass rate-limiter key helpers like client_ip or RequestHeader—they return per-caller identifiers rather than priority class names.

Full example: examples/load_shedding.py.

How load is measured

Load is a normalized value where 1.0 represents full capacity, computed as the maximum of:

  • In-flight ratio (max_in_flight=): active HTTP requests inside LoadSheddingMiddleware divided by max_in_flight.
  • Event-loop lag (max_lag=): timer delay (sampled every 100ms while traffic is active) divided by max_lag. Catches CPU-heavy or blocking requests even when concurrency is low.

Specify either or both. Inspect live metrics via shedder.load and shedder.in_flight; both are safe to read from another thread (such as a metrics exporter), where load uses the lag the event loop last measured.

Note: max_lag= requires a continuously running event loop (standard ASGI servers). For environments that stop the loop between requests (or single-loop test harnesses), use max_in_flight= alone or shedder.disabled() in tests. A script that drives the app in-process in a tight loop never yields to the event loop, which reads as sustained lag and sheds within a second—await asyncio.sleep(0) between requests, as the repository's benchmarks do.

Shedding response (503)

Shed requests receive HTTP 503 with Retry-After (configurable via retry_after=, default 1s) directly from the middleware (bypassing app exception handlers):

{"detail": "The server is busy. Try again in 1 second."}

Set retry_after= on the shedder to change the wait:

shedder = LoadShedder({"anonymous": 0.5, "free": 0.8}, max_in_flight=200, retry_after=5)

Code that calls shedder.admit() itself can raise Overloaded for the same response, adding response headers with headers=:

@app.get("/reports/{month}")
async def report(month: str, plan: Annotated[str, Depends(current_plan)]) -> dict[str, object]:
    slot = shedder.admit(plan)
    if slot is None:
        # The same 503 and Retry-After as LoadSheddingMiddleware, plus an extra header.
        raise Overloaded(shedder, headers={"X-Shed-Priority": plan})
    try:
        return await db.report(month)
    finally:
        slot.release()

Tuning thresholds

  • Set max_in_flight to the maximum concurrency a single worker handles comfortably (e.g., 200). A threshold of 0.5 starts shedding "anonymous" at 100 in-flight requests, reserving half of worker capacity for higher-priority traffic.
  • Healthy event-loop lag is a few milliseconds; max_lag=0.25 (250ms) is a sensible starting ceiling. Avoid max_lag below 10ms (too noisy).
  • Lag reflects the latest sample unsmoothed, so a single long event-loop stall sheds all configured classes briefly (~100ms), whereas max_in_flight sheds progressively by tier.

Placement and limitations

Place LoadSheddingMiddleware outermost (inside only CORSMiddleware and any auth middleware that priority reads from)—see Middleware order.

  • Process-local: Each worker tracks its own in-flight count and event-loop lag.
  • App-wide only: No route decorator—shedding must happen before routing/parsing work.
  • Long-lived responses: SSE/streaming responses count toward in_flight until the client disconnects.
  • Observability: Shed responses do not emit observer events or invoke app Overloaded exception handlers.

Testing

Disable with with shedder.disabled(): or LoadShedder(..., enabled=False).

enabled= can be set from configuration:

shedder = LoadShedder({"anonymous": 0.5}, max_in_flight=200, enabled=settings.shedding_on)