Bugpit

Lessons › Keep it running

The cache that took down the database

12,000 req/s, and the cache answers 4 in 5 reads, so the database is calm. Then the home page's cached answers all expire in the same second. Every request misses, and they all ask the database to rebuild the same thing.

Play this level

Part of Bugpit Pro. It runs in your browser: build the design, press Run, and watch what breaks.

The lesson

A cache hides load from the database. That's its job, and it's also the danger: the database is now sized for the traffic that gets past the cache, not for all of it.

When a popular key expires, every request that arrives before it's refilled is a miss. A thousand requests ask the database the same question at once. This is a cache stampede, also called a thundering herd.

The fix is to let one request rebuild the answer while the others wait for it, or get the old answer for a moment longer. Tick **Refill once** on the cache. This simulator treats the stampede as three quarters of cached answers vanishing at once, which is our assumption, not a measured figure.

Two more habits help. Add a little randomness to expiry times so keys don't all expire together. And decide how the cache is filled: cache aside (the app fills it on a miss) is simple, write through (every write updates the cache too) keeps it warm.

What you have to achieve

12,000 requests a second at the busiest hour, 2% of them writes.

What you learn

The database never saw the stampede: one request rebuilt each key and the rest waited a few milliseconds. A bigger database would also have survived, but you'd pay for it all month to cover a moment that one setting removes.

Check yourself

A thousand cache keys were all written at 9:00 with a 1 hour expiry. What happens at 10:00?

Show the answer

They all expire together and the database gets every request. Same expiry time means same expiry moment. Adding a random few minutes to each key (jitter) spreads the refills out.

A product's price changes. With cache aside, what should the app do?

Show the answer

Delete or update the cached copy when it writes. Otherwise people see the old price until it expires. Deleting the key on write is the usual way to invalidate it.

Try it yourself

More in Keep it running

← Push or poll Pay for the peak only at the peak →