SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
  • What is Caching?
  • Caching Strategies
  • Cache Eviction Policies
  • Cache Invalidation
  • HTTP Caching (Cache-Control, ETag)
  • Redis vs Memcached
  • Local Cache vs Distributed Cache
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/Caching Basics

Local Cache vs Distributed Cache

A cache inside each server, or one shared cache for all of them? Speed against consistency.

⏱ 12 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A local cache lives inside each app server's own memory. A distributed cache is a separate service (like Redis or Memcached) that all app servers share.

  • Local is the fastest possible read (no network), but every server has its own copy, so the copies can disagree.
  • Distributed gives one shared copy and much more space, but each read costs a network trip, and the cache is one more thing that can fail.
  • Many systems use both: a tiny, short-lived local cache in front of a shared one.

02Concept: What is it?

A local cache (also called an in-process or in-memory cache) is just a data structure inside your program: a map with a size limit and expiry times. Libraries such as Caffeine or Guava in Java give you this ready-made. Reading from it takes nanoseconds to microseconds, because there is no network, no copying between processes and no waiting.

The catch is that if you run ten copies of your app behind a load balancer, you have ten separate caches. Each one fills up on its own, and each one can hold a different version of the same data.

A distributed cache moves the cache out of the app. All the app servers talk to the same cache service over the network. There is one copy of each item (or a few, for safety), so everyone sees the same value.

Ten copies, or one shared copy
Local cache
πŸ–₯️App 1own cache: v1
πŸ–₯️App 2own cache: v2
πŸ–₯️App 3own cache: v1
↓each fills its own copy
πŸ—„οΈDatabase
Distributed cache
πŸ–₯️App 1
πŸ–₯️App 2
πŸ–₯️App 3
↓network
⚑Shared cacheone value: v2
↓on a miss
πŸ—„οΈDatabase
With a local cache, every server has its own. With a distributed cache, they all ask the same place.
🧠The trade in one line
Local is faster but can disagree. Distributed is slower (a little) but agrees.

03Real-Life Example

🍡Notes in Your Pocket or a Board on the Wall
A team of five waiters serves one restaurant. Each waiter can keep a small note in their pocket with today's specials. It is instant to check, but when the chef changes a dish, the waiters with old notes keep selling the old dish until they refresh. Or the team can look at one whiteboard in the kitchen. Everyone sees the same board, but it takes a walk to the kitchen each time. A smart team keeps a short pocket note that they replace every few minutes, and trusts the board for anything important.
Restaurant
Caching
A waiter’s pocket note
A local (in-process) cache
The whiteboard in the kitchen
A shared, distributed cache
The walk to the kitchen
The network round trip
Waiters with different old notes
Stale and inconsistent local copies
Replacing the note every few minutes
A short TTL on the local copy
The chef shouting β€œdish changed!”
An invalidation message to all servers
The recipe book in the office
The database
A read through two levels
πŸ™‹Request
→↓
πŸ“Local cacheL1: in memory
→↓miss
⚑Shared cacheL2: Redis
→↓miss
πŸ—„οΈDatabase

04Why Do We Need It?

⚑Local: the fastest read
No network at all. For a value read thousands of times a second, even a short trip adds up.
🀝Shared: one truth
All servers see the same value, and one update fixes it for everyone.
πŸ“¦Shared: more room
A cache cluster can hold far more than the heap of one app server.
♻️Shared: survives restarts
When an app server restarts or a new one starts, it does not begin with an empty cache.
πŸ›‘οΈLocal: no extra dependency
If the shared cache is down, a local cache can still answer for a short time.
🧯Both: protect hot data
A small local cache takes the load off one busy key in the shared cache.
Pick based on what hurts more: a slow read or a stale one. Often the answer is a small local cache in front of a shared one.

05Where Do We Use It?

βš™οΈLocal: config and feature flags
Small, read on every request, and fine to be a few seconds old.
πŸ”‘Local: public keys and lookup tables
Signing keys, country lists, currency codes. They rarely change.
πŸ‘€Shared: user sessions and profiles
Any server must see the same session, so the data cannot live in one server only.
πŸ›’Shared: product and price data
Must be the same on every server and large in total.
πŸ”’Shared: counters and rate limits
Many servers must add to the same number.
🧱Both: very popular items
A tiny local copy of the top items, shared cache for everything else.

06Types / Parts / How It Works

Side by side

Local cacheDistributed cache
Where it livesInside each app processA separate cache service (Redis, Memcached)
Read speedMemory speed, no networkOne network round trip (often well under a few milliseconds)
Copies of the dataOne per app server, can differOne shared copy (maybe replicas)
Size limitPart of the app heap, repeated on every serverSpread over many machines, much larger
After a restartStarts empty (cold) for that serverKeeps its data (if the cache itself stays up)
Update everywhereHard: needs expiry or a broadcastEasy: change the one copy
If it failsOnly that server is affectedEvery server loses it at once
Extra costNone to runServers to run, secure and monitor

Three ways to keep local copies fresh

MethodHow it worksGood and bad
Short TTLEach local copy expires after a few secondsSimple. The data can be stale for up to the TTL.
Broadcast invalidationOn a change, publish a message (for example with pub/sub) and every server drops that keyFresher. Messages can be lost or late, so keep a TTL as a safety net.
Version checkStore a version number in the shared cache. The local copy is used only if its version matchesAlways correct, but every read still costs a small check.

The two-level (L1 + L2) setup

Small and short in front, big and shared behind
πŸ“L1: localsmall, TTL of seconds
→↓miss
⚑L2: sharedlarge, TTL of minutes
→↓miss
πŸ—„οΈDatabase
Fastest, may be a bit stale Shared source of truth for the cache
The local level takes most reads. The shared level keeps everyone in line and protects the database.
VisualizerChange a value and see who still serves the old oneSwitch between local, shared and two-level. Change the life (TTL) of a local copy and add servers. Watch the red cells: those are stale answers after the update at second 10.
Where do the servers keep the data?

Each app server keeps its own copy in memory. Fast, but the copies do not know about each other, and nobody tells them when the data changes.

One read per second per server, for 30 seconds. The value changes at second 10 (marked with the line).
Server 1
Server 2
Server 3
local hitshared cachedatabase readstale answer
Stale answers
6
for up to 4 s
Cache hit rate
89%
not reaching the database
Database reads
9
in 30 seconds
Average read
2.2 ms
illustrative
6 answers were stale. After the update at second 10, the servers kept serving the old value until their own copy expired, up to 4 seconds later. Nothing told them it had changed. A shorter life shrinks this window but adds more database reads.

A simplified, deterministic model. Read times are illustrative (0.05 ms local, 1 ms to the shared cache, 20 ms to the database), not measurements. The writer updates the database and, when there is a shared cache, replaces its copy at the same moment. Servers start 2 seconds apart so their local copies do not all expire together.

07How to Use It / Steps / Implementation

Choosing and using them

  1. 1
    Ask how stale is acceptable
    A feature flag that is 5 seconds old is fine. A bank balance is not. The answer decides which cache you may use.
  2. 2
    Start with the shared cache
    It is simpler to reason about, because there is one copy. Add a local cache only when measurements show the network trip or one hot key is the problem.
  3. 3
    Keep the local cache small
    Cache only the hottest, smallest items. Set a maximum size and an eviction policy, so it cannot eat the memory of the app.
  4. 4
    Give local copies a short TTL
    Seconds, not hours. The TTL is your promise about how stale an answer can be.
  5. 5
    Invalidate on change when you can
    Publish a message when the data changes, so servers drop their copy at once. Still keep a TTL, in case a message is lost.
  6. 6
    Plan for the shared cache failing
    Decide what the app does if it is down: go to the database (with protection), serve from the local cache for a while, or fail clearly.
  7. 7
    Measure hit rate at each level
    A local cache with a tiny hit rate only wastes memory. Track L1 hits, L2 hits and database reads separately.
πŸ’‘Do not cache per-user data locally by accident
If a load balancer sends a user to different servers each time, a local cache of that user's data will often miss. Either cache shared data locally, or cache user data in the shared cache.

08Key Terms to Know

TermMeaning in easy words
Local cacheA cache inside the app process, in the app’s own memory
In-process cacheAnother name for a local cache
Distributed cacheA cache service shared by many app servers, spread over many machines
L1 / L2First-level (local) and second-level (shared) cache
Round tripOne request out and one answer back over the network
Stale dataA cached value that no longer matches the truth
InconsistencyDifferent servers returning different answers for the same key
TTLTime to live: how long a cached copy may be used
Invalidation messageA message telling servers to drop a cached key (often through pub/sub)
Cold startA cache that has just started and is empty, so nearly every read misses
HeapThe memory area of a program. A local cache has to fit inside it

09Pros, Cons and Trade-offs

βœ… Pros
  • Local: the fastest reads, no network
  • Local: no extra service to run
  • Distributed: one shared value for everyone
  • Distributed: large and survives app restarts
  • Two levels: fast and fairly consistent
  • Both work well with a short TTL
⚠️ Cons
  • Local: copies drift apart
  • Local: memory repeated on every server, empty after restart
  • Distributed: a network trip on every read
  • Distributed: one more system that can fail or get overloaded
  • Two levels: more to configure and reason about
  • Invalidating many local copies is hard

Trade-offs

ChoiceWe gainWe lose
Local onlySpeed and simplicityConsistency between servers, shared capacity
Shared onlyOne truth, big capacityA network trip on every read, a shared dependency
Two levelsSpeed and bounded stalenessMore moving parts, more places to be stale
Long local TTLMore local hits, fewer shared readsStaler answers
Short local TTLFresher answersMore trips to the shared cache
Broadcast invalidationFast refresh after a changeNeeds a message channel, and lost messages must be handled

10Common Problems and Mistakes

Common mistakes

  1. Using a local cache for data that must be exact. Balances, stock and permissions need a fresher source.
  2. A long TTL on local copies. Servers keep selling an old price for minutes.
  3. No size limit. An unbounded local cache grows until the app runs out of memory.
  4. Assuming all servers agree. Two users can see different answers a few seconds apart, and bug reports are hard to reproduce.
  5. Forgetting that every server repeats the memory. 50 servers with a 500 MB local cache is 25 GB of the same kind of data.
  6. No plan when the shared cache is down. All servers go to the database at once.
  7. Many cold servers at deploy time. Every new server starts empty and asks the shared cache or database for everything.

Things to watch

πŸ₯ΆCold start
After a deploy, all local caches are empty. Warm them, or roll out in small steps.
πŸ”€Flapping answers
A user refreshes and sees the new value, then the old one, as they hit different servers.
πŸ“Memory pressure
A big local cache means more garbage collection and a risk of out-of-memory errors.
🌩️Shared cache outage
All servers fall back to the database together. Use limits and protect against a stampede.

11Real-World Examples

β˜•Java services
A local cache such as Caffeine for hot data, with Redis behind it, is a very common pairing.
πŸ”Auth and config
Signing keys and settings are cached in each process for a short time, and refreshed from a shared source.
πŸ›οΈOnline shops
Product details in a shared cache, with the top sellers also held locally during a sale.
🌍Browsers and CDNs
The same idea at another level: a copy close to the user, with a limited life.
πŸ“±Feeds
Popular posts are kept in local memory on the servers that serve them most.
🧩Sidecars and proxies
A small cache next to each service, so it need not leave the machine for common reads.
πŸ“Note
The right mix depends on your data and traffic. Measure hit rates and staleness before choosing, and treat the numbers in this lesson as examples.
Mini case: a sale on the top 20 products
πŸ‘₯Shoppers
→↓
πŸ–₯️30 app serverslocal: top 20 items, 5 s
→↓rest
⚑Redis clusterall products
→↓misses
πŸ—„οΈDatabase
Reads that never leave the app serverillustrative
A tiny local cache absorbs the crowd; the shared cache holds everything else.

12Related Topics to Read Next

What is Caching?β†’

The basic idea behind both kinds of cache.

Distributed Cache Architecture→

How a shared cache is spread over many machines.

Redis vs Memcached→

The two most common shared caches.

Cache Invalidation→

How to remove old copies, including the ones on every server.

Cache Eviction Policies→

What a size-limited local cache throws away.

Hot Keys→

A local cache is a main defence against one overloaded key.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Local: in the app's memory. Fastest, but each server has its own copy.
  • βœ”Distributed: one shared service (Redis, Memcached). One truth, more room, a network trip.
  • βœ”Local risk: stale and different answers on different servers.
  • βœ”Fix staleness: short TTL, plus an invalidation message if you can.
  • βœ”Two levels: a small local cache in front of a shared one. Most reads stay local.
  • βœ”Must be exact? Do not use a long-lived local copy.
  • βœ”Shared cache down? Every server hits the database. Have a plan.
  • βœ”One line: β€œKeep a short pocket note, and trust the shared board.”
← Previous
Redis vs Memcached
Next β†’
CDN