Python / FastAPI Basics Interview Questions
How do you add caching to FastAPI endpoints to improve performance?
FastAPI has no built-in cache, but several patterns work well: in-process caching with functools.lru_cache / cachetools, Redis-backed caching with fastapi-cache2, and HTTP caching headers for client-side caching.
# Option 1: In-process LRU cache for slow dependencies from functools import lru_cache from fastapi import FastAPI, Depends from typing import Annotated app = FastAPI() @lru_cache(maxsize=128) def get_config_from_db(key: str) -> str: # Called once per unique key, then cached in memory return f"value_for_{key}" @app.get("/config/{key}") def get_config(key: str): return {"value": get_config_from_db(key)}
# Option 2: Redis cache with fastapi-cache2 # pip install fastapi-cache2[redis] from fastapi_cache import FastAPICache from fastapi_cache.backends.redis import RedisBackend from fastapi_cache.decorator import cache from redis import asyncio as aioredis from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): redis = aioredis.from_url("redis://localhost") FastAPICache.init(RedisBackend(redis), prefix="myapp-cache") yield app = FastAPI(lifespan=lifespan) @app.get("/expensive") @cache(expire=60) # cache for 60 seconds in Redis async def expensive_operation(): import asyncio await asyncio.sleep(2) # simulate slow DB query return {"result": "computed"}
# Option 3: HTTP Cache-Control headers from fastapi.responses import Response @app.get("/public-data") def public_data(response: Response): response.headers["Cache-Control"] = "public, max-age=3600" return {"data": "cacheable by CDN and browsers"}
More Related questions...