System Design · 02. Scaling · 12 min · Intermediate

Caching

Keep the answers you read often in fast memory.

In short

A cache keeps copies of hot data in memory. At a 90% hit rate the average read drops from 20 ms to 3.0 ms and the database does a tenth of the work.

Cache-aside fills it on a miss; TTLs and deletes keep it fresh; LRU makes room; locks and negative caching protect the database from stampedes and penetration.

Key ideas

  • The cache holds copies. The database stays the source of truth. (step 2)
  • Fixes: let only one request reload the key while the others wait or get the old copy (a lock, or single flight), refresh popular keys before they expire, and add a little randomness to TTLs. (step 9)

Good to know

  • Popular data is small: a few percent of the keys often answer most of the reads. (step 3)
  • Redis can also evict by least frequently used (LFU) or only among keys that have a TTL. (step 8)
  • Static files (images, scripts) belong in the browser and the CDN; per-user data usually in Redis. (step 11)

Watch out

  • Reads usually outnumber writes 10 to 1 or more, so repeated reads are the first thing to remove. (step 1)
  • A short TTL means fresher data and more misses; a long TTL means fewer misses and older data. Choose per kind of data. (step 5)
  • Write-back suits counters and view numbers, where losing a few seconds is acceptable. Never use it for payments. (step 6)
  • Delete after the database write is committed, and keep a TTL as a safety net for a delete that gets lost. (step 7)
  • Keep negative TTLs short, or a product created a minute ago will still look missing. (step 10)
UsersApp serverCache (Redis)Database

Key numbers

Hit rate
90%
Database reads
500/s
Average read
3.0 ms

Terms

Cache hit
The value was in the cache, so the read is answered from memory in about a millisecond.
Cache miss
The value was not in the cache, so the read goes on to the database.
Hit rate
The share of reads answered by the cache; it decides the average read time and the database load.
Cache-aside
The app reads the cache first and, on a miss, loads the database and fills the cache itself.
TTL (time to live)
How long a cached copy may be used before it expires.
Write-through
Every write goes to the cache and the database together.
Write-back
Writes go to the cache first and reach the database later, in batches.
Cache invalidation
Deleting a cached copy when the data changes, so the next read loads the new value.
LRU eviction
When memory is full, remove the value that was used least recently.
Cache stampede
Many requests miss the same expired key at once and all hit the database.
Cache penetration
Requests for keys that do not exist always miss and reach the database.
Negative caching
Caching "not found" for a short time so repeated misses stop at the cache.