21. Redis Caching & Performance Optimization
Caching is one of the most effective ways to improve API performance. Redis is an in-memory data store that can drastically reduce database load and response times. Frequently accessed data that rarely changes (like user profiles, product catalogs, or configuration) is perfect for caching. To test these examples, install Redis locally or use Docker.
What is Redis?
Redis is an open-source, in-memory key-value store. Because data is stored in RAM rather than on disk, Redis can serve responses in microseconds rather than milliseconds. It supports various data structures including strings, hashes, lists, sets, and sorted sets.
# Run Redis with Docker docker run --name redis -p 6379:6379 -d redis:alpine # Connect to Redis CLI docker exec -it redis redis-cli
import redis redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True) # Test connection try: redis_client.ping() print("Connected to Redis") except redis.ConnectionError: print("Redis connection failed")
Basic Caching Implementation
The most common caching pattern: check cache first, if miss, query database and store result in cache.
from fastapi import FastAPI, Depends import json import hashlib app = FastAPI() redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True) def get_cache_key(prefix: str, identifier: str) -> str: return f"{prefix}:{identifier}" @app.get("/products/{product_id}") async def get_product(product_id: int, db: Session = Depends(get_db)): cache_key = f"product:{product_id}" cached = redis_client.get(cache_key) if cached: return json.loads(cached) product = db.query(Product).filter(Product.id == product_id).first() if not product: raise HTTPException(404, "Product not found") redis_client.setex(cache_key, 3600, json.dumps({"id": product.id, "name": product.name})) return product @app.post("/products/{product_id}") async def update_product(product_id: int, product_data: ProductUpdate, db: Session = Depends(get_db)): product = db.query(Product).filter(Product.id == product_id).first() # update logic here redis_client.delete(f"product:{product_id}") return {"message": "Product updated. Cache invalidated."}
Cache-Aside Pattern
The Cache-Aside pattern is the most common caching strategy. The application is responsible for reading and writing to the cache.
class CacheService: def __init__(self, redis_client, default_ttl=300): self.redis = redis_client self.default_ttl = default_ttl async def get_or_set(self, key: str, fetch_func, ttl: int = None): ttl = ttl or self.default_ttl cached = await self.redis.get(key) if cached: return json.loads(cached) result = await fetch_func() await self.redis.setex(key, ttl, json.dumps(result)) return result async def invalidate(self, key: str): await self.redis.delete(key) async def invalidate_pattern(self, pattern: str): keys = await self.redis.keys(pattern) if keys: await self.redis.delete(*keys) cache_service = CacheService(redis_client, default_ttl=300) @app.get("/users/{user_id}") async def get_user(user_id: int, db: Session = Depends(get_db)): async def fetch_user(): return db.query(User).filter(User.id == user_id).first() return await cache_service.get_or_set(f"user:{user_id}", fetch_user, ttl=600)
Response Caching Middleware
Cache entire HTTP responses based on the request URL.
from fastapi import FastAPI, Request, Response from starlette.middleware.base import BaseHTTPMiddleware import hashlib class RedisCacheMiddleware(BaseHTTPMiddleware): def __init__(self, app, redis_client, ttl=60): super().__init__(app) self.redis = redis_client self.ttl = ttl async def dispatch(self, request: Request, call_next): if request.method != "GET": return await call_next(request) cache_key = hashlib.md5(f"{request.url.path}:{request.query_params}".encode()).hexdigest() cached = await self.redis.get(cache_key) if cached: data = json.loads(cached) return Response(content=data["body"], status_code=data["status_code"], headers=data["headers"]) response = await call_next(request) if response.status_code == 200: response_body = b"" async for chunk in response.body_iterator: response_body += chunk cache_data = { "body": response_body.decode(), "status_code": response.status_code, "headers": dict(response.headers) } await self.redis.setex(cache_key, self.ttl, json.dumps(cache_data)) return Response(content=response_body, status_code=response.status_code, headers=dict(response.headers)) return response app.add_middleware(RedisCacheMiddleware, redis_client=redis_client, ttl=60)
Using Redis for Rate Limiting
Redis is excellent for distributed rate limiting across multiple server instances.
from datetime import datetime class RedisRateLimiter: def __init__(self, redis_client, requests_per_minute=60): self.redis = redis_client self.requests_per_minute = requests_per_minute async def is_allowed(self, client_id: str) -> bool: key = f"rate_limit:{client_id}:{datetime.now().strftime('%Y%m%d%H%M')}" current = await self.redis.incr(key) if current == 1: await self.redis.expire(key, 60) return current <= self.requests_per_minute rate_limiter = RedisRateLimiter(redis_client) @app.middleware("http") async def rate_limit_middleware(request: Request, call_next): client_ip = request.client.host if not await rate_limiter.is_allowed(client_ip): raise HTTPException(429, "Rate limit exceeded") return await call_next(request)
Session Storage with Redis
Store user sessions in Redis for fast, distributed session management.
import uuid from datetime import datetime class SessionManager: def __init__(self, redis_client, session_ttl=86400): self.redis = redis_client self.session_ttl = session_ttl async def create_session(self, user_id: int, user_data: dict) -> str: session_id = str(uuid.uuid4()) session_key = f"session:{session_id}" session_data = { "user_id": user_id, "user_data": json.dumps(user_data), "created_at": datetime.now().isoformat() } await self.redis.hset(session_key, mapping=session_data) await self.redis.expire(session_key, self.session_ttl) return session_id async def get_session(self, session_id: str) -> dict: session_key = f"session:{session_id}" data = await self.redis.hgetall(session_key) if not data: return None return { "user_id": int(data["user_id"]), "user_data": json.loads(data["user_data"]), "created_at": data["created_at"] } async def delete_session(self, session_id: str): await self.redis.delete(f"session:{session_id}") session_manager = SessionManager(redis_client)
pip install redis. Run Redis with Docker as shown above.Knowledge Check
Ready to test your understanding of 21. Redis Caching & Performance Optimization?