Quick revision
The short answer
Keep Redis as the shared cache filled by cache-aside, and give the Caffeine cache on each pod a short TTL of about 3 seconds so it can never be older than the 5-second budget. On every committed product change, publish an invalidation event (Redis pub/sub or a Kafka topic fed by change events) that tells all 20 pods to drop the key, store a version with each cached value so an older refresh can never overwrite a newer one, and keep the local level only if measurements show it earns its place.
What to remember
In this answer, we designed invalidation for a Caffeine plus Redis cache with a 5-second freshness budget. Redis is filled by cache-aside and cleared after commit, each pod's Caffeine copy has a 3-second TTL that bounds staleness even when messages are lost, and invalidation events over Redis pub/sub or Kafka make the common case much fresher. Versions on cached values stop slow refreshes from writing old data back, and measurements of hit ratio and real staleness tell us whether the local level is worth keeping.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Keep Redis as the shared cache filled by cache-aside, and give the Caffeine cache on each pod a short TTL of about 3 seconds so it can never be older than the 5-second budget. On every committed product change, publish an invalidation event (Redis pub/sub or a Kafka topic fed by change events) that tells all 20 pods to drop the key, store a version with each cached value so an older refresh can never overwrite a newer one, and keep the local level only if measurements show it earns its place.
Background to this question
A two-level cache is a common way to get both speed and sharing: the local cache answers in microseconds without a network hop, and Redis saves the database from 20 pods each loading the same rows. The trouble is that 20 private copies of the same product can drift apart, and a few hundred changes per minute means a stale copy is not a rare event. In this answer, we will recap the two levels and cache-aside, design the read and write paths, add pod invalidation, see why the TTL is the real guarantee, deal with races using versions, and finish with how we would measure whether the design is worth it.
1A Quick Recap of the Two Levels
Caffeine is an in-process cache library for Java. Each pod keeps its own Caffeine map in the JVM heap, so a hit costs a hash lookup and nothing else. Redis is a separate in-memory data store that all 20 pods talk to over the network, so a hit costs about a millisecond but every pod sees the same value.
Cache-aside is the pattern where the application, not the cache, is in charge. On a read we look in the cache, and on a miss we load from the database and put the result in the cache. On a write we update the database and then remove the cached entry so the next reader loads the new value. Removing instead of updating is deliberate: deleting a key is safe to repeat and cannot write a wrong value.
A TTL, time to live, is how long an entry may stay in a cache before it is thrown away regardless of anything else. Staleness is how far behind the database a cached value is. Our requirement is that no reader ever sees a product value more than 5 seconds older than the committed one.
- Caffeine on the podabout 0.01 ms, private to one of 20 pods, TTL 3 s
- Redisabout 1 ms, shared by all pods, TTL a few minutes
- Product databasesource of truth, a few ms, the load we protect
3 layers, from the top down. Step through them one at a time.
2The Read and Write Paths
The read path goes from the closest level outwards. If Caffeine has the product, we return it. If not, we ask Redis, and on a Redis miss we load from the database, write the value to Redis and then to Caffeine. The write path updates the database in a transaction and, only after the commit succeeds, deletes the key in Redis and announces the change to every pod.
Notice the order on the write side: database first, invalidation after commit. If we invalidated first, a reader could reload the old row before our transaction commits and put the stale value straight back. In Spring the usual way to run code after commit is an @TransactionalEventListener with phase AFTER_COMMIT, or better, an outbox or change data capture feed that only ever contains committed changes.
3Telling 20 Pods to Drop a Key
Deleting the Redis key fixes the shared level, but the 20 Caffeine copies do not know about it. So every change also produces an invalidation message carrying the product id and its new version. Each pod subscribes and removes that id from its local cache. Redis pub/sub is simple and fast, but it is fire and forget: a pod that is restarting or briefly disconnected misses the message forever. A Kafka topic fed by change events, for example from Debezium reading the database log, is durable and ordered per key, and a pod can resume from its last offset, at the cost of more moving parts and somewhat higher delay.
6 messages in order. Play them, or step through them one at a time.
4Why the Local TTL Is the Real Guarantee
Invalidation messages make the cache fresh most of the time, but they cannot be the guarantee, because messages get lost. Redis pub/sub drops messages for disconnected subscribers, a pod can be paused by a long garbage collection, and a network partition can hide a whole group of pods. If freshness depended only on the message, a single lost message would leave one pod serving an old price until it restarted.
So the TTL carries the promise. With expireAfterWrite of 3 seconds, the worst case is bounded even when every message is lost: a value is at most 3 seconds old when it leaves Caffeine, plus the time Redis may have held it. Because the Redis entry is deleted after commit, and Redis is a single shared copy that does not depend on any message reaching it, the total stays inside 5 seconds with margin for the time to load and the clock. The messages simply make the common case far better than the bound, usually under 100 milliseconds.
5Versions Stop Old Refreshes From Winning
There is a race even when no message is lost. Pod A misses, reads version 17 from the database and is slow to write it to Redis. Meanwhile the product changes to version 18 and the key is deleted. Then pod A finally writes version 17 into Redis, and the stale value lives there for minutes. The fix is to store a version, such as an increasing column updated with each write, with every cached value, and to accept a write only if it is newer than what is cached.
Running the check and the write as one Lua script makes them atomic in Redis. The pods use the same rule locally: an invalidation carrying version 18 removes the entry, and a refresh that returns version 17 after seeing 18 is ignored.
6Measuring Whether the Local Level Earns Its Place
A local cache is only worth its complexity if it is hit often. Caffeine reports hit and miss counts when recordStats() is enabled, and Micrometer can publish them, so we can see the hit ratio per pod. With 20 pods and a 3-second TTL, each pod refreshes every hot key about every 3 seconds, so a product read fewer than a few times per 3 seconds on a pod barely benefits. If the local hit ratio is, say, under 30 percent, we remove the level and serve from Redis alone, which deletes a whole class of staleness bugs.
We should also measure staleness itself, not just assume it. A simple probe writes a test product, then reads it through several pods and records how long until each sees the new version. Alerting on the 99th percentile of that delay tells us when the invalidation path has broken, long before customers notice.
7Follow-up questions
How do you prevent a cache stampede when a hot key expires on all pods?
A stampede happens when a popular key expires and every request on every pod misses at once and hits the database together. We attack it at each level. In Caffeine, a loading cache coalesces concurrent misses so only one thread per pod loads the value, and refreshAfterWrite lets the old value be served while one background load refreshes it. Adding a small random jitter to TTLs stops all pods from expiring the same key in the same second. At the Redis level, a short lock key set with SET NX lets one pod rebuild the value while the others wait briefly or serve the slightly older value. Together these turn hundreds of database loads into one or two.
8Conclusion
In this answer, we designed invalidation for a Caffeine plus Redis cache with a 5-second freshness budget. Redis is filled by cache-aside and cleared after commit, each pod's Caffeine copy has a 3-second TTL that bounds staleness even when messages are lost, and invalidation events over Redis pub/sub or Kafka make the common case much fresher. Versions on cached values stop slow refreshes from writing old data back, and measurements of hit ratio and real staleness tell us whether the local level is worth keeping.
Open with
I would use cache-aside with Redis as the shared level and Caffeine on each pod as a small, short-lived level. Writes go to the database first, and only after commit do we delete the Redis key and publish an invalidation for that product id, either on Redis pub/sub or on a Kafka topic fed by change events.
Then, if they want more
Each pod drops the key when it hears the message. The important part is that I would not trust the messages for the guarantee, because pub/sub messages are lost when a pod is disconnected or paused.
So the local TTL is about three seconds, which bounds staleness inside the five-second requirement even if every message is missed; the messages just make the usual case nearly instant.
To avoid races where a slow reader writes an old value back after an invalidation, I store a version with each cached value and only accept writes that are newer, using a small Lua script in Redis and the same rule locally. For hot keys I would add refresh-ahead and TTL jitter to avoid stampedes.
Finally, I would measure the local hit ratio and the actual staleness with a probe. If the local level is not hitting often, I would remove it, because the simplest cache that meets the requirement is the one with the fewest consistency bugs.
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.
- Official documentation
- Spring Cloud documentation, Resilience4j documentation
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 "Your service uses a two-level cache: Caffeine on each of 20 pods and Redis shared....": https://scrivio-interview-library.netlify.app/spring-boot/distributed-data/0939589aad/