
When an API starts getting real traffic, database performance often becomes one of the first things developers notice.
A route that works perfectly with a few users may become slow when hundreds of requests start hitting it at the same time. The database receives repeated queries, connection usage increases, and response times begin to climb.
Imagine an application that displays product details. Every time a user opens a product page, the API fetches the same product information from PostgreSQL. If thousands of users request that product, the database may execute the same query thousands of times.
Most of those requests do not need fresh database data every single time.
This is where Redis caching becomes useful.
Redis allows us to store frequently accessed data in memory and return it quickly without repeatedly querying the database. But adding Redis to FastAPI is not just about storing a value and reading it back. A production-grade caching strategy also needs to handle cache expiration, stale data, cache invalidation, failures, and concurrent requests.
In this article, we’ll build a practical Redis caching approach for FastAPI and discuss the decisions that matter when deploying it to production.
What Is Redis Caching?
Redis is an in-memory data store that supports different data structures, including strings, hashes, lists, sets, and sorted sets.
For caching, we commonly store data using a key-value pattern.
For example:
Key: product:101
Value: {"id": 101, "name": "Laptop", "price": 60000}When a client requests product 101, the application first checks Redis.
If the data exists, Redis returns it. This is called a cache hit.
If the data does not exist, the application fetches it from the database. This is called a cache miss.
The application can then store the database result in Redis so that future requests can use it.
This pattern is known as cache-aside or lazy loading.
Why Use Redis with FastAPI?
FastAPI is an asynchronous Python framework, and Redis can work well alongside it when we use an asynchronous Redis client.
Caching can help with:
Reducing repeated database queries
Improving API response times
Reducing database load
Handling frequently accessed data
Reducing the cost of expensive computations
Improving resilience during traffic spikes
For example, consider an API that calculates product recommendations. If the calculation takes 300 milliseconds and the result can safely be reused for a short period, caching may save significant processing time.
However, caching is not automatically beneficial for every endpoint.
If an endpoint returns data that changes constantly, or if the cached value is expensive to serialize and rarely reused, caching may add complexity without delivering much value.
The first step is to identify the routes that actually benefit from caching.
1. Set Up Redis and FastAPI
For this example, we’ll use:
FastAPI
Redis
redis-pywith asyncio supportUvicorn
Install the dependencies:
python -m pip install fastapi uvicorn redisThe redis package includes an asynchronous client through redis.asyncio.
For local development, you can run Redis using Docker:
docker run --name fastapi-redis \
-p 6379:6379 \
-d redis:7Check whether Redis is running:
docker exec -it fastapi-redis redis-cli pingExpected output:
PONGFor production, Redis should be configured with suitable authentication, network restrictions, persistence or managed-service settings, and resource limits. Avoid exposing Redis directly to the public internet.
2. Create a Redis Connection for FastAPI
A Redis client should be created once per application process and reused.
Creating a new Redis connection for every request is not a good approach. It adds unnecessary connection overhead and makes resource management harder.
FastAPI's lifespan mechanism is a convenient place to create and close shared application resources.
Create a file called main.py:
from contextlib import asynccontextmanager
from fastapi import FastAPI
from redis.asyncio import Redis
@asynccontextmanager
async def lifespan(app: FastAPI):
redis_client = Redis.from_url(
"redis://localhost:6379",
decode_responses=True,
)
app.state.redis = redis_client
try:
yield
finally:
await redis_client.aclose()
app = FastAPI(lifespan=lifespan)
@app.get("/")
async def home():
return {"message": "FastAPI with Redis"}Let's understand the important parts.
Redis.from_url() creates a Redis client using the connection URL.
decode_responses=True tells the client to return strings instead of raw bytes. This is convenient when working with JSON data.
The Redis client is stored in:
app.state.redisThis allows routes and dependencies to access the same client.
The finally block closes the client when the application shuts down.
Run the application:
uvicorn main:app --reloadFor a production deployment, use a Redis URL supplied through environment variables or a secret-management system rather than hardcoding credentials or connection details.
3. Build a Simple Cache-Aside Function
Let's start with a basic example.
Imagine a product API that fetches product information from a database.
The simplified flow looks like this:
Client request
|
v
Check Redis cache
|
+---- Cache hit ----> Return cached data
|
+---- Cache miss ---> Query database
|
v
Store in Redis
|
v
Return responseWe can implement this approach directly in a FastAPI route.
import json
from fastapi import Request
@app.get("/products/{product_id}")
async def get_product(product_id: int, request: Request):
redis_client = request.app.state.redis
cache_key = f"product:{product_id}"
cached_product = await redis_client.get(cache_key)
if cached_product:
return json.loads(cached_product)
# Replace this with a real database query.
product = {
"id": product_id,
"name": "Laptop",
"price": 60000,
}
await redis_client.set(
cache_key,
json.dumps(product),
ex=300,
)
return productHere, ex=300 sets the expiration time to 300 seconds, or five minutes.
After five minutes, Redis automatically removes the key unless it has been refreshed.
This is a basic implementation, but there are a few things worth improving before using it in production.
For example:
What happens if Redis is unavailable?
What if two requests miss the cache at the same time?
How do we avoid caching invalid data?
How do we invalidate the cache after an update?
Let's address these concerns one by one.
4. Use a Reusable Cache Helper
Writing Redis logic inside every route quickly becomes repetitive.
A reusable helper makes the caching behavior easier to maintain.
import json
from typing import Any
from redis.asyncio import Redis
async def get_cached_json(
redis_client: Redis,
key: str,
) -> Any | None:
cached_value = await redis_client.get(key)
if cached_value is None:
return None
return json.loads(cached_value)
async def set_cached_json(
redis_client: Redis,
key: str,
value: Any,
ttl: int = 300,
) -> None:
serialized_value = json.dumps(value)
await redis_client.set(
key,
serialized_value,
ex=ttl,
)Now a route can use the helper:
from fastapi import Request
@app.get("/products/{product_id}")
async def get_product(product_id: int, request: Request):
redis_client = request.app.state.redis
cache_key = f"product:{product_id}"
cached_product = await get_cached_json(
redis_client,
cache_key,
)
if cached_product is not None:
return cached_product
product = {
"id": product_id,
"name": "Laptop",
"price": 60000,
}
await set_cached_json(
redis_client,
cache_key,
product,
ttl=300,
)
return productNotice that we check:
if cached_product is not None:rather than:
if cached_product:This distinction matters because an empty dictionary or an empty list can be a valid cached result.
Checking for None allows us to distinguish a missing cache entry from a valid but empty result.
5. Choose the Right Cache Key
Cache keys are easy to overlook, but they are an important part of the design.
A cache key should identify the exact data being cached.
For a product:
product:101For a user:
user:42For a product list:
products:category:electronics:page:1For a search query:
products:search:laptop:page:1If the response depends on multiple parameters, those parameters should be represented in the key.
For example, consider a product listing API:
@app.get("/products")
async def list_products(
category: str,
page: int = 1,
):
...A cache key that only uses the category could return the wrong page.
Instead, use:
cache_key = f"products:category:{category}:page:{page}"In a more complex application, the key might also need to include:
Sort order
Filters
Language
Tenant ID
User permissions
API version
If the response is user-specific, failing to include the relevant user or tenant context can become a data-isolation problem.
Never cache private data under a shared key if different users are supposed to receive different responses.
6. Cache Invalidation: The Difficult Part
Caching data is usually easy. Keeping it correct is harder.
Suppose a product is cached for five minutes. A user updates the product price from ₹60,000 to ₹55,000.
The database now contains the new price, but Redis may still contain the old one.
There are two common approaches.
Approach A: Delete the cache after updating the database
This is a common cache-aside strategy.
@app.put("/products/{product_id}")
async def update_product(
product_id: int,
request: Request,
):
redis_client = request.app.state.redis
# Update the product in the database here.
await redis_client.delete(
f"product:{product_id}"
)
return {
"message": "Product updated"
}The next request will miss the cache and fetch the updated data from the database.
The database update should happen before the cache is deleted. Otherwise, a request could refill the cache with the old database value during the update process.
For systems with strict consistency requirements, this simple ordering may still not be sufficient. More advanced approaches may be needed.
Approach B: Use a short TTL
Sometimes the application can tolerate data being slightly stale.
For example, a product catalog might use a five-minute TTL, while account balances or payment statuses should not be treated the same way.
A TTL is useful because it provides a natural limit on how long cached data can remain available.
But remember: a TTL is not a replacement for invalidation when an update must become visible immediately.
7. Avoid the Cache Stampede Problem
A cache stampede happens when a popular cache entry expires and many requests try to rebuild it at the same time.
Imagine a product page receives 500 requests per second.
The cached entry expires.
All 500 requests see a cache miss and query the database.
Instead of reducing database load, the cache expiration creates a sudden spike.
One way to reduce this problem is to use a lock so that only one request rebuilds the cache while other requests wait briefly or use a fallback.
Redis supports locks, but they need to be used carefully. Lock expiration, ownership, and failure handling all matter.
Here is a simplified example using a Redis lock:
import asyncio
async def load_product_with_lock(
redis_client,
product_id: int,
):
cache_key = f"product:{product_id}"
lock_key = f"lock:{cache_key}"
cached = await redis_client.get(cache_key)
if cached is not None:
return json.loads(cached)
async with redis_client.lock(
lock_key,
timeout=10,
blocking_timeout=2,
):
# Check again after acquiring the lock.
cached = await redis_client.get(cache_key)
if cached is not None:
return json.loads(cached)
# Replace this with a real database call.
product = {
"id": product_id,
"name": "Laptop",
"price": 60000,
}
await redis_client.set(
cache_key,
json.dumps(product),
ex=300,
)
return productThe second cache check is important. Another request may have already populated the cache while this request was waiting for the lock.
This example is intentionally simplified. In production, you should also consider what happens when the lock cannot be acquired, how long the database operation may take, and whether stale data can be served while rebuilding the cache.
8. Handle Redis Failures Gracefully
Redis is an additional dependency. It can become unavailable because of network problems, restarts, maintenance, or resource exhaustion.
A cache failure should not necessarily make the entire API unavailable.
For many cache-aside applications, the database can still serve the request when Redis is down.
A simple approach is to catch Redis errors around cache operations:
from redis.exceptions import RedisError
@app.get("/products/{product_id}")
async def get_product(
product_id: int,
request: Request,
):
redis_client = request.app.state.redis
cache_key = f"product:{product_id}"
try:
cached_product = await redis_client.get(cache_key)
if cached_product is not None:
return json.loads(cached_product)
except RedisError:
cached_product = None
# Replace this with a real database query.
product = {
"id": product_id,
"name": "Laptop",
"price": 60000,
}
try:
await redis_client.set(
cache_key,
json.dumps(product),
ex=300,
)
except RedisError:
# The API can still return the database result.
pass
return productThis is a cache-fallback strategy: Redis improves performance when available, but the database remains the source of truth.
However, this should not be applied blindly.
If Redis is being used for sessions, distributed locks, rate limiting, or other critical application state, falling back may not be safe. The correct behavior depends on what Redis is responsible for.
Also, avoid silently ignoring every error in a real production system. Log cache failures and monitor them so that repeated Redis problems do not go unnoticed.
9. Add Timeouts and Connection Pooling
Production applications should avoid waiting indefinitely for Redis.
A Redis client can be configured with connection and operation timeouts.
from redis.asyncio import Redis
redis_client = Redis.from_url(
"redis://localhost:6379",
decode_responses=True,
socket_connect_timeout=2,
socket_timeout=2,
health_check_interval=30,
)The exact timeout values should be based on your environment and latency requirements.
A timeout that is too high can cause requests to wait longer than necessary. A timeout that is too low may create avoidable failures during temporary network delays.
The Redis client manages connections and uses connection pooling internally. Reusing one client per application process is generally preferable to creating a new client for every request.
If you run multiple Uvicorn worker processes, each process will have its own Redis client and connection pool. Plan your connection limits accordingly.
10. Monitor Cache Performance
Once caching is deployed, you need to understand whether it is actually helping.
A few useful metrics include:
Cache hit rate
Cache miss rate
Redis request latency
Redis connection errors
Number of keys
Memory usage
Evictions
Database query volume
A cache hit rate can be calculated as:
[
\text{Cache Hit Rate} =
\frac{\text{Cache Hits}}
{\text{Cache Hits} + \text{Cache Misses}}
\times 100
]
For example, if 800 requests hit the cache and 200 miss it:
[
\frac{800}{800+200}\times100 = 80%
]
An 80% hit rate means most requests are being served from the cache. But a high hit rate does not automatically mean the application is fast. You should also measure response latency and database performance.
A cache that serves the wrong data quickly is not a successful cache.
11. Production Checklist
Before deploying Redis caching with FastAPI, review the following:
Use a shared Redis client instead of creating a client per request.
Keep Redis credentials in environment variables or a secret manager.
Use cache keys that include all relevant request parameters.
Set a TTL for cached values.
Decide how cache invalidation should work.
Avoid caching sensitive or user-specific data under shared keys.
Handle Redis failures according to the role Redis plays in the application.
Configure timeouts and connection limits.
Monitor cache hits, misses, latency, memory, and errors.
Test behavior when Redis is unavailable.
Consider cache stampedes for popular keys.
Avoid caching data that changes too frequently to provide meaningful benefit.
Conclusion
Redis caching can make a FastAPI application faster and reduce pressure on the database, but the implementation needs more thought than simply calling set() and get().
A reliable caching strategy starts with identifying data that is frequently requested and safe to reuse. From there, you need clear cache keys, sensible TTL values, invalidation rules, and a plan for handling Redis failures.
For many APIs, the cache-aside pattern is a good starting point. The application checks Redis first, loads data from the database on a miss, and stores the result for future requests.
As traffic grows, additional techniques such as distributed locks, stale-while-revalidate behavior, and monitoring can help keep the system stable.
The most important lesson is this: Redis should improve your application's performance without becoming a hidden source of incorrect data or unexpected failures.
Start with one endpoint, measure the improvement, and expand the caching strategy only when the results justify the extra complexity.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


