Skip to content

Invalidation

Invalidate cached data at the exact granularity that changed—from a single resource to the entire cache—in one constant-time write.

Invalidation levels

@app.post("/users/{user_id}/orders")
async def place(user_id: int, item: str) -> list[str]:
    db.orders[user_id].append(item)
    # One resource of one user: their orders are out of date, and their name is not.
    await users.entity(user_id).invalidate("orders")
    return db.orders[user_id]

@app.post("/users/{user_id}/refresh")
async def refresh(user_id: int) -> None:
    # Everything kept for one user.
    await users.entity(user_id).invalidate()

@app.post("/admin/users/refresh")
async def refresh_users() -> None:
    # Everything in the namespace, for every user.
    await users.invalidate()

@app.post("/admin/refresh")
async def refresh_everything() -> None:
    # Everything this cache keeps, in every namespace.
    await cache.invalidate()

Full example: examples/cache_invalidation.py.

Call Scope invalidated
await users.entity(42).invalidate("orders") One resource for one entity
await users.entity(42).invalidate() All resources for that entity
await users.invalidate() All entries in the namespace (with or without an entity)
await cache.invalidate() Entire cache

Note: await users.invalidate("defaults") invalidates the "defaults" resource kept on the namespace without an entity, not every entity's "defaults" resource.

Every invalidation is a single O(1) store write—no keys are scanned or deleted. Superseded entries become unreadable immediately and expire naturally via TTL.

Declarative invalidation

Attach @ns.invalidates to write functions or endpoints:

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

The wrapped function runs first; invalidation runs only if it succeeds without raising. Pass entity= to target an entity, and omit the resource name to invalidate the entire entity.

Invalidate after commit

An invalidation is only correct once other requests can read the write. In apps where a yield dependency commits the database session after the endpoint returns, @ns.invalidates on the endpoint runs before the commit: a concurrent read in that gap misses, loads the pre-commit value, and caches it for the full TTL.

Invalidate where the commit happens instead:

async def session() -> AsyncGenerator[Session]:
    opened = Session(db)
    yield opened  # the endpoint runs and returns here
    await opened.commit()
    # Invalidate only after commit: invalidating earlier lets a concurrent read
    # reload the pre-commit value and cache it for the full TTL.
    for user_id in opened.renamed:
        await users.entity(user_id).invalidate("name")
@app.put("/users/{user_id}/name")
async def rename(user_id: int, name: str, db: Annotated[Session, Depends(session)]) -> str:
    db.renamed[user_id] = name  # no invalidation here: nothing is committed yet
    return name

@ns.invalidates is correct as-is on a function that both writes and commits before returning.

The example shows where to invalidate, not where to commit. A commit in a dependency's exit code runs after the endpoint has returned. In recent FastAPI versions the response has already been sent by then, unless the dependency is declared with scope="function", so a failed commit reaches no caller. Commit before returning where the caller must learn of a failed write.

Full example: examples/cache_after_commit.py.

Write-through (set and delete)

@app.put("/users/{user_id}/name")
async def rename(user_id: int, name: str) -> str:
    db.names[user_id] = name
    # The new value is in hand, so it is kept in place of the old one: the next
    # request is answered from the cache and not from the database.
    await users.entity(user_id).set("name", name, type=str)
    return name

@app.delete("/users/{user_id}/orders")
async def clear(user_id: int) -> None:
    db.orders[user_id] = []
    # One value, removed.
    await users.entity(user_id).delete("orders")

set() and delete() rotate the resource's invalidation token as well, ensuring entries for that resource written by other app releases are also invalidated.

Write-through with set() is only safe with a single writer per resource: two concurrent writers can complete their set() calls in the opposite order from their database writes, leaving the older value cached. Where concurrent writes are possible, invalidate() and let the next read reload.

Preventing stale write-backs

If request A starts computing a value, request B mutates the underlying data and invalidates, and request A finishes afterwards, request A's stale result is returned to caller A but not written to the cache. The store atomically checks that no parent token changed during the load.

Reclaiming memory with purge()

@app.post("/admin/purge")
async def purge() -> dict[str, int]:
    # Invalidating removes nothing: what is out of date stays in the store until its
    # time is up, and cannot be read. A purge removes it now, for when the room is
    # wanted back.
    return {"removed": await cache.purge()}

purge() invalidates and then incrementally removes keys on a cache, namespace, or entity (using cursor scanning on Redis so the server is never blocked). Because invalidate() already prevents stale reads, purge() is only needed when you want to free store memory before TTL expiry.

On a store that cannot remove values by prefix (MemcachedStore, or a TieredStore over one), purge() invalidates, removes nothing, and returns 0. The cache logs one warning the first time, on the paceapi logger.

How O(1) invalidation works

Each level (cache, namespace, entity, resource) stores a small random generation token. Every cached entry records the tokens active when it was written; reads verify current tokens and treat any mismatch as a miss. Rotating one token invalidates arbitrarily many entries atomically without maintaining key sets.

Durability and consistency caveats

  • Redis failover / snapshot restore: If an asynchronous replica promotes before receiving a token write (or Redis restores an older snapshot), previous tokens can reappear until entries expire. Keep TTLs short for sensitive data.
  • Token eviction under maxmemory: Evicting a token is fail-safe—a new random token is generated on next access, turning old entries into misses rather than stale hits.
  • Process-local stores: MemoryStore invalidations apply only to the current process; TieredStore peer processes may serve L1 copies for up to local_ttl seconds; browser caches respect client_ttl until expiry.

Incident recovery

Call await cache.invalidate() during an incident: one write makes every entry previously cached under this cache's prefix a miss. Call it on an enabled cache, once for each prefix sharing the store: a disabled cache writes nothing to the store. Copies outside the store outlive it (see the caveats above): TieredStore peers serve L1 copies for up to local_ttl seconds, a MemoryStore is invalidated only in the calling process, and browsers reuse responses until client_ttl expires. For normal deployments, use release= isolation instead of invalidating.