Video in progress
In a service like trading or an ad auction, p99.9 latency must not exceed 5 ms. How do you prepare the JVM for this?
I remove the sources of pauses one by one: minimal allocation, a concurrent GC (generational ZGC) or an almost GC-free mode, warm-up before startup, watching safepoints and JIT deoptimization, and at the OS level CPU isolation, huge pages and an environment without swap. I measure every step by p99.9, not by the average.
📖 Answer
At 5 ms p99.9 the GC, the OS and the JIT are all sources of "noise". Item by item:
-
Allocation. Bring object creation on the hot path almost to zero: primitive structures, reusable buffers, off-heap (FFM or the Agrona/Chronicle style), ring buffers like the Disruptor. The goal is for young GC to be rare and short.
-
GC. Generational ZGC: pauses under a millisecond, but account for load barriers and allocation stalls, and keep a big heap reserve. Some systems fit a whole trading day into the heap, hardly call the GC, and restart at night. This is extreme, but it does happen in practice.
-
Warm-up. Before opening, bring all the hot paths up to C2 with synthetic traffic; AOT cache profiles. The first real request shouldn't land in the interpreter.
-
Safepoints and JIT. Watch the stops with
-Xlog:safepointand deoptimizations in JFR. Monitoring agents shouldn't take periodic thread dumps. -
OS.
isolcpus/CPU pinning: the worker threads on their own cores, without OS noise;-XX:+AlwaysPreTouchand huge pages: no page faults at runtime;- swap off, THP
madvise, constant CPU frequency (power saving off); - a single node on NUMA.
- Code. A lock-free or single-writer design, and waiting with busy-spin (
Thread.onSpinWait): latency in exchange for CPU. Logging that is asynchronous and allocation-free.
Measuring. p99.9/p99.99 with HdrHistogram, and a load generator that accounts for coordinated omission. A tool like jHiccup shows the JVM's/OS's own "freezes" separately from the application.
I state the trade-off openly too: a system like this is expensive (isolated cores, a big heap), its code is harder to read and requires special knowledge. In many cases, revisiting the requirement (5 ms only for the critical path), or splitting the hottest part into a separate, small component, is cheaper than making the whole service like this.
Sign up to mark studied questions and save your progress.