Sub topic 17
Profiling safely in production
This chapter assumes you can record and read a JFR file, use jcmd and jstat, and interpret GC logs and thread dumps from earlier chapters. It covers what changes when the JVM you are inspecting serves real users.
Why production is different
A profiler changes the thing it measures. On a laptop that costs a few seconds. In production the cost shows up as slower responses, a full disk, or an outage. Some problems also only appear under real traffic: a rare lock convoy, a cache that grows over days, or a GC pattern that needs production data volumes. You will need to profile there, and the goal is to get the evidence at the lowest risk.
Four risks come up repeatedly:
- Overhead: the profiler uses CPU, memory and I/O that the application needs.
- Pauses: some diagnostic commands stop the application threads.
- Disk: recordings and dumps can fill a volume that other things depend on.
- Data exposure: dumps contain real user data and secrets.
Choose the cheapest tool that answers the question
Work up a ladder. Move to the next rung only when the current one cannot answer your question.
GC logs and jstat read counters the JVM already keeps, so they are safe to leave on. A thread dump brings threads to a safepoint, which is a point where the JVM can pause them. It usually takes milliseconds, but it grows with thread count and stack depth. Take two or three dumps a few seconds apart so you can tell a stuck thread from one that was merely caught at a bad moment.
Run JFR continuously
Java Flight Recorder (JFR) was designed for production. It writes events into small thread-local buffers and flushes them to a ring of files. With the default settings, the JDK documentation puts overhead at roughly 1% or less. The profile settings sample more often and enable more events, so treat them as a short-term tool.
Start a continuous, bounded recording when the service starts:
java -XX:StartFlightRecording=name=continuous,disk=true,maxage=6h,maxsize=500m,dumponexit=true,filename=/var/log/app/exit.jfr,settings=default -jar app.jarEach option limits risk:
disk=truewrites the ring buffer to disk, so you can dump data from before the problem started.maxage=6handmaxsize=500mcap how much history is kept. The recorder discards the oldest data first, so disk use stays bounded.dumponexit=truesaves the last data when the JVM exits normally, for example on a deploy orSIGTERM.settings=defaultkeeps overhead low.
When an incident happens, dump the window you already have. Nothing needs to be restarted, and you do not need to reproduce the problem:
jcmd <pid> JFR.check
jcmd <pid> JFR.dump name=continuous filename=/tmp/incident.jfrJFR.check lists running recordings so you can confirm the name and state. JFR.dump copies the current contents without stopping the recording.
Time-box anything heavier
If the default events do not show enough, start a second recording with a fixed duration. Add the duration so that it ends on its own even if you lose your SSH session:
jcmd <pid> JFR.start name=deep duration=120s settings=profile filename=/tmp/deep.jfrKeep it short. Two minutes under real load is usually enough for a CPU profile.
To tune overhead further, copy default.jfc from $JAVA_HOME/lib/jfr/ and raise the threshold on events you do not need, or disable them. Pass the edited file with settings=/path/custom.jfc. A higher threshold, such as recording only lock waits longer than 20 ms, cuts event volume sharply without losing the slow cases you are after.
Be careful with heavy commands
Several commands look harmless and are not:
| Command | Risk | Mitigation |
|---|---|---|
| `jcmd <pid> GC.heap_dump` | Pauses all threads while it writes. By default it forces a full GC first. Output is about the size of the live heap. | Take it from one instance that has been removed from the load balancer. Check free disk first. |
| `jcmd <pid> GC.class_histogram` | Also forces a full GC unless you pass `-all`. | Use it as a cheap leak check on a drained instance. |
| `JFR.dump` with `path-to-gc-roots=true` | Walks the whole heap. Can pause for a long time. | Use it only on a drained instance. |
| `-XX:+HeapDumpOnOutOfMemoryError` | Writes a dump at the worst moment, when memory is already exhausted. | Set `-XX:HeapDumpPath` to a volume with enough space. |
| Attaching an instrumenting agent | Rewrites bytecode and adds cost to every call. | Prefer sampling in production. |
If you run in a container, remember that a heap dump may need free space close to the heap size. A 4 GB heap needs about 4 GB of free disk on the path you give. Also confirm the memory limit has headroom, since file writes can inflate page cache.
Protect the data you collect
A heap dump holds every object, including session tokens, passwords in strings, and personal data. A JFR file is less sensitive but can still record the command line, system properties and environment variables, which sometimes contain credentials. Handle both as sensitive:
- Write them to a directory only the service account and operators can read.
- Do not attach them to public tickets or chat.
- Delete them when the investigation ends.
- Run
jcmdas the same OS user as the target JVM. The attach mechanism refuses other users, and running as root only to get around that widens your access for no reason.
Contain the blast radius
Before you change anything on a live service, do these things:
- Pick one instance. Profile a single node or a canary, not the whole fleet. Compare it against its peers, which gives you a free baseline.
- Drain it if the command pauses the JVM. For heap dumps, remove the instance from rotation first, so users do not see the pause.
- Watch the user-facing metrics. Keep p99 latency and error rate on screen. If they move, stop the recording with
jcmd <pid> JFR.stop name=deep. - Write down what you ran. A later reader needs to know that a latency bump at 14:03 came from your recording.
- Prefer data you can take offline. Dump the file, copy it off the host, and analyze it in JDK Mission Control on your own machine. Analysis tools are heavy and should not run next to the service.
Interpreting results in production
Production recordings are noisier than benchmarks. Two habits help.
First, compare against a baseline. A recording from a healthy period, or from a healthy peer instance, shows what normal looks like. A method at 15% of CPU samples means little until you know it was 3% last week.
Second, connect the profile to the symptom you measured. If p99 latency rose, look at what the recording shows during those minutes: lock wait events, long GC pauses, or a CPU spike. Select the time range in JDK Mission Control instead of reading the whole recording. A hot method that is always hot may be unrelated to the incident.
A short checklist
Exercise
A service has a 6 GB heap and shows slowly rising memory. You want a heap dump from a production node. List three precautions you should take before running jcmd <pid> GC.heap_dump /tmp/heap.hprof.
Show answer
First, remove the node from the load balancer, because the command pauses all application threads and forces a full GC by default. Second, confirm the volume holding /tmp has at least about 6 GB free, since the file is roughly the size of the live heap and a full disk can hurt other processes. Third, restrict the file's permissions and plan to delete it afterwards, because it contains all in-memory data, including secrets and user information. Running jcmd as the same OS user as the JVM and watching the other nodes' latency are also good answers.
Exercise
Your team wants a recording available whenever an incident happens, without restarting the service. Which JFR options give you that with bounded disk use, and which command saves the data once the incident occurs?
Show answer
Start the JVM with -XX:StartFlightRecording=name=continuous,disk=true,maxage=6h,maxsize=500m,dumponexit=true,settings=default. The disk=true, maxage and maxsize options keep a rolling window on disk with a cap. When the incident happens, run jcmd <pid> JFR.dump name=continuous filename=/tmp/incident.jfr, which copies the current window without stopping the recording.