Quick revision
The short answer
Caffeine does not evict by recency alone. It uses Window TinyLFU: new entries first enter a small admission window, and when they leave it they must compete with an entry from the main area, winning only if a compact frequency sketch says they are used more often. A recently inserted key that is rarely used therefore loses to an older key that is used often. For a one-off scan such as a nightly report, this is a benefit: the scanned keys are seen once and are rejected, so the hot set survives, whereas plain LRU would have flushed it. It also means tests that expect strict LRU order are flaky, especially because eviction runs asynchronously; call cleanUp() when a test needs deterministic eviction.
What to remember
In this answer, we saw that Caffeine can evict a recently inserted entry because it uses Window TinyLFU. New entries enter a small LRU admission window and then have to beat the main area's victim on estimated frequency, which comes from a count-min sketch whose counters are halved periodically so popularity fades. For a nightly scan, rarely used keys lose that contest, so the hot set survives instead of being flushed as with plain LRU. Because eviction order is frequency-based and maintenance runs asynchronously, tests should not assume LRU order, and should use cleanUp() and a same-thread executor when they need deterministic eviction.
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.
Caffeine does not evict by recency alone. It uses Window TinyLFU: new entries first enter a small admission window, and when they leave it they must compete with an entry from the main area, winning only if a compact frequency sketch says they are used more often. A recently inserted key that is rarely used therefore loses to an older key that is used often. For a one-off scan such as a nightly report, this is a benefit: the scanned keys are seen once and are rejected, so the hot set survives, whereas plain LRU would have flushed it. It also means tests that expect strict LRU order are flaky, especially because eviction runs asynchronously; call cleanUp() when a test needs deterministic eviction.
Why this question is asked
Most of us learn caching with LRU, least recently used, where the entry untouched for the longest time is evicted first. So it surprises people when Caffeine evicts an entry they inserted a moment ago and keeps an entry from an hour earlier. That behaviour is deliberate, and it is one of the main reasons Caffeine achieves high hit ratios. Interviewers ask this question to see whether we understand admission, not just eviction, and what that means for workloads like nightly scans and for tests. In this answer, we will recap why LRU struggles with scans, walk through Window TinyLFU step by step, look at the frequency sketch, apply it to the nightly report, and see how to write tests that do not depend on eviction order.
1A Quick Recap: Why Plain LRU Fails on Scans
LRU keeps entries ordered by last use and evicts from the cold end. It works well when recently used data is likely to be used again. Its weakness is a scan, a one-off pass over many keys that will not be read again soon. Imagine a cache of 100,000 customer profiles holding the hot set that serves daytime traffic. At 02:00 a nightly report reads 2 million customers once each. Under LRU each scanned key becomes the most recent entry, and after 100,000 of them the entire hot set has been pushed out. At 08:00 the first real users find an empty cache, a problem called scan pollution.
2How Window TinyLFU Decides What to Keep
Caffeine splits its capacity into two parts. The admission window is small, about 1 percent of the maximum size by default, and is managed as LRU. It gives brand-new entries a short chance to prove themselves, which helps with bursts where a new key is read several times right after creation. The main area holds the rest, and is split again into a probation segment and a protected segment; entries that are accessed again while on probation are promoted to protected.
The interesting moment is when an entry falls off the end of the window. It becomes a candidate for the main area, and the main area's own eviction victim is picked. Caffeine then compares the two by their estimated access frequency. If the candidate is used more often, it is admitted and the victim is evicted. Otherwise the candidate itself is evicted, even though it is the newer of the two. That is exactly the behaviour the question describes. Caffeine also adapts the size of the window over time, growing it for recency-heavy workloads and shrinking it for frequency-heavy ones.
- Insert into the admission windowsmall LRU, about 1 percent of capacity
- Pushed out of the windowbecomes a candidate
- Pick the main area's victimfrom the cold end of probation
- Candidate frequency > victim frequency?YesAdmit candidate, evict victimNoEvict the candidate
- Accessed again on probationpromoted to the protected segment
5 steps in order. Play them, or step through them one at a time.
A new entry is only kept if the frequency sketch says it is more popular than what it would replace.
3The Frequency Sketch
To compare frequencies, Caffeine would need a count for every key it has ever seen, which would cost more memory than the cache itself. Instead it keeps a count-min sketch: a small table of 4-bit counters. Each key is hashed to a few counters, every access increments them, and the estimate for a key is the smallest of its counters. Collisions can only make an estimate too high, never too low, and the error is small for keys that matter.
Popularity must also be allowed to fade. So when the number of recorded accesses reaches a threshold, Caffeine halves every counter. A key that was hot last week but is no longer read loses its advantage over time, and a newly popular key can overtake it. The sketch also remembers keys that are not in the cache, which is what lets a key that keeps being requested eventually win admission.
4What It Means for the Nightly Report
Apply this to the 2 million key scan. Each scanned key enters the small window, is pushed out by the next scanned keys, and then competes with a main-area victim. Its estimated frequency is about 1, while the hot customers have high counts from the day's traffic. So nearly every scanned key is rejected, and the hot set stays in the main area. At 08:00 the hit ratio is roughly what it was the evening before.
There are two consequences to keep in mind. First, the report itself gets almost no benefit from the cache, which is fine because it reads each key once anyway; it would be even better to have the report bypass the cache entirely, for example with a separate method without @Cacheable, so it does not even touch the sketch. Second, the scan still costs CPU for hashing and maintenance work, so on a very large scan we may see more eviction activity in metrics without any loss of hit ratio for the day traffic.
5Testing Without Relying on Eviction Order
Because the policy is frequency-based, a test that inserts three entries into a cache of size two and expects the oldest to be evicted may pass on one run and fail on another. Eviction is also asynchronous: Caffeine records reads and writes in buffers and performs maintenance on an executor, by default ForkJoinPool.commonPool(), so right after a put the cache may briefly hold more than its maximum.
So tests should assert what the application relies on, such as the size never staying above the limit or a key being reloaded after it was invalidated, rather than which particular key was evicted. Calling cleanUp() and using a same-thread executor make the timing deterministic, and a fake Ticker makes time-based expiry testable without sleeping.
6Follow-up questions
Can Caffeine be configured to behave like strict LRU?
Not through a simple switch, because Window TinyLFU is the design. If a strict LRU order is truly required, a LinkedHashMap with access order and removeEldestEntry gives it for a small, single-threaded case. In practice it is better to change the test or requirement than the policy, because TinyLFU usually gives a higher hit ratio on real workloads.
Why have an admission window at all if frequency decides?
Without it, a brand-new key would always have a frequency near zero and could never get in, even if it is about to be read many times, such as a newly published product. The window lets new keys accumulate a few hits before they have to compete. Caffeine tunes the window size by hill climbing, measuring whether a larger or smaller window improves the hit ratio.
Does the sketch use a lot of memory?
No. It uses a few bits per counter and is sized in proportion to the cache's maximum size, so for a cache of 100,000 entries it is a small fraction of the memory of the entries themselves. That compactness is the whole reason the technique works.
7Conclusion
In this answer, we saw that Caffeine can evict a recently inserted entry because it uses Window TinyLFU. New entries enter a small LRU admission window and then have to beat the main area's victim on estimated frequency, which comes from a count-min sketch whose counters are halved periodically so popularity fades. For a nightly scan, rarely used keys lose that contest, so the hot set survives instead of being flushed as with plain LRU. Because eviction order is frequency-based and maintenance runs asynchronously, tests should not assume LRU order, and should use cleanUp() and a same-thread executor when they need deterministic eviction.
Open with
Caffeine uses Window TinyLFU rather than plain LRU. New entries go into a small admission window, about one percent of capacity, managed as LRU. When an entry is pushed out of that window it becomes a candidate, and it has to compete with the victim from the main area, which is a segmented LRU with probation and protected parts.
Then, if they want more
The winner is decided by estimated access frequency from a count-min sketch, a compact table of small counters that Caffeine halves periodically so old popularity fades. So a key inserted a second ago but rarely used loses to an older key that is used a lot, and the new key is the one evicted.
For a nightly report scanning two million keys once, that is exactly what we want: each scanned key has a frequency of about one, it loses against the hot daytime keys, and the hot set survives. With plain LRU the scan would flush the whole cache and the morning traffic would start cold.
I would still let the report bypass the cache if possible. The practical consequences are for tests: eviction order is not LRU, and maintenance runs asynchronously on an executor, so the size can briefly exceed the maximum. In tests I use a same-thread executor and call cleanUp(), and assert on behaviour rather than on which key was evicted.
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 Framework reference, Cache abstraction
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 "Why can Caffeine evict an entry that was inserted recently while keeping older entries...": https://scrivio-interview-library.netlify.app/databases/caching/ca1a27e942/