Migrating from fastapi-cache2¶
Guide for migrating FastAPI caching from fastapi-cache2 (v0.2.2) to paceapi.
See Migrating to paceapi for shared defaults (no globals, Redis cutover, fail-open reads).
API mapping¶
fastapi-cache2 |
paceapi |
|---|---|
FastAPICache.init(RedisBackend(redis), prefix="myapp") |
cache = Cache(RedisStore(redis), prefix="myapp") (no global singleton or startup init) |
InMemoryBackend() |
Cache() (default in-memory store) |
@cache(expire=60) on a route |
@pages.response("articles", ttl=60) (Caching responses) |
@cache(expire=60) on a helper function |
@pages.cached("rates", ttl=60) (async def only; Caching functions) |
expire= on init |
ttl= on Cache or Namespace |
namespace="articles" |
pages = cache.namespace("page") + resource name on decorators |
key_builder= |
entity=, vary=, and key= |
coder=JsonCoder |
Nothing on a route: @ns.response caches the response as sent. @ns.cached values default to JSON with Pydantic typed round-trips |
coder=PickleCoder |
Nothing on a route. For @ns.cached values, serializer=PickleSerializer() (trusted stores only) |
Custom Coder class |
Nothing on a route. For @ns.cached values, a Serializer instance |
await FastAPICache.clear(namespace="articles") |
await pages.invalidate("articles") or @pages.invalidates("articles") (Invalidation) |
await FastAPICache.clear(key=...) |
await pages.delete("name") |
cache_status_header="X-FastAPI-Cache" |
Standard Cache-Status header (RFC 9211) |
enable=False |
Cache(enabled=False) and cache.disabled() in tests |
FastAPICache.reset() in tests |
Instantiate a fresh Cache() per test |
injected_dependency_namespace= |
Not needed |
Migrated app example¶
Cache and namespaces:
# Was: FastAPICache.init(RedisBackend(redis), prefix="myapp") when the app started.
# A cache is an object like any other. With no store it keeps its values in memory; give
# it RedisStore(redis) to share them, and enabled=False to switch it off from a setting.
# `credentials` names the headers callers sign in with, so a route can be cached per
# caller. Without it, signed-in requests are not cached.
cache = Cache(prefix="myapp", credentials=["Authorization", "Cookie"])
# A namespace is an object you make once, where it was a string on each decorator.
pages = cache.namespace("page", ttl=60)
users = cache.namespace("user", ttl=300)
Public cached route:
# Was: @cache(expire=60)
@app.get("/articles")
@pages.response("articles", vary=["Accept-Language"])
async def articles(accept_language: Annotated[str, Header()] = "en") -> list[Article]:
return await db.all_articles(accept_language)
Per-user cached route:
# Was: @cache(expire=300, namespace="saved", key_builder=a_builder_that_read_the_user)
# `client_ttl` is for the browser, which does not hear of what is cleared here: leave
# it out where a user must see their own change at once.
@app.get("/me/saved")
@users.response("saved", entity=user_id, client_ttl=30)
async def saved(user: CurrentUser) -> list[Article]:
return await db.saved_by(user.id)
Declarative invalidation on write:
# Was a call to FastAPICache.clear in the endpoint, which cleared it for every user.
@app.put("/me/saved/{article_id}")
@users.invalidates("saved", entity=user_id)
async def save(user: CurrentUser, article_id: int) -> list[int]:
if article_id not in db.articles:
raise HTTPException(404, "No such article")
mine = db.saved.setdefault(user.id, [])
# Said twice, by a client that never heard back, it is saved once.
if article_id not in mine:
mine.append(article_id)
return mine
# In an app of your own this is behind whatever lets only an administrator in.
@app.post("/admin/articles/refresh")
async def refresh_articles() -> None:
# Was a call to FastAPICache.clear, with the namespace "articles".
await pages.invalidate("articles")
Cached async helper function:
# Was: @cache(expire=3600) on a function that is not an endpoint.
@pages.cached("rates", ttl=3600)
async def rates() -> dict[str, float]:
return await db.rates()
Custom / pickle serializer on a namespace:
# Was: @cache(coder=PickleCoder). Unpickling runs code, there as here: keep pickles
# only in a store that nothing you do not trust can write to.
blobs = cache.namespace("blob", ttl=600, serializer=PickleSerializer())
Full example: examples/from_fastapi_cache.py.
Behavioral differences¶
- Request-based response keys:
@ns.responsekeys on method, route template, path/query params, andvary=—notstr()of all endpoint arguments—so DB sessions never cause cache misses. - Signed-in requests: Requests with
AuthorizationorCookieare not cached on@ns.responseroutes until the cache is created withcredentials=[...]. Each caller then gets their own cached copy, sent asCache-Control: private. Passshared=Truewhere every caller gets the same response. - Separate server and client TTLs:
ttl=controls server storage only; browserCache-Control: max-age=is emitted only whenclient_ttl=is explicitly set. - Deterministic
ETag& full HTTP parsing:ETagis content-hashed (consistent across workers, unlike Pythonhash()).If-None-Matchsupports tag lists, weak tags, and*; requestCache-Controlparses multi-directive headers properly. - Preserved
Responsestatus & headers: ReturnedJSONResponse/Responseinstances preserve status codes and headers on cache hits. Non-2xx,Set-Cookie, streamed, background-task, andno-storeresponses are not cached. - Responses cached as sent:
@ns.responsestores the response FastAPI builds, withresponse_model=applied, and a hit serializes nothing. A namespace'sserializer=applies to@ns.cached,getandsetvalues, which must match their declared return type (ortype=). - O(1) invalidation: Replaces a single generation token instead of running blocking
KEYS+DELLua loops, and prevents in-flight stale loads from overwriting fresh invalidations. - Additional HTTP methods: Supports
GET,HEAD, and custommethods=(withkey=for body-bearing methods). - Store error handling: Reads fail open with rate-limited logging (once/minute) and observer events; invalidations/writes raise store errors.
- Clean keyspace on cutover: Old
fastapi-cache2keys without an expiry remain in Redis until you delete their prefix after migration.
Not supported¶
- DynamoDB backend (built-in stores are memory, Redis/Valkey, MongoDB, and Memcached; implement
CacheStorefor custom backends). - Custom cache-status header names (always RFC 9211
Cache-Status). - Key builders taking
(request, response)(pass endpoint/dependency parameters tokey=).
New capabilities unlocked¶
- Four-level O(1) invalidation
- Release isolation & automatic schema fingerprinting
- Single-flight, distributed locks, and stale-while-revalidate
- Typed round-trip deserialization for Pydantic models,
Decimal, dates, and more