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

Design a High-Throughput Distributed Log
Ingestion & Tail Pipeline.

Combine producer micro-batching, token-bucket backpressure, sequential page-cache appends, and zero-copy sendfile() consumer tailers with offset checkpointing and object-storage cold tiering.
Start the journey7 stages· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep the architecture evolvable without sacrificing reliability, sequential append-only commit logs + kernel page-cache residency + zero-copy `sendfile()` let commodity NVMe brokers sustain multi-GB/s ingest and fan-out without user-space buffer bloat.

TL;DR30-second simplified summary
▾

To sustain 5 GB/s ingest and 15 GB/s fan-out, producers batch and zstd-compress records by partition key behind per-tenant token-bucket admission control.

Brokers append to 1 GB segmented commit logs indexed by sparse mmap() .index files. Hot consumers tail via zero-copy sendfile() from the kernel page cache, while closed segments tier to S3 and failed records route after bounded retries to a DLQ.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Zero-Copy I/O, sendfile & io_uring
Zero-copy I/O keeps file bytes inside the Linux kernel page cache and streams them straight to a network socket via DMA scatter-gather, while io_uring batches asynchronous syscalls over shared memory ring buffers.
Backpressure & Flow Control
Backpressure lets a slow consumer signal an upstream producer to slow down or pause, preventing unbounded memory growth and out-of-memory crashes.
Dead Letter Queues
A secondary quarantine queue that captures messages a consumer repeatedly fails to process after a bounded number of retries, preventing poison pills from blocking healthy traffic.
Full walkthrough · 7 stages
01
STAGE 01 · REQUIREMENTS & MATHfoundation

Throughput, Fan-Out, and Back-of-the-Envelope Sizing.

Why this matters: Quantify sustained ingest, burst headroom, replication bandwidth, and disk/NIC limits before choosing storage primitives.

  • Ingest: 5M events/s × 1 KB avg = 5 GB/s sustained (15 GB/s burst, 3× headroom).
  • Replication (RF=3): Leader receives 5 GB/s and replicates 2× to followers = 10 GB/s inter-broker traffic. - Consumer Fan-Out (3×): 15 GB/s outbound read bandwidth.
Component Topology

Throughput, Fan-Out, and Back-of-the-Envelope Sizing

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
02
STAGE 02 · INGEST & BACKPRESSUREfoundation

Producer Micro-Batching & Token-Bucket Admission Control.

Why this matters: Absorb traffic spikes gracefully using client batching, zstd compression, and per-tenant token-bucket shedding.

Instead of sending 5M individual RPCs/sec, producer SDKs group records per partition (batch.size = 64 KB, linger.ms = 10) and compress batches with zstd (typically 3–4× reduction, cutting wire ingress from 5 GB/s to ~1.5 GB/s).

At the Ingest Gateway, each tenant has a token-bucket rate limiter backed by per-partition queue-depth signals:

  • If broker page-cache dirty ratio or replication lag exceeds threshold, the gateway returns 429 Too Many Requests with Retry-After.
  • Producers apply bounded exponential backoff with full jitter and spill locally to a bounded ring buffer before dropping/sampling low-priority debug logs.
Lifecycle & Failure Recovery

Producer Micro-Batching & Token-Bucket Admission Control

admitsucceedbudget exceededInitializedProcessingInvariant MetDegraded Fallback
Engineering Decision Framework
Problem
How to implement Design a High-Throughput Distributed Log Ingestion & Tail Pipeline 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
To keep the architecture evolvable without sacrificing reliability, sequential append-only commit logs + kernel page-cache residency + zero-copy sendfile() let commodity NVMe brokers sustain multi-GB/s ingest and fan-out without user-space buffer bloat.
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 Design a High-Throughput Distributed Log Ingestion & Tail Pipeline experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · STORAGE ENGINEintermediate

Segmented Append-Only Commit Log & Sparse Offset Index.

Why this matters: Design the on-disk segment layout and sparse index so writes stay sequential and offset seeks complete in O(1) memory + 1 disk hop.

Each topic is sharded into PP partitions; each partition is an ordered sequence of immutable 1 GB .log segments plus one active tail segment:

  • .log file: Raw length-prefixed record batches appended sequentially.
  • .index file: Sparse memory-mapped index mapping every ~4 KB of log bytes (offset -> physical_byte_position). Finding any offset requires a binary search in RAM followed by a single sequential read.
  • Durability: Synchronous quorum ack (acks=all, min-ISR=2) relies on multi-AZ replica memory + periodic OS page-cache flush, avoiding per-batch fsync() stalls unless strict financial durability is required.

Partitioned Commit Log Segment Append & Sparse Index

Compressed BatchActive SegmentSparse .indexClosed 1 GBSegments
04
STAGE 04 · ZERO-COPY READ PATHintermediate

Zero-Copy sendfile() Consumer Tailing & Page-Cache Isolation.

Why this matters: Serve 15 GB/s of real-time consumer fan-out directly from the kernel page cache without user-space copies or GC stalls.

Because real-time consumers tail within seconds of the producer head, the active .log segment is already hot in the Linux Kernel Page Cache.

  • Brokers serve consumer Fetch(partition, offset, max_bytes) requests via sendfile(), streaming bytes straight from the page cache to the consumer TCP socket via NIC scatter-gather DMA.
  • Zero user-space allocation: The broker JVM/Go/Rust process never allocates heap buffers for fetched payloads, eliminating GC pauses under 15 GB/s fan-out.
  • Cold-tail protection: Backfill consumers reading hours-old data are tagged to bypass or POSIX_FADV_DONTNEED pages—or routed to S3-backed tier readers—so they never evict the hot tail.
Request & State Flow

Zero-Copy sendfile() Consumer Tailing & Page-Cache Isolation

CallerService EntryCore ProcessorState Store1. Submit bounded request2. Apply domain invariant3. Persist or read state4. Return verified response
05
STAGE 05 · SAFE CONSUMER CODEintermediate

Idempotent Batch Processing with Bounded Retry, Backoff & DLQ.

Why this matters: Implement a consumer worker that commits offsets only after durable sink writes, with bounded exponential backoff and DLQ routing.

At-least-once tailing requires committing offsets only after the downstream sink succeeds (never auto-commit before processing). Poison-pill records must be bounded and diverted to a DLQ rather than blocking the partition forever.

import time, random
06
STAGE 06 · TIERED STORAGEadvanced

Immutable Segment Tiering to Object Storage (S3).

Why this matters: Decouple compute/NVMe retention from multi-month compliance retention using asynchronous S3 segment uploads.

Keeping 30–90 days of 5 GB/s logs on replicated NVMe drives would require petabytes of expensive local SSDs. Instead:

  1. Once a 1 GB segment rolls over and is immutable, an async uploader streams (segment.log, segment.index) to Object Storage (S3) and records the remote manifest in metadata storage.
  2. Local NVMe retains only the last 4–24 hours of hot segments.
  3. Rebalances and broker replacements become fast because brokers only re-replicate the hot tail, while historical replays fetch byte ranges directly from S3.
07
STAGE 07 · FAILURE MODESadvanced

Hot Partitions, Slow Consumers, and ISR Shrinking.

Why this matters: Anticipate and mitigate partition skew, follower lag, and consumer group rebalance storms.

  • Hot Partition Skew: If a single tenant_id generates 40% of traffic, hash partitioning pins one broker.

Mitigate with salted keys (tenant_id#rand(0..k)) for stateless logs or adaptive shard splitting. - Follower Lag & ISR Shrink: A degraded disk on one replica slows acks=all writes. Enforce replica.lag.time.max.ms to drop slow followers from the ISR cleanly while alerting on reduced redundancy.

Design Trade-Off

Hot Partitions, Slow Consumers, and ISR Shrinking

Before · Unbounded Coupling
  • No backpressure on spikes
  • Implicit shared state
  • Cascading tail latency
After · Bounded & Observable
  • Explicit capacity budgets
  • Isolated failure domains
  • Predictable p99 latency
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

A backfill job starts reading 12-hour-old log segments from disk, and real-time consumer p99 tail latency immediately jumps from 15 ms to 450 ms. What is the most likely root cause?

Recommended Learning Flow