Redis Caching Patterns
Caching is the most common use of Redis. A cache keeps a copy of data that is slow or expensive to produce (a database query, an API call, a rendered page) in memory, so the next request gets it in a fraction of a millisecond. The hard parts are not the commands, which are just GET and SET ... EX, but deciding when to fill the cache and when it is wrong.
Cache-aside (lazy loading)
The application owns the logic:
- Try
GETfrom Redis. - On a hit, return the cached value.
- On a miss, load from the database,
SETthe value with a TTL, and return it.
In Redis commands, a miss followed by a hit looks like this:
GET cache:product:42
SET cache:product:42 "{\"name\":\"Mug\",\"price\":8.5}" EX 300
GET cache:product:42
TTL cache:product:42redis> GET cache:product:42
(nil)
redis> SET cache:product:42 "{\"name\":\"Mug\",\"price\":8.5}" EX 300
OK
redis> GET cache:product:42
"{\"name\":\"Mug\",\"price\":8.5}"
redis> TTL cache:product:42
(integer) 300
And here is the whole pattern in Python, with a small in-memory stand-in for Redis and a fake slow database, so we can count hits and misses:
class FakeRedis:
"""Just enough of Redis for this demo: strings with an expiry, on a fake clock."""
def __init__(self):
self.data, self.now = {}, 0
def get(self, key):
value, expires = self.data.get(key, (None, None))
if expires is not None and expires <= self.now:
del self.data[key]
return None
return value
def set(self, key, value, ex):
self.data[key] = (value, self.now + ex)
def delete(self, key):
self.data.pop(key, None)
db_calls = 0
def load_product_from_db(pid):
global db_calls
db_calls += 1
return f"product {pid} (v{db_calls})"
r = FakeRedis()
def get_product(pid):
key = f"cache:product:{pid}"
cached = r.get(key)
if cached is not None:
return cached, "hit"
value = load_product_from_db(pid)
r.set(key, value, ex=300)
return value, "miss"
for t, pid in [(0, 42), (10, 42), (20, 7), (200, 42), (301, 42), (305, 42)]:
r.now = t
value, outcome = get_product(pid)
print(f"t={t:>3}s product {pid:<3} {outcome:<4} {value}")
print("database calls:", db_calls)t= 0s product 42 miss product 42 (v1)
t= 10s product 42 hit product 42 (v1)
t= 20s product 7 miss product 7 (v2)
t=200s product 42 hit product 42 (v1)
t=301s product 42 miss product 42 (v3)
t=305s product 42 hit product 42 (v3)
database calls: 3
At t=301 the 300-second TTL of product 42 had run out, so the next read reloaded it. Six requests cost only three database calls.
Invalidation: when the data changes
A cached value is a copy, and copies go stale. Common strategies:
| Strategy | How | Trade-off |
|---|---|---|
| TTL only | let the entry expire | simple; stale for up to the TTL |
| Delete on write | DEL cache:product:42 after updating the database |
fresh; next read pays the miss |
| Write-through | update the database and SET the cache together |
always warm; extra work on every write |
| Write-behind | write to Redis, flush to the database later | fastest writes; risk of loss |
Delete-on-write plus a TTL as a safety net is the usual default:
SET cache:product:42 "{\"price\":8.5}" EX 300
# ... the price is updated in the database ...
DEL cache:product:42
GET cache:product:42redis> SET cache:product:42 "{\"price\":8.5}" EX 300
OK
redis> DEL cache:product:42
(integer) 1
redis> GET cache:product:42
(nil)
Note: Delete the cache entry after the database write succeeds. Deleting first leaves a window in which another request can read the old value from the database and put it back into the cache.
Cache stampede
When a popular key expires, hundreds of requests may miss at the same moment and all hit the database together. Defences:
- A lock for the rebuild: only the request that wins
SET lock:key 1 NX EX 10reloads; the others wait briefly or serve the stale value. - TTL jitter: add a random few percent to every TTL so keys don't expire together.
- Early refresh: refresh in the background when the remaining TTL gets low.
SET lock:rebuild:product:42 worker-1 NX EX 10
SET lock:rebuild:product:42 worker-2 NX EX 10
SET lock:rebuild:product:42 worker-3 NX EX 10
GET lock:rebuild:product:42redis> SET lock:rebuild:product:42 worker-1 NX EX 10
OK
redis> SET lock:rebuild:product:42 worker-2 NX EX 10
(nil)
redis> SET lock:rebuild:product:42 worker-3 NX EX 10
(nil)
redis> GET lock:rebuild:product:42
"worker-1"
Only worker 1 got the lock; workers 2 and 3 saw (nil) and know someone else is already rebuilding.
Caching "not found"
If many requests ask for something that doesn't exist (a deleted product, a mistyped URL), every one of them misses and queries the database. Cache the absence too, with a short TTL:
SET cache:product:999 "__none__" EX 30
GET cache:product:999redis> SET cache:product:999 "__none__" EX 30
OK
redis> GET cache:product:999
"__none__"
What to cache, and for how long
| Data | Typical TTL |
|---|---|
| Rendered home page, product lists | 30 s – 5 min |
| User profile | 5 – 60 min, delete on update |
| Results of an external API | as long as its terms and freshness allow |
| Configuration, feature flags | minutes, or until a pub/sub "reload" message |
| Exchange rates, weather | as long as the source updates (often 10–60 min) |
Measure the hit ratio (keyspace_hits / (keyspace_hits + keyspace_misses) in INFO stats): a cache that rarely hits only adds latency.
Test yourself
In cache-aside, what does the application do on a cache miss?
- Returns an error
- Loads from the database, stores the value in Redis with a TTL, and returns it
- Waits for Redis to load it
- Deletes the database row
After updating a product in the database, what is a simple way to avoid serving a stale cached copy?
- Restart Redis
- Delete the cache key
- Increase the TTL
- Call PERSIST
What is a cache stampede?
- Too many keys in Redis
- Many requests missing at once and overloading the database when a hot key expires
- A Redis crash
- Keys being evicted by LRU