Python / FastAPI 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"}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
