Video in progress
How do you determine the heap size for a new service? What is wrong with the "let's set 8 GB, it'll be enough" approach?
I derive the heap from the live set: I measure the live data left after a Full GC or old collection under load, and add 2-4 times that as headroom, depending on the GC type. A guessed big heap hides problems, wastes money on memory and breaks the container budget.
📖 Answer
The live set is the live data that remains in the heap after the GC has cleaned fully: caches, sessions, the Spring context, the objects of requests being handled right now. The heap size should follow from it.
How I measure:
- I run the application with a realistic load (a load test, or a recording of prod traffic on staging) for at least an hour.
- From the GC log I take the heap values after old/mixed collections. Or, under load, one
jcmd <pid> GC.heap_infoand, in G1, the used amount after a concurrent cycle finishes. - I take the highest value as the live set.
Then the headroom:
- for G1, live set × 2-3 is usually a good starting point: evacuation and the young gen need room;
- for ZGC or Shenandoah, more, × 3-4: they work concurrently, and the application keeps allocating until the GC finishes;
- with Parallel GC for batch it can be less.
Why "let's set 8 GB" is bad:
- a leak or an unbounded cache goes unnoticed for weeks, then blows up overnight;
- in some GCs a Full GC on a big heap takes longer;
- in a container, heap + native + metaspace goes over the limit and you get OOMKilled;
- 30 replicas × 8 GB is real money.
The opposite mistake exists too: if the heap is too tight, the GC runs often, CPU burns, and you get "GC overhead" and worse latency.
Even after you calculate it, the number isn't permanent. After every big release or traffic growth I watch the live set metric (the Old size after GC) and set an alert.
Sign up to mark studied questions and save your progress.