← Back to FastAPI, page 3

fastapi-0050 · Hard senior

How would you add caching to a FastAPI API: HTTP caching headers with ETag, and server-side caching with Redis?

Use HTTP caching so clients, browsers and CDNs skip work: Cache-Control with max-age for public data, ETag and If-None-Match so clients revalidate cheaply with a 304 and no body, and Vary for headers that change the response. Use server-side caching (Redis or in-process TTL cache) for expensive computed results with explicit keys, TTLs and invalidation on writes, and protect against stampedes. Never cache per-user data in shared caches without private or Vary.

Full answer

Two layers solve different problems.

HTTP caching (client and CDN side)

  • Cache-Control: public, max-age=300 lets browsers and CDNs reuse a response for 5 minutes without asking. Suitable for public, slowly changing data such as a timetable. Use private for user-specific responses, no-store for sensitive data.
  • Validation with ETag: the server sends a fingerprint (for example a hash of the body or a version number). The client later sends If-None-Match: "<etag>". If unchanged, the server answers 304 Not Modified with no body: the client saves bandwidth, and the server can skip serialising if it can compute the ETag cheaply (from updated_at or a version column).
  • Vary: Accept-Encoding, Authorization tells caches which request headers change the response. A missing Vary can serve one user's data to another.
  • FastAPI does not add any of this automatically; set headers on the Response, or in a middleware.

Server-side caching

  • Cache expensive results (aggregations, calls to slow partners) in Redis with a key that includes every input: report:{class_id}:{term}.
  • TTL gives eventual freshness; invalidation on write (delete or update the key when marks change) gives immediate correctness. Do both.
  • Cache stampede: when a hot key expires, many requests recompute it at once. Use a lock around recomputation, early refresh with jittered TTLs, or serve slightly stale data while one request refreshes.
  • Cache negative results briefly (for not-found lookups) to protect the database.
  • Serialise with JSON or msgpack, not pickle, for data from shared stores.
  • Measure hit rate; a cache with a 10% hit rate is only added complexity.
  • In-process caches (functools.lru_cache, cachetools.TTLCache) are per worker, so each worker has its own copy; fine for small reference data, wrong when consistency across workers matters.

Rule: cache after the correctness story is clear: who may see this data, how stale may it be, and what event invalidates it.

python
import hashlib
import json
import time
from typing import Annotated

from fastapi import FastAPI, Header, Request, Response
from fastapi.testclient import TestClient

app = FastAPI()
TIMETABLE = {"version": 3, "monday": ["Maths", "DBMS", "Networks"]}
cache: dict[str, tuple[float, dict]] = {}          # a Redis stand-in: key -> (expires_at, value)
computed = {"n": 0}


@app.get("/timetable")
def timetable(response: Response, if_none_match: Annotated[str | None, Header()] = None):
    etag = '"v%d"' % TIMETABLE["version"]            # cheap to compute: from a version column
    response.headers["ETag"] = etag
    response.headers["Cache-Control"] = "public, max-age=300"
    response.headers["Vary"] = "Accept-Encoding"
    if if_none_match == etag:
        return Response(status_code=304, headers=dict(response.headers))
    return TIMETABLE


def cached(key: str, ttl: float, compute):
    hit = cache.get(key)
    if hit and hit[0] > time.time():
        return hit[1], "hit"
    value = compute()
    cache[key] = (time.time() + ttl, value)
    return value, "miss"


def expensive_report(class_id: str) -> dict:
    computed["n"] += 1
    return {"class": class_id, "average": 74.5}


@app.get("/reports/{class_id}")
def report(class_id: str, response: Response):
    value, status = cached(f"report:{class_id}", 60, lambda: expensive_report(class_id))
    response.headers["X-Cache"] = status
    response.headers["Cache-Control"] = "private, max-age=60"
    return value


@app.post("/marks/{class_id}")
def update_marks(class_id: str):
    cache.pop(f"report:{class_id}", None)            # invalidate on write
    return {"ok": True}


c = TestClient(app)
r = c.get("/timetable")
print(r.status_code, r.headers["etag"], r.headers["cache-control"])
r2 = c.get("/timetable", headers={"If-None-Match": r.headers["etag"]})
print(r2.status_code, repr(r2.content))
TIMETABLE["version"] = 4
print(c.get("/timetable", headers={"If-None-Match": '"v3"'}).status_code)

print([c.get("/reports/10A").headers["x-cache"] for _ in range(2)], "computations:", computed["n"])
c.post("/marks/10A")
print(c.get("/reports/10A").headers["x-cache"], "computations:", computed["n"])

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. A dict with expiry times stands in for Redis. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 200 "v3" public, max-age=300 304 b'' 200 ['miss', 'hit'] computations: 1 miss computations: 2

Key points

  • Cache-Control for reuse; private vs public vs no-store
  • ETag + If-None-Match give cheap 304 revalidation
  • Vary prevents serving one user's data to another
  • Redis keys include all inputs; TTL plus invalidation on write
  • Guard against stampedes; in-process caches are per worker

Common mistakes

  • Caching per-user responses with public Cache-Control or without Vary
  • Caching in Redis without an invalidation plan
  • Using in-process caches and expecting consistency across workers
  • Building cache keys that leave out an input and return wrong data
  • Using pickle for data in a shared cache

Follow-ups

  • How would you stop a cache stampede on a popular report?
  • What is the difference between max-age and no-cache?
  • How would you derive ETags for list responses cheaply?

Tips

  • Separate HTTP caching from server-side caching
  • Explain ETag revalidation and the 304 flow
  • Talk about invalidation, staleness and who may see the data