Caching Strategies
A cache keeps copies of frequently used data in a faster place: memory instead of disk, a nearby server instead of a distant database. A cache hit can be 10 to 100 times faster than going to the source, and every hit is load the database never sees. Caches appear at every layer: the browser, the CDN, the reverse proxy, the application (Redis, Memcached) and the database's own buffer pool.
The hit ratio decides everything
The average latency of a cached system is hit_ratio × cache_time + (1 - hit_ratio) × (cache_time + db_time). Small changes in the hit ratio have a big effect, both on latency and on how much traffic reaches the database:
CACHE_MS, DB_MS = 0.5, 20
REQUESTS_PER_S = 50_000
print("hit ratio avg latency db queries/s")
for hit in [0.0, 0.5, 0.8, 0.9, 0.95, 0.99]:
avg = CACHE_MS + (1 - hit) * DB_MS
db_qps = REQUESTS_PER_S * (1 - hit)
print(f"{hit:8.0%} {avg:10.2f} ms {db_qps:12,.0f}")hit ratio avg latency db queries/s
0% 20.50 ms 50,000
50% 10.50 ms 25,000
80% 4.50 ms 10,000
90% 2.50 ms 5,000
95% 1.50 ms 2,500
99% 0.70 ms 500
Going from 90% to 99% hits cuts database traffic by a factor of ten. That's why teams obsess over the last few percent.
Read strategies
Cache-aside (lazy loading) is the most common pattern. The application checks the cache; on a miss it reads the database and puts the result in the cache.
database = {"user:1": "Ada", "user:2": "Grace", "user:3": "Linus"}
cache = {}
stats = {"hits": 0, "misses": 0, "db_reads": 0}
def db_read(key):
stats["db_reads"] += 1
return database.get(key)
def get_user(key):
if key in cache:
stats["hits"] += 1
return cache[key]
stats["misses"] += 1
value = db_read(key)
cache[key] = value # populate on the way back
return value
def update_user(key, value):
database[key] = value
cache.pop(key, None) # invalidate, don't update: avoids races
for key in ["user:1", "user:2", "user:1", "user:1", "user:3", "user:2"]:
get_user(key)
update_user("user:1", "Ada Lovelace")
print(get_user("user:1"))
print(stats)Ada Lovelace
{'hits': 3, 'misses': 4, 'db_reads': 4}
The writer deletes the cache entry instead of overwriting it. If two writers update the cache in a different order than they updated the database, an overwrite could leave stale data cached forever; a delete just causes one extra miss.
Read-through caches look the same to the application, but the cache library itself loads missing data from the database.
Write strategies
| Strategy | On write | Pros | Cons |
|---|---|---|---|
| Write-through | Write cache and DB together, synchronously | Cache is always fresh | Every write pays both latencies |
| Write-back (write-behind) | Write cache now, flush to DB later in batches | Very fast writes, batching | Data loss if the cache dies before flushing |
| Write-around | Write DB only; cache fills on the next read | No cache pollution by write-once data | First read after a write is a miss |
A write-back cache absorbs repeated writes to the same key: only the latest value needs to reach the database.
class WriteBackCache:
def __init__(self):
self.data, self.dirty, self.db_writes = {}, set(), 0
def write(self, key, value):
self.data[key] = value
self.dirty.add(key)
def flush(self, db):
for key in sorted(self.dirty):
db[key] = self.data[key]
self.db_writes += 1
self.dirty.clear()
db = {}
cache = WriteBackCache()
for second in range(10): # a view counter updated 10 times
cache.write("views:home", second + 1)
cache.write("views:about", 1)
cache.flush(db)
print("db:", db)
print("writes received by cache: 20, writes sent to db:", cache.db_writes)db: {'views:about': 1, 'views:home': 10}
writes received by cache: 20, writes sent to db: 2
Expiry (TTL) and staleness
Every cached item should have a time to live. A TTL bounds how stale data can get even if an invalidation is lost. Choose it per data type: seconds for prices, hours for a user's avatar URL, days for static content with versioned file names.
Tip: Add a little random jitter to TTLs (for example 300 s ± 10%). Items cached at the same moment then don't all expire at the same moment.
Cache stampede
When a hot key expires, hundreds of concurrent requests can miss at once and all hit the database to rebuild the same value: a stampede (or thundering herd). The usual fix is request coalescing: the first miss takes a lock and rebuilds; the others wait for its result (or serve the stale value meanwhile).
def simulate(concurrent_requests, coalesce):
db_queries = 0
rebuilding = False
for _ in range(concurrent_requests): # all arrive while the key is missing
if coalesce and rebuilding:
continue # wait for the in-flight rebuild
rebuilding = True
db_queries += 1
return db_queries
for n in [10, 1_000]:
print(f"{n:5} simultaneous misses: no coalescing -> {simulate(n, False):5} DB queries, "
f"coalescing -> {simulate(n, True)} DB query") 10 simultaneous misses: no coalescing -> 10 DB queries, coalescing -> 1 DB query
1000 simultaneous misses: no coalescing -> 1000 DB queries, coalescing -> 1 DB query
Other defences: refresh hot keys before they expire (when the remaining TTL drops below a threshold, a background job recomputes them), and probabilistic early expiration, where each request has a small, growing chance of refreshing the value early.
What not to cache
- Data that must be perfectly fresh (an account balance in a payment flow).
- Data that is rarely re-read: it just evicts useful entries.
- Per-user data in a shared cache without the user in the key: a classic privacy bug.
Test yourself
In cache-aside, what should a writer normally do to the cached copy of the changed record?
- Overwrite it with the new value
- Delete (invalidate) it
- Nothing; the TTL will fix it
- Lock the whole cache
What is the main risk of a write-back cache?
- Slow writes
- Losing writes that were not yet flushed if the cache fails
- Reads always miss
- It can't batch writes
How does request coalescing prevent a cache stampede?
- It increases the TTL
- Only one request rebuilds a missing key while the others wait for its result
- It disables the cache
- It sends misses to a random replica