CONCEPT SHEET · Concepts

Caching

One-liner: Keep hot data in a faster, closer tier to cut latency and shed load from the source; the hard parts are invalidation and stampedes.

ArticleConcepts© Arthur Bernier Jr551 words1 code block

Say this#

How it works#

Cache layers, outermost first:

TEXT
browser cache (Cache-Control, ETag) -> CDN (CloudFront, Cloudflare) -> API gateway / reverse proxy (Nginx, Varnish)  -> application in-process (LRU map, Caffeine, Guava) -> distributed cache (Redis, Memcached) -> DB buffer pool

Cache-aside flow:

  1. GET key from Redis. Hit → return.
  2. Miss → read DB → SET key with TTL → return.
  3. On write: update DB, then DELETE the cache key (don't SET; avoids race with stale read). Next read repopulates.

Stampede fixes: per-key lock/single-flight, stale-while-revalidate, jittered TTLs, request coalescing at the proxy, pre-warming before deploys/traffic spikes.

Trade-offs#

ChoiceProCon
Cache-asideSimple, only hot data cached, cache failure is survivableFirst read is a miss; stale window until TTL/invalidation
Write-throughCache always freshWrite latency doubles; caches cold data
Write-backFastest writes, absorbs burstsData loss if cache dies before flush; complex
RedisRich types, persistence, pub/sub, Lua, single-threaded simplicitySingle-threaded per core; memory cost
MemcachedMultithreaded, simple, very fast for plain KVNo persistence, no data structures
In-process cacheNanosecond access, no networkPer-instance inconsistency; memory duplicated

Numbers#

  • In-process lookup ~100 ns; Redis/Memcached over LAN ~0.2-1 ms; DB query several ms to tens of ms.
  • Redis single node: ~100k ops/s order of magnitude (more with pipelining); Memcached scales with cores.
  • A 90% hit ratio cuts DB load 10x; 99% cuts it 100x. Quote the ratio.
  • TTLs: seconds for volatile data, minutes-hours for profile-like data; add ±10% jitter.

In the interview#

See also