Quick revision
The short answer
The cache has two separate problems. Its single lock serializes every read, because each get() changes the recency order, and plain LRU is not scan resistant, so one batch that touches every key evicts the hot entries. I would replace the implementation with Caffeine, whose Window TinyLFU policy admits entries by frequency and resists scans, keep the existing interface so the 30 services migrate by a dependency upgrade, measure before and after, and set a policy that general caches come from approved libraries.
What to remember
In this answer, we saw that the shared cache fails in two independent ways: its single lock serializes reads because every LRU get is a write, and LRU itself is not scan resistant, so the nightly batch flushes the hot set. Caffeine fixes both with concurrent reads and the Window TinyLFU admission policy. We migrate by keeping the existing interface and swapping the implementation, measure hit rate and latency per service with recordStats and Micrometer, and set a policy that general caches come from approved libraries.
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.
The cache has two separate problems. Its single lock serializes every read, because each get() changes the recency order, and plain LRU is not scan resistant, so one batch that touches every key evicts the hot entries. I would replace the implementation with Caffeine, whose Window TinyLFU policy admits entries by frequency and resists scans, keep the existing interface so the 30 services migrate by a dependency upgrade, measure before and after, and set a policy that general caches come from approved libraries.
Why this question is asked
Home-grown infrastructure code often outlives the reasons it was written. A cache that was fine for one service at modest traffic becomes a shared library, and its weaknesses show up everywhere at once. Interviewers ask this scenario at senior level because it mixes a technical diagnosis with an organisational change: we must explain why the cache fails, choose a replacement, and move 30 teams to it without breaking them. In this answer, we will diagnose the two problems, look at why Caffeine fixes both, plan a migration that keeps the API stable, decide how to measure success, and finish with the policy that stops this from happening again.
1Problem 1: Why the Lock Becomes a Bottleneck
An LRU cache, least recently used, evicts the entry that has not been touched for the longest time. To know that, it must update its recency order on every access, usually by moving the entry to the front of a linked list. So in an LRU cache, get() is not a read. It is a write to the list.
A synchronized cache protects that list with one lock. Every get() from every request thread must take the lock, even when the value is already there. At low load the lock is free most of the time and nobody notices. At high load, say 40 threads each doing 20,000 lookups a second, the threads queue behind the lock and the profiler shows them parked in monitor waits. Adding CPU does not help, because only one thread can be inside the cache at a time. A read-write lock does not help either, since reads modify the order.
2Problem 2: Why the Nightly Batch Empties the Cache
The second problem is about the policy, not the code. Plain LRU assumes that whatever was used most recently will be used again soon. A batch job that walks through every key once breaks that assumption. Each key it touches becomes the most recent entry, and each insert evicts the least recent one. If the cache holds 10,000 entries and the batch touches 2 million keys, every hot entry that daytime traffic relies on is pushed out, replaced by keys that will not be used again. We call this cache pollution, and a policy that survives it is called scan resistant.
In the morning the hit rate starts near zero, every request goes to the database, and latency spikes until the hot set is rebuilt. No amount of locking work fixes this, because the cache is doing exactly what LRU is supposed to do.
6 messages in order. Play them, or step through them one at a time.
LRU treats a key touched once by the batch as more valuable than a key used all day.
3Why Caffeine Fixes Both
Caffeine is a widely used Java caching library that solves both problems. For concurrency, it stores entries in a ConcurrentHashMap, so lookups do not take a global lock, and records accesses in small buffers that a single maintenance task applies to the eviction order later. Reads stay fast under contention, at the cost of a slightly approximate order.
For the policy, Caffeine uses Window TinyLFU. New entries first enter a small window that behaves like LRU. When an entry leaves the window, Caffeine compares how often it has been seen with how often the entry it would evict has been seen, using a compact frequency sketch, a small table of counters that estimates access counts for many keys in little memory. The newcomer is admitted only if it is more popular. A key the batch touches once has a frequency of one, so it loses against a hot key that has been read thousands of times, and the hot set survives the scan. Published benchmarks show this policy gets close to the best achievable hit rate on many workloads.
4Migrating 30 Services Without Breaking Them
The worst plan would be asking 30 teams to rewrite their cache calls. Instead, we keep the existing interface and swap what is behind it. If the library exposes something like a Cache<K, V> interface with get and put, we release a new version of the same library whose implementation delegates to Caffeine. Each service migrates by bumping one dependency version.
We should check the old cache's semantics before swapping. If code relied on an exact eviction order, on null values being stored, or on iteration over the entries, the new version must say so in its release notes, since Caffeine does not allow null keys or values and its eviction order is not strict LRU.
For Spring services, a longer-term option is to move to Spring's cache abstraction, @Cacheable backed by CaffeineCacheManager, which removes the shared library entirely. That is a bigger change per service, so I would offer it as the target for new code and keep the drop-in wrapper for existing code.
5Measuring Before and After
We should prove the change with numbers rather than assume it. Before migrating a service, we record its current hit rate, p99 latency of the cached path, CPU time spent in lock waits, and heap used by the cache. After migrating, Caffeine's recordStats() gives hit rate, miss count and eviction count, and Micrometer can publish them to the metrics system the teams already watch, so every service gets the same dashboard.
Then we roll out service by service, starting with the one that showed the worst contention and has good monitoring. Typical results to look for are lock waits disappearing from the profile and the morning hit rate staying high after the batch. If a service's hit rate drops, we look at its access pattern before moving on. A team that needs the batch to bypass the cache entirely can also read through a separate path, which is often the simplest fix for the batch itself.
- Release library v2 backed by Caffeinesame interface, stats enabled
- Pick the worst service firsthigh contention, good monitoring
- Record baselinehit rate, p99, lock waits, heap
- Upgrade and comparesame dashboard from Micrometer
- Better or equal?Yesmove to the next services in wavesNoinvestigate the access pattern, roll back if needed
5 steps in order. Play them, or step through them one at a time.
6Preventing the Next One
The root cause is organisational: a team built general-purpose infrastructure that the language ecosystem already provides, and nobody owned it as it spread to 30 services. I would set a short standard: general-purpose caches come from an approved library such as Caffeine, used directly or through Spring's cache abstraction, and custom cache code needs a measured reason and an owner. The standard should come with a ready example so following it is the easy path.
This is not a ban on custom code. If a team can show a need the library does not meet, the custom code stays, but it gets an owner, tests under concurrency, and benchmarks against the library.
7Follow-up questions
What would make you keep a hand-written cache?
A measured need that the libraries do not meet. Examples are an off-heap cache for tens of gigabytes where garbage collection pauses matter, a cache that must share memory with native code, or a very special eviction rule tied to the business, such as evicting by tenant budget. Even then, I would want benchmarks against Caffeine, concurrency tests, and a named owning team.
Could we just fix the nightly batch instead?
We should fix it as well, because a batch that reads every key through the request cache is wasteful. The batch can bypass the cache or use its own. But a scan-resistant policy protects us from the next unexpected scan too, such as a crawler or a reporting query, so the two fixes complement each other.
8Conclusion
In this answer, we saw that the shared cache fails in two independent ways: its single lock serializes reads because every LRU get is a write, and LRU itself is not scan resistant, so the nightly batch flushes the hot set. Caffeine fixes both with concurrent reads and the Window TinyLFU admission policy. We migrate by keeping the existing interface and swapping the implementation, measure hit rate and latency per service with recordStats and Micrometer, and set a policy that general caches come from approved libraries.
Open with
I would first separate the two problems, because they have different causes. The lock contention happens because in LRU every get updates the recency order, so the synchronized cache serializes every read; at high load threads just queue on the lock, and a read-write lock would not help.
Then, if they want more
The nightly emptying is a policy problem: LRU is not scan resistant, so a batch that touches every key once makes each of those keys look recent and evicts the hot set, and the morning starts with a near-zero hit rate. Caffeine solves both.
It uses a concurrent map and buffers access events so reads do not take a global lock, and its Window TinyLFU policy only admits a new entry if it is more frequent than the one it would evict, so one-time scan keys lose.
To migrate 30 services, I would keep the existing interface and release a new version backed by Caffeine, so teams upgrade a dependency rather than rewrite code, with release notes about null values and ordering.
I would measure hit rate, p99 latency and lock waits before and after with recordStats and Micrometer, and roll out service by service starting with the worst one. Finally I would set a standard that general caches come from approved libraries, keeping custom code only where someone can show a measured need and own it.
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 official documentation for the version you use. 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 "A team wrote its own synchronized LRU cache years ago and now uses it in 30 services....": https://scrivio-interview-library.netlify.app/java/coding-problems/e7cb7d6798/