Skip to content

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.response keys on method, route template, path/query params, and vary=—not str() of all endpoint arguments—so DB sessions never cause cache misses.
  • Signed-in requests: Requests with Authorization or Cookie are not cached on @ns.response routes until the cache is created with credentials=[...]. Each caller then gets their own cached copy, sent as Cache-Control: private. Pass shared=True where every caller gets the same response.
  • Separate server and client TTLs: ttl= controls server storage only; browser Cache-Control: max-age= is emitted only when client_ttl= is explicitly set.
  • Deterministic ETag & full HTTP parsing: ETag is content-hashed (consistent across workers, unlike Python hash()). If-None-Match supports tag lists, weak tags, and *; request Cache-Control parses multi-directive headers properly.
  • Preserved Response status & headers: Returned JSONResponse/Response instances preserve status codes and headers on cache hits. Non-2xx, Set-Cookie, streamed, background-task, and no-store responses are not cached.
  • Responses cached as sent: @ns.response stores the response FastAPI builds, with response_model= applied, and a hit serializes nothing. A namespace's serializer= applies to @ns.cached, get and set values, which must match their declared return type (or type=).
  • O(1) invalidation: Replaces a single generation token instead of running blocking KEYS + DEL Lua loops, and prevents in-flight stale loads from overwriting fresh invalidations.
  • Additional HTTP methods: Supports GET, HEAD, and custom methods= (with key= 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-cache2 keys 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 CacheStore for custom backends).
  • Custom cache-status header names (always RFC 9211 Cache-Status).
  • Key builders taking (request, response) (pass endpoint/dependency parameters to key=).

New capabilities unlocked