Video in progress
Why does a cache based on SoftReference cause GC and latency problems on prod?
Soft references are cleared only when the heap is under pressure. So such a cache keeps the heap permanently full, the GC does extra work for it, and the clearing happens all at once, at the worst possible time. A cache bounded by size and time gives a predictable result.
📖 Answer
The idea looks elegant: "keep it if there's memory, and if there isn't, the GC will clear it itself". Guava has softValues(), and Caffeine has a similar option. In practice:
- The heap is almost always full. In monitoring, old gen sits at 95%. You can't tell it apart from a real leak, and alerts lose their meaning.
- Which entry goes away and when is decided by the GC's heuristics, not by you. In HotSpot it depends on the time since the last access and the amount of free heap (
-XX:SoftRefLRUPolicyMSPerMB, by default 1000 ms per MB of free space). - Clearing comes in waves. When load grows and the heap gets tight, the GC drops thousands of entries at once, so the cache empties at exactly the heaviest moment and requests to the DB explode.
- Every soft reference is a separate
Referenceobject, and the GC processes them separately. When there are many, the reference processing time shows up in the GC log.
The Caffeine documentation itself recommends a size-based bound instead of soft values.
What I do:
Cache<Long, Report> cache = Caffeine.newBuilder()
.maximumWeight(200L * 1024 * 1024) // ~200 MB, approximate weight
.weigher((Long k, Report r) -> r.approxBytes())
.expireAfterAccess(Duration.ofMinutes(15))
.recordStats()
.build();
The size is definite, the hit rate shows up in metrics, and the rest of the heap stays free for real work. I allow SoftReference only for one or two large objects that can be recomputed, not for a server-side cache.
Sign up to mark studied questions and save your progress.