Skip to content

Request coalescing

When many concurrent requests arrive for the same uncached resource at the same time, CoalescingMiddleware executes the app once and broadcasts the response to all waiting callers.

from paceapi.integrations.starlette import CoalescingMiddleware
# While one request for a report is being answered, whoever else asks for the same
# report waits for it and is sent the same response. The warehouse is asked once for
# each month, however many are asking. Nothing is kept: the next request, once the
# response is out, asks the warehouse again.
#
# Requests are told apart by what they ask for, and by their `Authorization` and
# `Cookie` headers, so callers your app tells apart by those are never sent one
# another's. Whoever waits is sent what the first request read: keep a route out of
# this where a read must see a write that came just before it.
app.add_middleware(CoalescingMiddleware)

Coalescing does not retain responses after completion—subsequent requests execute normally. Combine with ResponseCacheMiddleware to both coalesce stampedes and cache results (see Middleware order).

Full example: examples/coalescing.py.

Request matching rules

Two requests coalesce only when both are GET requests (without a body) matching on:

  • Scheme, host, path, query string, and Origin header
  • credentials= headers (Authorization, Cookie by default) so authenticated callers only coalesce with their own concurrent requests
  • The signed-in user and the request's scopes, where Starlette's AuthenticationMiddleware runs before coalescing (Signed-in users)
  • vary= headers (e.g., Accept-Language)
  • Conditional and range headers (If-None-Match, If-Modified-Since, Range)

If your app identifies callers by another header (e.g., X-API-Key or X-Forwarded-For), pass the complete list in credentials= (replaces the default). Routes that vary on non-header identity (client TLS certificates or peer IP) should not be coalesced.

# Callers are identified by X-API-Key here. The list replaces the default, so
# Authorization and Cookie are listed again.
app.add_middleware(CoalescingMiddleware, credentials=["Authorization", "Cookie", "X-API-Key"])

Pass every option to a single CoalescingMiddleware. Added twice, the outer instance runs first with its own settings, so one without your credentials= could share a response before the other sees the request.

List request headers that change the response in vary=, so requests that differ in them are not coalesced:

# Reports are translated: a request is only answered with a response in its language.
app.add_middleware(CoalescingMiddleware, vary=["Accept-Language"])

A GET that announces a body (Content-Length or Transfer-Encoding) always reaches the app. A body sent with neither header, which HTTP/2 allows, is not detected: do not coalesce GET routes whose response depends on the request body.

If the downstream response includes its own Vary header, it is only shared with waiters whose matching request headers equal the leader's.

Signed-in users

A response made for a user that Starlette's AuthenticationMiddleware signed in is sent only to that user's own requests. How that is enforced depends on which middleware runs first:

  • Authentication outside coalescing (recommended): The user is known when a request is matched. Requests coalesce only when authentication gave them the same user and the same scopes, whatever their headers carry. Two users behind one gateway token are two callers.
  • Authentication inside coalescing: The user is not known when a request is matched, so requests are matched on their headers alone. A response made for a signed-in user is not shared: the requests waiting on it reach the app themselves once it starts. A response made for nobody is still shared, including with a request that authentication would have signed in. A middleware between the two that copies the scope hides the user from coalescing.

Add AuthenticationMiddleware after CoalescingMiddleware, so that it runs first:

# The middleware added last runs first. Authentication is added after coalescing,
# so a request's user is known when it is matched, and is part of the match.
app.add_middleware(CoalescingMiddleware)
app.add_middleware(AuthenticationMiddleware, backend=NamedByTheGateway())

If the authentication backend reads request.session, SessionMiddleware must run before it. Add SessionMiddleware last, so the order is sessions, authentication, coalescing. A coalesced request does not run the endpoint, so do not coalesce a GET route that writes to the session (Middleware order).

The user's identity must be a string, an integer or a UUID, and the scopes must be strings. A request with any other user or scopes always reaches the app. Users of two classes are two callers, even with the same identity. The identity must be unique across the whole app: if IDs repeat between tenants, include the tenant in it. Starlette's SimpleUser has no identity, so give your user class one:

class Account(SimpleUser):
    """A user that says what identifies it, which Starlette's `SimpleUser` does not."""

    @property
    def identity(self) -> str:
        return self.username


class NamedByTheGateway(AuthenticationBackend):
    """A stand-in for your authentication: here a gateway names the user in `X-User`."""

    async def authenticate(self, conn: HTTPConnection) -> tuple[AuthCredentials, BaseUser] | None:
        name = conn.headers.get("x-user")
        return (AuthCredentials(["authenticated"]), Account(name)) if name else None

This covers request.user only. Callers that a FastAPI dependency identifies from a header are told apart by the headers in credentials=.

FastAPI security schemes

A header that one of a route's fastapi.security schemes reads, such as the X-API-Key of APIKeyHeader(name="X-API-Key"), identifies a caller whether or not credentials= lists it. A response is sent only to waiting requests that carry the same value of that header, so one key never receives another key's response.

The route is not known when a request is matched, so requests with different keys still wait for the first response before they reach the app. List the header in credentials= to match them separately from the start.

Not detected, so list the header: a header that a dependency of your own reads (x_token: Annotated[str, Header()]), a scheme behind a middleware between CoalescingMiddleware and the route that copies the ASGI scope, and the dependencies of a frontend served with app.frontend() directly on the app (one served by an included router is detected).

Which responses are shared

Only cacheable responses with a known Content-Length ≤ max_body (1 MiB default) are shared:

  • 2xx success (excluding partial responses)
  • No Set-Cookie
  • No Cache-Control: no-store or no-cache
  • No Cache-Control: private unless the request carried credentials or is from a signed-in user
  • Made for the user the request was matched as: a response from an endpoint that signs the request in or out is not shared
  • Sent only to requests that carry the same value of each header a FastAPI security scheme of the route reads

Set the size limit in bytes with max_body=:

# Share responses of up to 64 KiB. A longer one is not buffered: every caller that
# waited for it asks the app itself.
app.add_middleware(CoalescingMiddleware, max_body=64 * 1024)

Streaming responses (no Content-Length) pass through unshared. If the leader's response is unshareable, fails, or is cancelled before completion, all waiters immediately execute against the app themselves.

With no waiters present, the leader's response streams out normally; when waiters attach, the leader's body is buffered until complete so a slow leader reader does not block waiters.

Trade-offs

  • Waiters do not run the app: Route dependencies and route-level rate limits run only for the leader. Place rate limits that must count every caller outside CoalescingMiddleware.
  • Read-your-writes: A waiter can receive data read by a leader that started before an intervening write. Requests with Cache-Control: no-cache or no-store bypass coalescing to force a fresh read. Exclude endpoints requiring strict linearizability.
  • Shared response headers: Per-request headers like X-Request-ID are copied from the leader. Rate-limit headers are stripped from follower copies since followers were not individually counted inside the middleware.
  • Uncacheable routes add wait latency: Followers wait until the leader sends headers before discovering a response isn't shareable; exclude routes that always set cookies, no-store, or errors.

Scoping to specific routes

Mount CoalescingMiddleware on a sub-app for routes that should coalesce (or pass middleware=[Middleware(CoalescingMiddleware)] on a Starlette Route/Mount).

Scope and placement

Coalescing is process-local, applies to GET only, and emits no observer events or response headers. See Middleware order for where it sits relative to sessions, rate limits, caches, concurrency limits, deadlines, and load shedding.