Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

Garbage collection consumes a noticeable share of CPU across your 2,000 JVM pods. Propose a program to reduce GC-related cost without hurting reliability.

Start by measuring GC CPU, pauses and allocation for every service in one place, rank services by GC cost, and work on the top few first. For those, use allocation profiling to find code fixes, right-size heaps so GC is not running constantly near the limit, keep JDKs current, and match the collector to the workload class. Every change goes out through canaries and is tracked as measured savings, so we cut cost without trading away reliability.

Why this question is asked

At 2,000 pods, even a few percent of CPU spent in GC is a large bill, often tens of cores running nothing but collectors. But this is also a reliability question, because the quickest way to save GC CPU, shrinking heaps, is also a quick way to cause out-of-memory crashes. Interviewers ask it to see whether we can turn tuning knowledge into a program: data first, priorities, safe rollout, and proof of savings. In this answer, we will set up fleet-wide measurement, rank where the money is, go through the levers in order of value, and design the rollout and tracking.

1Why a Program Instead of a Tuning Session

GC cost is spread unevenly. In most fleets a small number of services, high-traffic ones with heavy allocation, account for most of the GC CPU. Tuning 2,000 pods one by one is impossible, and applying one set of flags everywhere is risky, because a setting that helps one service can starve another. So we need the same thing any cost programme needs: one view of the data, a ranked list, and a safe way to change things.

2Collect the Same Metrics From Every Service

Most Java services already expose JVM metrics through Micrometer if they use Spring Boot Actuator. The useful ones are jvm.gc.pause (a timer of pause durations, tagged by cause and action), jvm.gc.memory.allocated (bytes allocated in the young generation), jvm.gc.memory.promoted, and jvm.gc.overhead, an estimate of the share of CPU time spent in GC. We collect them into one metrics system tagged by service, team and pod size, so we can compare across the fleet.

Metrics tell us where to look; they do not tell us why. For that we also keep GC logs, written with unified logging to a rotating file, and the ability to record JFR (Java Flight Recorder, the low-overhead profiler built into the JVM) on demand. JFR at its default settings typically costs around one percent, which is low enough to run continuously on a sample of pods.

YAML
# Standard JVM options added by the platform's base image
-Xlog:gc*:file=/var/log/app/gc.log:time,uptime,tags:filecount=5,filesize=20m
-XX:StartFlightRecording=name=continuous,settings=default,maxage=6h,disk=true
# Example fleet query (PromQL-style): GC CPU in cores per service
# sum by (service) (jvm_gc_overhead * on(pod) process_cpu_usage_cores)
Step throughFleet GC cost pipeline
  1. PodsMicrometer jvm.gc metrics, GC logs, JFR on a sample
  2. Metrics storetagged by service, team, pod size, JDK
  3. Cost rankingGC cores and dollars per service
  4. Investigationallocation profiles for the top services
  5. Changes and canariesone change at a time, measured savings

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

3Rank Services by GC Cost

We turn the metrics into money. For each service, GC CPU share times total CPU gives cores spent in GC; multiplied by the price of a core, that is a monthly cost. A typical result looks like this: of 140 services, the top 10 account for 70 percent of GC cores. Those ten are where the program starts. We also rank by risk signals, such as services with frequent full collections or heap use near the limit, because those are reliability problems disguised as cost problems.

Example ranking (illustrative numbers)
ServicePodsGC share of CPUGC cores
search-api30014%126
pricing18011%59
orders2506%45
auth1202%7
Work starts at the top of the list, where a fix pays back most.

4Fix Allocation Hot Spots in Code

For each top service we take an allocation profile, using async-profiler in alloc mode or the JFR allocation sample events, and look for the call sites that allocate the most bytes. Common finds are JSON serialisation that builds intermediate strings, logging that formats messages that are never written, boxing of numbers in hot loops, and per-request copies of large lists. A code fix that halves allocation roughly halves young collection work, and it also cuts CPU in the application itself, so this lever usually saves the most.

Text
# 60 seconds of allocation profiling on a live pod (async-profiler 3.x)
asprof -e alloc -d 60 -f /tmp/alloc.html <pid>
# or with JFR, then open the recording in JDK Mission Control
jcmd <pid> JFR.start name=alloc settings=profile duration=60s filename=/tmp/alloc.jfr

5Right-Size Heaps, Upgrade JDKs, Match Collectors

A heap that is too small makes GC run constantly, because each collection frees little space; this shows up as high GC overhead and old generation occupancy near the maximum after every collection. Giving such a service more heap often cuts GC CPU sharply, which is a case where spending memory saves CPU. The reverse also exists: services with large heaps that never use them, where we can shrink memory requests safely. We size from the live set measured after full or mixed collections, plus headroom, not from guesses.

Upgrading the JDK is the cheapest lever across the whole fleet. Each LTS release, 17, 21 and 25, brought GC improvements, such as generational ZGC in 21 and many G1 refinements. Moving services forward is a platform task that saves cost without touching application code.

Finally, we match the collector to the workload class: G1 as the default for most services, ZGC for latency-sensitive ones that can afford extra CPU and memory, and Parallel GC for batch jobs where only total run time matters. The rule is a class-level default with documented exceptions, not per-service experimentation.

6Roll Out Safely and Track Savings

Every change, whether a heap size, a collector or a JDK version, goes out the same way: to a canary group of pods first, compared with the rest under the same traffic, with guard metrics such as error rate, p99 latency, OOM kills and restarts. Only if the guards stay flat and GC CPU drops do we roll out further. We record the measured savings per change, in cores and money, so the program can show its value and so we can undo a change that later regresses.

7Follow-up questions

How do you avoid shrinking heaps too far?

We size from the live set, the occupancy right after a full or mixed collection, measured over a week that includes traffic peaks. The heap is set to a multiple of that, often two to three times for G1, and the container limit includes non-heap memory. The canary watches OOM kills, GC overhead and p99 latency, so if the smaller heap makes GC work harder we see it before the full rollout.

Why not standardise one set of GC flags for all 2,000 pods?

Because services have different allocation rates, live sets and latency needs, and a single set of flags cannot fit them all. JVM ergonomics already pick reasonable defaults from the container size. A small number of standard profiles, a default, a latency profile and a batch profile, is easier to maintain and safer than one rigid flag list.

What if a team does not want to change their code?

We show them their own numbers: GC cores, cost and the top allocation sites from their profile. Often the fix is a small change that also lowers latency, which they care about. For teams with other priorities, platform-level changes such as JDK upgrades and heap right-sizing still save cost without code work.

8Conclusion

In this answer, we built a program rather than a tuning session. We collected GC metrics, logs and JFR data from every service in one place, ranked services by GC cost, and focused on the top ones. Allocation profiling gave code fixes, heap right-sizing and JDK upgrades gave platform-level savings, and a collector per workload class kept choices simple. Every change went through canaries with guard metrics, and we tracked savings per change so the program could prove its value without hurting reliability.

What to say in the interviewAbout 80 seconds aloud

Open with

I would treat this as a cost program with data first. Step one is fleet-wide measurement: Micrometer already gives jvm.gc.pause, allocated and promoted bytes and a GC overhead estimate, so I would make sure every service exports those, tagged by service and pod size, and that GC logs and JFR are available on demand.

Then, if they want more

Step two is ranking: convert GC CPU share into cores and money per service. Usually a handful of services account for most of the spend, so those are where we start.

For each of them, I would take an allocation profile with async-profiler in alloc mode or JFR and look for hot spots, because cutting allocation saves both GC and application CPU.

Then right-size heaps: a heap running near its limit makes GC run constantly, so adding memory can save CPU, and oversized heaps can be trimmed, always sized from the measured live set.

At the platform level, keep JDKs current since each LTS improves the collectors, and use a collector per workload class: G1 by default, ZGC for latency, Parallel for batch. Every change goes through canaries with guard metrics like error rate, p99 and OOM kills, and we track savings per change.

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 "Garbage collection consumes a noticeable share of CPU across your 2,000 JVM pods....": https://scrivio-interview-library.netlify.app/java/garbage-collection/0f3f5fbc90/