A very popular cached item expires and the database is overwhelmed. What happened, and how do you prevent it?
Sketch your own answer first, then compare it with the one below.
A strong answer
This is a cache stampede, also called a thundering herd. While the item is cached, thousands of requests are absorbed. When it expires, all of them miss at once and each goes to the database to recompute the same value. The database sees a burst it was never sized for, gets slow, and the slowness makes more requests pile up.
Prevention options:
- Request coalescing. Only one request recomputes while the others wait for its result or are served the old value.
- Leases. The cache hands one client a token to refill the key and tells the others to retry shortly. This also prevents some stale-set races.
- Early or probabilistic refresh. Refresh a hot item shortly before it expires so there is never a gap.
- Jitter on expiry times, so many keys do not expire together.
- Serve stale data while revalidating in the background.
A cache restart is the same failure at a larger scale, since every key misses at once. Either way, limits on database concurrency are the last line of defence.
Sources
- Rajesh Nishtala, Hans Fugal, Steven Grimm, Marc Kwiatkowski, Herman Lee, Harry C. Li, Ryan McElroy, Mike Paleczny, Daniel Peek, Paul Saab, David Stafford, Tony Tung, Venkateshwaran Venkataramani (2013). Scaling Memcache at Facebook.