Skip to content

Quickstart

Cache organizes entries hierarchically so you can read, write, and invalidate values cleanly without key scanning.

Namespaces, entities, and resources

# Default 10-minute TTL for all entries in the "user" namespace.
users = cache.namespace("user", ttl=600)

@app.get("/users/{user_id}")
async def profile(user_id: int) -> object:
    if user_id not in PROFILES:
        raise HTTPException(status_code=404, detail="No such user.")
    # Returns the cached profile or loads and caches it on a miss.
    return await users.entity(user_id).get_or_set("profile", lambda: load_profile(user_id))

@app.put("/users/{user_id}")
async def rename(user_id: int, name: str) -> dict[str, str]:
    PROFILES[user_id] = {"name": name}
    # Invalidates all cached entries for this user in O(1); other users are unaffected.
    await users.entity(user_id).invalidate()
    return PROFILES[user_id]

Full example: examples/cache_basics.py.

Every cache entry is addressed by three levels:

  • Namespace (cache.namespace("user")): a logical category. Calling namespace("user") twice returns handles to the same namespace.
  • Entity (users.entity(42)): an optional entity ID within the namespace. Omit entity() for values that belong to no entity.
  • Resource ("profile"): the specific value name.

get_or_set returns the cached value or runs the loader on a miss and stores its result. Concurrent misses for the same key inside one process share a single loader call.

Calling await users.entity(42).invalidate() invalidates every resource stored for user 42 in O(1) without knowing which keys exist (see Invalidation).

TTLs

Every cached entry requires a TTL (in seconds). Resolution order (most specific wins): call (ttl=60) → namespace → cache. Storing a value with no TTL configured raises an error so entries never live forever by accident.

Pass ttl= to get_or_set to override the namespace's TTL for one value:

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

async def unread_count(user_id: int) -> int:
    # The unread count changes faster than the rest of the namespace, so this call
    # passes a TTL of its own: 30s instead of the namespace's 10 minutes.
    return await users.entity(user_id).get_or_set(
        "unread", lambda: db.unread_count(user_id), ttl=30, type=int
    )

set takes ttl= the same way, for example when the value states how long it is valid:

quotes = cache.namespace("quote", ttl=600)

async def remember(product_id: int, quote: Quote) -> None:
    # The supplier says how long its quote holds, so the price is cached for exactly
    # that long instead of the namespace's 10 minutes.
    await quotes.entity(product_id).set("price", quote.price, ttl=quote.valid_for)

Direct operations

  • await users.entity(42).get("profile", default=None) — fetch an entry or default.
  • await users.entity(42).set("profile", profile) — write or overwrite an entry.
  • await users.entity(42).delete("profile") — delete an entry.

Reads always return deserialized copies, so mutating a returned object never mutates cached state.

Typed values and serializers

By default, values are serialized as JSON. Pass type= to serialize and deserialize rich Python/Pydantic types:

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

@app.get("/users/{user_id}/orders")
async def orders(user_id: int) -> list[Order]:
    # Declared with a type, the orders come back from the cache as orders: a total
    # is a Decimal again and a date a datetime, where plain JSON would give text.
    return await users.entity(user_id).get_or_set(
        "orders", lambda: load_orders(user_id), type=list[Order]
    )

@app.post("/users/{user_id}/orders")
async def place(user_id: int, order: Order) -> list[Order]:
    placed = [*ORDERS.get(user_id, []), order]
    ORDERS[user_id] = placed
    # Kept with the same type that it is got with.
    await users.entity(user_id).set("orders", placed, type=list[Order])
    return placed

Typed serialization uses Pydantic (pydantic>=2.7.0, bundled with FastAPI or via pip install "paceapi[pydantic]"), preserving models, Decimal, datetime, etc. Reads must pass the same type= used on write.

get takes the same type=:

async def cached_orders(user_id: int) -> list[Order] | None:
    # Read with the type the orders were set with: they come back as `Order` models.
    # Read with another type, or with none, they are a miss.
    return await users.entity(user_id).get("orders", type=list[Order])

Pydantic models are automatically fingerprinted by JSON schema—when a model's fields change on deploy, old entries miss instead of failing deserialization (see Deploys and schema changes).

Other serialization options:

  • PickleSerializer: pass on Cache or a namespace for arbitrary picklable Python objects. Security: unpickling executes arbitrary code—only use with a trusted store.
  • Custom Serializer: implement a name and byte encode/decode methods for formats like MessagePack or Protobuf.

A serializer passed to Cache is the default for every namespace:

# The default serializer for every namespace of this cache. Pickle stores sets, tuples
# and class instances as they are: only use it with a store that nothing untrusted
# can write to.
cache = Cache(serializer=PickleSerializer())
permissions = cache.namespace("permissions", ttl=300)

Stores

In-memory (default)

Cache() defaults to process-local memory (LRU-bounded at 10,000 entries). Ideal for development, tests, and single-process apps; not shared across workers.

Redis / Valkey

Use RedisStore (pip install "paceapi[redis]") to share cached values and invalidations across processes:

# The client is yours: create it as you would for anything else, and close it when
# your app shuts down. Nothing connects until the first request.
redis = from_url("redis://localhost:6379")
# The release is whatever names this build of your app: here, a variable your deploy sets.
cache = Cache(RedisStore(redis), release=os.environ.get("RELEASE"), store_timeout=0.25)

See Rate limiting → Stores for shared client ownership, connection-pool queueing, ACLs, and supported Redis/Valkey versions. Cache-specific notes:

  • Round trips: Single-node Redis executes reads and writes in 1 Lua script round trip. Redis Cluster requires additional commands because cache/namespace/entity tokens may live on different hash slots.
  • Pool size: A hit is 1 store call and a stored miss is 2 (a read, then a write). RedisStore runs at most half of the client's max_connections at once, never more than 64, and queues the rest, so size the pool at twice the store calls you expect in flight. redis-py's default of 100 connections allows 50 at once; a pool of 20 allows 10.
  • Sharing a store: One RedisStore instance can be shared across both Limiter and Cache. Give distinct caches different prefix= values if sharing a Redis database.
  • decode_responses=True: Clients created with decode_responses=True support JSON serialization but cannot store binary serializers like PickleSerializer.

MongoDB

Use MongoStore (pip install "paceapi[mongodb]") to share cached values, O(1) invalidations, locks, and prefix purge() across processes using an existing MongoDB database:

# The client is yours: create it as you would for anything else, and close it
# when your app shuts down. Nothing connects until the first request.
client: AsyncMongoClient[dict[str, object]] = AsyncMongoClient("mongodb://localhost:27017")
store = MongoStore(client["myapp"])
limiter = Limiter(store)
cache = Cache(store, ttl=300)

Binary serializers (PickleSerializer, compressed payloads) work natively via BSON, purge() removes entries in batches using an indexed _id range scan, and TTL indexes clean up expired documents automatically.

Memcached

Use MemcachedStore (pip install "paceapi[memcached]") to share cached values, O(1) invalidations, and cross-process locks across processes:

async def make_store(
    host: str = "localhost", port: int = 11211
) -> tuple[emcache.Client, MemcachedStore]:
    # The client is yours: create it at app startup and close it on shutdown.
    # The store runs half of max_connections at once: here 16 calls, 1 by emcache's default.
    client = await emcache.create_client(
        [emcache.MemcachedHostAddress(host, port)], max_connections=32
    )
    return client, MemcachedStore(client)

Because paceapi invalidates via O(1) generation tokens, invalidate() works at every level (cache, namespace, entity, and resource). Memcached cannot enumerate keys by prefix, so purge() invalidates, removes nothing, and returns 0: the values expire by their TTL. The cache logs one warning the first time; call invalidate() instead.

Tiered store (L1 memory + L2 Redis)

Wrap a shared store in TieredStore to cache hot reads in process memory for local_ttl seconds:

# Shared L2 store (use RedisStore(client) in production).
shared = MemoryStore()

# Cache hot reads in process-local L1 memory for 2s to avoid repeated L2 round trips.
# Local writes update L1 immediately; peer worker writes become visible within `local_ttl`.
cache = Cache(TieredStore(shared, local_ttl=2.0))

Writes through the same Cache update L1 immediately. Writes or invalidations from other processes (or another TieredStore instance) may remain stale in L1 for up to local_ttl seconds—use TieredStore for read-heavy, slightly stale-tolerant data, not read-your-writes paths.

Note: L1 expiry uses the process monotonic clock, which pauses when a VM is suspended.

Store errors

  • Reads fail open: On a store read failure or timeout (store_timeout=1.0 default), Cache treats it as a miss and computes the value so requests succeed.
  • Writes and invalidations raise: set, delete, invalidate, and purge propagate store errors so lost invalidations do not silently leave stale data behind.
  • Observability: Failures are rate-limited logged on paceapi and reported to CacheObserver instances passed via Cache(observers=[...]) (see Observability).

An observer implements on_cache and on_cache_error:

class CacheStats:
    """Counts cache outcomes per namespace and logs store failures."""

    def __init__(self) -> None:
        self.outcomes: Counter[tuple[str | None, str]] = Counter()

    def on_cache(self, event: CacheEvent) -> None:
        # Counted per namespace, not per entity: one counter per user would not scale.
        self.outcomes[event.namespace, event.outcome] += 1

    def on_cache_error(self, event: CacheErrorEvent) -> None:
        # `source` is what failed: the store, a serializer or a cached function.
        logger.error(
            "Cache %s failed on %s in %s: %r",
            event.source,
            event.operation,
            event.namespace,
            event.error,
        )

stats = CacheStats()
cache = Cache(store, observers=[stats])

Testing

Disable caching for unrelated tests with cache.disabled() (or Cache(enabled=False)):

def test_a_route_without_its_cache() -> None:
    with basics.cache.disabled(), TestClient(basics.app) as client:
        client.get("/users/1")
        client.get("/users/1")
    assert basics.LOADS[-2:] == [1, 1]  # loaded both times: nothing was kept

Mutations (set, delete, invalidate) called while disabled do not reach the store. The cache records that one happened and, once re-enabled, invalidates everything cached before its next store call, so earlier entries cannot resurface. Other processes sharing the store are not told until then.

To switch caching off for a whole environment, pass enabled= when creating the cache:

cache = Cache(enabled=settings.cache_on)

For deterministic TTL tests, inject FrozenClock:

def test_a_profile_is_loaded_again_when_its_time_is_up() -> None:
    clock = FrozenClock()
    app = basics.create_app(Cache(clock=clock))
    before = len(basics.LOADS)
    with TestClient(app) as client:
        client.get("/users/1")
        clock.advance(599)
        client.get("/users/1")
        assert len(basics.LOADS) == before + 1  # still kept, a second short of ten minutes

        clock.advance(1)
        client.get("/users/1")
        assert len(basics.LOADS) == before + 2