Skip to content

Lesson 18 of 59Data and storage

Redis and Caching

Use Redis from FastAPI for cache-aside with TTLs, invalidation, rate limiting and sessions, and know when caching makes things worse.

17 min read0/4 questions

Your product page runs the same three queries thousands of times a minute, and the answer only changes when someone edits the product. Every one of those requests waits on Postgres and adds load to it. A cache keeps a copy of a recent answer somewhere much faster, so most requests never reach the database. Redis is the tool almost every Python team uses for this, and also for rate limits, sessions and short-lived shared state. This lesson covers the patterns and the traps, because a wrong cache is worse than a slow one.

What Redis is

Redis is an in-memory data store. It keeps everything in RAM, so reads and writes typically take well under a millisecond, and it runs as a separate server that all your API workers share. You talk to it with simple commands. It is not just a dictionary of strings: it has real data structures, each with its own commands.

TypeExample commandTypical use
StringSET product:42 "{...}" EX 300Cached JSON, counters with INCR
HashHSET session:ab12 user_id 7 role adminAn object with fields, like a session
ListLPUSH jobs "..."Simple queues
SetSADD online_users 7Unique members, membership checks
Sorted setZADD leaderboard 1500 "ada"Rankings, scores, time-ordered items

Every key can have a TTL (time to live): Redis deletes it automatically when it expires. Redis can save snapshots to disk, but treat it as a place for data you can afford to lose or rebuild. Your source of truth stays in Postgres. (Valkey is a compatible open-source fork, and the same client code works with it.)

Run one locally with docker run --name redis -d -p 6379:6379 redis, and poke at it with docker exec -it redis redis-cli.

Cache-aside

The most common caching pattern is cache-aside (also called lazy loading): the app checks the cache first, and only on a miss does it load from the database and store the result for next time.

Cache-aside on a product page
ClientClientFastAPIFastAPIRedis: product:42, TTL 300sRedisproduct:42, TTL 300sPostgreSQL: source of truthPostgreSQLsource of truthGET /products/42GET keySELECT on miss

A request arrives for product 42.

1/4

Here is the logic of a cache with both a TTL and a size limit. Real Redis evicts keys under memory pressure using a policy you configure, and least-recently-used (LRU) is a common choice. This version uses a fake clock so you can watch keys expire:

Pythonlru_ttl_cache.py
from collections import OrderedDict class Cache: def __init__(self, max_items, now): self.max_items = max_items self.now = now # a function that returns the current time self.data = OrderedDict() # key -> (value, expires_at) self.hits = self.misses = 0 def get(self, key): item = self.data.get(key) if item is None or item[1] <= self.now(): self.data.pop(key, None) # expired keys are removed on read self.misses += 1 return None self.data.move_to_end(key) # mark as recently used self.hits += 1 return item[0] def set(self, key, value, ttl): self.data[key] = (value, self.now() + ttl) self.data.move_to_end(key) if len(self.data) > self.max_items: evicted, _ = self.data.popitem(last=False) # least recently used print(f"evicted {evicted}") clock = [0]cache = Cache(max_items=2, now=lambda: clock[0])db_queries = 0 def get_product(pid): global db_queries key = f"product:{pid}" value = cache.get(key) if value is None: db_queries += 1 value = {"id": pid, "name": f"Product {pid}"} cache.set(key, value, ttl=300) return value for t, pid in [(0, 1), (1, 1), (2, 2), (3, 1), (4, 3), (5, 2), (400, 1)]: clock[0] = t get_product(pid) print(f"t={t:>3} product {pid}: keys={list(cache.data)}") print(f"hits={cache.hits} misses={cache.misses} db_queries={db_queries}")
Output
Press Run (⌘ Enter) to see what happens.

Product 2 was evicted at t=4 because product 1 had been used more recently. At t=400 everything had expired, so product 1 was a miss again. The expired product:2 still sits in the dict because this toy only removes expired keys when they are read or evicted; Redis also cleans them up in the background.

Predict the outputPython

Using the Cache class above, what does this print?

clock = [0]
c = Cache(max_items=2, now=lambda: clock[0])
c.set("a", 1, ttl=10)
c.set("b", 2, ttl=10)
c.get("a")
c.set("c", 3, ttl=10)
print(sorted(c.data))
Need a nudge? Hints walk you through it.

Redis in FastAPI

Use the async client, redis.asyncio, from async def routes. Create one client when the app starts (it holds a connection pool) and close it on shutdown with a lifespan handler:

app/main.py
from contextlib import asynccontextmanager
from typing import Annotated
 
import redis.asyncio as redis
from fastapi import Depends, FastAPI, Request
 
 
@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.redis = redis.Redis.from_url(settings.redis_url, decode_responses=True)
    yield
    await app.state.redis.aclose()
 
 
app = FastAPI(lifespan=lifespan)
 
 
def get_redis(request: Request) -> redis.Redis:
    return request.app.state.redis
 
 
RedisDep = Annotated[redis.Redis, Depends(get_redis)]
app/api/products.py
CACHE_TTL = 300
 
 
@router.get("/products/{product_id}")
async def get_product(product_id: int, r: RedisDep, db: DB) -> ProductRead:
    key = f"shop:v1:product:{product_id}"
    if cached := await r.get(key):
        return ProductRead.model_validate_json(cached)
 
    product = await load_product(db, product_id)        # raises 404 if missing
    body = ProductRead.model_validate(product)
    await r.set(key, body.model_dump_json(), ex=CACHE_TTL)
    return body

decode_responses=True gives you str back instead of bytes. ex=300 sets the TTL in seconds. In tests, swap get_redis with app.dependency_overrides for a fake.

Key naming matters more than it looks. Use a colon-separated pattern like app:version:entity:id. The app prefix stops two services sharing a Redis from colliding. The version (v1) lets you invalidate every key at once after a deploy changes the cached shape: bump it to v2 and the old keys simply expire.

Invalidation

There is an old joke that the two hard problems in computer science are naming things, cache invalidation and off-by-one errors. When the product changes, the cached copy is wrong. Your options:

  • Short TTL only. Accept data up to N seconds stale. Simple, and fine for many pages.
  • Delete on write. After the update commits, await r.delete(key). The next read repopulates it. Delete rather than overwrite, so two concurrent writers cannot leave an older value behind.
  • Both. Delete on write for freshness and keep a TTL as a safety net for the write path you forgot.

A subtle trap is the stampede: a popular key expires and hundreds of requests miss at the same moment, all hitting the database. Fixes include adding random jitter to TTLs so keys do not expire together, and letting only one request rebuild the value while others wait or serve the old copy.

Quick check
A product update commits to Postgres. What should the API do with the cached shop:v1:product:42?
Need a nudge? A hint rules out a wrong answer.

Rate limiting with counters

INCR is atomic: even with 50 workers hitting it at once, every call gets a unique, increasing number. That makes a fixed-window rate limiter a few lines:

app/deps.py
import time
 
from fastapi import HTTPException, Request
 
 
async def rate_limit(request: Request, r: RedisDep) -> None:
    window = int(time.time() // 60)                           # the current minute
    key = f"shop:rl:{request.client.host}:{window}"
    count, _ = await r.pipeline(transaction=True).incr(key).expire(key, 60).execute()
    if count > 100:
        raise HTTPException(status_code=429, detail="Too many requests")

The pipeline sends both commands in one round trip, inside a transaction, so a key can never be left without its expiry. Attach it with dependencies=[Depends(rate_limit)]. A fixed window allows a burst at the boundary between two minutes. Sliding windows (using a sorted set of timestamps) or token buckets smooth that out, and libraries exist for both.

Sessions and pub/sub

Sessions are a natural fit: generate a random session id, store session:<id> as a hash with a TTL of, say, a week, and send the id in an HttpOnly cookie. Logging out is DEL, which is something stateless JWTs cannot do easily.

Pub/sub lets processes broadcast messages: one process runs PUBLISH chat:room1 "hi" and every process subscribed to chat:room1 receives it instantly. Messages are fire-and-forget: a subscriber that is offline misses them. It is perfect for telling every web worker "push this to your WebSockets", which you will do in the WebSockets lesson. For durable messages, use Redis Streams or a real queue.

When Redis is down

Redis is fast, but it is still a network service, and it will restart, fail over or hit its memory limit at some point. Decide in advance what your API does then. For a cache, the answer is usually to fail open: wrap the cache calls, log the error, and fall back to the database, so users get a slower page instead of a 500. Give the client short timeouts (socket_timeout and socket_connect_timeout on the connection) so a hung Redis costs milliseconds, not the whole request budget. For a rate limiter you have to choose: failing open lets traffic through unlimited, failing closed blocks everyone. Most teams fail open and alert.

Also set a memory limit and an eviction policy on the server. With maxmemory-policy allkeys-lru, Redis evicts the least recently used keys when it is full, which is exactly what a cache wants. The default on many installs is noeviction, which makes writes fail once memory is full. Managed Redis services expose both settings.

When not to cache

Caching adds a second copy of your data, and with it a new class of bugs. Skip it when:

  • The query is already fast. Fix the index first. A cache on top of a missing index hides the problem until the cache is cold.
  • The data must be exactly current, like account balances or stock at checkout.
  • The hit rate will be low: highly personalised responses or rarely repeated searches only add a network hop.
  • You cache per user but key globally. Caching /me under a key without the user id shows one person's data to everyone. Every input that changes the response must be in the key.

Measure the hit rate after adding a cache. If it is not high, the cache is costing you more than it saves.

Match the pairs0/5 matched

Match each need to the Redis feature.

Choose an item, then its match on the other side.
Quick check
Which of these is the worst candidate for caching?
Need a nudge? A hint rules out a wrong answer.
Key terms
Redis
An in-memory data store with strings, hashes, lists, sets and sorted sets, shared by all your workers.
TTL
Time to live: how long a key exists before Redis deletes it automatically.
cache-aside
Read the cache first; on a miss, load from the database and store the result with a TTL.
cache invalidation
Removing or updating cached data when the source changes, usually by deleting the key after a commit.
LRU eviction
When memory is full, remove the key that was used least recently.
cache stampede
Many requests miss the same expired key at once and overload the database.
pub/sub
Publish a message to a channel and every current subscriber receives it. Not stored for offline subscribers.