Multi-tenant SaaS caching¶
This recipe shows how to structure caching for a multi-tenant application:
- Isolate tenant data by
entity="tenant_id"so one tenant can be invalidated in O(1) without affecting others. - Use
release=isolation for tenant data while keeping reference data (plans) persistent across deploys. - Serve expensive dashboard aggregates with
refresh_after=andstale=so requests stay fast, and drain background refresh tasks cleanly on shutdown.
Lifespan and graceful drain¶
Background refreshes triggered by stale= or refresh_after= run after the response returns. Await cache.drain() in your lifespan shutdown hook so in-flight refreshes finish before the process exits:
@asynccontextmanager
async def lifespan(_: FastAPI) -> AsyncGenerator[None]:
yield
await cache.drain()
app = FastAPI(lifespan=lifespan)
Namespaces¶
Separate deploy-scoped tenant data from deploy-persistent reference data:
# Release-isolated tenant data: rolling deploys never mix incompatible formats.
tenants = cache.namespace("tenant", ttl=300)
# Persistent reference data: survives deploys without a cold start.
plans = cache.namespace("plan", ttl=3600, persistent=True)
Cached queries¶
Declare explicit key= arguments and return types. @tenants.cached round-trips Pydantic models and fingerprints their JSON schema automatically:
@tenants.cached("settings", entity="tenant_id", key=("tenant_id",))
async def load_settings(tenant_id: str) -> TenantSettings:
return await db.get_settings(tenant_id)
@tenants.cached(
"dashboard",
entity="tenant_id",
key=("tenant_id", "period"),
ttl=60,
stale=300,
refresh_after=45,
lock=True,
)
async def load_dashboard(tenant_id: str, period: str) -> DashboardSummary:
return await db.compute_dashboard(tenant_id, period)
@plans.cached("details", key=("plan_id",))
async def load_plan(plan_id: str) -> dict[str, object]:
return await db.get_plan(plan_id)
Routes and scoped invalidation¶
Writes invalidate only what changed—a single resource (settings) or every cached value for one tenant (tenants.entity(tenant_id).invalidate()):
@app.get("/tenants/{tenant_id}/settings")
async def get_settings(tenant_id: str) -> TenantSettings:
return await load_settings(tenant_id)
@app.put("/tenants/{tenant_id}/settings")
@tenants.invalidates("settings", entity="tenant_id")
async def update_settings(tenant_id: str, body: TenantSettings) -> TenantSettings:
return await db.save_settings(tenant_id, body)
@app.get("/tenants/{tenant_id}/dashboard")
async def get_dashboard(tenant_id: str, period: str = "7d") -> DashboardSummary:
return await load_dashboard(tenant_id, period)
@app.post("/tenants/{tenant_id}/reset")
async def reset_tenant(tenant_id: str) -> dict[str, str]:
# One constant-time write invalidates both settings and dashboards for this tenant.
await tenants.entity(tenant_id).invalidate()
return {"reset": tenant_id}
@app.get("/plans/{plan_id}")
async def get_plan(plan_id: str) -> dict[str, object]:
return await load_plan(plan_id)
The routes omit authentication to stay on caching. entity= separates cache entries and is not access control: check that the caller may act on tenant_id before reading or writing.
Key details¶
- Background refreshes cannot use request-scoped resources. Functions decorated with
stale=orrefresh_after=may run after the HTTP request finishes, so they must open any DB sessions or clients they need rather than reusing a closed request dependency. lock=Trueis best-effort cross-process coordination. In multi-worker deployments withRedisStore, one worker refreshes while peers wait up tolock_wait(default 5s); if the lock expires (lock_ttl, default 30s) orlock_waitelapses, another worker may also compute the value.- Persistent namespaces survive rolling deploys. When a Pydantic model's schema changes, its fingerprint changes automatically; bump
schema=if the meaning of a field changes without changing its shape.
Full source: examples/multi_tenant_cache.py.