DevOps & CI/CD Bug Report

A debug log line in a hot loop cut our service's throughput by 40 percent

A release that only added logging made a pricing service 40 percent slower at peak. The log statement ran inside a per-item loop, built its message eagerly, and wrote synchronously to a file appender behind a lock. How profiling showed it, and the fixes: levels, lazy messages, async appenders and sampling.

Leila Farahani Leila Farahani @leilafarahani · November 19, 2026 · 7 min read · 74 Views
Banner: a log statement in a hot loop slowing a service

Our pricing service computes prices for carts, iterating over items and applying discount rules. A release that, according to its changelog, only "added logging for discount debugging" went out on a Wednesday. At the next traffic peak, throughput per instance dropped from about 1,900 requests per second to about 1,150, p99 latency doubled, and the autoscaler added eight instances to compensate.

The diff was small. In the inner loop, which runs once per cart item per discount rule:

for (DiscountRule rule : rules) {
    for (CartItem item : cart.items()) {
        log.debug("Evaluating rule " + rule.id() + " for item " + item.sku()
                  + " with context " + context.toJson());
        if (rule.applies(item, context)) {
            ...
        }
    }
}

And the production configuration had been changed in the same release to help with the debugging:

<Logger name="com.example.pricing.discounts" level="debug" additivity="false">
  <AppenderRef ref="File"/>
</Logger>

Profile

We attached async-profiler to one instance under load for 60 seconds:

./asprof -d 60 -e cpu -f /tmp/cpu.html $(pgrep -f pricing-service)
./asprof -d 60 -e lock -f /tmp/lock.html $(pgrep -f pricing-service)

The CPU flame graph showed about 31 percent of samples under DiscountEngine.evaluate, inside Context.toJson() and StringBuilder.append. The lock profile showed request threads spending significant time waiting on a monitor inside the file appender's output stream:

java.lang.Thread.State: BLOCKED (on object monitor)
    at org.apache.logging.log4j.core.appender.OutputStreamManager.writeBytes(OutputStreamManager.java:...)
    - waiting to lock <0x00000006c1a2b3c8> (a org.apache.logging.log4j.core.appender.RollingFileManager)
    at org.apache.logging.log4j.core.appender.AbstractOutputStreamAppender.directEncodeEvent(...)

With 200 request threads, they were taking turns to write to one file.

Three separate costs

The single log statement had three costs, multiplied by how often it ran. A large cart with 40 items and 25 rules executes the loop body 1,000 times for one request.

1. Eager message construction. String concatenation with + runs before log.debug is even called. Java evaluates the argument first, so context.toJson(), which serialised the whole pricing context (customer segment, active campaigns, currency), ran 1,000 times per request. This cost is paid even when debug is disabled, because the logger only checks the level after receiving the finished string.

2. Formatting and I/O. With debug enabled, each event was formatted with the pattern layout and written to the file. A thousand lines per request at 1,900 requests per second is about two million lines per second per instance, around 1.5 GB per minute of log data.

3. Synchronous, serialised writes. Log4j2's default appenders write on the calling thread. The file appender protects its output stream with a lock, so concurrent writers queue. Request threads stopped doing pricing work and waited for their turn to write log lines.

Why it was not caught in testing

The load test environment used the default configuration with info level, and in the test data carts had three to five items. The eager toJson() cost was there but small. The debug level was only enabled in production's configuration, by the same release, for the investigation.

Environment

Item Value
Runtime Java 21, Log4j 2.23, rolling file appender, 200 request threads
Loop items x rules, up to about 1,000 iterations per request
Before 1,900 req/s per instance, p99 45 ms
After the release 1,150 req/s per instance, p99 96 ms

1. Turn the level back down, and keep debug out of hot loops

The immediate fix was reverting the logger level to info. That recovered most of the throughput, but not all, because of the eager toJson().

The line itself was the real problem. Debug output at the level of individual loop iterations is rarely useful in production. We moved to one summary line per request, at debug:

log.debug("Evaluated {} rules x {} items, {} discounts applied in {} us",
          rules.size(), cart.items().size(), applied.size(), elapsedMicros);

2. Parameterised and lazy messages

Log4j2 (and SLF4J) parameterised messages with {} placeholders defer formatting until the level check passes. For arguments that are expensive to compute, pass a supplier so the computation itself is deferred:

log.debug("Discount context for cart {}: {}", cart.id(), (Supplier<?>) context::toJson);

Log4j2's API accepts Supplier arguments and only calls them if the event will be logged. With debug disabled, the cost of this line is a level check: a few nanoseconds.

3. Asynchronous logging

To keep request threads from waiting on I/O at all, we switched to Log4j2's asynchronous loggers, which hand events to a background thread through a lock-free ring buffer:

# log4j2.component.properties
log4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
log4j2.asyncLoggerRingBufferSize=262144
log4j2.asyncQueueFullPolicy=Discard
log4j2.discardThreshold=INFO

In Log4j 2.x, asynchronous loggers need the LMAX Disruptor library on the classpath. The two queue settings decide what happens when logging outpaces the disk: with Discard and threshold INFO, events at INFO and below are dropped when the buffer is full, while WARN and ERROR still block until there is space. We accept losing debug and info lines under extreme load; we do not accept losing errors, and we do not accept request threads stalling on logging.

Asynchronous logging has a trade-off: events still in the buffer are lost if the process crashes hard. For audit events that must not be lost, we use a separate synchronous logger to a separate appender.

4. Sampling for high-volume diagnostics

For the original goal, understanding which discounts applied to which items, we added sampled tracing instead of logs. One request in a thousand records the full rule evaluation as span events on its trace. Engineers can find detailed examples when they need them, at a cost of 0.1 percent of the volume.

5. A log volume budget

We now track log bytes per request per service as a metric, and alert when it more than doubles after a deploy. That would have flagged this release within minutes, before the traffic peak.

1. Microbenchmark of the logging call with debug disabled (JMH, one thread):

Variant Time per call
"..." + context.toJson() 4,800 ns
"{}", context.toJson() 4,750 ns (argument still computed)
"{}", (Supplier<?>) context::toJson 6 ns
if (log.isDebugEnabled()) guard 2 ns

The parameterised form alone does not help when an argument is expensive; the supplier or a guard does.

2. Load test with the original worst case, large carts, debug level enabled on purpose:

Configuration Throughput p99
Original release (sync, eager) 1,140 req/s 98 ms
Lazy messages, sync appender 1,420 req/s 71 ms
Lazy messages, async loggers 1,860 req/s 47 ms
Summary line only, async, info level 1,930 req/s 44 ms

3. Production. After the fix, throughput returned to about 1,920 requests per second per instance, the extra instances scaled away, and log volume fell from 1.5 GB per minute to about 40 MB.

4. Security implications. context.toJson() included the customer's email and segment, so the debug lines had put personal data into log files at high volume, retained for 30 days. We purged those files and added a rule in code review and a log scrubber pattern for email addresses. Logging less is also logging less personal data.

Takeaways

  • A log line's cost is paid on every execution, including building its message when the level is off.
  • Use parameterised messages and suppliers (or level guards) for expensive arguments.
  • Use asynchronous logging so request threads never wait on log I/O, and decide what to drop when the buffer fills.
  • Keep per-iteration logging out of hot loops; use summaries or sampled traces instead, and watch log volume per request.

References: Log4j2 asynchronous loggers, Log4j2 API, lazy logging with Supplier, async-profiler, OWASP Logging Cheat Sheet.

Add a label

#performance #logging #observability #log4j2 #async-logging
Written by
Leila Farahani @leilafarahani

I lead a small team responsible for observability and quality tooling, and I spend a fair share of my time on application security reviews. That mix means I see many incidents twice: once when they happen and again when we ask why nothing warned us. The posts here come from that second look. An alert that never fired because the metric disappeared, sampling that dropped exactly the traces we needed, a catch-all that reported success for weeks, a secret recoverable from an image layer, tests that passed against mocks while production failed. Each one covers how the gap was found, what we changed in code or configuration, and how we verified the fix with a test or a drill. Security topics stay defensive and practical: controls you can add to your own code and a way to test each one.

Advertisement

Comments

0

No comments yet. Be the first to comment!

Sign In to post a comment.