archive2023

Finding why a Java service is slow: JFR, Mission Control and async-profiler

How I profile a slow Spring Boot service: start a JFR recording on a running JVM, read it in JDK Mission Control, then use async-profiler flame graphs for CPU, allocation and wall-clock time, also inside containers.

8 min read#dev#java#performance

When a Java service gets slow, the first idea is often to change the GC or the size of a thread pool. Without data, that is a guess. This is the order I follow instead, from the first number to the flame graph.

The tools are JDK Flight Recorder (JFR), JDK Mission Control (JMC) to read the recordings, and async-profiler for flame graphs. All of them are free, and all of them work on a running service in production.

Measure first

Before any profiling, write down what “slow” means. Which endpoint, which percentile, under which load. Get the number from your metrics (Actuator with Micrometer, or the access log). Then you can check later if a change helped.

Also decide if the problem is CPU or waiting. If the CPU of the container is high while it is slow, look at CPU profiles. If the CPU is low and requests are still slow, the threads are waiting for something: the database, another HTTP service, a lock, a connection pool. A CPU profile will show almost nothing useful in that case. This one decision saves a lot of time.

JFR: start a recording

JFR is built into the JVM. It has been in OpenJDK since JDK 11 (JEP 328), and it was backported to OpenJDK 8u262. Talks from the JFR developers give the overhead of the default settings as below 1%, so I leave it running on production services without worry. The profile settings collect more (more stack samples, lower thresholds) and cost more, so use them for short recordings.

You can start a recording when the JVM starts:

java -XX:StartFlightRecording=duration=5m,filename=/tmp/app.jfr,settings=profile \
     -jar app.jar

Or keep a continuous recording in memory and only write it to disk when you need it:

java -XX:StartFlightRecording=name=bg,maxage=30m,settings=default \
     -jar app.jar

Most of the time the service is already running and I do not want to restart it, because a restart may hide the problem. Then use jcmd, which comes with the JDK:

jcmd -l                                   # find the pid
jcmd <pid> JFR.start name=slow settings=profile duration=5m filename=/tmp/slow.jfr
jcmd <pid> JFR.check                      # list running recordings

If a continuous recording is running, dump the last minutes to a file:

jcmd <pid> JFR.dump name=bg filename=/tmp/bg.jfr

Run the slow requests while the recording is active. A recording of an idle service tells you nothing.

In a container, jcmd must run as the same user as the JVM, inside the same container. With Docker that is docker exec -it <container> jcmd 1 JFR.start ... if Java is PID 1. Then copy the file out with docker cp or kubectl cp. If the image has only a JRE and no jcmd, use the -XX:StartFlightRecording flag instead, or switch to a JDK image for debugging.

One extra flag makes the stack traces more exact, because the JVM then records debug info at more places than safepoints:

-XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints

What to look at in JMC

Open the .jfr file in JDK Mission Control (I use JMC 8). It first shows the Automated Analysis page. It is a list of rules with a score. I read it, but I do not trust it fully; it is a hint where to look. Then I go through these pages:

  • Method Profiling. The hot methods by number of samples. Look at the stack trace of the top methods, not only the top frame. If the top frame is HashMap.get, the question is who calls it so often.
  • Memory / Allocations. Which classes are allocated most, and from which stack traces. A high allocation rate means more GC work, even if each object is small.
  • Garbage Collections. Pause times and how often GC runs. If pauses are long or frequent, check the heap size and the allocation rate before you change GC flags.
  • Lock Instances. Monitors where threads waited (jdk.JavaMonitorEnter events). Only waits above a threshold are recorded, so short waits do not show here.
  • Threads. A timeline per thread with its state. Many request threads in “blocked” or “waiting” at the same time is a strong sign.
  • Socket I/O and File I/O. Reads and writes above a threshold, with the remote host and the duration. Slow database or HTTP calls show here.
  • Exceptions. A service that throws thousands of exceptions per second for normal control flow pays for every stack trace.

The Event Browser shows every event type in a table. When a page does not answer my question, I look there.

async-profiler

JFR samples Java stacks only. async-profiler also sees native frames, JVM internals (GC threads, the JIT compiler) and kernel frames, and it makes flame graphs directly. It does not have the safepoint bias problem of older Java profilers. The current release is 2.9 (from the GitHub releases). It runs on Linux and macOS.

tar xzf async-profiler-2.9-linux-x64.tar.gz
cd async-profiler-2.9-linux-x64
./profiler.sh -d 30 -f /tmp/cpu.html <pid>

This profiles CPU for 30 seconds and writes an HTML flame graph. The output format is chosen from the file name: .html gives a flame graph.

Other modes I use:

# allocation profile: who allocates the most bytes
./profiler.sh -e alloc -d 30 -f /tmp/alloc.html <pid>

# lock contention
./profiler.sh -e lock -d 30 -f /tmp/lock.html <pid>

# wall-clock: all threads, running or not; -t splits by thread
./profiler.sh -e wall -t -i 5ms -d 30 -f /tmp/wall.html <pid>

Wall-clock mode is the one for latency problems. It samples all threads at a fixed interval, no matter if they run, sleep or wait. So a request thread that waits 200 ms for the database shows a wide bar under the JDBC driver. The CPU profile would not show it at all. The catch is that idle threads (pool threads waiting for work) also fill the graph. With -t each thread gets its own tree, and I just look at the request threads (in Tomcat they are named http-nio-8080-exec-*).

How to read a flame graph

  • Each box is a stack frame. The frame below is its caller.
  • The width of a box is the share of samples where this frame was on the stack. Width is time (or bytes in alloc mode), not call count.
  • The x-axis order is alphabetical. It is not a timeline. Left and right mean nothing.
  • Look for wide boxes near the top. A wide plateau at the top is code that uses the time itself. A wide box low in the graph with many thin children means the cost is spread out below it.
  • Colors show the frame type (Java, native, kernel, inlined). They do not show how hot a frame is.
  • Click a box to zoom in. Use the search (Ctrl+F) to highlight a method, for example Pattern.compile or Logger, and the graph shows the matched percentage.

Containers

By default async-profiler uses perf_events from the Linux kernel. In Docker this often fails, because the default seccomp profile blocks the perf_event_open system call, and the host may set kernel.perf_event_paranoid to a high value. The README lists the options:

  • Profile from the host as root, with the host PID of the Java process.
  • Run the container with --security-opt seccomp=unconfined (and maybe --cap-add SYS_ADMIN). I do not like this for production.
  • Use --fdtransfer, which lets a privileged helper open the perf events for the profiled process.
  • Use -e itimer. It is like cpu mode but does not need perf_events.

On Kubernetes I almost always use itimer, because I cannot change the pod security settings just to profile:

kubectl cp async-profiler-2.9-linux-x64.tar.gz mypod:/tmp/
kubectl exec -it mypod -- sh -c 'cd /tmp && tar xzf async-profiler-2.9-linux-x64.tar.gz'
kubectl exec -it mypod -- /tmp/async-profiler-2.9-linux-x64/profiler.sh \
    -e itimer -d 30 -f /tmp/cpu.html 1
kubectl cp mypod:/tmp/cpu.html ./cpu.html

With itimer you lose kernel stacks, but for a Java service that is usually fine. If the image is Alpine, download the musl build, not the glibc one. alloc, lock and wall modes do not use perf_events, so they work in a container without extra settings.

Common findings

This is the list I check first. Each one is a thing I have seen in profiles more than once, in different code bases.

  • Too much logging. Logger frames, layout formatting and appender I/O in the CPU or wall graph. Often DEBUG is left on for a package, or a log line builds a large string (a whole JSON payload) on every request. Check the log level and use parameterized messages.
  • Regex compiled in a loop. Pattern.compile in the CPU graph. String.replaceAll, String.matches and String.split with a regex compile a new Pattern on each call. Compile the pattern once into a static final field.
  • N+1 queries. In wall-clock mode, many thin stacks under the JDBC driver and socket reads, called from a loop in a service method, or from Hibernate lazy loading. JFR Socket I/O shows many short reads to the database. Fix it with a join fetch or a batch query, and count the SQL statements per request in a test.
  • Lock contention. -e lock or the JMC Lock Instances page shows one monitor where many threads wait. Typical cases are a synchronized method on a shared object, a small connection pool (threads wait in HikariPool.getConnection), or an old library with a global lock.
  • Exceptions for control flow. Throwable.fillInStackTrace in the CPU graph.
  • High allocation in serialization. Jackson creating an ObjectMapper per request shows up in both CPU and alloc graphs. Create it once and reuse it.

After a fix, I record again with the same settings and the same load and compare. If the number from the first step did not move, the fix was not the cause, even if the graph looks nicer.

For a problem that shows up only a few times per day, keep a continuous recording with maxage running and dump it with JFR.dump right after the slow event, before the data ages out.