Designing a Distributed Cache: Consistent Hashing and Eviction
Building a distributed cache is one of the purest tests of distributed systems fundamentals. It exposes whether a candidate understands hash distribution, memory management, and network failure modes. When I interview senior engineers, I look for candidates who skip generic buzzwords and talk about memory bounds and cache stampedes.
1. Why Modulo Hashing Breaks and Consistent Hashing Saves You
If you partition keys across N cache servers using hash(key) % N, adding or removing a single node changes the denominator. Almost 100 percent of your keys immediately remap to the wrong server.
Your cache hit rate drops to zero. Hundreds of thousands of concurrent queries hammer your database at the exact same moment. Your primary database crashes under the surge.
Consistent hashing solves this by mapping both cache servers and keys onto a 360-degree circular ring (from 0 to 2^32 - 1). A key is stored on the first server encountered moving clockwise along the ring. When a node is added or removed, only k / N keys need remapping on average.
Virtual Nodes
In pure consistent hashing, servers can land unevenly on the ring. Assign 100 to 200 virtual tokens per physical node to distribute the keys uniformly across all machines.
2. Implementing O(1) LRU Eviction in Memory
When memory fills up, how does the cache decide what to discard?
Least Recently Used (LRU) is the standard policy. To make get, put, and evict all run in strictly O(1) time complexity, you combine two data structures:
1. A doubly linked list where each node contains the key and value. The most recently accessed items sit at the head; the oldest items sit at the tail.
2. A hash map where keys point directly to their corresponding nodes in the linked list.
When a key is read or updated, unlink its node and move it to the head in O(1). When memory limits are reached, pop the tail node and remove its entry from the hash map in O(1).
Imagine a hot key holding the trending news feed expires at 12:00:00.
Between 12:00:00 and 12:00:01, 40,000 requests read a cache miss. All 40,000 threads execute the expensive database query simultaneously.
You have two ways to kill the stampede:
First: Singleflight mutex locking. The first request to encounter the miss acquires a lock and queries the database. All subsequent requests wait on the in-flight promise and read the result once ready.
Second: Probabilistic early expiration (XFetch algorithm). Clients compute a probability of refreshing the key slightly before its strict TTL based on read latency and remaining time.
4. Write Strategies: Cache-Aside vs Write-Through
The most reliable pattern for general read-heavy workloads is Cache-Aside (Lazy Loading):
Read path: Check cache. On hit, return data. On miss, read database, write back to cache, return data.
Write path: Write update directly to database, then DELETE the key from the cache. Do not update the cache directly. Deleting prevents race conditions where an out-of-order write sets stale data.
Write-Through updates the cache and database synchronously in one transaction. Slower writes, but guarantees read consistency.
Write-Behind (Write-Back) writes immediately to the cache and batches writes to disk asynchronously. Incredible write speed, but data is lost if the cache node crashes before flushing.
Key Architecture Decisions & Trade-offs
Decision Area
Options Evaluated
Recommendation
Partitioning Strategy
Modulo hashing vs Consistent hashing with virtual nodes
Consistent hashing with virtual nodes. Prevents catastrophic complete cache invalidation during node reboots.
Cache Invalidation on Write
Update cache key vs Delete cache key
Delete cache key. Eliminates race conditions between concurrent database writes.
Stampede Mitigation
Distributed lock vs In-process singleflight
In-process singleflight on gateway servers. Eliminates distributed lock contention over the network.
Frequently Asked Interview Follow-ups
What is the difference between Memcached and Redis?
Memcached is multithreaded and simple, designed purely for key-value string storage. Redis is single-threaded per instance, supports complex data structures (hashes, sets, sorted sets), provides persistence options (RDB and AOF), and features built-in pub/sub.
How do you handle hot keys that overwhelm a single cache node?
Replicate hot keys across multiple read nodes with randomized suffixes (e.g. key#1, key#2), or store hot keys in a small local in-memory cache on the API gateway instances.
How do you choose between LRU and LFU eviction?
LRU discards items not accessed recently; it works best when recent data is most relevant. LFU tracks access frequency; it is better when a core set of items is continually popular regardless of bursts.
Ready for the interview loop?
Test your design under real pressure
Simulate a full 45-minute technical session on SWEPrep. Diagram architecture on the canvas, justify your trade-offs, and receive instant rubric feedback.