Caching
Where caches live (client, CDN, gateway, application, distributed, database), read and write strategies (cache-aside, read-through, write-through, write-behind, write-around, refresh-ahead), eviction policies, TTLs and invalidation, consistency races, stampedes and hot keys, Redis vs Memcached, sizing and metrics.
Why cache?
Caching stores the results of expensive work (DB queries, computations, remote calls, rendered pages) in faster storage so repeated requests are served cheaply. Benefits: lower latency, less load on databases and services, higher throughput, sometimes resilience (serve stale when the origin is down). Costs: staleness, complexity, memory, another component to fail.
Where caches live
| Layer | Caches | Invalidation |
|---|---|---|
| Browser / mobile app | HTTP responses, assets, app state | Cache-Control, ETags, versioned URLs |
| CDN | static assets, media, public API responses, HTML | TTL, purge by URL/tag, versioned URLs |
| API gateway / reverse proxy | full responses | TTL, purge |
| Application (in-process) | hot objects, config, computed values | TTL, pub/sub invalidation; per-instance (inconsistent across instances) |
| Distributed cache (Redis/Memcached) | query results, sessions, objects, counters | TTL, explicit delete, CDC |
| Database | pages (buffer pool), query plans, materialized views | automatic / refresh |
Read strategies
Cache-aside (lazy loading)
import json, random
def get_user(user_id: str):
key = f"user:{user_id}:v2" # version the key format
cached = redis.get(key)
if cached is not None:
return json.loads(cached)
user = db.fetch_one("SELECT * FROM users WHERE id = %s", (user_id,))
if user:
ttl = 300 + random.randint(0, 60) # jitter avoids synchronized expiry
redis.set(key, json.dumps(user), ex=ttl)
else:
redis.set(key, "null", ex=30) # negative caching (bounded)
return user
def update_user(user_id: str, fields: dict):
db.update_user(user_id, fields) # 1. source of truth first
redis.delete(f"user:{user_id}:v2") # 2. invalidate (don't set!)
Read-through
The cache library/service itself loads from the DB on a miss (e.g. Caffeine LoadingCache, DAX for DynamoDB, NCache). Simpler application code, same semantics as cache-aside.
Write strategies
| Strategy | Write path | Read freshness | Risk | Best for |
|---|---|---|---|---|
| Cache-aside + invalidate | DB, then delete key | stale until next miss/TTL (small window) | race on concurrent read/write | general purpose |
| Write-through | cache and DB synchronously | fresh | slower writes, cache pollution | read-after-write heavy data |
| Write-back (behind) | cache now, DB later (batched) | fresh in cache | data loss on cache failure | counters, metrics, high write bursts |
| Write-around | DB only | populated on read | first read slow | write-once, read-rarely data (logs, uploads) |
| Refresh-ahead | background refresh before expiry | fresh for hot keys | wasted refreshes | predictable hot keys |
Eviction and expiration
| Policy | Evicts | Good for |
|---|---|---|
| LRU | least recently used | general recency workloads |
| LFU (with aging) | least frequently used | stable popularity (catalogs, CDNs) |
| TTL | expired entries | data with freshness limits |
| FIFO / random | oldest / random | simple, cheap |
| W-TinyLFU, S3-FIFO, SIEVE | modern, scan-resistant | high hit ratios on real traces |
Implementing LRU (a classic interview task): hash map + doubly linked list → O(1) get/put. See the design problems topic.
Consistency pitfalls
The stale-set race in cache-aside
Other gotchas
- Update vs delete on write: concurrent "set" operations can leave the older value last; prefer delete.
- Dual-write ordering: invalidate after the DB commit, not before.
- Multi-key consistency: a page assembled from several cached keys may mix versions.
- Negative caching: cache "not found" briefly to protect against repeated misses (and enumeration attacks), but keep the TTL short.
- Serialization changes: version your cache keys (
user:{id}:v2) when the format changes.
Stampedes and hot keys
import threading
_inflight: dict[str, threading.Event] = {}
_lock = threading.Lock()
def get_with_singleflight(key, loader, ttl=300):
val = redis.get(key)
if val is not None:
return val
with _lock:
ev = _inflight.get(key)
leader = ev is None
if leader:
ev = _inflight[key] = threading.Event()
if not leader:
ev.wait(timeout=2) # followers wait for the leader's result
return redis.get(key) or loader() # fallback if the leader failed
try:
val = loader()
redis.set(key, val, ex=ttl)
return val
finally:
with _lock:
_inflight.pop(key, None)
ev.set()
| Problem | Mitigation |
|---|---|
| Stampede on expiry | single-flight, probabilistic early refresh, stale-while-revalidate, TTL jitter |
| Cold cache after restart/deploy | warm-up jobs, gradual traffic shift, persistent cache (Redis AOF), replicas |
| Hot key | local L1 cache, key replication (key#n), read replicas, coalescing |
| Hot write counter | sharded counters, in-memory aggregation with periodic flush |
| Big values | compress, split, store blobs elsewhere |
| Cache penetration (requests for keys that never exist) | negative caching, Bloom filter of valid keys |
Distributed caching
- Partitioning: consistent hashing (client-side for Memcached) or hash slots (Redis Cluster: 16,384 slots).
- Replication for availability (Redis primary/replica with Sentinel or Cluster failover); replicas serve reads with possible lag.
- Multi-level: L1 in-process (Caffeine, microseconds, per instance) + L2 distributed (Redis, sub-ms) + DB.
- Failure mode: the system must survive cache loss — can the database handle the full load if the cache disappears? If not, the cache is a critical dependency; protect the DB with rate limiting and circuit breakers.
Redis vs Memcached
| Redis / Valkey | Memcached | |
|---|---|---|
| Data types | strings, hashes, lists, sets, sorted sets, streams, geo, HLL, bitmaps | strings |
| Persistence | RDB snapshots, AOF | none |
| Replication / HA | yes (Sentinel, Cluster) | no (client-side only) |
| Scripting / atomic ops | Lua, transactions, many atomic commands | CAS, incr |
| Threading | single-threaded execution (+ I/O threads) | multi-threaded |
| Typical extra uses | rate limiting, leaderboards, locks, queues, pub/sub | pure object cache |
Sizing and metrics
- Hit ratio (target depends; 90%+ for read-heavy caches) and miss latency.
- Working set: often 20% of objects serve 80% of reads → cache that fraction.
- Example: 10M daily active users × 2 KB profile × 20% hot ≈ 4 GB → a small Redis cluster with replicas.
- Watch evictions, memory fragmentation, network bandwidth (big values!), CPU (single-threaded Redis), and connection counts.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.