02. Scaling / Lesson 4 of 5

Caching

Keep the answers you read often in fast memory.

  • 12 min
  • Intermediate
  • 12 steps
  • Hit rate—
  • Database reads5,000/s (bad)
  • Average read20.0 ms (warning)
UsersApp serverDatabase⚠ CPU 92%
  • Request
  • Cache hit
  • Cache miss
  • Write
Step 1/12

Step 1 of 12: Every page view reads the database

Read every step as text
  1. Step 1: Every page view reads the database

    The product page is read 5,000 times a second, and each read is a database query of about 20 ms.

    Most of those reads ask for the same few popular products, so the database does the same work again and again and runs out of CPU.

    Reads usually outnumber writes 10 to 1 or more, so repeated reads are the first thing to remove.

  2. Step 2: Add a cache: memory in front of the database

    A cache such as Redis or Memcached keeps key → value pairs in memory. Reading one takes about 1 ms, much less than a query.

    It starts empty (a cold cache), so at first every read still goes to the database and fills the cache on the way back.

    The cache holds copies. The database stays the source of truth.

  3. Step 3: A hit is fast; a miss costs a trip to the database

    A hit means the value was in the cache: about 1 ms. A miss means it was not: we pay the cache check and the query.

    With 90% hits the average read is 0.9 × 1 + 0.1 × 21 = 3.0 ms, and the database sees only one read in ten: 500/s.

    Popular data is small: a few percent of the keys often answer most of the reads.

  4. Step 4: Cache-aside: the app fills the cache itself

    In cache-aside (also called lazy loading) the app asks the cache first. On a miss it reads the database, stores the answer in the cache, then returns it.

    Only data that someone actually reads ends up in the cache, and if the cache goes down the app can still read the database.

  5. Step 5: TTL: how long a copy may be old

    Each cached value gets a time to live (TTL), here 60 seconds. After that it expires and the next read fetches a fresh copy.

    Until then the cache can be out of date: the price changed in the database 40 seconds ago, but the cache still answers with the old one.

    A short TTL means fresher data and more misses; a long TTL means fewer misses and older data. Choose per kind of data.

  6. Step 6: Write-through and write-back

    With write-through, every write goes to the cache and the database together. Reads are always fresh, but each write waits for both.

    With write-back, the write goes to the cache only and reaches the database later, in batches. Writes are very fast, but if the cache dies first, those writes are lost.

    Write-back suits counters and view numbers, where losing a few seconds is acceptable. Never use it for payments.

  7. Step 7: Invalidate: delete the copy when the data changes

    With cache-aside, a common rule is: write to the database, then delete the cached key. The next read misses and loads the new value.

    Deleting is safer than setting the new value, because two writers setting values at the same time could leave the older one in the cache.

    Delete after the database write is committed, and keep a TTL as a safety net for a delete that gets lost.

  8. Step 8: Eviction: when memory is full

    Memory is limited. When the cache is full and a new value arrives, something must go. LRU (least recently used) removes the value nobody has read for the longest time.

    Popular keys are read constantly, so they stay; a product read once last week is dropped.

    Redis can also evict by least frequently used (LFU) or only among keys that have a TTL.

  9. Step 9: A stampede: one key expires, a thousand requests miss

    The home page key expires at 12:00:00. In the next few milliseconds, 1,000 requests miss together and all run the same heavy query.

    The database, sized for the 10% misses, suddenly gets them all at once and slows down for everyone.

    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.

  10. Step 10: Penetration: misses that can never hit

    Requests for products that do not exist (a typo, a scraper or an attack) always miss: there is nothing to cache, so every one reaches the database.

    Fix it with negative caching: store "not found" for a short time, such as 30 seconds. For huge key spaces, a Bloom filter answers "definitely not here" before any lookup.

    Keep negative TTLs short, or a product created a minute ago will still look missing.

  11. Step 11: Caches at every layer

    Caching is not only Redis. The browser keeps files it has seen, a CDN keeps copies near the user, the app can keep a small in-process cache, and the database caches pages in memory too.

    Each layer that answers a request saves every layer behind it. The nearer to the user, the faster, and the harder to invalidate.

    Static files (images, scripts) belong in the browser and the CDN; per-user data usually in Redis.

  12. Step 12: Caching in one picture

    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.