Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

A service spends 15 percent of CPU on logging and p99 latency spikes when the log collector is slow. What would you change?

We attack it from two sides. First we log less: lower noisy loggers to WARN or INFO, remove per-item lines inside loops, and sample repetitive events. Then we take the remaining writes off the request threads with an asynchronous appender, such as Logback's AsyncAppender or Log4j2 async loggers, decide explicitly whether a full queue blocks or drops events and monitor the drops, remove caller data such as line numbers from the pattern, and write to stdout so a node agent ships the logs instead of the application talking to a slow collector.

Why this question is asked

When a service spends 15 percent of its CPU on logging and its p99 latency follows the health of the log collector, logging has become part of the request path. That is a reliability problem, not only a cost problem: an outage of the observability system turns into an outage of the business service. Interviewers ask this scenario because the fix requires both a technical change and a judgement call about losing log lines. In this answer, we will find out where the cost comes from, reduce the volume, make writing asynchronous, choose between blocking and dropping, remove expensive pattern elements, and change how logs leave the service.

1Finding Out Where the Time Goes

Before changing anything, we confirm the diagnosis with a profiler. A CPU flame graph from async-profiler or a JFR recording shows how much time sits under Logback or Log4j2 frames, and a wall-clock profile or a thread dump during a collector slowdown shows threads waiting inside the appender. We also count lines: if the service writes 40,000 lines per second at 2,000 requests per second, that is 20 lines per request, which is usually the real cause.

Typically we find three things together: far too many lines, expensive formatting such as caller data or large JSON payloads, and a synchronous appender that sends over the network or writes to a slow disk. The p99 spikes come from the last one. Logback appenders hold a lock while they write, so when one write takes 200 ms because the collector is slow, every request thread that wants to log queues up behind it.

Step throughWhy a slow collector raises p99 latency
Request thread 1Request thread 2Sync appenderLog collector
log.info(...) takes the lock
send line
log.info(...) waits for the lock
ack after 200 ms (collector slow)
return, lock released
now thread 2 can write

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

With a synchronous appender, the collector's latency becomes the request's latency.

2Reduce the Volume

The cheapest log line is the one we do not write. We look at the top loggers by volume and ask for each whether anyone has searched for those lines in the last month. Common wins are framework loggers left at DEBUG, a line per item inside a loop over a batch, and request and response bodies logged in full.

Java
# application.properties
logging.level.root=INFO
logging.level.org.hibernate.SQL=WARN
logging.level.com.acme.pricing.RuleEngine=WARN
// Before: one line per item, 500 lines for one batch
for (Item item : batch) { log.info("priced item {} at {}", item.id(), price(item)); }
// After: one summary line per batch
log.info("priced batch {} items={} failed={} ms={}", batchId, batch.size(), failed, elapsed);

For events that are useful but repetitive, such as a retry warning that fires 3,000 times a minute during a dependency outage, we sample or rate-limit them: log the first occurrence and then a summary every minute with a count. Counts belong in metrics anyway, where they cost almost nothing. In practice this step alone often cuts volume by 70 to 90 percent and removes most of the CPU cost.

3Write Asynchronously

Next we take the remaining writes off the request threads. An asynchronous appender puts each log event into an in-memory queue and returns at once; a background thread takes events from the queue and passes them to the real appender. In Logback we wrap the existing appender.

XML
<!-- logback-spring.xml -->
<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>8192</queueSize> <!-- default is 256, too small for bursts -->
<discardingThreshold>0</discardingThreshold> <!-- 0: do not silently drop INFO and below -->
<neverBlock>true</neverBlock> <!-- drop instead of blocking when full -->
<includeCallerData>false</includeCallerData>
<appender-ref ref="CONSOLE"/>
</appender>
<root level="INFO"><appender-ref ref="ASYNC"/></root>

Log4j2 offers async loggers built on the LMAX Disruptor, a lock-free ring buffer, enabled by setting log4j2.contextSelector to the AsyncLoggerContextSelector or by using AsyncLogger elements in the configuration; they have higher throughput than a queue-based appender. Either way, the request thread now only pays for creating the event and putting it into the queue, a few microseconds, and a slow collector affects the background thread rather than the requests.

4Decide What Happens When the Queue Is Full

An asynchronous appender only moves the problem if the queue fills up, and during a long collector outage it will. Then there are only two choices: block the caller until there is room, which brings the latency spikes back, or drop the event, which loses log lines. There is no third option, so we make the choice deliberately per service.

Logback's defaults are worth knowing. By default, when the queue has less than 20 percent of its capacity left, AsyncAppender silently discards TRACE, DEBUG and INFO events and keeps WARN and ERROR; and when the queue is completely full it blocks, unless neverBlock is true. For most request-serving services we prefer neverBlock=true: losing some INFO lines during an outage is better than failing requests. For an audit trail, dropping is not acceptable, but an audit trail should not go through the general application log anyway. Whatever we choose, we monitor it: we expose the number of dropped events as a metric and alert on it, so a drop is a known event and not a mystery gap in the logs.

Step throughWhen the async queue is full
  1. Event arrives at async appender
  2. Queue has room?
    YesEnqueue and return in microsecondsNoApply the full-queue policy
  3. Policy is block?
    YesCaller waits, latency risesNoEvent dropped
  4. Count drops as a metricalert when drops are above zero

4 steps in order. Play them, or step through them one at a time.

5Remove Expensive Pattern Elements

Some pattern conversions are much more expensive than the rest. Caller data, which means %L for the line number, %M for the method, %F for the file and %C for the class, is computed by creating a stack trace for every event and walking it. That can cost several microseconds per line and dominates the cost of formatting. With an async appender it is worse: the stack trace must be captured on the calling thread before the event is queued, so the caller pays for it anyway, which is why includeCallerData is false by default.

We replace caller data with the logger name, %logger{36}, which is just the class name we passed to LoggerFactory and costs nothing to print. We also check for other surprises in the format, such as very long MDC values, multi-line JSON payloads or stack traces logged for expected errors.

6Write to stdout and Let an Agent Ship

Finally, we change where logs go. If the application sends logs over the network to the collector itself, for example with a TCP or HTTP appender, the application is coupled to the collector's health. Instead, we write to stdout, or to a local file on a VM, which is fast and local, and let a node agent such as Fluent Bit, Vector or the OpenTelemetry Collector tail it and ship it. The agent has its own buffers and retries, and when the collector is slow, it falls behind rather than slowing our requests.

After the changes, we measure again: logging CPU back to around 2 to 3 percent, p99 flat during a simulated collector slowdown, and a drop counter that stays at zero in normal operation. Those three numbers tell us the fix worked.

7Follow-up questions

Does an async appender lose logs when the application crashes?

It can. Events still in the queue when the JVM dies abruptly are lost, and on a normal shutdown Logback waits only up to maxFlushTime (1 second by default) to drain the queue. That is another reason to keep the queue flowing quickly to a local stdout or file and to log the most important errors synchronously only if we truly need them.

Is Log4j2 always faster than Logback?

Log4j2's async loggers with the Disruptor usually have higher throughput and lower latency than Logback's queue-based AsyncAppender, especially with many threads. But for most services the bigger gains come from writing fewer lines and removing caller data. Switching frameworks is a larger change than tuning the one we have, so we measure before deciding.

Why not keep a small queue so we notice problems early?

A small queue fills during ordinary bursts, such as a deployment or a traffic spike, and then either blocks requests or drops lines when nothing is wrong. We size it for bursts, for example a few thousand events, and notice problems through the drop metric and the agent's lag instead.

8Conclusion

In this answer, we confirmed with a profiler that logging was in the request path, reduced volume by lowering levels, replacing per-item lines with summaries and sampling repetitive events, and moved writes off request threads with Logback's AsyncAppender or Log4j2 async loggers. We decided explicitly whether a full queue blocks or drops and monitored drops, removed caller data such as %L and %M from the pattern, and wrote to stdout so a node agent, not the application, deals with a slow collector.

What to say in the interviewAbout 90 seconds aloud

Open with

First I would confirm the cause with a profiler: a flame graph showing time under the logging frames, and a thread dump during a collector slowdown showing request threads waiting in the appender.

Then, if they want more

A synchronous appender holds a lock while it writes, so a slow collector becomes request latency. Then I would fix it in order.

Step one is volume, because the cheapest line is one we never write: raise noisy framework loggers to WARN, replace per-item logs in loops with one summary per batch, and sample or rate-limit repetitive warnings, moving counts into metrics. That often removes most of the CPU cost.

Step two is an asynchronous appender, Logback's AsyncAppender with a larger queue than the default 256, or Log4j2 async loggers on the Disruptor, so request threads only enqueue.

Step three is the full-queue decision: blocking brings the latency back and dropping loses lines, so for a normal service I would set neverBlock to true, be aware of the default discarding of INFO and below when the queue is eighty percent full, and alert on a drop counter.

Step four, remove caller data like %L and %M, which builds a stack trace per event. And step five, write to stdout and let a node agent ship the logs, so the application never waits on the collector.

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 documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Boot reference
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 service spends 15 percent of CPU on logging and p99 latency spikes when the log...": https://scrivio-interview-library.netlify.app/spring-boot/boot-logging/028345c3d1/