Quick revision
The short answer
maximumSize counts entries, not bytes, so when the release made each profile bigger, the same 2 million entries started using much more heap, and the old generation filled with long-lived cache objects that the collector has to keep scanning. I would measure the real retained size per entry with a heap dump or by estimating it, compare it with the heap budget, then switch to maximumWeight with a weigher that approximates bytes, cache a compact projection instead of the full profile, and check with recordStats() whether a smaller cache keeps most of the hit ratio. If the data truly has to be that large, it belongs in an external or off-heap cache rather than a bigger heap.
What to remember
In this answer, we saw that maximumSize limits the number of entries, not their size, so adding fields to the profile multiplied the heap the cache retained and filled the old generation with long-lived objects. We measured retained size with a heap dump or histogram and checked the hit ratio with recordStats(). We then fixed it by limiting by weight with an approximate byte weigher, by caching a compact projection and testing whether a smaller cache keeps most of the hits, and, if the data really has to be large, by moving it to an external or off-heap cache instead of growing the heap.
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.
maximumSize counts entries, not bytes, so when the release made each profile bigger, the same 2 million entries started using much more heap, and the old generation filled with long-lived cache objects that the collector has to keep scanning. I would measure the real retained size per entry with a heap dump or by estimating it, compare it with the heap budget, then switch to maximumWeight with a weigher that approximates bytes, cache a compact projection instead of the full profile, and check with recordStats() whether a smaller cache keeps most of the hit ratio. If the data truly has to be that large, it belongs in an external or off-heap cache rather than a bigger heap.
Why this question is asked
A cache that worked for months can turn into a production problem with no change to the caching code at all. Here the only change was a few new fields on a class, and suddenly the service spends its time in garbage collection. Interviewers ask this to see whether we connect cache configuration with memory and GC behaviour, and whether we investigate with measurements before changing settings. In this answer, we will recap what maximumSize actually limits, do the arithmetic, measure the real per-entry size, look at the fixes in order of preference, and decide when the data should leave the heap altogether.
1A Quick Recap: What maximumSize Limits
Caffeine's maximumSize(2_000_000) promises that the cache holds at most 2 million entries. It says nothing about how big each entry is. The cache keeps a reference to each value, and that value keeps its whole object graph alive: the profile object, its strings, its lists, the objects in those lists. All of that is retained heap, memory that cannot be freed while the entry is cached.
Because the entries live a long time, they are promoted out of the young generation and end up in the old generation, the part of the heap for long-lived objects. A healthy old generation has room to spare. Here it stays near its limit, so the collector keeps running expensive old-generation work to find space, which is what shows up as high GC time.
2Doing the Arithmetic
The fastest way to see the problem is to put numbers on it. Suppose each profile used to retain about 800 bytes: a few strings, some numbers and an address. The release added a list of preferences, a marketing segment and a longer history field, and a profile now retains about 2.5 kilobytes.
| Before the release | After the release | |
|---|---|---|
Entries (maximumSize) | 2,000,000 | 2,000,000 |
| Retained size per entry | about 800 bytes | about 2.5 KB |
| Cache total | about 1.6 GB | about 5 GB |
| Heap (-Xmx) | 8 GB | 8 GB |
| Room left for everything else | comfortable | too little: constant old-gen collections |
3Measuring the Real Retained Size
Estimates are a start, but we should measure before changing anything. A heap dump taken from a production-like instance with jcmd <pid> GC.heap_dump, opened in a tool such as Eclipse Memory Analyzer, shows the retained size of the Caffeine cache object and lets us divide by the number of entries. A class histogram from jcmd <pid> GC.class_histogram is lighter and quickly shows which classes dominate the heap. For a single object, a library such as JOL (Java Object Layout) can print its layout and footprint in a test.
Alongside memory, we look at the cache's statistics. With recordStats() enabled, Micrometer exports hit and miss counts, so we know the current hit ratio and can judge how much a smaller cache would cost us.
4Fix 1: Limit by Weight Instead of Count
maximumWeight with a weigher makes the cache limit what we really care about. The weigher returns a number for each entry when it is inserted, and Caffeine keeps the total under the maximum. The unit is ours to choose; an approximation of bytes is the most useful.
Notice that the weight is computed once, at insertion, so it should be cheap and roughly right rather than exact. Now a future release that grows the profile again cannot silently grow the heap; it will simply hold fewer entries, and the hit ratio metric will tell us if that hurts.
5Fix 2: Cache Less Per Entry, or Fewer Entries
Often the cache does not need the whole profile. If callers use the name, tier and a few flags, caching a compact record with only those fields can cut the per-entry size by a factor of five, and it also removes the coupling between the cache and every future field added to the entity.
We should also question the size. If the hit ratio is 96 percent at 2 million entries and the access pattern is skewed, as most customer traffic is, a cache of 500,000 entries might still reach 92 percent. Caffeine's frequency-based eviction keeps the popular entries, so a smaller cache often loses little. We can test this with a canary instance running a lower limit and compare hit ratios and database load.
6Fix 3: Move Large Data Out of the Heap
If the business really needs millions of large profiles cached, a bigger heap is the wrong answer: it makes pauses longer and the GC work larger. A shared external cache such as Redis keeps the data out of the JVM, at the cost of a network round trip and serialization per read, and it is shared by all instances, so the total memory across the fleet drops too. Some providers also offer off-heap storage inside the process; check your provider's support. A small local cache in front of the external one can keep the hottest few thousand profiles at in-memory speed.
7Follow-up questions
Why is a large long-lived cache expensive for generational collectors?
Generational collectors are built on the assumption that most objects die young, so collecting the young generation is cheap. Cache entries break that assumption: they survive, get copied between survivor spaces and promoted into the old generation, and when they are evicted they die there, which only an old-generation or mixed collection can clean up. The collector also has to track references from old objects to young ones and, during concurrent marking, traverse the whole live graph, millions of objects for a large cache. So a big, churning cache increases both the frequency and the cost of the most expensive GC work.
Would weak or soft values solve this?
Soft values let the GC clear entries under memory pressure, which sounds attractive but usually performs badly: the GC decides what to drop with no knowledge of popularity, clearing happens in bursts during collections, and it makes heap use unpredictable. A size or weight bound is a much better way to control memory.
How would you stop this from happening after the next release?
By making the cache's memory visible and bounded. We export the cache size and an estimate of its weight as metrics, alert when old-generation occupancy after a collection stays above a threshold, and use maximumWeight so the cache adapts. A load test that runs with production-like data before release catches the rest.
8Conclusion
In this answer, we saw that maximumSize limits the number of entries, not their size, so adding fields to the profile multiplied the heap the cache retained and filled the old generation with long-lived objects. We measured retained size with a heap dump or histogram and checked the hit ratio with recordStats(). We then fixed it by limiting by weight with an approximate byte weigher, by caching a compact projection and testing whether a smaller cache keeps most of the hits, and, if the data really has to be large, by moving it to an external or off-heap cache instead of growing the heap.
Open with
My first suspicion is that maximumSize counts entries, not bytes. The limit is still two million, but each profile now retains more memory, so the cache's footprint grew with the release, and because entries are long-lived they sit in the old generation, which stays near its limit and forces repeated expensive collections.
Then, if they want more
I would confirm it with numbers: a heap dump in Memory Analyzer to get the retained size of the cache and divide by the entry count, or a class histogram to see what dominates, and compare that with the heap budget.
If profiles went from roughly 800 bytes to 2.5 kilobytes, two million entries is about five gigabytes, which explains it. I would also check the hit ratio with recordStats and the Micrometer cache metrics.
Then the fixes: switch to maximumWeight with a cheap weigher that approximates bytes, so growth in the class shrinks the entry count instead of growing the heap. Cache a compact projection, a record with only the fields callers need, rather than the entity.
And try a smaller cache on a canary, because with skewed traffic and TinyLFU, half a million entries might keep most of the hit ratio. If the business really needs that much data cached, I would move it to Redis or an off-heap option with a small local cache in front, rather than raising the heap.
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 "A service holds a Caffeine cache of 2 million customer profiles with maximumSize set and...": https://scrivio-interview-library.netlify.app/databases/caching/8bbe19a6c8/