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):
- Look the key up in the cache.
- On a hit, use it.
- 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.
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.
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:
| Why | Redis | |
|---|---|---|
| Expiry | The entry's TTL ran out | SET key value EX 600 |
| Eviction | Memory is full and space is needed | maxmemory 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.
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:
- Write the change to the database first.
- 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.
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
DELloses 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.
| Choice | You gain | You pay |
|---|---|---|
| Cache-aside vs write-through | Cache-aside is simple and only caches what is read; write-through keeps the cache fresh after writes | Cache-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 TTL | Long: a higher hit rate and fewer reloads | Long: staler data for longer, and a longer wait to repair a lost invalidation. Short: more misses and database load |
| Local vs distributed cache | Local: no network hop, and it survives a cache outage | Local: 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 down | Open: the app keeps working | Open: 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.
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")4public Product find(long id) { // only runs on a cache miss5return repository.findById(id).orElseThrow();6}78@CacheEvict(cacheNames = "products", key = "#product.id")9public void update(Product product) { // writes the database, then deletes the cached entry10repository.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.
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.