Scrivio Interview library
ScenarioIntermediate8 min read · updated 12 November 2026

How do you choose the heap size for a new service before production? Describe a method based on measurement rather than guesswork.

We choose the heap from a measurement of the live data set: run a realistic load test, read how much heap is still occupied right after the collector has cleaned up, and size the heap at about three to four times that number (more for ZGC). Then we check GC frequency and pauses, test the peak moments such as cache warmup or a batch job, confirm the container still has room for non-heap memory, and repeat the measurement whenever the service changes significantly.

Why this question is asked

The heap setting is one of the few JVM options that almost every service needs, and it is usually set by guessing: someone writes -Xmx4g because the last service had it. A heap that is too small makes the collector run constantly and burns CPU, while a heap that is too large wastes money and can push the container past its memory limit. Interviewers ask this question to see whether we treat sizing as an engineering measurement or as folklore. In this answer, we will define the live data set and measure it, turn it into a heap size, check the allocation rate and pauses, test the peaks, fit the result into the container, and decide when to measure again.

1A Quick Recap: What the Heap Holds

The heap is the memory area where Java objects live. At any moment it contains two kinds of objects: objects that are still reachable from the program, and garbage that nobody refers to any more but that the collector has not reclaimed yet. The first group is called the live data set, or live set. It is the part we cannot get rid of: sessions, caches, connection state, the objects a request is working on right now.

The garbage part is not a problem in itself. It is the price of fast allocation. A collector needs free space to work with: the more room it has above the live set, the less often it has to run, and the less CPU it spends. So the heap size is really a choice of how much headroom we give the collector above the live set. That is why the live set is the number we must measure first.

2Measuring the Live Data Set Under Realistic Load

We run the service under a load test that looks like production: the same mix of requests, realistic data sizes, and enough time to reach a steady state, usually 30 to 60 minutes after warmup. We start with a deliberately generous heap, so the measurement is not distorted by a struggling collector, and we turn on GC logging.

The live set is the heap occupancy right after a collection that has cleaned the whole heap. With G1, the default collector, full GCs are rare, so we read the occupancy after the mixed collections, the ones that clean old regions as well as young ones. In steady state the low points after those collections form a fairly flat line, and that line is our live set.

Shell
java -Xms6g -Xmx6g -Xlog:gc*:file=gc.log:time,uptime -jar orders.jar
# in gc.log, the heap after each collection (before->after(total)):
# [1824.112s] GC(311) Pause Young (Mixed) (G1 Evacuation Pause) 2410M->702M(6144M) 41.2ms
# [1871.540s] GC(318) Pause Young (Mixed) (G1 Evacuation Pause) 2388M->688M(6144M) 39.8ms

Notice that the number after the arrow keeps returning to about 700 MB. That is the live set of this service under this load. If it kept rising from one collection to the next instead of flattening, we would not have a live set at all, we would have a leak, and sizing would have to wait until that is fixed.

3Turning the Live Set Into a Heap Size

A common starting point for G1 and the Parallel collector is a heap of three to four times the live set. With a live set of 700 MB, that gives roughly 2.1 to 2.8 GB, so we might try 2.5 GB. The reason for the multiple is that the young generation needs room for new objects, and the old generation needs space above the live set so that objects promoted between cleanups do not fill it.

ZGC needs more headroom. It collects concurrently, while the application keeps allocating, so it needs free memory to absorb all the allocation that happens during a cycle. If it runs out, threads stall waiting for memory. For ZGC we usually start higher, say four to five times the live set, and watch for allocation stalls in the log.

Step throughFrom measurement to heap size
  1. Load test with a generous heaprealistic traffic, 30 to 60 minutes of steady state
  2. Read heap after mixed or full GCthe flat floor, here about 700 MB
  3. Multiply by 3 to 4about 2.5 GB for G1, more for ZGC
  4. Rerun with the new heapcheck GC CPU, frequency and pauses
  5. Within targets?
    YesTest peaks and container fitNoRaise the heap or reduce allocation
  6. Record the numbersre-measure after big changes

6 steps in order. Play them, or step through them one at a time.

4Checking Allocation Rate and Pause Targets

The multiple is only a first guess, so we rerun the test with the chosen heap and look at how hard the collector works. The allocation rate, the megabytes of new objects per second, decides how often young collections happen. If the service allocates 800 MB per second and the young generation is 400 MB, there is a young GC every half second.

We look at three numbers. GC CPU time should stay small, for example under 5 percent of the service's CPU. Pause times must fit the latency goal, such as p99 pauses under 50 ms. And the old generation must not creep toward full, because then G1 starts more frequent mixed collections and eventually a full GC. If any of these is off, a heap that is too small is the usual reason, and the fix is either more heap or, often better, less allocation in the code.

5Testing the Peaks, Not Only the Average

A steady load test misses the moments when the live set is temporarily much larger. Typical ones are startup, when a cache is warmed with a few hundred thousand entries; a nightly batch job that loads a large file inside the same service; or a failover that shifts traffic from other instances onto this one. We include each of these in the test and record the highest heap-after-GC value we see.

So if the steady live set is 700 MB but the batch job briefly pushes it to 1.3 GB, the heap must still give the collector room above 1.3 GB. A heap of 2.5 GB is tight then, and 3 GB may be the safer choice. The goal is that the worst normal hour of the week does not end in a full GC or an OutOfMemoryError.

6Fitting the Heap Into the Container

The heap is not the whole process. The JVM also needs metaspace for class metadata, the code cache for compiled code, a stack for every thread, GC bookkeeping structures, direct byte buffers used by network libraries, and native memory used by libraries. Together these often add 300 to 700 MB for a typical Spring Boot service. The number that the container limit is compared against is the resident set size (RSS), the physical memory the process really uses.

We measure the non-heap part instead of guessing it, with Native Memory Tracking, and then check RSS under load.

Shell
java -XX:NativeMemoryTracking=summary -Xmx2560m -jar orders.jar
jcmd 4711 VM.native_memory summary | head -4
# Total: reserved=4512MB, committed=3190MB -> committed is what we budget for
ps -o rss= -p 4711 # 3172908 (KB), about 3.0 GB RSS
# container limit 3.5 GiB, heap 2.5 GiB, about 450 MB of headroom left

If RSS approaches the container limit, the kernel kills the process without any Java error, which is much harder to diagnose than a slow GC. So we leave a margin, express the heap as a percentage of the limit with -XX:MaxRAMPercentage when the service runs in containers, and write the measured numbers down next to the setting. Finally, the measurement is not permanent: a new feature that adds a cache, a framework upgrade or a jump in data volume changes the live set, so we repeat the test after significant changes and at least on each JDK upgrade.

7Follow-up questions

Why not just set the heap very large to be safe?

Because memory costs money and a bigger heap is not always faster. In containers, a heap that leaves too little room for non-heap memory gets the process OOM killed by the kernel. With older collectors, a huge heap could also mean longer full GC pauses. The right heap gives the collector enough room to keep its CPU cost and pauses within target, and no more.

How do I measure the live set if I cannot force a full GC?

Read the occupancy after G1 mixed collections in the GC log, or use the Micrometer metric jvm.gc.live.data.size, which reports the old generation size after a collection. Both avoid the pause that a forced full GC causes.

8Conclusion

In this answer, we saw that heap sizing starts with the live data set, the heap occupancy after a cleaning collection in steady state under realistic load. We sized the heap at three to four times that for G1, more for ZGC, then checked allocation rate, GC CPU and pauses, tested peaks such as cache warmup and batch jobs, made sure RSS stays below the container limit with room for non-heap memory, and agreed to measure again when the service changes.

What to say in the interviewAbout 90 seconds aloud

Open with

I start from the live data set, because everything else is a multiple of it. I run a realistic load test with a generous heap and GC logging, let it reach steady state, and read the heap occupancy right after the mixed collections, or after a full GC if I can afford one.

Then, if they want more

That flat floor, say 700 megabytes, is the live set. For G1 I start with three to four times that, so about two and a half gigabytes, and for ZGC I give more headroom because it collects while the application allocates.

Then I rerun with that heap and check the allocation rate, GC CPU, which I want under a few percent, the pause times against the latency goal, and that the old generation is not creeping up.

I also test the peaks, like cache warmup at startup or a batch job inside the service, because they can double the live set for a while.

Then I make sure it fits the container: I measure non-heap memory with Native Memory Tracking, check RSS under load, and leave a margin under the limit so the kernel never kills the pod. I usually express the heap as MaxRAMPercentage in containers. Finally I write the numbers down and repeat the measurement after big feature changes or JDK upgrades.

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.
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 "How do you choose the heap size for a new service before production? Describe a method...": https://scrivio-interview-library.netlify.app/java/jvm-tuning/3836009de1/