Cache
By Ankur NayakReviewed
A cache keeps copies of frequently read data in fast memory, close to where it is needed, so most reads skip the slower database or service behind it. It is the cheapest way to cut latency and protect a database from read load.
How it works
In the most common pattern, cache-aside, the application checks the cache first. A hit returns immediately; a miss reads the source of truth and stores the result for next time. Writes either update the cache as well (write-through) or simply delete the entry so the next read refills it.
Caches work because access is skewed: a small share of keys gets most of the traffic. An eviction policy such as LRU keeps that hot set in memory, and a TTL bounds how stale an entry can get.
Distributed caches such as Redis or Memcached shard keys across many nodes, usually with consistent hashing, so the cache can grow with the dataset and survive the loss of a node.
Key points
- Cache-aside, write-through and write-back trade freshness against write cost
- Every entry needs a TTL or an invalidation path
- Hit ratio is the number that matters; measure it
- A cold cache after a restart can overload the database (thundering herd)
When to use it, and pitfalls
Use it for
- Read-heavy workloads with a hot subset of keys
- Expensive computations or remote calls whose results can be reused
- Session data and counters that tolerate a small risk of loss
Watch out for
- Stale reads when an invalidation is missed
- Thundering herd when a hot key expires; use request coalescing or jittered TTLs
- Treating the cache as a database: anything that must survive belongs in durable storage
Trade-offs
Invalidate on write vs. update on write
Delete the cached entry on write and let the next read refill it.
Pros: Simple and safe under concurrent writes; No wasted work for keys nobody reads
Cons: One extra miss after every write
Used in
Related building blocks
Frequently asked questions
What is the difference between cache-aside and write-through?
With cache-aside the application loads data into the cache only on a miss and invalidates it on writes. With write-through every write goes to the cache and the database together, so reads after writes are always hits, at the cost of caching data that may never be read.
How do you prevent a thundering herd on a cache?
Let only one request rebuild a missing key while others wait (request coalescing or a short lock), add random jitter to TTLs so hot keys don't expire together, and warm the cache before sending full traffic to a new cluster.
Sources
- Key eviction · Redis Docs
- EVCache: Netflix's distributed in-memory datastore · Netflix on GitHub