Video in progress

A service holds a 10 GB on-heap cache and GC pauses have become a problem. How do you decide between moving to an off-heap cache, shrinking the cache, or moving it to an external cache?

First I measure the cache's real hit rate and the size it actually needs; often shrinking it is enough. If necessary I try switching the GC (for example to ZGC). I take an off-heap cache if the serialization cost and complexity are worth it; if the cache has to be shared across replicas, I choose an external cache like Redis.

📖 Answer

10 GB of long-lived objects is heavy for a GC: in G1, Old is full, every marking cycle re-marks everything, and cache updates dirty the remembered sets and cards. But "let's move it off-heap" shouldn't be the first answer.

1. Measure. In Caffeine, recordStats(): hit rate, evictions. Often it turns out that 20% of the cache size covers 90% of requests. Dropping from 10 GB to 2 GB makes the GC problem go away immediately, with almost no change in DB load.

2. Make the object shape compact. Is the cache holding full Hibernate entities and their collections? A small record, or compressed JSON in a byte[], takes 3-5 times less space, and the number of objects (the main cost for the GC) drops sharply.

3. Switch the GC. Generational ZGC can work better than G1 with a big, stable Old, because marking and relocation are concurrent. It is the cheapest experiment, with no code change.

4. Off-heap. Chronicle Map, Ehcache's off-heap tier, or your own on top of MemorySegment (the Foreign Memory API, final in Java 22). The benefit: the GC doesn't see this memory. The cost: deserialization on every read (CPU and short-lived objects), managing the memory budget by hand, a leak is invisible in a heap dump, and debugging is hard.

5. An external cache (Redis, etc.). If there are many replicas and each one holds the same 10 GB, that is a total waste of memory. An external cache adds network latency (0.3-1 ms) and a new point of failure. A two-level solution is often good: a small local Caffeine + Redis.

My order: 1 → 2 → 3, and only after that 4 or 5. After each step I measure p99 and GC CPU.