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.

Video lesson · Chapter 1 of 5

One profile, three possible outcomes

0:00 / 3:01

Distributed cache in 90 seconds

1:30Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A distributed cache keeps copies of often-used data in the memory of several machines. Programs read and write it by key, and the machines share the keys between them.

It sits beside the database, not in place of it. The database holds the truth. The cache holds answers that would be slow or expensive to work out again, and it may forget any of them.

Why it exists

Memory answers a key lookup far faster than a query that plans, locks and reads a disk. When the same answers are wanted again and again, most requests never need the database.

One machine is not enough for long. It has a limited amount of memory, one network card and one command loop, and when it stops, every request falls on the database at once.

A short history

  1. 22 May 2003

    Memcached is released. Brad Fitzpatrick wrote it for the website LiveJournal.

  2. 26 February 2009

    Redis is released by Salvatore Sanfilippo, with lists, sets and other structures beside plain values.

  3. April 2013

    Facebook engineers describe their Memcached deployment at the NSDI conference: billions of requests a second and trillions of items.

  4. March 2024

    Redis moves to source-available licences. The Linux Foundation announces Valkey, a fork of the last BSD-licensed version.

Words to know

Shard
One part of the keys, and the machine that owns that part.
Slot
A small numbered bucket. A key always falls in the same slot; slots are assigned to shards.
Hit rate
The share of reads the cache can answer by itself.
Eviction
Throwing out an item because memory is full.
TTL
Time to live: the item is ignored after this time.
Primary and replica
The copy that takes writes, and a copy that follows it.
Hot key
One key with far more traffic than the others.
Stampede
Many requests rebuilding the same missing item at the same time.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3NumbersWork out a number when the answer changes what you build.
  4. 4API and dataThe contract first, then the data that serves it.
  5. 5DesignStart with the smallest system that works. Change it only when something breaks.
  6. 6Deep divesCompare the options before you open them, then say which you would pick.
  7. 7Explain your choicesAnswer first. Then compare your reasoning.
  8. 8By levelThe same question is judged differently for mid, senior and staff.
  9. 9MockAnswer against the clock, then score yourself.

Understand it

Picture it

Squirrels, trees and spare nuts

Three trees and a painted rule
One tree, and it is full

The rule spreads the nuts, the baskets survive a storm, and one famous nut still makes a queue.

Scope

What are we building?

A general-purpose cache, a service like Redis, for a large company: sessions, query results, counters, leaderboards, rate limits, messages and short locks. We design the cache itself, not only how to use one.

  • Find it

    Any client reaches the right machine in one hop.

  • Fit it

    Memory is limited, so something must be evicted.

  • Survive it

    A machine dies; its keys come back in seconds.

  • Protect the database

    Misses must never arrive all at once.

Without and with a cache (our assumptions)

WithoutWith
Who answersThe database, alwaysThe cache for 90% of reads
Typical time20 ms1 ms on a hit
Load on the database100%10%, ten times less
To growCostly database replicasAdd cache shards

Similar systems

SystemKnown for
Redis, ValkeyRich data types, one command loop
MemcachedPlain key-value, many threads
HazelcastIn-memory data grid in Java
Apache IgniteData and compute grid
AerospikeKey-value with data on flash
ElastiCache, Memorystore, Azure's Redis serviceManaged by a cloud provider

The finished system

Where the design ends up

The whole system

App servers hold a cache client with a slot map and local copies. The client talks directly to shard primaries. Each primary streams to a replica on another machine. A controller checks the primaries. Misses go to the database, whose change stream deletes cached keys. Metrics go to monitoring.
Blue is the read path, pink is replication, orange is control and invalidation. Dashed means asynchronous or only sometimes.

Read next

Who owns which idea

IdeaIts own page
Spreading keys, local and shared tiersDistributed caching
Rings, virtual nodes, slotsConsistent hashing
Primary, replicas, failover, split brainCache replication
LRU, LFU and friendsCache eviction
StampedesThundering herd
Cache and database agreementCache consistency
Read and write patternsCache-aside, write-through, write-back
Which productMemcached vs Redis

For the interview go to Approach, then Scope, Numbers, API, Design and Deep dives. If you are revising, start with the Mock.

Summary

The whole topic in one minute.

A distributed cache is a hash table spread over machines. Clients work out a slot from the key, look the slot up in a small map and talk straight to the owner. Each owner has a replica, and a controller changes the map when one fails.

The design stays simple because the data can be lost. That decides most questions: copies are sent without waiting, full memory means eviction, and a missing item is read from the database again. The care goes into protecting the database at those moments.

  • 1.74M requests a second at peak decides the number of shards; memory does not.
  • Keys map to 16,384 fixed slots; slots map to shards. Only the second map ever changes.
  • Replicate without waiting: a crash may lose a few milliseconds of writes.
  • A hot key is not solved by more shards. Copy it closer to the readers.
  • Delete on write, expire on time, rebuild once.

Sources