Try
↑ ↓ move↵ openesc close

Interview prep / Caching

Senior · Caching · System design interview question

A service runs in two regions. Writes go to the primary region's database and replicate asynchronously to the second region, where a cache fronts the local replica. Users there sometimes see old data for a long time, not just briefly. How can that happen, and how do you fix it?

Sketch your own answer first, then compare it with the one below.

A strong answer

The cause is a race between the invalidation and the replication. A write commits in the primary region. The invalidation reaches the second region's cache quickly, and the cache deletes the key. The replica has not applied the write yet. A reader misses, reads the old row from the lagging replica, and puts the old value in the cache. The invalidation has been spent, so the stale value stays until its TTL expires.

Ways to close it:

  • Drive invalidations from the replica's own commit stream. The delete is then issued only after the replica holds the new data, so a refill cannot read the old row. This is the approach used by large memcache deployments.
  • Use a remote marker. Before the write, set a marker for the key in the second region. Readers that see the marker go to the primary region for a fresh value, then the marker is cleared once replication has caught up. Recently written keys cost a cross-region read, which is the price of correctness.
  • Version the values. Store the row version or log position with the cached value and accept a fill only if it is at least as new as what is known.
  • Keep a TTL as a backstop for any invalidation that is lost.

Pick by what stale reads cost. Profile photos can use the TTL alone, while account state needs the marker.

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.

Learn it by running it

The caching and eviction lesson explains the mechanism behind this question, and its lab lets you change the parameters and watch the effect.

Your progress is saved in this browser. Sign in to keep it on every device. Privacy · Terms