AlgoViz

Design a Distributed Cache (Redis)

medium 45 min

Build 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

Our systemClientApp serverCacheDatabase

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

App serversShard 1Shard 2Shard 25Database
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

    critical

    Adding one server to 25 moves about 96% of keys, and the database takes the reads.

    Wrong
    node = nodes[hash(key) % len(nodes)]
    Right
    node = slot_map[crc16(key) % 16384]
  • Write the cache before the database

    critical

    If the database refuses, readers saw a change that never happened.

    Wrong
    cache.set(k, v)db.update(k, v)
    Right
    db.update(k, v)cache.delete(k)
  • Release a lock you may no longer hold

    major

    Your lock can expire while you work. A plain delete then removes another's lock.

    Wrong
    cache.delete(lock)
    Right
    cache.delete_if_equal(lock, my_token)
  • Use one TTL for everything

    major

    Keys loaded together expire together.

    Wrong
    cache.set(k, v, ttl=3600)
    Right
    cache.set(k, v, ttl=3600 + randint(0, 600))
  • Add shards for a hot key

    major

    One key has one owner.

    Wrong
    shards += 10
    Right
    local.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.