Design a Distributed Cache (Redis)
medium 45 minBuild a service like Redis: many machines that together behave as one fast key-value store in memory.
See it run
Reads, writes, copies, eviction, routing, one rebuild and invalidation, one hop at a time.
Operations
Read: cache-aside
The application looks in the cache first and fills it after a miss.
Step 1 of 8
Request arrives
request
GET /user/123
A phone, browser or other service asks for user 123. The application organises the rest.
Step 1: Request arrives
def get_user(id): key = f"user:{id}" row = cache.get(key) if row is None: row = db.select(id) cache.set(key, row, ttl=3600) return row- Time
- 1 ms hit
- Cost
- 21 ms miss (assumed)
- Hit rate
- 90% assumed
If the cache call fails, read the database under a limit. Never turn a cache error into a user error.
In the real world
The same distributed cache doing real jobs. Pick one and step through it.
Follow the load to the database.
Step 1 of 4
Normal
- Database
- 174,000/s
90% hits. The database sees 174,000 reads a second at peak.
Step 1: Normal
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Hash modulo the number of servers
criticalAdding one server to 25 moves about 96% of keys, and the database takes the reads.
Wrongnode = nodes[hash(key) % len(nodes)]Rightnode = slot_map[crc16(key) % 16384]Write the cache before the database
criticalIf the database refuses, readers saw a change that never happened.
Wrongcache.set(k, v)db.update(k, v)Rightdb.update(k, v)cache.delete(k)Release a lock you may no longer hold
majorYour lock can expire while you work. A plain delete then removes another's lock.
Wrongcache.delete(lock)Rightcache.delete_if_equal(lock, my_token)Use one TTL for everything
majorKeys loaded together expire together.
Wrongcache.set(k, v, ttl=3600)Rightcache.set(k, v, ttl=3600 + randint(0, 600))Add shards for a hot key
majorOne key has one owner.
Wrongshards += 10Rightlocal.get(key, max_age=1.0)
Interview tips
Lead with numbers
- 1.74M a second at peak, 25 shards.
- 500 GB is only 20 GB each: commands bind.
- Misses: 174,000 a second.
State the contract
- It may forget.
- Ordered per key while the primary lives.
- A failover can lose milliseconds.
Follow the load
- Where do misses go?
- Who caps them?
- What if a shard starts empty?
Mention the limits
- No atomic work across shards.
- One region, or one cache in each.
- Money is decided in the database.