Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

Heap occupancy after GC grows by about 50 MB per hour in production, and the service fails with OutOfMemoryError every three days. Walk through your investigation from first signal to verified fix.

First we confirm it is a real leak: heap occupancy after GC rising steadily day and night, not just a busy period. Then we compare class histograms taken hours apart to see which types grow, take a heap dump once the leak is large enough and follow the dominator tree and paths to GC roots to the code that holds the objects, or use JFR's old object samples for a lower-risk view. The usual causes are unbounded caches and maps, listeners never removed, ThreadLocal values and high-cardinality metrics, and the fix is verified only when post-GC occupancy stays flat for a full day.

Why this question is asked

A service that fails every three days is easy to keep alive with restarts, and that is exactly why such leaks survive for months. Each restart hides the problem, and nobody has time for a slow investigation. Interviewers ask this question to see whether we can investigate methodically, from the first signal to proof of the fix. In this answer, we will go through each of those steps with the commands and the reasoning, look at the usual causes, and finish with how to verify the fix.

1Confirm the Trend From GC Data

Heap use in a Java service always goes up and down. Objects are allocated, the heap fills, the collector frees the garbage, and the line drops again. The number that tells us about leaks is the occupancy right after a collection, because that is roughly the live set, the objects still reachable. If the live set grows steadily, something is holding on to objects.

So we look at GC logs or a metric such as heap used after GC over several days, not hours. A real leak of 50 MB per hour grows by about 1.2 GB a day and keeps growing at night, when traffic is low. A busy period, by contrast, raises occupancy during the day and drops back at night. With 3.6 GB of headroom, 50 MB per hour runs out in about 72 hours, which matches the three-day crash cycle and tells us the numbers are consistent.

Java
# unified GC logging, already in the standard runtime profile
-Xlog:gc*:file=/logs/gc.log:time,uptime:filecount=10,filesize=50m
# what we look for: the number after the arrow keeps rising, day and night
[2026-11-02T09:00] GC(4121) Pause Young (Normal) 2410M->1105M(4096M) 18ms
[2026-11-02T21:00] GC(6377) Pause Young (Normal) 2980M->1702M(4096M) 21ms
[2026-11-03T09:00] GC(8630) Pause Young (Normal) 3560M->2301M(4096M) 25ms # about +50 MB per hour

2Compare Class Histograms Hours Apart

Before taking a full heap dump, we narrow the suspects cheaply. A class histogram lists, for each class, how many live instances exist and how many bytes they use. We take one now and another a few hours later and compare them. The classes whose counts grow steadily between the two are our suspects.

Shell
jcmd <pid> GC.class_histogram > histo-0900.txt # note: runs a full GC first
jcmd <pid> GC.class_histogram > histo-1500.txt
# num #instances #bytes class name (09:00 -> 15:00)
# 1: 4,120,000 263 MB -> 7,310,000 468 MB java.util.HashMap$Node
# 2: 4,080,000 130 MB -> 7,250,000 232 MB com.shop.session.CartSnapshot
# 3: 310,000 12 MB -> 311,000 12 MB java.lang.String (stable)

Notice that GC.class_histogram forces a full collection to count only live objects, so on a large heap it causes a pause of a second or more. We run it on one instance, ideally one we have taken out of the load balancer, or at a quiet time. Here about 3 million CartSnapshot objects and their HashMap nodes appeared in six hours, which points at a map of cart snapshots, but a histogram cannot tell us who holds it.

3Take a Heap Dump and Follow the References

A heap dump is a snapshot of every object and every reference between them. We take it when the leak has had time to grow, for example a day after a restart, so the leaking objects stand out clearly against the normal live set.

Shell
jcmd <pid> GC.heap_dump /dumps/orders-$(hostname).hprof # live objects only, full GC first
Step throughA leak's path to a GC root
  1. GC root: class CartCacheloaded by the application class loader
  2. static field SNAPSHOTSConcurrentHashMap
  3. 7.3 million HashMap nodesnever removed
  4. 7.2 million CartSnapshot objectsretained size about 2 GB

4 layers, from the top down. Step through them one at a time.

The dump is roughly the size of the live heap, here several gigabytes, and writing it pauses the JVM for seconds, so again we use an instance out of rotation and a disk with enough space. Then we open it in a tool such as Eclipse Memory Analyzer.

Two views do most of the work. The dominator tree lists the objects that keep the most memory alive: an object dominates another if every path from the GC roots to the second passes through the first, so removing it would free everything beneath. A leak usually shows as one collection retaining a large share of the heap, such as a ConcurrentHashMap retaining 2 GB. Then paths to GC roots, excluding weak and soft references, show the chain that keeps that collection reachable, for example a static field in a class called CartCache. That chain points at the line of code to fix.

4A Lower-Risk Alternative: JFR Old Object Samples

A heap dump of a large heap is slow, pauses the service and contains every customer's data. JFR offers a lighter alternative. Its old object sample event tracks a sample of allocated objects and keeps those that survive a long time, together with the stack trace where they were allocated. When we dump the recording with paths to GC roots enabled, JFR also records the reference chain that keeps each sampled object alive.

Shell
jcmd <pid> JFR.dump name=continuous path-to-gc-roots=true filename=/dumps/leak.jfr
# in JDK Mission Control, Memory > Old Object Sample:
# CartSnapshot allocated at CartService.snapshot(CartService.java:142)
# reachable from CartCache.SNAPSHOTS (static) -> ConcurrentHashMap -> Node

This is often enough to identify the leak without a heap dump at all: it shows both where the objects were created and who keeps them. Computing the paths to GC roots does cause a pause at dump time, so it is still best done on one instance, but the file is far smaller than a heap dump and contains much less data. Old object sampling with stack traces is enabled in the profile settings; check your recording's settings.

5The Usual Causes

Once we know which objects grow and who holds them, the cause is usually one of a few patterns. The most common is an unbounded cache or map: a map used as a cache with entries added per user, session or request and never evicted, as in our CartCache. Close behind are listeners or callbacks registered on a long-lived object and never removed, so each one keeps its whole object graph alive; ThreadLocal values never removed on pooled threads; and metrics with high-cardinality tags, where every new user id creates a meter that the registry keeps forever.

The fix follows the cause. For a cache, we use a real cache library with a maximum size and expiry, such as Caffeine, or remove entries when the session ends. For listeners we unregister them, for ThreadLocals we call remove() in finally, and for metrics we use bounded tags.

6Verifying the Fix

A leak fix is proven only by the same signal that found it. After deploying the fix, we watch heap occupancy after GC for at least a full day, covering the daily traffic peak and the quiet night. It should rise to a plateau and stay flat. We also repeat a class histogram a few hours apart and check that the suspect class no longer grows. And we keep an alert on post-GC occupancy rising over 24 hours, so a future leak is caught early.

Step throughFrom first signal to verified fix
  1. Post-GC heap rising day and nightGC logs or metrics
  2. Class histograms hours apartwhich types grow?
  3. Heap dump or JFR old object sampleson an instance out of rotation
  4. Dominator tree and path to GC rootswho holds the objects?
  5. Fix the causebounded cache, remove listener, remove()
  6. Post-GC heap flat for 24 hours?
    YesDone, keep the trend alertNoBack to the histograms

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

7Follow-up questions

How do you take a heap dump in Kubernetes without losing the pod?

We remove the pod from the Service by changing a label, so it receives no traffic, then use kubectl exec to run jcmd and write to a volume, and kubectl cp or a sidecar to move the file to secure storage. Changing the label also makes the ReplicaSet start a replacement, so capacity is preserved.

8Conclusion

In this answer, we investigated a heap that grows 50 MB per hour. We confirmed the leak from heap occupancy after GC rising steadily day and night, compared class histograms hours apart to find the growing types, took a heap dump and used the dominator tree and paths to GC roots to find who holds them, or used JFR old object samples for a smaller, safer view. We went through the usual causes, unbounded caches, listeners, ThreadLocals and high-cardinality metrics, and verified the fix by seeing post-GC occupancy stay flat over a full day.

What to say in the interviewAbout 90 seconds aloud

Open with

I would start by confirming it is a leak and not load: I look at heap used after GC in the GC logs or metrics over several days.

Then, if they want more

If it climbs about 50 megabytes an hour at night as well as during the day, that is a growing live set, and with roughly 3.6 gigabytes of headroom it matches failing every three days.

Next I narrow it cheaply with jcmd GC.class_histogram on one instance, a few hours apart, and compare which classes grow; that might show millions of new CartSnapshot objects and HashMap nodes. The histogram forces a full GC, so I take the instance out of rotation first.

Then, about a day after a restart, when the leak is big but not critical, I take a heap dump with jcmd GC.heap_dump, open it in Memory Analyzer, look at the dominator tree for the collection retaining most memory, and follow the path to GC roots, excluding weak references, to find the static field or bean holding it.

JFR's old object sample with path to GC roots is a lighter alternative that also shows the allocation site. The usual causes are unbounded caches or maps, listeners not removed, ThreadLocals and high-cardinality metric tags. After the fix, I only call it done when post-GC occupancy is flat for a full day, and I keep an alert on that trend.

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 "Heap occupancy after GC grows by about 50 MB per hour in production, and the service...": https://scrivio-interview-library.netlify.app/java/jvm-diagnostics/8b453b9c28/