Sub topic 3
Consistency and Staleness Trade-offs
Assume you know basic programming, client-server requests, databases, latency, and throughput.
Consistency and staleness
A cache can return an older value than the database. This is staleness. A short time-to-live (TTL) reduces staleness but causes more database requests. Invalidation removes an entry after a write, but every write path must remember to invalidate the same key.
Choose based on the data:
- User profile formatting can tolerate brief staleness.
- Account balances usually require a strongly consistent source.
- Product listings often use TTL plus invalidation.
Preventing cache stampedes
A cache stampede occurs when many requests see an expired entry and all query the database together. The database receives a sudden load spike.
Use a per-key lock. The first request rebuilds the value. Other requests wait, then check the cache again and reuse the result. Add a small random amount to TTLs so many entries do not expire at once.
with key_lock(key):
value = cache.get(key)
if value is None:
value = database.fetch(key)
cache.set(key, value, ttl=60)
return valueHTTP caching and validation
HTTP caching moves reuse to browsers and CDNs. Cache-Control sets freshness. An ETag identifies a representation. After it becomes stale, the client can send If-None-Match; a matching tag lets the server return 304 Not Modified without sending the body.
HTTP/1.1 200 OK
Cache-Control: public, max-age=3600
ETag: "v42"
GET /report HTTP/1.1
If-None-Match: "v42"
HTTP/1.1 304 Not ModifiedDistributed caches
A distributed cache stores entries across several nodes. Consistent hashing maps each key to a node while minimizing key movement when nodes join or leave. Replication improves availability but can create more consistency work.
Measure effectiveness
Track hit ratio, miss latency, database load, eviction count, entry age, and errors. A high hit ratio is not enough if hits are slow or values are frequently stale. Compare cache-enabled latency and backend load with a measured baseline.
Choose a strategy
Use cache-aside for a simple application-controlled pattern. Prefer write-through when cached data should update with writes. Use write-back only when delayed persistence is acceptable and data loss is handled. Select TTLs and eviction rules from workload measurements, not guesses.
Exercise
A cache has a high hit ratio, but users see outdated prices. What should you investigate first?
Show answer
Check TTL and invalidation behavior, then determine whether price updates bypass the invalidation path.