Skip to content

Caching functions

Decorate async functions with @ns.cached to memoize results by arguments with automatic single-flight deduplication and typed deserialization.

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

# Kept for each user and each page. The database is handed in on every call and
# says nothing about what was asked for, so the key names the arguments that do.
@users.cached("orders", entity="user_id", key=("user_id", "page"))
async def load_orders(db: Database, user_id: int, page: int = 1) -> list[Order]:
    return await db.page_of_orders(user_id, page)

# Once this has returned, every page of that user's orders is out of date.
@users.invalidates("orders", entity="user_id")
async def place_order(db: Database, user_id: int, order: Order) -> Order:
    await db.add_order(user_id, order)
    return order

@app.get("/users/{user_id}/orders")
async def orders(user_id: int, page: int = 1) -> list[Order]:
    return await load_orders(db, user_id, page)

@app.post("/users/{user_id}/orders")
async def place(user_id: int, order: Order) -> Order:
    return await place_order(db, user_id, order)

Full example: examples/cache_functions.py.

@ns.cached preserves the function's exact type signature for editors, pyright, mypy, and ty. Concurrent calls for the same uncached key within a process execute the function once.

Cache keys

Arguments are normalized by parameter name with defaults applied, so load_orders(db, 1) and load_orders(db, user_id=1, page=1) produce the same key.

Non-serializable arguments (such as database sessions or HTTP clients) cannot be hashed reliably and raise an error on first call rather than silently producing broken keys. Specify which arguments form the key with key=:

  • Parameter names: key=("user_id", "page")
  • Key function: a callable whose parameters match the decorated function's parameter names by name

Any parameter omitted from key= is excluded from the cache key.

Entity scoping

Pass entity= (a parameter name or a callable over the function's parameters) to associate entries with an entity so users.entity(42).invalidate() invalidates all cached functions for that entity.

If entity= evaluates to None, the cache is bypassed (neither read nor written) so calls without an entity never collide under a placeholder. Omit entity= entirely for global values that belong to no entity.

Return types and strictness

@ns.cached infers the cache type from the function's return annotation (e.g., -> list[Order]). Pass type= to override it, or omit annotations for plain JSON.

For example, when wrapping a client method whose annotation does not name the type:

# The vendor's client does not annotate what `fetch_invoice` returns. `type=` declares
# it, so results are cached and returned as `Invoice` models. Without it they would
# be treated as plain JSON, which cannot store a model.
fetch_invoice = invoices.cached("latest", entity="customer_id", type=Invoice)(
    billing.fetch_invoice
)

Values must match the declared type strictly and round-trip equal to themselves—subclasses, raw dicts where a Pydantic model is declared, or models containing SecretStr raise TypeError rather than silently corrupting cached values.

Decorated functions must be async def; decorating a synchronous function raises an error immediately to avoid blocking the event loop.

Automatic invalidation

Pair @ns.cached with @ns.invalidates on write functions. If the write function raises, nothing is invalidated.

Stampede and background refresh options

@ns.cached supports ttl=, lock=, stale=, and refresh_after=—see Stampedes and stale values.