← Back to Home

⚡ Caching Patterns and Redis

Hit ratios under real traffic skew, eviction policies, cache-aside and friends, and four failure modes reproduced: stampedes, stale-data races, synchronised expiry and cache penetration.

A cache is a bet that you'll ask the same question again soon, and that a slightly old answer is good enough. When the bet pays off, a cache cuts latency and protects your database. When it doesn't, it adds a component that can serve wrong data, fall over all at once, or take the database down with it.

This article covers where caches go, how much they help, which eviction policy to use, and the four failure modes every team meets eventually: stampedes, stale data races, synchronised expiry and cache penetration. Each one is measured or reproduced, with PostgreSQL 16 as the database and a Redis protocol server as the cache.

A note on the setup: the Redis server here is fakeredis running as a TCP server, a Python implementation of the Redis protocol, because a real Redis binary wasn't available in the lab. The behaviour of every pattern (commands, Lua scripts, expiry, locking) is the same, and database query counts are exact. Absolute latencies are not: fakeredis adds about 30 ms under 200 concurrent clients where real Redis would add well under a millisecond. The latency tables include a baseline row so you can see that overhead.

Where Caches Live

There's a cache at almost every layer between a user and your data:

Layer Examples Typical hit latency
Browser HTTP cache, Cache-Control, service workers 0 (no request)
CDN / edge Cloudflare, CloudFront, Fastly 5 to 30 ms (nearby)
Reverse proxy nginx proxy_cache, Varnish under 1 ms + network
Application, in process A dictionary or LRU map in your service under 1 µs
Application, shared Redis, Memcached, Valkey 0.2 to 1 ms over the network
Database Buffer pool, query plan cache Covered in #0027

This article is about the application layer: a shared cache like Redis in front of a database, plus the in-process option. The patterns apply to the others too.

How Much Can a Cache Help?

The hit ratio (the share of requests answered from the cache) decides everything. If a cache hit costs 0.5 ms and a database query 20 ms, the average cost per request is:

hit ratio 50%:  0.5 × 0.5 + 0.5 × 20.5 = 10.5 ms   (database still gets half the traffic)
hit ratio 90%:  0.9 × 0.5 + 0.1 × 20.5 =  2.5 ms   (database load ÷ 10)
hit ratio 99%:  0.99 × 0.5 + 0.01 × 20.5 = 0.7 ms  (database load ÷ 100)

Notice the miss path costs more than having no cache: a lookup that fails, then the query. And the gap between 90% and 99% is a factor of ten in database load. Small changes in hit ratio matter a lot.

What hit ratio you get depends on how skewed your traffic is and how much you can cache. Real traffic usually follows a power law (Zipf distribution): a few keys are very popular, and a long tail is rarely requested. The exponent s says how skewed it is; web content is often around 0.8 to 1.2.

Simulating 1 million requests over 100,000 keys, with four eviction policies:

Zipf s=0.8: 100,000 keys, 1,000,000 requests
  cache size (% of keys) |   LRU  | sampled LRU (5) |   LFU  | random
     0.1% (   100 keys)   |   6.8% |       6.7%      |  15.8% |   5.8%
       1% (  1000 keys)   |  20.4% |      20.2%      |  30.2% |  17.9%
       5% (  5000 keys)   |  36.9% |      36.5%      |  45.3% |  33.3%
      10% ( 10000 keys)   |  46.7% |      46.3%      |  53.8% |  42.8%
      25% ( 25000 keys)   |  63.2% |      62.7%      |  67.3% |  59.2%

Zipf s=1.0: 100,000 keys, 1,000,000 requests
  cache size (% of keys) |   LRU  | sampled LRU (5) |   LFU  | random
     0.1% (   100 keys)   |  29.0% |      28.6%      |  40.5% |  25.1%
       1% (  1000 keys)   |  50.6% |      50.2%      |  59.3% |  46.5%
       5% (  5000 keys)   |  66.5% |      66.1%      |  72.0% |  62.7%
      10% ( 10000 keys)   |  73.5% |      73.1%      |  77.5% |  70.1%
      25% ( 25000 keys)   |  82.9% |      82.6%      |  84.7% |  80.3%

Zipf s=1.2: 100,000 keys, 1,000,000 requests
  cache size (% of keys) |   LRU  | sampled LRU (5) |   LFU  | random
     0.1% (   100 keys)   |  60.6% |      60.1%      |  69.1% |  55.4%
       1% (  1000 keys)   |  79.5% |      79.2%      |  84.0% |  76.3%
       5% (  5000 keys)   |  88.5% |      88.3%      |  90.4% |  86.4%
      10% ( 10000 keys)   |  91.4% |      91.3%      |  92.5% |  89.9%
      25% ( 25000 keys)   |  94.5% |      94.4%      |  94.6% |  93.8%

What this shows:

Try it with your own numbers. The simulation runs 60,000 requests over 10,000 keys in your browser:

The Four Ways to Use a Cache

Pattern Read path Write path Use when
Cache-aside (lazy loading) App checks cache; on a miss, reads the DB and fills the cache App writes the DB, then deletes the cache entry The default. Simple; the cache only holds what's been asked for.
Read-through Cache library loads from the DB itself on a miss Same as cache-aside You want loading logic in one place (a caching library, or a CDN in front of an origin).
Write-through Reads always hit a warm cache App writes cache and DB together, synchronously Data is read right after being written; you can afford slower writes.
Write-behind (write-back) Same as write-through App writes the cache; the DB is updated later, asynchronously Very high write rates (counters, metrics). You accept possible data loss if the cache dies.

Cache-aside in Python with Redis is a few lines:

def naive(key, ttl=60):
    v = r.get(key)
    if v is not None: return json.loads(v)
    v = load_from_db(key)                     # every request that misses goes to the database
    r.set(key, json.dumps(v), ex=ttl)
    return v

It works well until the moment a popular entry expires.

Failure 1: The Stampede

A hot key expires. In the next few milliseconds, every request for it misses, and every one of them runs the same expensive query. This is a cache stampede (also called dog-piling or a thundering herd).

To measure it, 200 threads request the same key at the same instant. The database query takes 100 ms, and the application has a pool of 20 database connections:

baseline: all hits       DB queries:   0 | latency p50   30.1 ms  p99   64.4 ms  max   68.3 ms
naive cache-aside        DB queries: 200 | latency p50  594.7 ms  p99 1040.0 ms  max 1046.1 ms
lock (SET NX)            DB queries:   2 | latency p50  196.8 ms  p99  302.0 ms  max  321.1 ms
lock + re-check          DB queries:   1 | latency p50  274.6 ms  p99  366.9 ms  max  388.3 ms
stale-while-revalidate   DB queries:   1 | latency p50   76.6 ms  p99  112.6 ms  max  117.9 ms

(Three runs gave the same query counts every time; latencies varied by about ±50 ms. The baseline row is the cost of 200 concurrent requests to the fakeredis server when every request hits.)

Naive cache-aside sent all 200 requests to the database. With 20 connections, that's 10 waves of 100 ms, so the unluckiest request waited over a second, for data that had been in the cache a moment earlier. In production the database also serves everything else, so a stampede on one hot key slows the entire application. And if the slowdown makes requests time out and retry, the load gets worse, not better.

Fix 1: Let one request rebuild

Take a short lock in Redis. The request that gets it rebuilds the entry; the others wait briefly and check the cache again:

def with_lock(key, ttl=60, lock_ms=5000):
    while True:
        v = r.get(key)
        if v is not None: return json.loads(v)
        token = uuid.uuid4().hex
        if r.set(f"lock:{key}", token, nx=True, px=lock_ms):      # only one request rebuilds
            try:
                v = load_from_db(key); r.set(key, json.dumps(v), ex=ttl); return v
            finally:
                # release only our own lock (it may have expired and been taken by someone else)
                r.eval("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) end return 0", 1, f"lock:{key}", token)
        time.sleep(0.01)                                           # others wait briefly and re-check

That cut 200 queries to 2, not 1. Why two? A request read the cache (empty) just before the first rebuild finished, then tried the lock just after it had been released, got it, and rebuilt again. The fix is the same double-checked pattern used for lazy initialisation in concurrent code: check the cache again after taking the lock.

        if r.set(f"lock:{key}", token, nx=True, px=lock_ms):
            try:
                v = r.get(key)                                     # re-check: someone may have just rebuilt it
                if v is not None: return json.loads(v)
                v = load_from_db(key); r.set(key, json.dumps(v), ex=ttl); return v

One query. The other details in that function matter too:

Inside a single process you can get the same effect without Redis, by sharing one in-flight request per key ("request coalescing", or Go's singleflight package). Do both if you run many instances.

Fix 2: Serve stale data while refreshing

Most data doesn't become wrong the instant its TTL passes. Store a "fresh until" time inside the value and keep the entry for much longer. When the entry is past fresh, one request refreshes it in the background, and everyone, including that request, gets the slightly old value immediately:

def stale_while_revalidate(key, fresh_s=60, stale_s=3600):
    raw = r.get(key)
    if raw is not None:
        entry = json.loads(raw)
        if time.time() < entry["fresh_until"]: return entry["v"]
        if r.set(f"lock:{key}", "1", nx=True, px=5000):           # one request refreshes in the background
            threading.Thread(target=refresh, args=(key, fresh_s, stale_s)).start()
        return entry["v"]                                          # everyone else gets the stale value now
    return refresh(key, fresh_s, stale_s)                          # truly cold: nothing to serve


def refresh(key, fresh_s, stale_s):
    v = load_from_db(key)
    r.set(key, json.dumps({"v": v, "fresh_until": time.time() + fresh_s}), ex=stale_s)
    r.delete(f"lock:{key}")
    return v

One database query, and latency equal to the all-hits baseline: nobody waited for the database. This is the same idea as HTTP's Cache-Control: stale-while-revalidate, and it's the best default for data where a few seconds of staleness is fine. It also helps when the database is down: you can keep serving stale data (stale-if-error) instead of failing.

A third option, probabilistic early expiration (the "XFetch" algorithm), has each request recompute early with a probability that rises as expiry approaches, weighted by how long the recompute takes. Under steady traffic one request almost always refreshes before expiry, with no locks at all.

Failure 2: The Cache Serves Stale Data

Cache-aside has a race that bites under load. A reader misses, reads the database, and is paused (a garbage-collection pause, a slow network, a busy CPU). Meanwhile a writer updates the row and deletes the cache entry. Then the reader resumes and writes what it read earlier. Here are both classic races, forced step by step against PostgreSQL and Redis:

Race 1: reader fills the cache with a value read before a writer's update
  reader: cache miss, reads DB (price 100)                 DB price=100  cache=(empty)
  writer: UPDATE price=120, DELETE cache key               DB price=120  cache=(empty)
  reader: now SETs what it read earlier                    DB price=120  cache=100
  -> stale until the TTL expires (one hour)

Race 2: two writers update the cache instead of deleting it
  writer A: UPDATE price=130                               DB price=130  cache=(empty)
  writer B: UPDATE price=140                               DB price=140  cache=(empty)
  writer B: SET cache 140                                  DB price=140  cache=140
  writer A: SET cache 130 (arrived late)                   DB price=140  cache=130
  -> cache disagrees with the database

Both leave the cache wrong until the entry expires. Race 2 is why the usual advice is "delete on write, don't set": a delete can't install an old value. But Race 1 happens with delete-on-write too, just less often.

Options, in order of effort:

  1. Short TTLs put an upper bound on how long any stale value can survive. Always set one: a cache entry without a TTL is a bug waiting to be found.
  2. Delayed double delete: delete on write, and again a second or so later, after any in-flight reader has finished. Cheap; it narrows the window rather than closing it.
  3. Versioned writes: store the row's version (or updated_at) with the value, and only overwrite an entry with a newer version. A small Lua script does it atomically:
local cur = redis.call('GET', KEYS[1])
if cur then
  local v = cjson.decode(cur).version
  if v >= tonumber(ARGV[2]) then return 0 end
end
redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[3])
return 1
Both races again, with versioned writes (SET only if newer)
  race 2: B then late A (A's write accepted: False)        DB price=140  cache=140
  race 1, writer SETs new value (stale accepted: False)    DB price=120  cache=120

For Race 1 the writer must set the new version rather than delete, so that the late reader finds a newer version and backs off. With versions, setting on write is safe.

  1. Invalidate from the database's change stream: a process reads the database's replication log (with Debezium, or PostgreSQL logical decoding) and deletes or updates cache entries in commit order. This is the most robust approach for heavily cached, frequently updated data, and the most work to run.

Be honest about the requirement first. A product description that's 30 seconds stale is fine. An account balance or stock level that's stale is not, and probably shouldn't be served from a cache at all. Read it from the database, or from a cache that's updated in the same transaction.

Failure 3: Everything Expires at Once

After a deploy, a cache flush or a Redis restart, thousands of keys get cached within a few seconds of each other. With a fixed TTL, they all expire within a few seconds of each other too, and the misses hit the database together. Simulating 10,000 keys warmed at the same moment, with a 300-second TTL and 2,000 requests per second:

TTL jitter ± 0%: peak 1804 DB queries/s (at t=300s) | worst 1-second spike after t=900s:  557 | average  30.8/s
TTL jitter ±10%: peak  197 DB queries/s (at t=292s) | worst 1-second spike after t=900s:  150 | average  30.7/s
TTL jitter ±20%: peak  105 DB queries/s (at t=327s) | worst 1-second spike after t=900s:   78 | average  29.8/s

Without jitter, the database sees almost 60 times its average load for one second, five minutes after the deploy. And the echo doesn't go away: 15 minutes later there are still spikes of 557 per second, because keys refreshed together keep expiring together.

The fix is one line: add a random jitter of ±10 to 20% to every TTL. Same average load, and the peak falls by a factor of 9 to 17.

r.set(key, value, ex=int(ttl * random.uniform(0.9, 1.1)))

A related problem: a cold cache after a restart or failover sends 100% of traffic to the database. If the database can't handle the full load without the cache, the cache has become a critical dependency, not an optimisation. Plan for it: warm the cache before shifting traffic, ramp traffic gradually, or keep enough database capacity.

Failure 4: Cache Penetration and Hot Keys

Cache penetration is a stream of requests for keys that don't exist, such as random product IDs from a scraper or an attack. Each one misses the cache, misses the database, and caches nothing, so every request reaches the database. Two fixes:

Hot keys are the opposite: one key so popular it overloads the single Redis shard that owns it (a celebrity's profile, a flash-sale item, a global configuration value). Options:

Redis in Brief

Redis is the most common shared cache, and most of its behaviour follows from a few design choices:

On licensing: in 2024 Redis moved from the BSD licence to source-available licences, and the Linux Foundation forked the last open-source version as Valkey, now used by several cloud providers. Redis 8 (2025) added the open-source AGPL licence as an option. For caching, the two are interchangeable.

Memcached is the simpler alternative: multi-threaded, strings only, no persistence, no replication. It's still a good choice for a large, plain key-value cache.

Design Checklist

Key Takeaways

Copied to clipboard!