Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Design a two-level cache for a read-heavy service: a local Caffeine cache in each instance in front of a shared Redis cache in front of the database. Describe read and write paths, TTLs and how invalidation reaches the local caches.

Try it yourself

Cache-aside: one read, three cache states

See what a cache hit saves, what a miss costs, and why a write deletes the cached entry instead of updating it.

Read this example as text

When the entry is in the cache (a hit)

  1. A request arrives. A caller asks the service for product 42. The cache already holds it.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Hit: the value comes back. The entry is there and still fresh, so the cache answers at once. The database is never touched.

1 cache call, 0 database reads.

When it was never cached (a miss)

  1. A request arrives. A caller asks the service for product 42. Nobody has asked for it before, so the cache holds nothing.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. The key was never stored. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When its time to live has run out

  1. A request arrives. A caller asks the service for product 42. The cache held it once, but its time to live ran out 12 seconds ago.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. An expired key is the same as a missing one: Redis no longer returns it, and removes it. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When the price changes afterwards

  1. The price changes. Later, someone updates the price to 25. The service writes the database first: UPDATE products SET price = 25 WHERE id = 42.
  2. Delete the cached entry. Then it deletes the key: DEL product:42. It does not write 25 into the cache. Deleting is simpler and safer: the next read misses and loads whatever the database holds then.
  3. The next read will miss. The cache is empty for this key again, so the next request repeats the miss path and stores 25.

3 cache calls, 1 database read, 1 database write.

What this example leaves out
  • One request at a time. Two requests missing at the same moment (a stampede) are not shown.
  • The write deletes the key. Some systems update the cache instead, which this example does not model.
  • The numbers are counts of round trips, not measured times.

A read checks the local Caffeine cache first, then Redis, then the database, and fills each level on the way back. A write updates the database, evicts the Redis key, and broadcasts an invalidation so every instance evicts its local copy. Local entries get a much shorter TTL than Redis entries, so even a lost invalidation message can only leave an instance stale for a bounded time.

Why this question is asked

Read-heavy services often reach a point where Redis alone is not fast enough or costs too many network round trips, and a cache inside each instance looks like free speed. The trouble is that a local cache is a copy that other instances cannot see, so every write now has to reach many copies. Interviewers ask this question to see whether we can design the read path, the write path and the staleness bounds together, instead of just stacking caches. In this answer, we will recap what each level is for, walk through the read path and the write path, choose TTLs, look at how invalidation reaches the local caches and what happens when it does not, and see how to build this in Spring and measure it.

1A Quick Recap of the Three Levels

Our service runs as several instances, say 12 pods behind a load balancer. Each pod has a local cache, Caffeine, which is an in-memory map inside the JVM with size limits and expiry. Reading from it costs well under a microsecond, but each pod has its own copy and knows nothing about the others.

Behind the pods sits Redis, a shared in-memory store reached over the network. A read costs about half a millisecond to a millisecond, and every pod sees the same value. Behind Redis is the database, the source of truth, where a read might take 5 to 50 milliseconds.

So the local level saves network trips, the Redis level protects the database from all pods at once, and the database decides what is true. A two-level cache, sometimes called an L1/L2 cache, puts the first two in front of the third.

Step throughThe two-level cache
  1. Caffeine in each pod (L1)sub-microsecond, private to one JVM, short TTL
  2. Redis (L2)about 1 ms, shared by all pods, longer TTL
  3. Databasesource of truth, 5 to 50 ms per query

3 layers, from the top down. Step through them one at a time.

Each level is a copy of the one below it.

2The Read Path

A read goes down the levels until one of them has the value, then fills the levels above it on the way back up. The reason we fill on the way back is that the next read for the same key should stop as high as possible.

Java
public Product get(long id) {
Product p = local.getIfPresent(id); // L1 hit: done in nanoseconds
if (p != null) return p;
p = redis.opsForValue().get("product:" + id); // L2 hit: one network trip
if (p == null) {
p = repository.findById(id).orElseThrow(); // miss everywhere: query the database
redis.opsForValue().set("product:" + id, p, Duration.ofMinutes(30));
}
local.put(id, p); // fill L1 for the next read on this pod
return p;
}

Notice that a miss in one pod does not mean a database query. If another pod already loaded the product, Redis has it, and this pod only pays one network trip. There is one catch: when a popular key expires, many requests may miss at the same moment and all query the database. Caffeine's get(key, loader) lets only one thread per pod load a key, and for Redis a short lock or early refresh keeps the stampede small.

3The Write Path

When a product changes, we update the database first, because it is the source of truth. Then we evict the Redis key rather than writing the new value into it. Evicting is safer: if two writers race, a put could leave the older value in Redis, while an eviction just makes the next reader load the current row.

Last, every pod must evict its local entry. The pod that did the write can do it directly, but the other 11 pods cannot see that call. So the writer publishes a small invalidation message, such as the key product:42, on a Redis pub/sub channel or a Kafka topic, and each pod listens and evicts that key from its Caffeine cache.

Java
@Transactional
public void update(Product p) {
repository.save(p);
// after commit, so readers never reload the old row
afterCommit(() -> {
redis.delete("product:" + p.getId());
redis.convertAndSend("cache-invalidation", "product:" + p.getId());
});
}
// in every pod
void onMessage(String key) { local.invalidate(parseId(key)); } // product:42 -> evict 42
Step throughWriting product 42
Pod ADatabaseRedisPod B
update product 42, commit
DEL product:42
evict 42 from local cache
PUBLISH cache-invalidation product:42
message product:42
evict 42 from local cache

6 messages in order. Play them, or step through them one at a time.

The writer cleans its own copy directly; the other pods learn about the write from the broadcast.

The order matters. If we evicted before the transaction committed, another pod could read the old row in the gap and put it back into Redis. Doing the eviction and the broadcast after commit closes most of that gap.

4Choosing the TTLs

A TTL, time to live, is how long an entry may stay before it expires on its own. The local TTL should be much shorter than the Redis TTL, for example 30 seconds locally and 30 minutes in Redis. The reason is that the local copies are the ones invalidation can miss. Redis pub/sub delivers a message only to subscribers connected at that moment, so a pod that was reconnecting, paused in a long garbage collection or just starting will never see it.

With a 30 second local TTL, the worst case after a lost message is 30 seconds of stale data on that one pod, and then it reads Redis again. That bound is the real promise of the design, and we should agree it with the product owner. Prices in a checkout may need 5 seconds; a product description can live with a minute. If the data can never be stale, it should not be in a local cache at all.

5Building It in Spring and Measuring It

Spring's cache abstraction does not give us tiering out of the box. CompositeCacheManager is often mistaken for it, but it only asks several cache managers in turn which one has a cache with the given name, and then uses that single cache. It never reads Caffeine and falls back to Redis for the same key.

So we either write a small Cache implementation that wraps a CaffeineCache and a RedisCache and does the read and write paths above, or use a library that provides a two-level cache. Writing our own is about a hundred lines and keeps the behaviour visible.

Finally, we expose metrics per level: hits and misses for Caffeine (recordStats() feeds Micrometer), hits and misses for Redis, and database queries per second. Without them we cannot tell whether the local level earns its complexity. If the L1 hit ratio is 85 percent and Redis latency is our bottleneck, it does; if L1 hits are 10 percent, we have added invalidation work for nothing.

6Follow-up questions

What happens if an instance misses an invalidation message?

That pod keeps serving its old local copy until the local TTL expires, while every other pod already shows the new value. That is why the local TTL must be short and agreed as the staleness bound. To shrink the window further, a pod that reconnects to the pub/sub channel can clear its whole local cache, since it cannot know what it missed, and using a durable topic such as Kafka instead of pub/sub lets a pod catch up on messages it missed.

Why evict Redis instead of writing the new value into it?

Two concurrent writers can finish in a different order from the order in which their database commits happened, so the last put may hold the older value and stay there for the whole Redis TTL. An eviction cannot be out of date, because the next reader always loads whatever is committed.

When is a local cache a bad idea?

When the data changes often relative to how often it is read, when every reader must see a write immediately, or when the data set is so large that each pod's copy wastes a lot of heap. In those cases Redis alone, or a better database query, is simpler and safer.

7Conclusion

In this answer, we saw that a two-level cache reads local, then Redis, then the database, filling each level on the way back, and that writes update the database, evict Redis after commit and broadcast an invalidation that every pod applies to its local cache. Because broadcasts can be lost, the local TTL is short and acts as the staleness bound. Spring's CompositeCacheManager does not provide tiering, so we write a small composite Cache or use a library, and we measure hits per level to prove each level is worth having.

What to say in the interviewAbout 80 seconds aloud

Open with

I would put a small Caffeine cache in each pod in front of a shared Redis cache. On a read I check Caffeine, then Redis, then the database, and I fill Redis and then Caffeine on the way back, using a loading call so only one thread per pod loads a hot key.

Then, if they want more

On a write I update the database, and after the transaction commits I delete the Redis key and publish an invalidation message with the key, on Redis pub/sub or a topic. Every pod subscribes and evicts that key locally. I evict rather than put, so racing writers cannot leave an old value behind.

Pub/sub can lose messages, for example when a pod is reconnecting, so the local TTL is short, say 30 seconds against 30 minutes in Redis, and that local TTL is the staleness bound I would agree with the product owner. On reconnect a pod can also clear its local cache.

In Spring I would not use CompositeCacheManager for this, because it only picks one cache by name and does not fall through levels, so I would write a small two-level Cache implementation. And I would publish hit and miss metrics for each level, so we can see whether the local cache is actually earning its keep.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Design a two-level cache for a read-heavy service: a local Caffeine cache in each...": https://scrivio-interview-library.netlify.app/databases/caching/73d898b75c/