Migrating from aiocache¶
Guide for migrating async caching from aiocache to paceapi.
See Migrating to paceapi for shared defaults (no globals, Redis cutover, fail-open reads).
API mapping¶
aiocache |
paceapi |
|---|---|
caches.set_config(...) / caches.set_default_cache(...) |
cache = Cache(RedisStore(client)) (explicit instance) |
Cache.MEMORY |
Cache() (default MemoryStore) |
Cache.REDIS + endpoint= / port= |
Cache(RedisStore(client)) with your own redis.asyncio client |
@cached(ttl=60, namespace="products", serializer=JsonSerializer()) |
@products.cached("detail", entity="sku", key=("sku",)) |
serializer=PickleSerializer() |
serializer=PickleSerializer() on Cache or Namespace (trusted stores only) |
Custom BaseSerializer |
Serializer protocol |
key_builder= |
entity= + key= (explicit parameter names or key callable) |
plugins=[HitMissRatioPlugin(), TimingPlugin()] |
Cache(observers=[...]) (Observability) |
await cache.get(k) / set(k, v) / delete(k) |
await ns.entity(id).get(r) / set(r, v) / delete(r) (or get_or_set) |
await cache.clear(namespace="products") |
await products.invalidate() (O(1)) |
Migrated app example¶
Namespace setup:
# Replaces `caches.set_config(...)` / `Cache.REDIS` + `JsonSerializer()`.
# Pass `RedisStore(client)` to `Cache(...)` for shared Redis storage.
products = cache.namespace("products", ttl=60)
Typed cached function (preserving Pydantic models and Decimal without pickle):
# Replaces `@cached(ttl=60, namespace="products", serializer=JsonSerializer())`.
# Return annotation preserves Pydantic models and `Decimal` without PickleSerializer.
@products.cached("detail", entity="sku", key=("sku",))
async def get_product(sku: str) -> Product:
return await db.fetch_product(sku)
Direct invalidation by entity or namespace:
# Direct namespace operations replace `cache.get()` / `cache.set()` / `cache.clear()`.
@app.get("/products/{sku}")
async def read_product(sku: str) -> Product:
return await get_product(sku)
@app.put("/products/{sku}")
async def update_price(sku: str, price: Decimal) -> Product:
updated = await db.set_price(sku, price)
await products.entity(sku).invalidate()
return updated
@app.post("/admin/clear")
async def clear_products() -> dict[str, bool]:
await products.invalidate()
return {"cleared": True}
Full example: examples/from_aiocache.py.
Behavioral differences¶
- Typed JSON instead of pickle for rich types:
aiocache'sJsonSerializerreturns plain dicts/strings, pushing users towardPickleSerializerfor models orDecimal.paceapiround-trips Pydantic models,Decimal, and dates safely over JSON with automatic schema fingerprinting. - Single-flight deduplication by default: Concurrent calls for the same uncached key inside a process execute once (in
aiocache, concurrent misses each invoke the function unless you add external locking). Addlock=Truefor best-effort cross-process coordination. - Explicit key arguments: Non-serializable parameters (e.g., DB sessions) raise loudly instead of relying on
str()repr; declarekey=(...)to select key parameters explicitly. - O(1) invalidation:
invalidate()rotates a single generation token instead of scanning/clearing namespace keys. - HTTP response caching included: For FastAPI/Starlette routes,
@ns.responsehandles auth ordering,ETag/304,Cache-Control,Vary, andCache-Statusautomatically. - No
multi_cached: Built-in stores are memory, Redis/Valkey (standalone and cluster), MongoDB, Memcached (MemcachedStore), andTieredStore.