Caching hard
In a Cache-Aside system, a race condition causes permanent staleness: (1) Reader fetches stale data V1 from DB. (2) Writer updates DB to V2 and deletes cache. (3) Reader writes V1 to cache. The cache now holds V1, but the DB holds V2. How does Facebook's 'Lease' mechanism (Memcached) prevent this?
- A It enforces a distributed 2-Phase Commit between the Memcached cluster and the primary MySQL writer to ensure atomic state transitions.
- B The Reader obtains a unique lease token on a miss; if a Writer invalidates the key before the Reader's update, the write-back is discarded.
- C It utilizes a pessimistic locking strategy that forces every incoming GET request to acquire a shared read lock on the underlying database row.
- D It leverages Vector Clocks to detect causality violations and merges the divergent V1 and V2 values using a custom conflict resolution policy.
Answer: B. The Reader obtains a unique lease token on a miss; if a Writer invalidates the key before the Reader's update, the write-back is discarded.
Facebook's **Lease** mechanism solves the **Stale Set** race condition. When a client fetches a missing key, Memcached returns a 'lease' (a token). If another client deletes (invalidates) the key while the first client is fetching from the DB, the lease becomes invalid. When the first client tries to write the stale value back to the cache, Memcached checks the lease, sees it's invalid, and rejects the write.
One system design question a day, with spaced repetition so the ones you miss come back.
Get the appRelated questions
- In the Cache-Aside pattern, what happens when the application requests data that is missing from the cache (a 'Cache Miss')?
- Why use a centralized Distributed Cache (like a Redis Cluster) over local in-memory caches on each web server?
- Setting a short TTL (e.g., 60 seconds) on a cached object helps to:
- What is the primary architectural goal of introducing a cache into a system?
- Most caching systems rely on the principle of 'Temporal Locality', which states:
- Your cache uses an LRU (Least Recently Used) eviction policy. When the cache is full, which item is removed?