SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
  • CDN
  • Distributed Cache Architecture
  • Cache Stampede
  • Cache Warming
  • Hot Keys
  • Cache Penetration and Cache Avalanche
  • CDN Push vs Pull
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Caching/Distributed Caching

Distributed Cache Architecture

Spread a cache over many machines (like Redis or Memcached) so it can grow and survive failures.

โฑ 15 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A distributed cache spreads cached data over many machines. Together they act like one big, fast memory shared by all your app servers.

  • One machine has limited memory and is a single point of failure. Many machines can grow and survive failures.
  • Each key lives on one node (and maybe a copy on another). A rule decides which node.
  • Popular tools: Redis and Memcached.

02Concept: What is it?

A cache on one app server only helps that server. If you run 20 app servers, they would each keep their own copy, waste memory, and show different data. A distributed cache is one shared cache that all app servers use over the network.

Local cache vs shared cache
Local cache in each server
๐Ÿ–ฅ๏ธApp 1
โšกown cache
๐Ÿ–ฅ๏ธApp 2
โšกown cache
Shared distributed cache
๐Ÿ–ฅ๏ธApp 1
๐Ÿ–ฅ๏ธApp 2
๐Ÿ–ฅ๏ธApp 3
โ†“
โšกNode A
โšกNode B
โšกNode C
With a shared cache, one fill helps every app server.
๐Ÿง Two questions every distributed cache must answer
1. Which node holds this key? (partitioning / sharding). 2. What if that node dies? (replication and failover).

03Real-Life Example

๐ŸตLibrary branches
A city has one huge library with every book. Walking there is slow. So the city opens branch libraries with the popular books. There are rules: books A to H are in branch 1, I to P in branch 2, and so on. If a branch burns down, a second branch keeps copies of its books.
City libraries
Distributed cache
Central library
Database (slow, has everything)
Branch library
Cache node (fast, popular items)
โ€œA to H go to branch 1โ€ rule
Partitioning: key โ†’ node
Branch keeps copies for another branch
Replication
Reader asks the front desk which branch
Client or proxy routing
One book everyone wants
Hot key
One lookup
๐Ÿ–ฅ๏ธApp serverget user:42
โ†’โ†“hash(user:42)
๐ŸงฎRouterpicks Node B
โ†’โ†“
โšกNode Bhit: returns value
โ‡ขโ‡ฃmiss
๐Ÿ—„๏ธDatabase

04Why Do We Need It?

๐Ÿ“ˆMore memory
Ten nodes with 64 GB each hold 640 GB. One machine cannot.
๐Ÿš€More throughput
Requests are shared across nodes, so no single node is the limit.
๐Ÿ›ŸSurvives failures
With replicas, a dead node does not wipe out your cache.
๐ŸคOne shared view
All app servers see the same cached data.
๐Ÿ”ŒStateless app servers
Sessions and shared data live in the cache, not inside one server.
๐Ÿ›ก๏ธProtects the database
A fast shared layer takes the read load off your DB.
When one cache machine is not enough in size, speed or safety, spread the cache over many.

05Where Do We Use It?

๐Ÿ‘คLogin sessions
So any app server can recognise a user.
๐Ÿ“„Database query results
Product pages, profiles, feeds.
๐ŸงพComputed values
Counts, scores, recommendations that are costly to compute.
๐ŸšฆRate limit counters
Shared counters across all servers.
๐Ÿ†Leaderboards
Redis sorted sets are a classic fit.
๐Ÿ”ŒAPI responses
Cache results from slow outside services.

06Types / Parts / How It Works

Redis and Memcached, in simple words

PointMemcachedRedis
Data typesSimple key and value (strings)Strings, lists, sets, sorted sets, hashes and more
ReplicationNot built inBuilt in (a primary and replicas)
Saving to diskNo, memory onlyOptional (snapshots, append log)
ClusteringDone by the client (it picks the node)Redis Cluster splits keys into slots across nodes
ThreadsMulti-threadedMostly one main thread for commands (newer versions add some I/O threads)
Good forA plain, fast cacheCache plus counters, queues, leaderboards, sessions

How do we choose the node for a key?

Modulo: hash(key) % N
Simple, but fragile
  • Easy to understand
  • Add or remove a node and N changes, so most keys map to a new node
  • A big wave of misses hits the database
Consistent hashing
Nodes and keys sit on a ring
  • Add or remove a node and only a small share of keys move
  • Virtual nodes spread the load evenly
  • Used by many cache clients and databases

Redis Cluster uses a related idea: 16,384 fixed hash slots split among the nodes. Moving a slot moves only that slotโ€™s keys. Read more in Consistent Hashing.

Who does the routing?

StyleHow it worksGood and bad
Client-sideThe client library knows all nodes and picks oneNo extra hop. Every client must know the topology.
Proxy-basedA proxy sits in front and routes requestsClients stay simple. The proxy is one more thing to run and to make highly available.
Server-side redirectAny node can answer โ€œask node B insteadโ€Used by Redis Cluster (MOVED replies). Smart clients cache the map.

Replication and failover

Primary and replica
โšกPrimaryreads and writes
โ†’โ†“copies data
โšกReplicastandby / reads
โ‡ขโ‡ฃpromoted if primary fails
โšกNew primary
If the primary dies, a replica is promoted. Replication is usually asynchronous, so the last few writes can be lost.
VisualizerAdd a node, crash a nodeSwitch between Modulo and Consistent hashing, then add a node. Then crash one with replication on and off.
How keys are placed
Replication
Hot key (k7)
๐Ÿ—„๏ธ Node A5 keys
k20k21k22k23k24
Requests21%
๐Ÿ—„๏ธ Node B19 keys
k1k2k3k4k5k6k7k8k9k10k11k12k13k14k15k16k17k18k19
Requests79%
๐Ÿ—„๏ธ Node C0 keys
empty
Requests0%
Nodes
3
Keys moved
โ€“
Modulo would move
โ€“
Ring would move
โ€“
Keys lost
0
24 keys are spread over 3 cache nodes. Add a node, remove one, or crash one, then look at how many keys had to move.

07How to Use It / Steps / Implementation

Designing a distributed cache layer

  1. 1
    Decide what to cache
    Hot, read-heavy data that is costly to get. Not everything.
  2. 2
    Choose the tool
    Memcached for a plain cache. Redis if you need replication or richer data types.
  3. 3
    Choose how keys map to nodes
    Prefer consistent hashing or fixed slots over plain modulo.
  4. 4
    Add replicas
    At least one copy per shard, in another machine or zone.
  5. 5
    Pick eviction and memory limits
    Each node needs a max memory and an eviction rule (for example LRU).
  6. 6
    Choose a read pattern
    Usually cache-aside: check the cache, then the DB, then fill the cache.
  7. 7
    Plan for failure
    Timeouts, retries with limits, and a fallback to the database that will not overload it.
  8. 8
    Monitor
    Hit ratio, memory, evictions, latency and the busiest keys.
โš ๏ธHot keys and big keys
One hot key (like a celebrityโ€™s profile) can overload the node that holds it, even if keys are spread evenly. Fixes: a tiny local cache in each app server, or splitting the key into several copies (k#1, k#2). A big key (a huge list) slows its node. Keep values small or split them.

08Key Terms to Know

TermMeaning in easy words
NodeOne cache server in the group
Shard / partitionA slice of the keys that lives on one node
ReplicaA copy of a shard on another node
PrimaryThe node that takes writes for a shard
FailoverSwitching to a replica when the primary fails
Consistent hashingA way to map keys to nodes so few keys move when nodes change
Hash slotOne of a fixed number of buckets of keys (Redis Cluster uses 16,384)
Hot keyA key that gets far more requests than others
Big keyA key with a very large value
EvictionRemoving items when memory is full
Hit ratioThe share of reads served from the cache
Split brainTwo nodes both think they are the primary

09Pros, Cons and Trade-offs

โœ… Pros
  • Scales memory and traffic by adding nodes
  • Survives node failures with replicas
  • Shared by all app servers
  • Protects the database
โš ๏ธ Cons
  • More machines, more cost, more to monitor
  • Network hop on every lookup
  • Data can be stale or lost on failure
  • Resharding and hot keys are tricky
  • Cache and database can disagree

Trade-offs

ChoiceWe gainWe lose
Replication onFailover, no cold cache after a crashMore memory, copies can lag behind
Replication offCheaper, simplerA crash loses data and floods the DB
Consistent hashingFew keys move when nodes changeMore complex than modulo
Client-side routingNo extra hopEvery client needs the node list
Proxy routingSimple clientsAn extra hop, another system to run

10Common Problems and Mistakes

Common mistakes

  1. Using modulo and then adding a node. Most keys move, the cache looks empty, and the database is hit hard.
  2. No replicas. One crashed node wipes out its keys and causes a wave of misses.
  3. Treating the cache as the only copy of the data. A cache can lose data at any time. The database is the source of truth.
  4. No memory limit or eviction rule. The node runs out of memory.
  5. Ignoring hot keys. One node melts while others are idle.
  6. No timeout on cache calls. A slow cache makes the whole app slow.

Problems to know

๐Ÿ”ฅHot key
One key gets a flood of traffic.
๐Ÿ˜Big key
One huge value blocks its node.
๐Ÿง Split brain
A network split makes two primaries.
๐ŸŒŠStampede after a crash
Missing keys all go to the DB at once.

11Real-World Examples

๐Ÿ”ดRedis
Used for caches, sessions, leaderboards and rate limits in countless companies.
๐Ÿง Memcached
A long-time, simple, fast cache used by many large web sites.
โ˜๏ธManaged cache services
Amazon ElastiCache, Azure Cache for Redis and Google Memorystore run clusters for you.
๐Ÿ“ธSocial feeds
Profiles and recent posts are cached in large clusters to protect the database (general idea).
๐Ÿ›’Shopping carts and sessions
Stored in a fast shared store so any server can serve the user.
๐ŸŽฎGame leaderboards
Sorted sets give instant top-10 lists.
๐Ÿ“Note
These are general ideas. Real clusters vary in size and settings.
A typical setup
๐Ÿ–ฅ๏ธApp
๐Ÿ–ฅ๏ธApp
๐Ÿ–ฅ๏ธApp
โ†“
Shard 1
โšกPrimary
โšกReplica
Shard 2
โšกPrimary
โšกReplica
โ‡ฃmisses
๐Ÿ—„๏ธDatabase
App / replica Primary On a miss
Each shard has a primary and a replica. App servers read and write through the cache first.

12Related Topics to Read Next

What is Caching?โ†’

The basics this topic builds on.

Consistent Hashingโ†’

The key idea for spreading keys over nodes.

Cache Eviction Policiesโ†’

What each node does when its memory is full.

Cache Stampedeโ†’

What happens when many keys vanish at once.

Cache Warmingโ†’

Fill a new or restarted node before users arrive.

Single Point of Failure (SPOF)โ†’

Replicas remove the cache as a single point of failure.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: one shared cache made of many nodes.
  • โœ”Why: more memory, more speed, survives failures, shared by all servers.
  • โœ”Key to node: prefer consistent hashing or hash slots over modulo.
  • โœ”Safety: replicas and failover. Remember replication can lag.
  • โœ”Tools: Memcached (simple) and Redis (rich, replication, cluster).
  • โœ”Watch for: hot keys, big keys, and stampedes after failures.
  • โœ”Rule: the database is the truth. The cache can lose data.
  • โœ”One line: โ€œA distributed cache is a shared, fast memory made of many machines, with a rule that says which machine holds which key.โ€
โ† Previous
CDN
Next โ†’
Cache Stampede