Skip to content

Caching responses

@ns.response caches HTTP endpoint responses with built-in ETag/304, Cache-Control, Vary, and Cache-Status support.

users = cache.namespace("user", ttl=300)

# Placed below `@app.get`, so auth runs before cache lookup.
# Signed-in callers each get their own copy, sent as `Cache-Control: private`.
@app.get("/preferences")
@users.response("preferences", entity=user_id, client_ttl=30)
async def preferences(user: CurrentUser) -> Preferences:
    return await db.preferences_of(user.id)

# Invalidates only this user's cached preferences after the write succeeds.
@app.put("/preferences")
@users.invalidates("preferences", entity=user_id)
async def change(user: CurrentUser, new: Preferences) -> Preferences:
    await db.save(user.id, new)
    return new

Full example: examples/cache_responses.py.

Runs after authentication

Place @ns.response below the route decorator (@app.get(...)). FastAPI runs all route dependencies (including authentication) before invoking the endpoint, so cached responses are never served to unauthenticated callers.

On plain Starlette endpoints without FastAPI dependencies, place any auth decorator above @ns.response.

Cache key composition

Response keys are derived from the HTTP request, not arbitrary endpoint parameters (so DB sessions or clients never pollute keys):

  • HTTP method and declared route template
  • Path parameters and normalized query parameters (order-independent)
  • Request headers listed in vary=
  • For a signed-in request, the values of the credential headers and the Starlette user's identity and scopes, unless the route is shared=True
  • Additional dependency values explicitly named via key=

key= takes the names of endpoint arguments, or a function of them:

# The response depends on the caller's country, which a dependency derives from the
# client address: it is in neither the path nor the query. `key=` names the endpoint
# argument to add to the cache key.
@app.get("/shipping")
@pages.response("shipping", key="country")
async def shipping(country: Annotated[str, Depends(country_of)]) -> list[str]:
    return await db.shipping_options(country)

Per-caller and shared responses

A cached response is never sent to a caller it was not made for. A request is signed in when it carries a credential header (Authorization or Cookie, unless the cache names others) or when Starlette's AuthenticationMiddleware has authenticated it. On a FastAPI route, a header that one of the route's security schemes reads is a credential header too.

  • Not signed in: Requests share one cached copy.
  • Signed in, caller unknown (default): The request is not cached. The endpoint runs, and a warning is logged once per route.
  • Signed in, caller known: The request gets its own cached copy. The cache knows the caller in two cases:
    • Cache(credentials=[...]): You name the request headers your callers sign in with. Copies are keyed on a digest of those headers' values. This relies on the headers identifying the user (see the warning below).
    • Starlette authentication: AuthenticationMiddleware has authenticated the request and the user's identity is a string, an integer or a UUID. No credentials= is needed. The identity and the request's scopes (request.auth.scopes) are part of the key, in addition to the credential headers.
  • shared=True: One copy for every caller the route's dependencies admit. Use it when the response is the same for everyone.
  • Cache-Control: private: Sent on every response the endpoint returns to a signed-in request, on either kind of route and whether or not it was cached, so shared proxies and CDNs do not store it. An endpoint's own Cache-Control: public is removed from such a response (logged once per route). Two paths are not covered and are sent as they are: an HTTPException the endpoint raises, and a request whose method is not in methods=.
  • entity=: Names what the response is about (a parameter name or a callable over endpoint parameters) and enables users.entity(id).invalidate(). It does not affect who may be sent the response. If entity= evaluates to None, the cache is bypassed. A parameter named by entity= must be annotated str, int, or UUID; pass a callable for anything else (entity=lambda user: user.id).

To cache a copy per caller, name the headers your callers sign in with when you create the cache:

# The headers callers sign in with. Naming them lets `@users.response` cache a copy per
# caller. Without `credentials`, signed-in requests are not cached.
cache = Cache(credentials=["Authorization", "Cookie"])

List every header a caller can sign in with. A request that carries none of them is treated as not signed in and shares the anonymous copy, so leaving Cookie out of the list makes a request that carries only a cookie anonymous. An API that also takes keys in another header lists that header too:

# Callers sign in with a bearer token, a session cookie or an `X-API-Key` header.
# Each caller's responses are cached separately, keyed on the values of all three.
cache = Cache(credentials=["Authorization", "Cookie", "X-API-Key"])

With Starlette's AuthenticationMiddleware, the cache reads request.user.identity and needs no credentials=. Starlette's BaseUser does not define identity, so give your user class an identity property that returns a string, an integer or a UUID. A user without one is not cached. The identity must be unique across the whole app: if IDs repeat between tenants, include the tenant in it.

class Member(SimpleUser):
    @property
    def identity(self) -> str:
        return self.username  # what the cache tells one user from another by

class Sessions(AuthenticationBackend):
    async def authenticate(
        self, conn: HTTPConnection
    ) -> tuple[AuthCredentials, BaseUser] | None:
        name = sessions.get(conn.headers.get("Authorization", ""))
        return (AuthCredentials(["authenticated"]), Member(name)) if name else None

app = FastAPI()
app.add_middleware(AuthenticationMiddleware, backend=Sessions())
accounts = Cache().namespace("account", ttl=60)  # no `credentials=`

def signed_in(request: Request) -> str:
    user: BaseUser = request.user
    if not user.is_authenticated:
        raise HTTPException(401, "Not signed in")
    return user.identity

@app.get("/usage")
@accounts.response("usage")
async def usage(customer: Annotated[str, Depends(signed_in)]) -> dict[str, str]:
    return await db.usage_of(customer)

A shared=True route whose response is the same for every signed-in user:

# The catalogue is the same for every signed-in user, so one copy serves them all
# instead of one copy per credential. The route's dependencies still run on every
# request.
@app.get("/catalog")
@pages.response("catalog", shared=True)
async def catalog(user: CurrentUser) -> list[str]:
    return await db.products()

Trade-offs of per-caller copies:

  • One copy per credential, not per user: A rotated token starts with an empty cache, and old copies expire by TTL. users.entity(id).invalidate() still invalidates all of them.
  • Cookies: The whole Cookie header is part of the key, so a changed cookie (analytics IDs, consent choices) starts a new copy. Browsers send cookies to most public sites: mark public routes shared=True, or they are cached per browser. Test clients send no cookies by default and will not reveal this.

The credential headers must identify the user

With Cache(credentials=[...]), copies are told apart by the values of those headers, not by who your app decides the user is. Two users who arrive with the same values share a copy:

  • A gateway's own token: If every request carries the same Authorization (a gateway or service token) and the user is named in another header, list that header: Cache(credentials=["Authorization", "X-User-Id"]).
  • A session ID kept across logins: If a session cookie keeps its value when a different user signs in, rotate it at login. key= separates the copies in this cache only: a browser both users share sends the same Cookie for each, and can reuse the first user's response while client_ttl lasts.
  • No credential header at all: A caller identified only by a client TLS certificate or a peer address looks anonymous and shares the anonymous copy. Leave such routes uncached.

Starlette's AuthenticationMiddleware covers all three in this cache: the user it authenticates is part of the key, whatever headers the request carries. A browser's cache is separate, and tells requests apart only by the headers in Vary. A response to a signed-in request that carries no credential header is therefore sent Cache-Control: private, no-store, and a session cookie that keeps its value across logins still has to be rotated at login.

On plain Starlette, authenticate in a decorator above @ns.response. An endpoint that checks the caller in its own body is not run on a hit.

FastAPI security schemes

A security scheme from fastapi.security (APIKeyHeader, APIKeyCookie, HTTPBearer, HTTPBasic, OAuth2PasswordBearer, ...) reads a caller's credentials from a request header. paceapi finds the schemes among a route's dependencies, including those of its routers and of the app and those put in place with dependency_overrides, and treats the header each one reads as a credential header on that route, whether or not credentials= lists it:

  • Listed in credentials=: each caller gets a cached copy, as above.
  • Not listed: a request that carries the header is not cached. The endpoint runs, the response is sent Cache-Control: private with the header in Vary, and a warning names the header once per route. A request without the header (on a route where the scheme is optional) is cached as usual. The exception is a request that Starlette's AuthenticationMiddleware has authenticated as a user with an identity: it is cached per user as above, and the header's value is part of the key.
api_key = APIKeyHeader(name="X-API-Key")
# The route's security scheme reads `X-API-Key`, so the header says who is calling.
# Listed here, each key gets its own cached copy. Left out, a request that carries
# the header is not cached, and a warning names the header once for each route.
cache = Cache(credentials=["Authorization", "Cookie", "X-API-Key"])
accounts = cache.namespace("account", ttl=60)

@app.get("/usage")
@accounts.response("usage")
async def usage(key: Annotated[str, Depends(api_key)]) -> dict[str, str]:
    return await db.usage_of(CUSTOMERS[key])

An APIKeyHeader scheme reads the header it names, an APIKeyCookie scheme reads Cookie, and every other scheme in fastapi.security reads Authorization. A key in the query string (APIKeyQuery) is already part of the cache key. A scheme class of your own is assumed to read Authorization. A header that such a class reads instead, or that a dependency of your own reads (x_token: Annotated[str, Header()]), is not detected: list it in credentials=.

What is cached

A cached response is its status code, headers, and body bytes. A hit sends them again unchanged: nothing is validated or serialized.

  • Returning a Response caches that response.
  • Returning a Python value or model from a FastAPI endpoint caches the response FastAPI builds from it: validated and serialized with the route's response_model= and response_model_* settings, with the route's status code and response class. The endpoint's return annotation does not matter, and a value FastAPI cannot serialize is the same error as without the decorator.
# The route declares its model with `response_model=`. The response FastAPI builds
# with it is cached, whatever the endpoint's return annotation says.
@app.get("/articles/{article_id}", response_model=Article)
@pages.response("article")
async def article(article_id: int) -> object:
    return {**(await db.article(article_id)).model_dump(), "draft": "not in the model"}

Headers a dependency sets on the Response parameter before the endpoint runs, such as rate limit headers, are sent with every response and are not stored. Headers the endpoint sets on it are stored with the response and replace a dependency's header of the same name. Headers that describe one request are never stored, whoever set them: rate limit headers, Retry-After, Date, Age and Server.

A stored response has no schema fingerprint. After a response model changes, entries stored before the change are served in the old shape until their TTL ends, unless the cache has a release= or you raise the namespace's schema=.

Responses are not cached if they:

  • Return a non-2xx or partial (206) status
  • Set Set-Cookie
  • Return a StreamingResponse, a FileResponse, or a Response with an attached background task (also when the route's response_class= is one whose body is not in memory)
  • Emit Cache-Control: no-store or no-cache
  • Emit Cache-Control: private, unless the copy is one caller's own (a signed-in request on a route without shared=True)
  • Emit a Vary header referencing a request header absent from vary= (credential headers count on routes without shared=True)
  • Answer a request that was signed in or out while the endpoint ran, on a route without shared=True. Authenticate in a dependency, or in a decorator above @ns.response, so the caller is known before the cache is read

A response that sets a cookie, has a body that is not in memory, has a background task, or has a Vary header that vary= does not list is logged at WARNING on the paceapi logger, once per route and reason, with the endpoint's name and what to change. A status that is not cached and the endpoint's own no-store, no-cache, private or Vary: * are not logged.

Note: FastAPI BackgroundTasks parameters are not executed on cache hits—avoid attaching required per-request side effects to cached routes.

Responses are cached for the namespace's TTL unless the route passes ttl=:

pages = cache.namespace("page", ttl=3600)

# Stock levels change faster than the rest of the catalogue: this route's responses
# expire after 15s instead of the namespace's hour.
@app.get("/products/{product_id}/stock")
@pages.response("stock", ttl=15)
async def stock(product_id: int) -> dict[str, int]:
    return await db.stock_of(product_id)

HTTP headers

  • ETag: Generated from content; matching If-None-Match requests receive 304 Not Modified with an empty body.
  • Cache-Control: client_ttl= sets max-age independently of the server ttl=. Responses to signed-in requests add private. A Cache-Control set by the endpoint is preserved, with private added and public removed for signed-in requests. A signed-in request that carries no credential header is sent private, no-store, added to the endpoint's own Cache-Control if it set one, unless the route is shared=True: a browser's cache could not tell that caller from the next.
    • Server invalidations cannot purge browser caches; only set client_ttl= to staleness you can tolerate.
  • Vary: Appends vary= headers to any existing Vary header, plus the credential headers on routes without shared=True and on any response to a signed-in request.
  • Cache-Status (RFC 9211):
Cache-Status Meaning
paceapi; hit; ttl=41 Served from cache with 41s remaining
paceapi; fwd=miss; stored Computed by endpoint and stored
paceapi; fwd=miss Computed by endpoint, not cacheable
paceapi; fwd=request; stored Recomputed due to client no-cache and stored
paceapi; fwd=bypass Cache skipped (e.g., client no-store, entity= evaluated to None, or a signed-in request whose caller the cache does not know)

Client cache directives

  • Cache-Control: no-cache forces endpoint execution and refreshes the cached entry.
  • Cache-Control: no-store bypasses reading and writing the cache.

Because clients can trigger recomputation with no-cache, pair expensive cached routes with a rate limit.

Concurrent misses

@ns.response does not coalesce concurrent misses. Requests that arrive together for a response that is not cached yet each run the endpoint and each store the result: 16 simultaneous requests for one cold key run it 16 times. (get_or_set and @ns.cached load once per process; see Stampedes and stale values.)

To collapse such a burst, add CoalescingMiddleware to the app. It coalesces GET requests: one runs the endpoint and its response is stored, the requests waiting on it are sent the same response (its Cache-Status: paceapi; fwd=miss; stored included), and the next request is a hit.

  • Which responses are shared: Only a response the cache would store, with a Content-Length of at most max_body (1 MiB by default). Otherwise each waiting request reaches the route itself: it is answered from the cache if the first response was stored by then, as one longer than max_body is, and runs the endpoint if the first request failed or was cancelled (Which responses are shared).
  • Which callers coalesce: Requests coalesce only when their credential headers (Authorization and Cookie by default) carry the same values. Requests with the same values are treated as one caller and sent one response; requests that carry no credentials coalesce with each other. A user signed in by Starlette's AuthenticationMiddleware is told apart as well: put it outside CoalescingMiddleware, and a user's requests coalesce only with that user's own (Signed-in users). Callers that a dependency identifies from another header are not told apart: pass every such header in CoalescingMiddleware(credentials=[...]), the ones in Cache(credentials=[...]) included, and do not coalesce a route whose callers are told apart by something outside the headers, such as a client certificate (Request matching rules).
  • Process-local: Each worker coalesces its own requests, so a burst spread over four workers runs the endpoint up to four times for each group of matching requests.
  • Placement: Waiting requests do not reach the app, so route dependencies and route-level rate limits run once per coalesced burst. See Trade-offs, and Middleware order for where it sits among rate limits, deadlines and concurrency limits.

Non-GET methods

GET and HEAD are cached by default. Pass methods= to cache other methods; methods with request bodies also require key= to specify which body fields form the key.

def filters(query: SearchQuery) -> tuple[str, list[str]]:
    return query.text, sorted(query.tags)

# The search filters are in the request body, which is not part of the cache key.
# `methods=` caches the POST, and `key=` says what in the body identifies a search.
@app.post("/search")
@pages.response("search", methods=["POST"], key=filters)
async def search(query: SearchQuery) -> list[str]:
    return await db.search(query.text, query.tags)

App-wide response cache middleware

For public responses that should bypass routing and dependencies entirely, use ResponseCacheMiddleware:

pages = cache.namespace("pages", ttl=60)
baskets = cache.namespace("basket", ttl=60)

# In front of the whole app: what is the same for everyone is answered from here
# for a minute without the app being reached. A request that says who it is from,
# with an Authorization header or a cookie, is passed on and nothing is kept for it.
app.add_middleware(ResponseCacheMiddleware, namespace=pages, resource="public", client_ttl=30)

@app.get("/products/{product_id}")
async def product(product_id: int) -> dict[str, object]:
    name = await db.product(product_id)
    if name is None:
        raise HTTPException(404, "No such product")
    return {"id": product_id, "name": name}

# What is someone's own is kept on its route, which runs once they are known.
@app.get("/basket")
@baskets.response("basket", entity="user")
async def basket(user: Annotated[str, Depends(current_user)]) -> list[str]:
    return await db.basket(user)

@app.put("/products/{product_id}")
async def rename(product_id: int, name: str) -> dict[str, object]:
    await db.rename(product_id, name)
    await pages.invalidate("public")  # every page kept in front is out of date now
    return {"id": product_id, "name": name}

Full example: examples/cache_middleware.py.

Key differences from @ns.response:

  • Runs before the app: Requests with Authorization or Cookie bypass the middleware by default. So does a request Starlette's AuthenticationMiddleware has authenticated, when that middleware is added after this one and so runs first. If it runs inside this middleware instead, the response to a request it authenticated is not stored, but that request can still be served a response cached for anonymous requests. credentials= defaults to the cache's; pass a full replacement list to override it for this middleware. For a fully public site whose only cookies are ones your pages never read, pass credentials=[]; otherwise every browser carrying any cookie bypasses the cache.
  • Bypassed routes skip route dependencies: Place rate limits that must count cache hits outside ResponseCacheMiddleware (see Middleware order).
  • FastAPI security schemes: The middleware looks a request up before it is matched to a route, so it cannot know in advance which header a route's security scheme reads. Without entity=, it stores nothing for a route whose scheme reads a header that is not in credentials=, and logs one warning that names the route and the header. List the header: requests that carry it then bypass the middleware, and the rest are cached. Two cases are not detected: a middleware between this one and the route that copies the ASGI scope hides the route, and a frontend served with app.frontend() directly on the app has no route to read (one served by an included router is detected).
  • Keying & methods: Keys on scheme, host, path, query, and vary=. Caches GET only (HEAD passes through). Adds vary= and credentials= headers to response Vary.
  • Buffering: Buffers cacheable responses up to max_body (1 MiB default). Event streams, uncacheable statuses/headers, and bodies exceeding max_body stream through unbuffered. Non-SSE streaming responses and responses with background tasks under max_body are cached (background tasks do not rerun on hits).
  • Middleware that adds Vary: Place CORSMiddleware (Vary: Origin) and GZipMiddleware (Vary: Accept-Encoding) outside ResponseCacheMiddleware, or include their headers in vary=.
  • Optional entity=: Accepts a connection key function for per-caller middleware caching. Because the app does not run on hits, entity= must only read unforgeable credentials (and revoked tokens remain cached until TTL expiry). Per-caller entries are invalidated via pages.entity(key).invalidate("public") or pages.invalidate().

Pass ttl= to cache the middleware's responses for a different time than the namespace's TTL:

pages = cache.namespace("pages", ttl=3600)
# Responses cached by the middleware expire after 60s instead of the namespace's hour.
app.add_middleware(ResponseCacheMiddleware, namespace=pages, resource="public", ttl=60)

If callers are identified by another header, pass the complete list in credentials=:

# This API also identifies callers by `X-API-Key`. The list replaces the default, so
# `Authorization` and `Cookie` are listed again. A request that carries any of the
# three passes through to the app, and its response is not cached.
app.add_middleware(
    ResponseCacheMiddleware,
    namespace=pages,
    resource="public",
    credentials=["Authorization", "Cookie", "X-API-Key"],
)

List request headers that change the response in vary=:

# Pages are translated, so `Accept-Language` is part of the cache key. A response
# whose own `Vary` names a header that is not listed here is not cached at all.
app.add_middleware(
    ResponseCacheMiddleware, namespace=pages, resource="public", vary=["Accept-Language"]
)

Set the largest body that is buffered and cached, in bytes, with max_body=:

# Buffer and cache responses of up to 64 KiB. A longer one streams through uncached.
app.add_middleware(
    ResponseCacheMiddleware, namespace=pages, resource="public", max_body=64 * 1024
)

With entity=, each caller the key identifies gets cached responses of their own:

# Each API key gets cached responses of its own, sent as `Cache-Control: private`.
# The app does not run on a hit, so a revoked key is still answered until its
# responses expire: keep `ttl=` short. A request without the header is not cached.
# Listing the header in `credentials=` sends it as `Vary`, so a browser keeps each
# key's responses apart as well.
app.add_middleware(
    ResponseCacheMiddleware,
    namespace=pages,
    resource="api",
    ttl=30,
    entity=RequestHeader("X-API-Key"),
    credentials=["Authorization", "Cookie", "X-API-Key"],
)

Rule of thumb: use @ns.response for authenticated routes (runs after auth, per caller with credentials=) and ResponseCacheMiddleware for public pages.