Scrivio Interview library
DesignAdvanced7 min read · updated 12 November 2026

A trading platform must keep p99.9 latency under 2 milliseconds, but every request writes about ten log lines. Logging shows up at 15 percent of CPU and causes latency spikes during disk flushes. Describe how you would redesign logging for this system.

I would first measure with async-profiler, CPU and allocation profiles, to split the 15 percent into formatting, allocation, locking and I/O. Then reduce volume, logging state transitions and errors while moving per-request numbers to metrics and traces and sampling routine events; switch to garbage-free or low-allocation logging with Log4j2 async loggers, a pre-sized ring buffer and no caller data; take all I/O off the hot threads with a drop policy for low levels under bursts; and keep audit-grade records on a separate durable path such as a journal or event store. In extreme cases logging runs on dedicated cores or in a separate process, and every change is verified with latency tests under realistic load.

Why this question is asked

A p99.9 target of 2 milliseconds means that only one request in a thousand may take longer than 2 ms. At that level, things that are invisible in ordinary services become the dominant cost: a single disk flush that blocks for 5 ms, a garbage collection pause caused by log allocations, a lock held by another thread while it writes a line. Logging at 15 percent of CPU with ten lines per request is a strong signal that logging is on the critical path. Interviewers ask this design question to see whether we measure before changing things and whether we separate the different jobs logging is doing. In this answer, we will profile the cost, cut volume, make the remaining logging cheap, take I/O off the hot threads, give audit its own path, and look at extreme options and verification.

1Measure Where the 15 Percent Goes

Logging cost has four parts, and they need different fixes. Formatting turns arguments into text. Allocation creates strings, arrays and event objects, which later cause garbage collection pauses. Locking happens when many threads write through the same appender or queue. I/O is the actual write, and a write to a file can block for milliseconds when the operating system flushes its page cache to disk.

async-profiler can show all of this on the running service with little overhead: a CPU profile shows how much time sits under the logging framework's methods, an allocation profile shows how many bytes per request come from logging, and a lock profile shows contention. Java Flight Recorder gives similar data. Correlating latency spikes with disk activity, for example with operating system I/O statistics, confirms whether the spikes line up with flushes.

Java
# CPU and allocation profiles of the running JVM for 60 seconds
./asprof -e cpu -d 60 -f cpu.html <pid>
./asprof -e alloc -d 60 -f alloc.html <pid>
./asprof -e lock -d 60 -f lock.html <pid>
// example findings (illustrative):
// cpu: 14.8% under org.apache.logging / ch.qos.logback, half of it in message formatting
// alloc: 3.1 KB per request from logging, about 40% of all allocation
// lock: appender lock is the top contended monitor at peak

With numbers like these, we know that formatting and allocation are as important as I/O, so moving to an async appender alone would not be enough.

2Cut Volume First

Ten lines per request at, say, 20,000 requests per second is 200,000 lines per second. Most of them probably record routine steps: order received, validated, risk checked, routed, acknowledged. That information is better carried by other tools. Per-request numbers, such as latency of each stage, belong in metrics, which cost a few counter updates. The path of an individual request belongs in a trace, sampled. Logs should record what metrics and traces cannot: state transitions such as an instrument halted or a session reconnected, decisions that need explaining, and errors.

So I would aim for about one log line per request or fewer on the hot path, with routine events sampled, for example one in a thousand successful orders logged in full. Cutting from ten lines to one removes about 90 percent of the logging cost before we tune anything.

Where each kind of information should go
InformationBeforeAfter
Stage latencies per requestINFO line per stagemetrics (histograms)
Path of one request5 to 6 INFO linessampled trace
Routine successINFO per ordersampled 1 in 1,000
State transitions, decisionsmixed in with the restINFO, always
ErrorsERRORERROR, always
Order and execution recordsINFO linesseparate durable journal

3Make the Remaining Logging Cheap

For what remains, the logging library should allocate almost nothing per event. Log4j2 has a garbage-free mode, in which async loggers reuse pre-allocated ring buffer events, parameterised messages are formatted into reused buffers, and layouts encode directly into byte buffers. It depends on settings such as thread locals being enabled, which Log4j2 turns off by default when it detects a web application, so check that your configuration really runs garbage-free. Primitive arguments should not be boxed, and string concatenation in log calls must go, because it builds the string even when the line is filtered.

Caller data must be off everywhere: includeLocation="false" and no %class, %method or %line in patterns, because each of those captures a stack trace per event. Parameterised logging with simple argument types keeps formatting cheap.

Java
// Allocates on every call: concatenation runs even if INFO is off
log.info("Order " + orderId + " filled at " + price);
// Low allocation: parameterised; with Log4j2 garbage-free settings no per-event garbage
log.info("Order {} filled at {}", orderId, price);
// Hot path: log only the transition, not every fill
if (state != previous) log.info("Instrument {} state {} -> {}", symbol, previous, state);

4Take I/O Off the Hot Threads and Give Audit Its Own Path

The latency spikes during disk flushes come from request threads waiting on a write. Async loggers with a ring buffer sized for the worst burst move that wait to a background thread. Under an extreme burst, a full buffer would make request threads wait again, so for this system I would choose the discarding full policy for INFO and below: losing a routine line is acceptable, stalling an order is not. WARN and ERROR still wait, which is acceptable because they are rare.

That raises an important question: what about records that must never be lost, such as order and execution records needed for regulation and reconciliation? Those should not be log lines at all. They belong on a separate durable path designed for it: an append-only journal, a replicated event store or a message topic written with acknowledgements, often already part of the trading architecture. That path has its own latency budget and guarantees, and it lets the operational logs be lossy under pressure without any compliance risk.

Step throughHot path after the redesign
Order threadRing bufferLog writerJournal
append execution record (durable path)
ack
one state-change event, no allocation
continue: no wait for I/O
take events in batches
format and write; disk flush blocks only this thread

6 messages in order. Play them, or step through them one at a time.

5Extreme Options and Verification

If that is still not enough, there are stronger isolation options. The background logging thread can be pinned to a dedicated core, so its CPU use and cache effects do not disturb the trading threads. Some systems go further and write binary events to a shared-memory queue, such as a memory-mapped file, read by a separate process that formats and ships them, so the trading JVM never formats text at all.

Every step must be verified with latency tests under realistic load, not with averages. A load test that replays a recorded day's traffic, including the opening burst, should report p99, p99.9 and maximum latency, with logging configured exactly as in production. A change is accepted only if p99.9 stays under 2 ms with margin during the burst, and the test becomes part of the release pipeline so a new log line on the hot path is caught before it ships.

6Follow-up questions

What would you still log synchronously, if anything?

Very little on the hot path. Start-up and shutdown messages, configuration errors and fatal conditions before the system exits can be synchronous, because they are rare and we want them on disk before the process dies. Records that must never be lost go to the durable journal, which is synchronous in its own way, with acknowledgements, rather than through the logging framework. Ordinary WARN and ERROR events can stay asynchronous with the waiting policy, so they are not dropped.

Why not just use a faster disk?

A faster disk reduces the size of flush stalls but does not remove the problem: request threads would still wait for writes, contend on locks and allocate garbage for formatting. Moving I/O off the hot threads and reducing allocation address the causes, after which disk speed only affects how fast the background thread drains the buffer.

How do you debug production problems with so little logging?

With the other signals: metrics show where latency or errors changed, sampled traces show the path of affected requests, state-transition logs explain decisions, and the durable journal holds the full record of orders and executions. For a specific investigation, per-instrument or per-session debug can be enabled briefly through a filter, outside the hottest paths.

7Conclusion

In this answer, we redesigned logging for a system with a 2 ms p99.9 target. We profiled with async-profiler to split the cost into formatting, allocation, locking and I/O, cut volume by moving per-request numbers to metrics and traces and sampling routine events, made the remaining logging garbage-free with Log4j2 async loggers, parameterised messages and no caller data, took I/O off the hot threads with a drop policy for low levels under bursts, moved audit-grade records to a separate durable journal, and considered dedicated cores or a separate process, all verified with realistic latency tests.

What to say in the interviewAbout 90 seconds aloud

Open with

I'd start by measuring rather than guessing. With async-profiler I'd take CPU, allocation and lock profiles to split that 15 percent into formatting, allocation, lock contention and I/O, and I'd check whether the latency spikes line up with disk flushes.

Then, if they want more

Then the biggest win is usually volume: ten lines per request is too many on a hot path. Per-request numbers like stage latencies become metrics, the path of a request becomes a sampled trace, routine successes are sampled, and logs keep state transitions, decisions and errors. Getting to about one line per request removes most of the cost.

For what's left, I'd make it cheap: Log4j2 async loggers with a pre-sized ring buffer, garbage-free settings, which I'd verify because Log4j2 disables some of them in web environments, parameterised messages, no concatenation, and no caller data.

Then I'd make sure request threads never wait for I/O: the background thread writes, and under extreme bursts INFO and below are discarded instead of blocking. That only works if nothing important is in those logs, so order and execution records go on a separate durable path, a journal or event store with acknowledgements.

If needed, the log thread gets a dedicated core, or logging moves to a separate process reading a shared-memory queue. And every change is checked with a replay of real traffic, looking at p99.9 during the opening burst, not averages.

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 official documentation for the version you use. 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 "A trading platform must keep p99.9 latency under 2 milliseconds, but every request...": https://scrivio-interview-library.netlify.app/java/java-logging/85c7f9fe7a/