Finding bottlenecks in a high-throughput Java service
Under load, a Java service usually isn't short of speed everywhere. One resource is full, and everything else is waiting for it. The job is to find that resource, and guessing is the slowest way to do it, so I follow the same order each time.
Start with the right numbers
Averages hide the problem. A service with a 20 ms average can have a 2-second p99, and that is the experience of real users. Record latency as a histogram and look at p50, p95, p99 and the maximum together.
Beware of coordinated omission when you load test. A closed-loop tool that waits for each response before sending the next one politely slows down when the server stalls, so the stall barely appears in the results. Use a tool that holds a constant arrival rate, such as wrk2, Gatling's open model or k6's constant-arrival-rate executor.
Little's law tells you what to expect:
requests in flight = arrival rate × time in the system
At 2,000 requests per second and 20 ms each, you have about 40 requests in flight. If latency climbs to 200 ms, it's 400. Pools sized for 40 are now queues, and queues are where latency comes from.
Ask where requests wait
Before opening a profiler, check the places where work queues up:
| Place | What to look at |
|---|---|
| Web server threads | Busy count against the maximum |
| Database connections | Time to acquire a connection, pending threads |
| Outbound HTTP clients | Pool use, time waiting for a connection |
| Executors | Queue depth and rejected tasks |
| Kafka or other consumers | Consumer lag |
With Spring Boot and Micrometer, most of this is already exposed. hikaricp.connections.acquire is the one I look at first. Slow queries and a too-small pool look the same from the outside, and this metric tells you that requests are waiting to reach the database before any query has even started.
If a pool is full, a larger pool is rarely the answer. It moves the queue into the database, where it is harder to see and more expensive. Find out why connections are held so long.
Take thread dumps
A thread dump is the cheapest profiler there is. Take three or four, a few seconds apart, during the slow period:
for i in 1 2 3 4; do jcmd "$PID" Thread.print > "dump-$i.txt"; sleep 5; done
Then look for repetition. If most threads are in the same stack across dumps, that's your answer. Common findings are many threads BLOCKED on one monitor, many WAITING on a pool, or all of them stuck in a socket read to one dependency.
A synchronized block around something slow is a classic. So is a logging appender that writes synchronously to a slow disk.
Profile with JFR
Java Flight Recorder comes with the JDK and is cheap enough for production:
jcmd "$PID" JFR.start name=load settings=profile duration=120s filename=/tmp/load.jfr
jfr summary /tmp/load.jfr
jfr print --events jdk.JavaMonitorEnter /tmp/load.jfr | head -50
Open the file in JDK Mission Control for hot methods, lock contention, allocation by site and socket I/O. async-profiler is the other tool I use often, because its flame graphs include native code and it avoids safepoint bias. Use wall-clock mode when threads are waiting rather than burning CPU: a CPU profile of a service that is blocked on I/O will carefully show you nothing useful.
Check allocation and GC
Turn on GC logging permanently. It costs almost nothing, and you'll want the history:
-Xlog:gc*:file=/var/log/app/gc.log:time,uptime,level,tags:filecount=5,filesize=20m
Look at pause times and at how much of the time the process spends in GC. High allocation is usually the actual cause of GC pressure, and JFR will show which code does it. Before you tune collector flags, try allocating less: repeated string building, boxing in hot loops and serializing the same object over and over are all common and fixable.
If pauses themselves are the problem and the heap is large, a low-pause collector such as ZGC can be the right move.
Change one thing
Once you have a suspect:
- Write down what you expect the change to do to a specific metric.
- Make one change.
- Re-run the same load, with the same data.
- Keep the change only if the metric moved.
Then look again, because removing one bottleneck reveals the next one. Stop when you meet the target. Without a target, performance work has no end, and it tends to leave complicated code behind in places that never mattered.
The tools have changed over the years, but the method hasn't: measure, find the queue, find out why it's full, change one thing and measure again.