Skip to content

Middleware order

When combining traffic management, rate limiting, and response caching, middleware order determines what each layer sees.

from paceapi import ConcurrencyLimit, Deadline, Limiter, LoadShedder
from paceapi.integrations.starlette import (
    CoalescingMiddleware,
    ConcurrencyLimitMiddleware,
    DeadlineMiddleware,
    LoadSheddingMiddleware,
    RateLimitMiddleware,
)
shedder = LoadShedder({"anonymous": 0.5, "free": 0.8}, max_in_flight=200, max_lag=0.25)
everything = Deadline(30)
limiter = Limiter()
busy = ConcurrencyLimit(50, wait=0.5)
# Starlette executes middleware added last on the outside (read bottom-to-top).

# 5. Innermost: cap concurrent requests reaching the app.
app.add_middleware(ConcurrencyLimitMiddleware, limit=busy)

# 4. Coalesce concurrent identical GETs so followers do not consume concurrency slots.
# Callers are identified by X-API-Key here, so it is listed with the default headers.
app.add_middleware(CoalescingMiddleware, credentials=["Authorization", "Cookie", "X-API-Key"])

# 3. Rate-limit outside coalescing so every inbound request is counted.
app.add_middleware(RateLimitMiddleware, limiter=limiter, rates=rate)

# 2. Enforce deadline across store waits, coalescing waits, and concurrency queues.
app.add_middleware(DeadlineMiddleware, deadline=deadline)

# 1. Outermost: shed low-priority traffic cheaply before counting or queueing.
app.add_middleware(LoadSheddingMiddleware, shedder=shedder, priority=plan)

Because app.add_middleware() wraps outer layers last, read the block above bottom-to-top to trace an inbound request:

Client
  → CORSMiddleware (if used)
  → SessionMiddleware (only if authentication reads the session)
  → AuthenticationMiddleware (if used)
  → LoadSheddingMiddleware
  → DeadlineMiddleware
  → RateLimitMiddleware
  → CoalescingMiddleware
  → ResponseCacheMiddleware (if used)
  → Session / cookie-setting middleware (if used)
  → ConcurrencyLimitMiddleware
  → App & route decorators

Full example: examples/traffic_together.py (the ordering properties below are verified by tests/examples/test_traffic_examples.py, and the authentication order by tests/examples/test_traffic_options.py).

Rationale for each layer

  1. LoadSheddingMiddleware outermost (inside only CORS and any auth middleware needed by priority): shed traffic fails cheaply before consuming rate limits or concurrency slots, while in_flight accounts for every request held anywhere in the stack.
  2. DeadlineMiddleware outside all waiting layers: covers time spent waiting on rate-limit stores, coalescing leaders, and concurrency queues so queued requests still time out with 504 on schedule.
  3. RateLimitMiddleware outside coalescing and response caching: ensures every inbound request is counted against the caller's rate limit, even when served from cache or coalesced.
  4. CoalescingMiddleware outside ResponseCacheMiddleware and ConcurrencyLimitMiddleware: coalesced callers never consume concurrency slots, and concurrent cache misses perform a single cache lookup, app execution, and cache write.
  5. Starlette's AuthenticationMiddleware outside CoalescingMiddleware: the signed-in user and the request's scopes are known when a request is matched, so a user's requests coalesce only with that user's own (Signed-in users). Outermost, it also serves a load shedder whose priority reads the user.
  6. Session / cookie middleware inside CoalescingMiddleware: ensures Set-Cookie is visible to coalescing, so a response that sets a cookie is never shared. Callers identified by any header other than Authorization or Cookie must be listed in credentials=.

    Exception — authentication that reads the session: an authentication backend that reads request.session needs SessionMiddleware to run first, so SessionMiddleware goes outside AuthenticationMiddleware, and both outside CoalescingMiddleware. Each request's session cookie is then written from its own session, after coalescing, and is never shared. A coalesced request does not run the endpoint, so its cookie carries the session as it arrived and can overwrite what the endpoint wrote for the leader: do not coalesce a GET route that writes to the session (Scoping to specific routes). 7. ConcurrencyLimitMiddleware innermost: protects downstream resources (DB pools, worker capacity) directly in front of the app.

Always-answered routes

With the stack above, a load balancer's health check is rejected with 503 when every concurrency slot is held, and with 429 once it polls faster than the rate limit allows a single address—removing the instance from rotation exactly when capacity is tight.

Each rejecting layer has an exemption: LoadShedder never sheds a request whose priority is None, and ConcurrencyLimitMiddleware and RateLimitMiddleware skip requests whose key returns None when on_missing_key="skip":

def plan(connection: HTTPConnection) -> str | None:
    """Priority class for load shedding; `None` is never shed."""
    if connection.url.path in ALWAYS:
        return None
    return PLANS.get(connection.headers.get("x-api-key", ""), "anonymous")


def everyone(connection: HTTPConnection) -> str | None:
    """One shared concurrency pool; health checks take no slot."""
    return None if connection.url.path in ALWAYS else "everyone"


async def caller(connection: HTTPConnection) -> str | None:
    """Per-IP rate limit key; health checks are not counted."""
    return None if connection.url.path in ALWAYS else await client_ip(connection)
# A `None` key plus `on_missing_key="skip"` exempts the health check from each limit.
app.add_middleware(ConcurrencyLimitMiddleware, limit=busy, key=everyone, on_missing_key="skip")
app.add_middleware(CoalescingMiddleware)
app.add_middleware(
    RateLimitMiddleware, limiter=limiter, rates=rate, key=caller, on_missing_key="skip"
)
app.add_middleware(DeadlineMiddleware, deadline=deadline)
app.add_middleware(LoadSheddingMiddleware, shedder=shedder, priority=plan)

DeadlineMiddleware and CoalescingMiddleware have no per-route exemption, and a health check needs none: it returns immediately, and one response can safely serve concurrent probes.

Full example: examples/traffic_health_check.py.

With a response cache

Place ResponseCacheMiddleware directly inside CoalescingMiddleware. On an expired entry under a 100-request burst, coalescing collapses the burst into 1 cache miss, 1 app call, and 1 cache write; reversing them causes 100 cache reads and 100 writes.

Route-level decorators

Route decorators (@limit.held(), @deadline.enforced(), @ns.response(), and FastAPI Depends(limiter.limit(...))) execute inside all middleware. Requests satisfied by CoalescingMiddleware or ResponseCacheMiddleware never reach route decorators—do not put routes that require per-request metering/billing behind coalescing or public response caching.

Decorator order: Stack @ns.response above @deadline.enforced() above @limit.held(), all below the route decorator (placed above it, they silently do nothing). With @enforced() above @held(), time queued for a slot counts toward the deadline and a request still queued at the deadline gets 504. Reversed, the request queues for up to wait= first and its deadline starts only once it holds a slot.

Multi-worker note

Concurrency limits, deadlines, load shedding, and coalescing are all process-local. Only rate limits and caches backed by RedisStore share state across workers.