System designPerformanceIntermediate

Caching in System Design

From first principles to millions of requests per second: where to cache, how reads and writes interact with the cache, how caches fail, and how to talk about all of it in an interview.

The short answerA cache is a small, fast store (usually memory) that keeps copies of data that is expensive to fetch or compute, so repeated requests skip the slow database or service. It trades freshness and extra complexity for lower latency and less load. The database stays the source of truth; the cache is an optimisation you must be able to invalidate, lose and rebuild safely.

HLD book
01Fundamentals

What is a cache?

A faster storage layer that keeps frequently used, or expensive-to-compute, data close to whoever needs it.

Say your app shows a user profile. Reading it from a distributed database might take 5 to 20 milliseconds and a little database CPU. Reading the same bytes from memory in Redis takes well under a millisecond and costs the database nothing. Do that for every page view and the difference decides whether you need one database or ten.

That is the whole idea: pay once to fetch something, then serve the copy many times. Everything else in this guide is about the two hard parts, keeping the copy acceptably fresh and surviving when the cache misbehaves.

Without a cache

Every request reaches the database or downstream service.

  • Higher latency on every read
  • More load on the database
  • Traffic spikes hit the database directly

With a cache

Repeated reads are served from memory.

  • Sub-millisecond reads for hot data
  • Far fewer database queries
  • Spikes are absorbed before the database
02Architecture

Where can you cache?

Almost every layer between the user and the database can cache something. Large systems combine several layers instead of relying on one Redis cluster.

A request, layer by layer
UserBrowser or mobile app
Browser / CDN cacheStatic assets, images, public pages
Application serversLocal in-memory (L1) cache
Distributed cacheRedis or Memcached (L2)
DatabaseSource of truth

Each layer you hit saves the ones below it. A CDN hit never reaches your servers; a Redis hit never reaches your database.

Browser cache

CSS, JavaScript, fonts and cacheable API responses, controlled with Cache-Control and ETag headers.

CDN / edge cache

Static and public content stored in data centres close to users.

Local application cache

A small per-process cache with microsecond reads. Each server has its own copy.

Distributed cache

A shared cache such as Redis that every application server reads from.

Database cache

Buffer pools and page caches the database manages itself.

Computed-result cache

Expensive calculations: search results, recommendations, rendered pages.

03Core interview topic

Caching strategies

Saying “we'll add Redis” isn't an answer. Interviewers want to hear how reads and writes move between the cache and the database.

  1. Cache-aside

    Lazy loading
    Read
    The app checks the cache. On a miss it reads the database and writes the result into the cache.
    Write
    The app writes to the database and deletes the cached key.
    Good for
    Read-heavy systems where only some rows are ever hot.
    Trade-off
    The first read after a miss is slow, and data can be stale if a delete fails.
  2. Read-through

    The cache loads for you
    Read
    The app asks the cache. The cache itself loads missing data from the store.
    Write
    Depends on the cache; usually paired with write-through or invalidation.
    Good for
    Keeping loading logic out of application code.
    Trade-off
    Needs a cache or library that supports loaders.
  3. Write-through

    Synchronous write
    Read
    Usually served straight from the cache.
    Write
    Each write updates the cache and the database before success is returned.
    Good for
    Data where cache and database must agree after every write.
    Trade-off
    Slower writes, since two systems are updated each time.
  4. Write-back

    Write-behind
    Read
    Usually served from the cache.
    Write
    The write lands in the cache first; the database is updated later in batches.
    Good for
    Very high write rates where a small delay is fine.
    Trade-off
    Writes not yet flushed are lost if the cache fails.
  5. Refresh-ahead

    Proactive refresh
    Read
    Hot keys are reloaded shortly before their TTL ends, so readers never see a miss.
    Write
    Combined with another strategy, usually cache-aside.
    Good for
    Very hot, predictable keys where an expiry would cause a spike.
    Trade-off
    May refresh data nobody asks for again.

Cache-aside, step by step

Cache-aside read path
Client
APIGET /users/42
RedisGET user:42 → miss
DatabaseSELECT … then SET in Redis

On a hit, the flow stops at Redis. On a miss, the API loads the row, stores it with a TTL, and returns it.

Cache-aside read with a TTLjs
async function getUser(userId) {
  const key = `user:${userId}`;

  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);           // hit

  const user = await db.getUser(userId);           // miss: go to the source
  if (!user) return null;

  await redis.set(key, JSON.stringify(user), "EX", 300); // keep for 5 minutes
  return user;
}
04Memory management

Cache eviction policies

Cache memory is finite. When it fills up, something has to go. The eviction policy decides what.

PolicyEvictsWorks well when
LRUThe least recently used keyRecent access predicts future access: sessions, feeds.
LFUThe least frequently used keyLong-term popular items must survive bursts of one-off reads.
FIFOThe oldest inserted keyYou want the simplest possible policy.
TTLKeys whose time is upData goes stale after a known period.
RandomAny keyOverhead matters more than precision.
05The hard part

Cache invalidation

Caching is easy when data never changes. The hard part is keeping cached data fresh enough after writes.

Delete on write

Update the database, then delete the key. The next read loads the fresh value. The usual default.

Update the cache

Update the database, then overwrite the cached copy. Faster next read, but concurrent writers can race.

Let the TTL expire

Accept stale data for a bounded time and let keys expire naturally. Simple, but never immediate.

Update, then invalidatejs
async function updateUser(userId, changes) {
  await db.updateUser(userId, changes);   // 1. the source of truth first
  await redis.del(`user:${userId}`);     // 2. drop the stale copy
  return { ok: true };
}
06High traffic

Cache stampede (thundering herd)

A hot key expires, and thousands of requests discover the miss in the same instant.

What a stampede looks like
Req 1
Req 2
Req 3
Req N
Redishot:key expired → miss for everyone
DatabaseThousands of identical expensive queries at once

Six ways to stop it

Single-flight / mutex

Only one request rebuilds the value; the others wait for it or get the old one.

TTL jitter

Add a random offset to expiry times so keys don't all expire together.

Stale-while-revalidate

Serve the slightly stale value while one background job refreshes it.

Refresh-ahead

Reload very popular keys before their TTL runs out.

Request coalescing

Merge identical concurrent misses into one backend call.

Rate-limit the misses

Cap how much miss traffic may reach the database.

TTL jitterjs
const BASE_TTL = 300;                              // 5 minutes
const jitter = Math.floor(Math.random() * 60);     // + 0 to 59 seconds

// keys written together now expire across a whole minute, not one second
await redis.set(key, value, "EX", BASE_TTL + jitter);
07Hot keys

The celebrity problem

A celebrity posts, and tens of millions of people request the same profile. One key becomes far hotter than everything else, and its shard melts.

One key, one shard, all the traffic
User
User
User
User
celebrity:123A single Redis key on a single shard

The cluster has spare capacity overall, but sharding sends every request for this key to one node.

Local L1 cache

Keep the hot object inside each app server for a few seconds, so most requests never reach Redis.

Read replicas

Spread reads for the key across replicas of its shard.

Key replication

Store copies as hot:123:0 … hot:123:9 and read a random one, spreading load across shards.

CDN / edge

For public content, serve it from the edge and keep it away from your origin.

Longer TTL

If freshness allows, don't rebuild extremely popular content often.

Pre-warming

Load known hot data before a predictable event such as a sale or a match.

08Scale

How do you handle millions of requests?

One Redis node is not an architecture. At scale you shave traffic off at every layer before it can reach the primary database.

Traffic shrinks at every layer
Millions of usersWeb and mobile
CDN / edgeAbsorbs static and cacheable traffic
Load balancerSpreads requests across servers
API 1L1 cache
API 2L1 cache
API NL1 cache
Redis clusterSharded, replicated L2 cache
Database clusterPrimary, replicas, partitions
09Distributed cache

Designing Redis well

Redis is fast, but poor key design, missing TTLs or one hot shard still cause real outages.

Name keys like paths

Redis key namingtext
user:42
user:42:profile
product:1001
movie:778:show:992
show:992:seat:A10
show:992:seat:A10:lock
feed:user:42:v3

Use namespaces

user:42 and product:42 never collide, and keys are easy to scan and debug.

Always set a TTL

Keys without one go stale and use memory forever.

Keep values small

Huge serialised objects cost network, CPU and memory on every read.

Watch the hit ratio

A cache that rarely hits adds complexity for little gain.

Find hot keys early

One popular key can overload a shard while the cluster looks healthy.

Plan for Redis being down

Decide in advance what the app does without it.

10Case study

Seat booking with Redis locks

Apply caching and distributed locking to a ticketing system where 100 people tap the same seat in the same second.

Seat states

AVAILABLECan be selected
HELDTemporary Redis lock
BOOKEDSaved in the database

If payment fails, checkout is abandoned or the hold expires: HELD → AVAILABLE.

The booking flow

User selects seat A10
Seat reservation APIValidate the show and the seat
Atomic Redis lockSET show:992:seat:A10:lock <token> NX PX 300000
5-minute holdEveryone else sees the seat as taken
PaymentIdempotent, safe to retry
DatabaseConditionally mark the seat BOOKED
Acquire a temporary seat holdjs
const lockKey = `show:${showId}:seat:${seatId}:lock`;
const token = crypto.randomUUID();          // proves who owns the lock

const acquired = await redis.set(lockKey, token, "NX", "PX", 5 * 60 * 1000);
if (!acquired) {
  throw new Error("Seat is already held by another user");
}
// continue to checkout…

Why store a unique token?

User A gets the lock, then stalls. The lock expires and User B gets a new one for the same seat. When A finally cleans up, a plain DEL would delete B's lock. Checking the token first, atomically, prevents that.

Safe unlock (Lua script, runs atomically in Redis)lua
if redis.call("get", KEYS[1]) == ARGV[1] then
  return redis.call("del", KEYS[1])
else
  return 0
end

What happens when 100 people tap A10?

U1
U2
U3
U100
Redis SET … NXAtomic: only one request can create the key
1 winnerGets the hold, goes to checkout
99 othersNX fails → “seat unavailable”

Redis must not be your only protection

The Redis hold makes checkout fast under heavy concurrency, but locks can be lost on failover or expire mid-request. The final write must be guarded by the database itself:

Final guard in the databasesql
UPDATE seats
SET    status = 'BOOKED', booking_id = :bookingId
WHERE  show_id = :showId
  AND  seat_id = :seatId
  AND  status  = 'AVAILABLE';   -- 0 rows updated means someone else won

Payment succeeds

  1. Verify the payment
  2. Create the booking idempotently
  3. Mark the seat BOOKED in the database
  4. Release the Redis lock
  5. Publish a booking event

Payment fails

  1. Record the failed attempt
  2. Release the lock safely, using the token
  3. Or simply let the TTL expire
  4. The seat becomes AVAILABLE again
  5. Notify other viewers of the seat map
11Production engineering

Caching failure scenarios

A strong design answer explains what happens when the happy path breaks.

What goes wrongWhat you do
Redis goes downFail open or closed per use case. Profile reads can fall back to the database behind a circuit breaker and rate limit; seat locks need strict handling.
Cache and database disagreeThe database wins. Repair with TTLs, invalidation retries, versioned keys or change events.
Many keys expire togetherTTL jitter, refresh-ahead and staggered warm-up.
One key gets extremely hotLocal cache, replicas, CDN, key replication or precomputed responses.
Redis memory is fullSet a maxmemory policy, give every key a TTL, alert on evictions and fragmentation.
Network partitionDecide if stale reads are acceptable; never treat a distributed lock as an absolute guarantee.

Metrics worth a dashboard

  • Hit ratio
  • Miss ratio
  • p50 / p95 / p99 latency
  • Memory used
  • Evictions
  • Hot keys
  • Connections
  • CPU
  • Network I/O
  • Replication lag
12Trade-offs

When should you not cache?

Adding Redis to every design is not automatically good design. Skip the cache when:

  • The data changes constantly and stale reads are unacceptable.
  • The query is already cheap and traffic is low.
  • The expected hit ratio is tiny, because every request is unique.
  • The operational cost of another system outweighs the speed-up.
  • The data is sensitive and copying it needs a security model you don't have.
  • Every read needs strong transactional consistency.
  • Rule of thumb: measure first. Add a cache when a specific read path is slow or expensive, and know the hit ratio you expect.
Interview prep

Caching interview questions, with answers

Say your answer out loud first, then open the card to compare. These are the questions interviewers actually ask.

1

What problem does caching solve?

It cuts latency and load by serving repeated reads from a faster layer instead of the database or a remote service. That lets the same backend absorb far more traffic and smooths out spikes. The cost is possible staleness, extra memory and another component that can fail.

2

What is the difference between cache-aside and read-through?

In cache-aside the application owns the logic: it checks the cache, and on a miss it reads the database and writes the value into the cache. In read-through the application only talks to the cache, and the cache itself (or its library) loads missing values from the database. Read-through keeps application code simpler but needs a cache or library that supports loaders.

3

When would you choose write-through over write-back?

Choose write-through when the cache and database must agree after every write and you can afford the extra write latency, for example account settings or inventory counts. Choose write-back when write throughput matters more and losing the last few seconds of writes is acceptable, for example view counters or analytics.

4

What is a cache stampede?

When a popular key expires, many concurrent requests miss at the same moment and all go to the database to rebuild the same value. The database sees a sudden burst of identical expensive queries and can fall over, which is why it is also called the thundering herd problem.

5

How would you prevent a thundering herd?

Let only one request rebuild the value (a mutex or single-flight) while others wait or get the stale value; add random jitter to TTLs so keys don't expire together; serve stale-while-revalidate; refresh very hot keys ahead of expiry; and rate-limit miss traffic to the database as a last line of defence.

6

What is TTL jitter?

Adding a small random amount to each key's expiry time, for example 300 seconds plus 0 to 60 seconds. It spreads expirations out so thousands of keys written at the same time don't all expire in the same second and trigger a mass rebuild.

7

What is the celebrity or hot-key problem?

One key receives far more traffic than any other, such as a celebrity's profile or a viral post. All of that traffic lands on the single shard that owns the key, so that node saturates even though the cluster as a whole has plenty of capacity.

8

How do you invalidate the cache after a database update?

The usual pattern is: write to the database, then delete the cache key, and let the next read repopulate it. Deleting is safer than updating the cache because two concurrent updates can write cached values in the wrong order. Pair it with a TTL so any missed delete heals itself.

9

What happens if the database update succeeds but cache invalidation fails?

The cache keeps serving the old value until it expires. Defences are a short TTL as a safety net, retrying the delete from a queue, driving invalidation from the database change log (change-data-capture), or using versioned keys so new writes simply use a new key.

10

What happens if Redis is unavailable?

It depends on the data. For ordinary reads you can fail open and go to the database, but with a circuit breaker and rate limit so the database isn't flattened. For correctness-critical uses such as locks or rate limits you may need to fail closed and reject the operation. Decide this per use case before the outage, not during it.

11

How do you cache across many application servers?

Use a shared distributed cache such as a Redis cluster so every server sees the same values, optionally with a small in-process cache on each server for the hottest data. Keys are spread across shards, usually with consistent hashing or hash slots.

12

What is the difference between an L1 local cache and an L2 distributed cache?

L1 lives inside each application process: nanosecond to microsecond reads, no network hop, but each server has its own copy and keeping them in sync is hard, so TTLs are short. L2 is a shared network cache like Redis: about a millisecond away, consistent across servers, and much larger.

13

LRU vs LFU: when would you use each?

LRU evicts what hasn't been used for the longest time, which works when recent access predicts future access, like sessions or feeds. LFU evicts what is used least often, which protects long-term popular items from being pushed out by a burst of one-off reads, like a product catalogue during a scan.

14

How would you design caching for millions of requests per second?

Reduce traffic at every layer: browser and CDN for public content, an L1 cache in each server for the hottest keys, a sharded Redis cluster with replicas as L2, and only misses reaching a replicated, partitioned database. Add stampede protection, hot-key handling and monitoring of hit ratio and tail latency.

15

How would you prevent double booking using Redis?

Hold the seat with an atomic SET key token NX PX ttl so only one request can create the hold, and store a unique token so only the holder can release it. Then confirm the booking in the database with a conditional update that only succeeds if the seat is still AVAILABLE.

16

Why must the database still protect final booking correctness?

Redis locks can be lost on failover, expire while a slow request is still running, or be bypassed by a bug. The durable database is the source of truth, so a conditional update or unique constraint there is what actually guarantees one seat is sold once.

17

How do idempotency and caching interact in a payment or booking flow?

Retries are normal, so every booking request carries an idempotency key. The first request does the work and stores its result under that key; retries return the stored result instead of booking or charging again. The cache can hold that result for speed, but the record of the payment must be durable.

18

What metrics would you monitor for Redis?

Hit and miss ratio, p50/p95/p99 latency, memory use and fragmentation, eviction rate, expired keys, hot keys, connected clients, CPU and network throughput, and replication lag. A falling hit ratio or rising evictions is usually the first sign of trouble.

Check yourself

Quick quiz

6 questions. Pick an answer to see why it's right or wrong.

Question 1 of 60 / 6

Your app checks Redis, and on a miss reads the database and stores the result in Redis. Which strategy is this?

Reference

Caching glossary

The terms from this guide, in one line each.

Cache hit / miss
A hit is served from the cache; a miss has to go to the slower source.
Hit ratio
Hits ÷ total reads. Below ~80% a cache often isn't paying for itself.
TTL
Time to live: how long a key may stay before it expires.
Eviction
Removing keys because memory is full, chosen by a policy such as LRU or LFU.
Cache-aside
The application checks the cache and loads it on a miss. Also called lazy loading.
Write-back
Writes go to the cache first and reach the database later, asynchronously.
Cache stampede
Many requests rebuilding the same expired key at once. Also: thundering herd.
Hot key
One key with far more traffic than the rest, overloading a single shard.
Single-flight
Only one caller does the expensive rebuild; the rest share its result.
L1 / L2 cache
L1 is in-process on each server; L2 is a shared network cache such as Redis.
Summary

Key takeaways

  1. The database is the source of truth. A cache must be safe to lose, invalidate and rebuild.
  2. Name your strategy: cache-aside for most read-heavy systems, write-through for consistency, write-back for write throughput.
  3. On writes, update the database and delete the cache key. Keep a TTL as a safety net for missed deletes.
  4. Expect stampedes and hot keys at scale: single-flight, TTL jitter, local caches and key replication are the standard answers.
  5. Redis locks are for fast temporary holds; final correctness belongs in the database with a conditional update.
  6. Decide per use case what happens when the cache is down: fail open with protection, or fail closed.
Questions

Caching: frequently asked questions

What is caching in system design?

Caching stores frequently used data in a faster layer, usually memory, so repeated requests avoid the slower database or service. It lowers latency and load at the cost of possible staleness and extra complexity.

Is Redis a cache or a database?

Both, depending on use. Redis is an in-memory data store with optional persistence. In most system designs it is used as a cache or for short-lived shared state such as sessions, rate-limit counters and locks, with a durable database behind it.

What is a cache stampede?

A cache stampede happens when a popular cached value expires and many requests miss at the same time, all hitting the database to rebuild it. It is prevented with single-flight rebuilds, TTL jitter, stale-while-revalidate and refresh-ahead.

What is the celebrity or hot-key problem?

It occurs when one key gets far more traffic than others, overloading the single cache shard that holds it. Fixes include a local in-process cache, read replicas, replicating the key under several names, a CDN for public content and pre-warming.

Can Redis prevent double booking?

Redis can hold a seat briefly with an atomic SET NX and a TTL, which handles high concurrency well, but the database must still enforce correctness with a conditional update, and the flow should be idempotent.

How long should a cache TTL be?

As long as the data can safely be stale. Profiles might tolerate minutes, prices seconds, and static assets days. Add jitter so keys don't expire together, and rely on invalidation, not TTL alone, for data that must change immediately.

Next topicDatabase Design

SQL vs NoSQL, indexing, replication, sharding, transactions and consistency: where cache misses end up.

Go deeperMaster the full system design round

Go beyond caching: requirements, APIs, data modelling, scaling, queues, locking and complete interview designs such as BookMyShow and Uber.

  • Caching
  • Databases
  • Rate limiting
  • Queues
  • BookMyShow
  • Uber
Explore the book

Last reviewed 18 November 2026