Skip to main content
← PROBLEMS / ENGINEERING
An end-to-end domain learning journey

Non-Blocking Async &
Structured Logging.

Synchronous FileAppender with immediateFlush=true serializes all 200 Tomcat threads behind a single monitor lock and 10,800 unbatched write() syscalls/sec, collapsing throughput when EBS IOPS saturate.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If latency budgets leave no room for synchronous retries, use Log4j2 `AsyncLogger` (LMAX Disruptor ring buffer) with `immediateFlush=false`, `256 KB` buffered batching, and `Discard` overflow threshold for INFO/DEBUG so disk stalls never block HTTP workers.

TL;DR30-second simplified summary
▾

Core Mechanics: Enabling verbose JSON/DEBUG logging during an incident turns every HTTP request into multiple local disk writes.

Visual & Structural Flow: Depicts Tomcat Worker Serialization vs. Disruptor Ring Buffer (200 Tomcat Threads -> Disruptor Ring (65K) -> gp3 EBS (3,000 IOPS)); Lock-Free Ring Buffer to Fluent Bit Tailer (HTTP Workers -> Disruptor 65K -> 256KB Buffer -> app.log + FluentBit).

Trade-Offs & Production: Simply wrapping FileAppender in Logback's AsyncAppender still fails under EBS stalls: Default Blocking Queue: AsyncAppender defaults to neverBlock=false (and Log4j2. Use Log4j2 AsyncLogger (-Dlog4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector) writing to /var/log/app/app.log for Fluent Bit.

Failure Modes & Application: Decoupling request threads from local disk I/O is standard across high-throughput microservices and observability pipelines: Kubernetes DaemonSet Tailing: Services write structured ECS/JSON logs.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why synchronous file logging takes down web servers.

Why this matters: The mechanism: understand how Why synchronous file logging takes down web servers works from first principles.

Think of Why synchronous file logging takes down web servers as the intuition layer for Non-Blocking Async & Structured Logging: The mechanism: understand how Why synchronous file logging takes down web servers works from first principles.

Enabling verbose JSON/DEBUG logging during an incident turns every HTTP request into multiple local disk writes. On 4 co-located pods sharing a 3,000 IOPS gp3 EBS volume, 1,800 RPS/pod × 6 lines = 10,800 lines/sec (8.1 MB/s) per pod saturates the disk queue (depth 128, 45 ms per write), locking up all 200 Tomcat worker threads inside FileOutputStream.writeBytes.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Thread-pool serialization and IOPS saturation.

Why this matters: The problem: see what breaks without Thread-pool serialization and IOPS saturation under real concurrency or scale.

Synchronous FileAppender (immediateFlush=true) creates three compounding failures:

  1. Monitor Lock Contention: All 200 Tomcat threads serialize on one OutputStream.write() lock.
  2. Syscall & IOPS Amplification: 10,800 tiny unbatched 750 B flushes/sec exhaust the shared 3,000 IOPS EBS budget.
  3. Cascading 503s: Even /health and fast cached endpoints stall because no worker threads remain free.
Sync vs. Async Logging

Tomcat Worker Serialization vs. Disruptor Ring Buffer

200 Tomcat ThreadsDisruptor Ring(65K)gp3 EBS (3,000IOPS)1. Sync: 10,800 write()+flush/s ->45ms stall2. Async: CAS deposit in ~50ns(non-blocking)3. 1 bg thread: 256KB endOfBatch(~32 writes/s)4. Ring full: discard DEBUG/INFO,keep ERROR

Batching 10,800 events/sec into 256 KB sequential writes cuts EBS IOPS by >98% and frees HTTP workers.

Engineering Decision Framework
Problem
How to implement Non-Blocking Async & Structured Logging without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
If latency budgets leave no room for synchronous retries, use Log4j2 AsyncLogger (LMAX Disruptor ring buffer) with immediateFlush=false, 256 KB buffered batching, and Discard overflow threshold for INFO/DEBUG so disk stalls never block HTTP workers.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Non-Blocking Async & Structured Logging experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive async logging traps (blocking queues & gzip stalls).

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Simply wrapping FileAppender in Logback's AsyncAppender still fails under EBS stalls:

  • Default Blocking Queue: AsyncAppender defaults to neverBlock=false (and Log4j2 defaults to Wait), so once the queue fills, all 200 Tomcat threads block again.
  • Synchronous Gzip Rotation: Compressing a 1 GB rotated file on the appender thread stalls log draining for seconds; rotate at 100 MB uncompressed (max=5) and let Fluent Bit / logrotate compress off-thread.
Design Trade-Off

Naive async logging traps (blocking queues & gzip stalls)

Before · Seq Scan + Unbounded Bloat
  • Implicit cast breaks B-Tree
  • Deadlock or XID wraparound risk
  • Long tx blocks VACUUM
After · Indexed Plan + Bounded MVCC
  • Index-only scan in <2 ms
  • Deterministic lock ordering
  • Autovacuum keeps bloat flat
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: LMAX Disruptor Ring Buffer + Discard Backpressure.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Use Log4j2 AsyncLogger (-Dlog4j2.contextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector) writing to /var/log/app/app.log for Fluent Bit:

  • Bounded Ring Buffer: 65,536 (2^16) pre-allocated slots hold ~6 s of 10,800 events/sec bursts in ~48 MB (within the 64 MB budget) with zero GC allocation.
  • Batched Flushing: immediateFlush=false with bufferSize=262144 (256 KB) flushes only on endOfBatch, turning 10,800 syscalls/sec into ~32-150 sequential writes/sec (< 1 s durability lag).
  • Priority Shedding: AsyncQueueFullPolicy=Discard with discardThreshold=INFO drops verbose logs under disk stall while preserving ERROR/FATAL and enabling shutdownHook for clean SIGTERM drain.
Buffered Log Pipeline

Lock-Free Ring Buffer to Fluent Bit Tailer

HTTP Workers50ns CAS ring publishDisruptor 65K~48MB, Discard<=INFO256KB BufferFlush on endOfBatchapp.log + FluentBit100MB rotate, <150…batched sequential write

A single background consumer drains the 65K-slot Disruptor ring into 256 KB sequential writes.

<Configuration status="WARN" shutdownHook="enable">
  <Properties>
    <Property name="log4j2.asyncLoggerRingBufferSize">65536</Property>
    <Property name="log4j2.asyncQueueFullPolicy">Discard</Property>
    <Property name="log4j2.discardThreshold">INFO</Property>
  </Properties>
  <Appenders>
    <RollingRandomAccessFile name="AppFile" fileName="/var/log/app/app.log"
        filePattern="/var/log/app/app-%i.log" immediateFlush="false" bufferSize="262144">
      <JsonTemplateLayout eventTemplateUri="classpath:EcsLayout.json"/>
      <Policies><SizeBasedTriggeringPolicy size="100 MB"/></Policies>
      <DefaultRolloverStrategy max="5"/>
    </RollingRandomAccessFile>
  </Appenders>
  <Loggers>
    <Root level="INFO"><AppenderRef ref="AppFile"/></Root>
  </Loggers>
</Configuration>
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where non-blocking log pipelines are applied.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Decoupling request threads from local disk I/O is standard across high-throughput microservices and observability pipelines:

  • Kubernetes DaemonSet Tailing: Services write structured ECS/JSON logs to /var/log/app/ via RollingRandomAccessFile while Fluent Bit or Vector tails and zstd-compresses batches to Kafka/ClickHouse.
  • Low-Latency Trading & Payment APIs: Garbage-free Disruptor logging keeps p99 latency flat even during EBS/storage brownouts.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why must `AsyncQueueFullPolicy=Discard` (with `discardThreshold=INFO`) be paired with `immediateFlush=false` in Log4j2 when EBS IOPS saturate?

Recommended Learning Flow