LazyLayersv9.1.0
Learn caching

Distributed cache system design

Distributed cache system design as an interview answer and a real build: sizing math, consistent hashing, L1 and L2, replication, hot keys, failures, Node.js.

A distributed cache is a cache shared by many application servers over the network, with its data spread across several cache nodes. Every server reads the same cached values, and capacity grows by adding nodes. Cache system design is the job of choosing how the data is split, copied, expired and kept correct while servers and nodes come and go.

Level: ten to a hundred · You need: The cache-aside pattern, Redis cache in Node.js and Cache stampede

This lesson is written as an interview answer and as a real build. Interviewers for "design a distributed cache" (a common system design interview question) follow one path: requirements, numbers, a high-level design, deep dives, failure cases. We follow it, then build the result in Node.js.

Rendering diagram...

What requirements do you ask for first?

Ask before you draw. The answers change the design.

TypeRequirementWhy it matters
Functionalget, set with a TTL, deleteThe smallest API a cache needs
FunctionalDelete by tag or patternClearing every key for one user or product is a common need
FunctionalValues are rebuildable from a source of truthIf they are not, you are designing a database, not a cache
Non-functionalLow latency, for example under 1 ms at the 99th percentileDecides whether an in-process layer is needed
Non-functionalHigh availabilityA cache outage must not become a site outage
Non-functionalScalable capacity and throughputDecides sharding
Non-functionalBounded staleness, for example under 5 sDecides TTLs and invalidation

Say what you leave out: strong consistency, transactions and durability. A cache that must never be stale is a database.

How do you estimate size and traffic?

Show the method, and give the answer after it. The inputs below are an example, not a real system.

Input (example)Value
Peak reads50,000 per second
Peak writes5,000 per second
Keys100 million
Average value size1 KB
Target hit ratio95%
Replication1 replica per shard
Usable memory per node32 GB
  1. Data size. 100 million keys × 1 KB = 100 GB.
  2. With replicas. One replica doubles it to 200 GB.
  3. Nodes. 200 GB ÷ 32 GB = 6.25, so 7 nodes. Keep headroom for growth and uneven shards.
  4. Database load. 5% misses × 50,000 reads = 2,500 reads per second reach the database, instead of 50,000.
  5. Network. 50,000 reads × 1 KB = 50 MB per second, about 400 Mbit per second, which one network link can carry.

The hit ratio does the most work in this arithmetic. Moving from 95% to 99% cuts database reads from 2,500 to 500 per second.

What does the high-level design look like?

The diagram above is the whole design. A client request reaches an app server. The server checks its own memory (L1), then the shared cache (L2), and only then the database. Writes go to the database and then invalidate the cache. An event bus tells every server to drop its local copy.

The rest of this lesson goes through each box and what breaks.

Local cache or distributed cache?

Local cache (in process)Distributed cache (shared)
Read costNanosecondsA network round trip, about 0.5 ms in a datacenter ("Latency numbers every programmer should know")
CapacityOne process's memoryThe sum of all nodes
ConsistencyEach server has its own copyOne copy that every server sees
FailureDies with the processSurvives a server restart
Cold startEvery deploy starts emptySurvives deploys

You rarely pick one. A local copy next to the application is called a near cache, and a shared store behind it is the distributed cache.

What about caching in microservices?

Each service should own its cache keys, with a namespace per service such as orders: or catalog:. One service reading another service's cache keys couples their data formats. If service B must know when service A's data changed, A publishes an event, and B drops its own copy.

Multi-level caching: L1 and L2

A multi-level cache, or multi level cache, keeps the same data in two or more layers ordered by distance. L1 is process memory. L2 is the shared store, usually Redis. A read walks from the nearest layer outward and fills the nearer layers on the way back.

Rendering diagram...

L1 keeps the hottest keys at nanosecond speed and takes read load off Redis. L2 means a server that just started, or just evicted a key, still avoids the database. The cost is that L1 is a copy per server, so L1 TTLs are short (10 seconds in lazy-layers-cache by default) and L1 holds a bounded number of entries. See multi-tier layers and layers.

How do you shard with consistent hashing?

One node cannot hold 200 GB, so the keys are split across nodes. The obvious rule is hash(key) % N, and it has a flaw: when N changes, almost every key maps to a new node. Going from 4 to 5 nodes moves about 80% of keys, and the cache starts nearly empty.

Consistent hashing fixes this with a circle. Hash each server to a point on the circle and hash each key to a point. A key belongs to the first server clockwise from it.

Rendering diagram...

Add a node and it takes over only the keys between it and its counterclockwise neighbor, about 1/N of them. Remove a node and its keys move to the next one.

With three points, one node can own a large arc by luck. Virtual nodes fix that. Each server appears at many points on the circle (100 to 200 is common), so the load evens out, and a failed server's keys spread over many neighbors instead of crushing one.

hash-ring.ts
import { createHash } from 'node:crypto'

function hash(value: string): number {
  return createHash('sha1').update(value).digest().readUInt32BE(0)
}

type Point = { hash: number; node: string }

export class HashRing {
  private points: Point[] = []
  private readonly virtualNodes: number

  constructor(nodes: string[], virtualNodes = 150) {
    this.virtualNodes = virtualNodes
    for (const node of nodes) this.add(node)
  }

  add(node: string): void {
    for (let i = 0; i < this.virtualNodes; i++) {
      this.points.push({ hash: hash(`${node}#${i}`), node })
    }
    this.points.sort((a, b) => a.hash - b.hash)
  }

  remove(node: string): void {
    this.points = this.points.filter((point) => point.node !== node)
  }

  // The first point clockwise from the key's hash owns the key.
  nodeFor(key: string): string {
    if (this.points.length === 0) throw new Error('the ring has no nodes')
    const target = hash(key)
    let low = 0
    let high = this.points.length
    while (low < high) {
      const mid = (low + high) >> 1
      if (this.points[mid]!.hash < target) low = mid + 1
      else high = mid
    }
    return this.points[low % this.points.length]!.node
  }
}

In a run of this code with 10,000 keys on 4 nodes, each node held 2,283 to 2,741 keys, and adding a fifth node moved 2,278 keys. With hash % N on the same sequential IDs, 8,000 would have moved.

Redis Cluster does the same job with a fixed table instead of a ring. It maps every key to one of 16,384 hash slots (CRC16 of the key, modulo 16,384), and each node owns a range of slots. Adding a node means moving slots to it. If you run Redis Cluster, you do not write a ring yourself.

How do replication and failover work?

Each shard has a primary and one or more replicas. Writes go to the primary and copy to the replicas, usually asynchronously. If the primary dies, a replica is promoted, by Redis Sentinel or by Redis Cluster itself.

Asynchronous replication means the last few writes can be lost during a failover. For a cache that is acceptable, because the source of truth is the database and a lost entry is a miss. It would not be acceptable for a database.

Without a replica, a lost shard turns all of its keys into misses at once, and the database takes the load. This is why replicas and stampede protection go together.

What gets evicted when memory is full?

A cache has a fixed size, so it must choose what to drop. LRU (least recently used) drops the entry untouched for the longest time and is the usual default. LFU drops the least frequently used. Redis exposes these as maxmemory-policy values such as allkeys-lru and allkeys-lfu.

"Design an LRU cache" is a separate interview question: a hash map for lookup plus a doubly linked list for order gives O(1) get and put. The LRU cache lesson builds it, and covers SIEVE and S3-FIFO, the policies lazy-layers-cache can use in L1.

How do you keep every server's copy correct?

Cache coherence is the requirement that all copies of one piece of data agree. The term comes from CPU caches, where each core holds a copy of memory. In an application, every server's L1 entry for user:42 is such a copy, and so is the Redis entry. A write to the database makes all of them old.

Deleting the key in Redis is not enough, because it does not reach the L1 copies in other processes. The standard answer is an event bus: the server that writes the data publishes "key user:42 changed", and every server drops its local copy. Redis Pub/Sub, Redis Streams, NATS and RabbitMQ all work.

Two details matter:

  • Messages can be late or lost. Keep a TTL as the backstop, so a missed event ends in staleness measured in seconds, not forever.
  • Order matters. A delayed "set" event must not undo a newer delete. A per-key version or generation lets receivers ignore an older event.

See cache invalidation for when to delete versus expire.

How do you handle a hot key?

A hot key is one key with far more traffic than the others, such as the home page config or a viral product. Consistent hashing places each key on exactly one node, so that node takes all the traffic while the rest sit idle. Adding nodes does not help.

FixHow it worksTrade-off
Local L1 copiesEach app server keeps the value in memory for a few seconds, so only one read per server per TTL reaches RedisStaleness up to the L1 TTL
Key splittingStore the value under hot:1 to hot:8 and read a random one, so the load spreads over several nodesA write must update all copies
Replica readsSend reads for that shard to its replicasReplicas lag the primary

Local copies are the cheapest and fix most cases.

What about stampedes?

When a hot key expires, every server misses at the same moment and all of them query the database. The fixes are to share one load per key inside a process, to let one server in the fleet load while the others wait, and to refresh before the TTL ends. Read cache stampede and the stampede protection guide.

What happens when the cache fails?

The rule is that the cache degrades the request but never fails it.

  • Fail open. If a cache read errors or times out, treat it as a miss and go to the database.
  • Serve stale. If the database is slow or down, return the last known value past its TTL for a short window.
  • Circuit breakers. After repeated failures, stop calling a sick cache node for a few seconds, so requests do not queue on it.
  • Timeouts everywhere. A cache call with no deadline can hold a request open longer than the database call it was meant to avoid.

See resilience for how lazy-layers-cache applies each one.

What do interviewers ask, and how do you answer?

QuestionA short model answer
Why add a cache?Reads repeat, and memory is faster than the database. A cache cuts latency and database load. It trades freshness for speed.
Local or distributed?Both. L1 for nanosecond reads of hot keys, L2 for a shared copy and capacity that outlives one process.
How do you split the data?Consistent hashing with virtual nodes, or Redis Cluster hash slots. Adding a node moves about 1/N of the keys.
What if a node dies?Promote a replica. Without one, its keys become misses, so protect the database from the burst.
Which eviction policy?LRU by default, LFU when popularity is stable, and a bounded L1 so memory cannot grow without limit.
Cache-aside or write-through?Cache-aside for most apps: read through the cache, write to the database, then delete the key. See caching strategies.
How do you keep copies consistent?Delete after the commit, publish the delete on an event bus, and keep a TTL as the backstop.
How do you handle a hot key?Local L1 copies first, then key splitting if one value is still too busy.
How do you stop a stampede?One load per key per process, a lease so one server loads for the fleet, TTL jitter, and early refresh.
What if Redis goes down?Fail open to the database, serve stale values briefly, and use a breaker so requests do not wait on a dead node.
How do you size it?Keys × value size × replicas, divided by memory per node, plus headroom. Check it against the target hit ratio.

Build it with lazy-layers-cache

The pieces above (L1 memory, Redis L2, an event bus, load sharing, fail-open reads) are one setupCache call. Redis Pub/Sub is the default event bus.

cache.ts
import { setupCache } from 'lazy-layers-cache'

export type Product = { id: string; name: string; priceCents: number }

export const cache = await setupCache<string, Product>({
  namespace: 'catalog-api',
  redis: { required: true }, // L2 and the event bus, from REDIS_URL
  ttlMs: 300_000, // L2 lives 5 minutes
  levels: { L1: { policy: 's3fifo', maxEntries: 10_000 } }, // L1 is bounded
})
products.ts
import { cache, type Product } from './cache.ts'
import { db } from './db.ts'

export function getProduct(id: string): Promise<Product | undefined> {
  return cache.getOrSet(`product:${id}`, () => db.products.find(id), {
    ttlJitter: 0.1, // spread expiry so keys do not all expire together
  })
}

export async function getProducts(ids: string[]): Promise<(Product | undefined)[]> {
  return cache.getOrSetMany(ids.map((id) => `product:${id}`), async (missing) => {
    const rows = await db.products.findMany(missing.map((key) => key.slice('product:'.length)))
    return new Map(rows.map((row) => [`product:${row.id}`, row]))
  })
}

export async function renameProduct(id: string, name: string): Promise<void> {
  await db.products.update(id, { name }) // commit first
  await cache.invalidate(`product:${id}`) // then drop L1 on every server, L2, and in-flight loads
}

This maps onto the design:

Design concernWhat the library does
Multi-level read pathgetOrSet reads L1, then L2, then your loader, and fills the layers.
Coherenceinvalidate publishes on the event bus, so every server drops its L1 copy. Every delete advances a per-key generation, so a late older set event is ignored.
StampedesCallers in one process share one load, and a Redis lease lets one server load for the fleet. In a recorded run, 1,200 callers on 6 servers caused 20 origin loads.
Redis failureAn L2 error is a miss, and fail-safe returns a stale value if the loader fails. In a recorded run, a 4 s Redis freeze caused 0 errors, and the worst stale value was 56 ms old.
Round tripsRedis calls in the same tick run as one Lua script per 64 keys. In a recorded run, reading 500 keys took 8 script calls instead of 500.
Hot keysA hot key is served from L1 after its first load, so Redis sees one read per server per L1 TTL.

The batching numbers apply to standalone Redis and Sentinel. On Redis Cluster each call runs its own script, because a script cannot span slots. Sharding itself is Redis Cluster's job here. See batch scripts and the event bus guide.

To go from one server to a fleet, read multi-instance setups and production. To test it under load, see load testing.

You have now seen the whole arc: a Map, a bounded cache, Redis, a database behind it, and a fleet that stays correct. Back to the course overview.

Further reading

Questions

What is a distributed cache?

A distributed cache is a cache shared by several application servers over the network, with its data spread across multiple cache nodes. Every server reads the same cached values, and total capacity grows by adding nodes instead of memory on one machine. Redis Cluster and Memcached pools are common examples.

How do you design a distributed cache in a system design interview?

State the requirements, estimate size and traffic, then draw clients, app servers, cache shards with replicas, and the database. Go deeper on consistent hashing, eviction, invalidation, hot keys, stampedes, and what happens when a node dies. Name each trade-off aloud, such as freshness against latency.

What is consistent hashing and why does a cache use it?

Consistent hashing places servers and keys on a circle, and each key belongs to the first server clockwise from it. When a server joins or leaves, only about 1/N of the keys move, instead of most of them with hash % N. A cache uses it so adding a node does not empty the cache.

What is the difference between a local cache and a distributed cache?

A local cache lives in one process's memory, so reads take nanoseconds but each server holds its own copy and copies can disagree. A distributed cache is one shared store reached over the network, so reads cost a round trip but all servers see the same value. Most systems use both.

What is cache coherence?

Cache coherence means that every copy of the same data agrees. The term comes from CPU caches. In an application, each server's in-memory copy of a key is a separate cache line, so a write must reach every copy through an invalidation event, a short TTL, or both.

How do you handle a hot key in a distributed cache?

A hot key sends all its traffic to one cache node, and consistent hashing cannot split it. Keep a short-lived copy in each app server's memory so most reads never leave the process. If one value is still too busy, store several copies under suffixed keys and read a random one.

On this page