TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท performance ยท distributed systems ยท redis

Distributed caching

Keeping copies of frequently read data in fast shared memory, such as Redis, so every application server can skip slow database work, and keeping those copies correct as the data changes.

14 min6 animations

๐Ÿ–จ๏ธ Cheat sheet

The board next to the library

Imagine a school where every answer lives in a library at the far end of the building. It's always right, but walking there takes ages, and the librarian can only help a few people at a time.

So someone puts a board in the hallway. When you look something up in the library, you write the answer on the board on your way back. The next person who needs it reads the board and never makes the walk.

The library is the database. The board is the cache.

What a cache is for

A cache keeps copies of data somewhere much faster to read than where it really lives. Reading a key from Redis takes well under a millisecond; a database query often takes tens of milliseconds, and every query uses some of the database's limited capacity.

The most common pattern is cache-aside (also called lazy loading):

  1. Look the key up in the cache.
  2. On a hit, use it.
  3. On a miss, load from the database, store the result in the cache with a time-to-live (TTL), and use it.

The database stays the source of truth. The cache is only ever a copy, so losing it costs speed, never data.

Look on the board first5 steps
๐Ÿ“‹ Hallway answer board๐Ÿง’Curious visitor๐Ÿ“š Library (far away)
Press play and watch it happen!

One board for everyone

A school has many classrooms. If each one keeps its own notebook of answers, they drift apart: one hears the price changed, the others don't, and two classrooms give two different answers to the same question.

One shared board in the hallway fixes that. Everyone reads and writes the same board.

Local versus distributed caches

Real systems run several copies of the same application behind a load balancer. An in-process cache (a HashMap, or a library like Caffeine) is the fastest possible, but each server has its own copy. An update on one server leaves the others serving stale data until their entries expire.

A distributed cache such as Redis or Memcached is a separate service that every server talks to over the network. There's one copy of each entry, so all servers agree, and the cache survives application restarts and deploys.

Many systems use both: a small local cache with a short TTL for the hottest data, in front of the shared one.

Why the cache is shared5 steps
๐ŸซClassroom 1๐ŸซClassroom 2๐Ÿ““ Notebook 1๐Ÿ“’ Notebook 2๐Ÿ“š Library
Press play and watch it happen!

A board with limited space

The board is only so big. Every answer gets a rub-out time, so nothing stays up forever, and when the board is full the answer nobody has looked at for the longest time gets rubbed out to make room.

Expiry and eviction

Two different things remove entries:

WhyRedis
ExpiryThe entry's TTL ran outSET key value EX 600
EvictionMemory is full and space is neededmaxmemory plus a policy such as allkeys-lru

TTLs bound how stale data can get. Choose them per kind of data: a product description can live for hours, stock levels for seconds. With LRU eviction, rarely used keys drop out on their own, so the cache naturally fills with whatever is popular right now.

Expiry and eviction5 steps
๐Ÿ“‹ Board with room for 3๐Ÿง’Curious visitorPrice answerStock answerAna answer
Press play and watch it happen!

When the answer changes

When the price in the library changes, the old answer on the board is now wrong. So whoever changes the library also rubs the old answer off the board. They don't write the new one up: the next person who needs it fetches it fresh, so the board rarely ends up with a value older than the library's, and the rub-out time cleans up the rare times it does.

Invalidation

"There are only two hard things in computer science: cache invalidation and naming things." The usual approach with cache-aside:

  1. Write the change to the database first.
  2. Then delete the cache key (DEL), rather than writing the new value into the cache.

Deleting avoids a race where two concurrent writers update the cache in the opposite order to the database and leave the older value cached. The TTL is still the safety net: if the app crashes between the database write and the delete, the stale entry disappears when it expires.

Other strategies exist, such as write-through (the write goes through the cache to the database) and write-behind (the cache writes to the database later). Both trade simplicity for consistency or speed in different ways.

Keeping the board correct when data changes5 steps
๐Ÿ“‹ Hallway answer board๐Ÿง’Visitors๐Ÿ‘ฉโ€๐Ÿ’ผShop owner๐Ÿ“Œ Pencil price๐Ÿ“š Library
Press play and watch it happen!

More boards, and when a board goes wrong

A big school needs more board space than one wall can hold, so it has several boards, and every answer always goes on the same board, chosen by its name.

Boards go wrong in a few ways:

  • A popular answer is rubbed out. Everyone who was about to read it finds a blank spot and walks to the library together. The rule: only one person fetches a missing answer, and the rest wait at the board. Also, rub-out times are spread a little, so popular answers don't all vanish at once.
  • A board falls down. Everyone who needed it runs to the library at the same moment. So good schools keep a spare copy of every board, and bring answers back gradually after a fall.
  • The answer is out of date. Someone changes the library's book, and a slow reader puts the old answer back up just after it was rubbed off, or the person forgets to rub it off at all.
  • Nobody ever finds the answer. People keep asking for something that doesn't exist, and every question ends in a wasted walk. A short note on the board saying "no such thing" saves the trips, and a quick check against a list of real names stops the rest.
  • One answer is huge or wildly popular. Its board gets crowded while the others sit idle. So the school keeps answers short, and puts copies of a very popular answer on a few boards.

What can go wrong

Sharding spreads keys over several cache nodes so the cache can hold more and serve more. Redis Cluster maps every key to one of 16,384 hash slots and gives each node a range of them. Clients hash the key and go straight to the right node. (See Redis and Valkey for the server itself.)

  • Cache stampede when a hot key expires. One popular key's TTL runs out and every concurrent request misses and runs the same query. Symptom: a spike in database CPU and query latency at regular intervals, with timeouts. Fix: request coalescing (a lock or single-flight, so one request reloads and the others wait), jittered TTLs (add random seconds so many keys don't expire together), and early refresh (refresh a hot key shortly before it expires, or probabilistically as the expiry nears).
  • Stale data after a write. With cache-aside, a reader can miss, read the old row, and then write it to the cache after a writer has already updated the database and deleted the key, leaving the old value cached. A crash between the database write and the DEL loses the invalidation completely. Symptom: users see old data until the TTL passes. Fix: delete after the write (see Invalidation above) narrows the window but can't close this race. Close it with versioned values (only cache a value newer than what is there), leases, or a delayed second delete. Make invalidation survive crashes by driving it from the database's change log or an outbox, and keep a short TTL as the safety net that bounds staleness.
  • The cache goes down. When a node or the whole cluster is lost, every key misses and the database takes the full load. Symptom: connection errors from the client, a hit rate near zero, and the database saturating. Fix: replicas that take over, then failing open with limits: fall back to the database but cap concurrent queries and shed load, rather than letting a flood in or failing every request. After a restart, warm up the cache (preload hot keys) before sending full traffic.
  • Missing keys hammer the database. Lookups for keys that don't exist never find a cached value, so each one reaches the database (cache penetration), whether by accident or from an attacker. Symptom: a low hit rate with the database busy on queries that return nothing. Fix: cache the "not found" result with a short TTL (negative caching), and put a Bloom filter of the real keys in front, since it can say "definitely not present".
  • A hot key or large value saturates one node. A key's slot lives on one node, so one very popular key or a multi-megabyte value can max out that node's CPU or network while others idle. Symptom: one node with high latency and bandwidth. Fix: keep values small, split them, or copy a hot key under several names or into a small local cache in front.
ChoiceYou gainYou pay
Cache-aside vs write-throughCache-aside is simple and only caches what is read; write-through keeps the cache fresh after writesCache-aside serves stale data until invalidated and has a miss on first read; write-through makes writes slower and caches data nobody reads
Long TTL vs short TTLLong: a higher hit rate and fewer reloadsLong: staler data for longer, and a longer wait to repair a lost invalidation. Short: more misses and database load
Local vs distributed cacheLocal: no network hop, and it survives a cache outageLocal: each server holds its own copy, so copies drift. Distributed: one shared copy, but a network hop and one more thing that can fail
Fail open vs fail closed when the cache is downOpen: the app keeps workingOpen: the database may overload unless you limit it. Closed: protects the database but returns errors

In Spring, @Cacheable(sync = true) asks the cache provider to let one caller compute a missing value while the others wait (default false). It is only a hint: with Spring Data Redis 3.4+ the default lock-free RedisCacheWriter does not serialise loads. For real single-flight, put a local cache such as Caffeine (which honours sync) in front, opt into RedisCacheWriter.lockingRedisCacheWriter(...) (one lock per cache, not per key), or take your own lock. Spring's Redis cache stores null results by default (spring.cache.redis.cache-null-values is true), which gives you negative caching. A custom CacheErrorHandler (for example a LoggingCacheErrorHandler) lets calls fall through to the database when Redis throws, which is failing open.

Many cache servers, and what happens when one fails5 steps
๐Ÿซ Hallway of boards๐Ÿง’Lots of visitors๐Ÿ“‹Board A to H๐Ÿ“‹Board I to Q๐Ÿ“‹Board R to Z๐Ÿ“š Library
Press play and watch it happen!
A hot key expires and everyone misses at once4 steps
๐Ÿ“‹ Hallway answer board๐Ÿง’Crowd of visitors๐Ÿ“Œ Popular answer๐Ÿ“š Library
Press play and watch it happen!

Caching in a Java app

In a Spring app you don't have to write "check the board, else walk to the library" yourself. You put a label on a method that says "remember answers for this", and Spring checks the board before the method runs.

Spring's cache abstraction

Spring wraps cached methods in a proxy, just like @Transactional (see the Spring concept). With spring-boot-starter-data-redis and spring-boot-starter-cache on the classpath, and @EnableCaching on a configuration class:

1@Service2class ProductService {3    @Cacheable(cacheNames = "products", key = "#id")4    public Product find(long id) {          // only runs on a cache miss5        return repository.findById(id).orElseThrow();6    }7 8    @CacheEvict(cacheNames = "products", key = "#product.id")9    public void update(Product product) {   // writes the database, then deletes the cached entry10        repository.save(product);11    }12}

Set the TTL with spring.cache.redis.time-to-live. Cached values must be serializable, and the proxy rule applies here too: calling find from inside ProductService bypasses the cache.

๐Ÿ”ง Going deeper

What to cache: data that is read far more often than it changes, and expensive to compute or fetch. Don't cache data that must always be exact, such as an account balance at the moment of payment.

Measure it: watch the hit rate. A cache with a low hit rate adds a network hop to every request and saves almost nothing.

๐Ÿ—๏ธ Design it in CloudArch

Build the architecture on a canvas, push load through it and see what breaks.

  • ๐ŸŽฏMission: the database pays for repeated readsAdd a cache and set its hit rate, until the monthly bill drops under $3,000.10-minute mission
  • ๐Ÿ“ฐDesign a news feedThe latest posts from everyone you follow, instantly, at scale.practice problem
  • ๐Ÿ”—Design a URL shortenerShort codes for long links, and billions of redirects.practice problem

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Distributed caching, told the same way as the story.
  1. Why put a board in the hallway?
  2. The price changes in the library. What does whoever changed it do to the board?
  3. One board falls down. Why is that dangerous?
  4. A very popular answer is rubbed out and a crowd arrives. What stops them all walking to the library?
  5. People keep asking for an answer that exists nowhere. Why does every question still reach the library?
Answer every question to check.Passing marks Distributed caching as done.
Got the hang of Distributed caching? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ•ธ๏ธ Distributed systems from zeroStep 6 of 7

โ† Previous on the pathโญ• Consistent hashingNext on the path โ†’๐Ÿ“ฌ Apache Kafka

๐ŸŽฏ Backend interview prepStep 7 of 9

โ† Previous on the pathโšก Circuit breakers and retriesNext on the path โ†’โš–๏ธ CAP theorem

๐Ÿงฐ Caching with Redis, Valkey and HazelcastStep 1 of 8

Next on the path โ†’๐ŸŽฝ Redis and Valkey

๐Ÿ‘‰ Read next

  • โญ•Consistent hashingPlates around a round table: when someone sits down or leaves, only their neighbours' plates change hands.
  • ๐Ÿ—ž๏ธAmazon CloudFrontA newsstand in every neighbourhood, sending a runner to the print works only when its copy is missing or stale.
  • ๐ŸชAmazon ElastiCacheHiring an agency to run your shop's express counter, staff and standby clerk included, while you choose what it stocks.
  • ๐ŸHazelcastWorker bees sharing honey in numbered cells, each copied to a second bee, so work goes to the honey.
  • ๐ŸŽฝRedis and ValkeyA sports club's kit room by the pitch, with labelled cubbies and one quick kit manager handling each request.