DEV Community

Cover image for Redpanda Under the Hood: What Actually Happens When You Replace Kafka with C++, Thread-per-Core, and Direct I/O
Syed Anzar
Syed Anzar

Posted on

Redpanda Under the Hood: What Actually Happens When You Replace Kafka with C++, Thread-per-Core, and Direct I/O

If you run Apache Kafka at scale, you already know the operational tax. You spend hours tuning JVM garbage collection flags, wrestling with G1GC or ZGC pause times, and watching latency spikes whenever the OS page cache gets dirty. When a tail consumer pulls gigabytes of historical data, your real-time ingest pipeline stutters because Linux flushes dirty pages and locks memory buffers.

Redpanda took a different route. Instead of building on top of the Java Virtual Machine, its engineers rewrote the entire streaming architecture in C++ on top of the Seastar framework. It uses a thread-per-core model, bypasses the Linux page cache with Direct I/O (O_DIRECT), and maps Raft consensus groups directly to individual topic partitions.

The result is full wire compatibility with the Kafka client protocol without ZooKeeper, without the JVM, and without OS page cache contention.

Here is what actually happens beneath the surface when your client sends a batch of records to Redpanda.


1. The Bottleneck Redpanda Was Built to Solve

To understand why Redpanda behaves differently from Kafka, you have to look at how Kafka interacts with the host operating system.

Kafka relies on the operating system page cache for performance. When a producer sends a batch of records:

  1. The Kafka broker accepts the batch via Java NIO sockets.
  2. The broker writes the bytes to the partition log using standard filesystem write calls.
  3. The Linux kernel buffers these writes in kernel page cache (RAM). The write returns immediately to user space as "written," even though it has not hit physical storage yet.
  4. Consumers read data using the sendfile() system call, allowing the Linux kernel to transfer cached pages directly from the page cache to the network socket without copying bytes into JVM user space (zero-copy read).

This design was brilliant in 2011 when spinning hard disks dominated data centers. The Linux page cache smoothed out random I/O and aggregated sequential writes.

On modern NVMe SSDs capable of millions of IOPS and single-digit microsecond latencies, this design creates significant friction:

  • OS Page Cache Lock Contention: The Linux kernel manages page cache pages with global locks. Under heavy concurrent read/write pressure across dozens of partitions, kernel locks become a massive bottleneck.
  • Double Caching and Memory Pressure: When Kafka runs alongside other services or inside Kubernetes containers, the Linux kernel dynamically reclaims page cache memory. If another process demands RAM, cached Kafka pages are evicted, forcing subsequent consumer reads to pull from disk.
  • Stop-the-World GC Pauses: Even though Kafka keeps message payloads off the JVM heap, partition metadata, connection state, consumer offsets, and internal queues live on the heap. Under high connection counts, GC pauses can stall the broker for hundreds of milliseconds, spiking p99 and p999 tail latencies.

Redpanda eliminates all three problems by removing both the JVM and the OS page cache from the critical path.


2. The Seastar Engine: Thread-per-Core Architecture

At the center of Redpanda is the Seastar asynchronous C++ framework, originally developed for ScyllaDB.

Most multi-threaded servers use a thread pool. A pool of worker threads picks up tasks from a shared work queue. When multiple threads touch the same data structures (like a partition log or connection table), they synchronize access using mutexes, spinlocks, or atomic primitives.

Under high load on modern multicore CPUs (32, 64, or 128 cores), lock contention degrades performance. Worse, when two CPU cores read and write to the same cache line, the CPU hardware must invalidate cache lines across L1 and L2 caches using cache-coherency protocols (MESI). This cross-core bus traffic kills throughput.

Traditional Thread Pool:
[ Thread 1 ] \
[ Thread 2 ] -- [ Mutex / Lock ] --> [ Shared Partition State ] (L1/L2 Cache Invalidation)
[ Thread 3 ] /

Redpanda / Seastar Thread-per-Core:
[ Core 0 / Thread 0 ] -> [ Partition A State ] (Core-Local Memory, Zero Locks)
[ Core 1 / Thread 1 ] -> [ Partition B State ] (Core-Local Memory, Zero Locks)
[ Core 2 / Thread 2 ] -> [ Partition C State ] (Core-Local Memory, Zero Locks)
         \                                  /
          [ SPSC Queue (Structured Messaging) ]
Enter fullscreen mode Exit fullscreen mode

Pinning Threads to Hardware Cores

During bootstrap, Redpanda inspects the CPU hardware topology using libhwloc. It creates exactly one OS thread per CPU core and pins each thread permanently to that core (pthread_setaffinity_np). A thread pinned to Core 0 never migrates to Core 1.

Each core-pinned thread runs an independent Seastar reactor loop:

  • It handles network polling via epoll or io_uring.
  • It executes non-blocking compute fibers.
  • It submits asynchronous disk I/O requests.
  • It reaps completion events from the kernel.

Because each thread owns its execution domain entirely, Redpanda operates as a "shared-nothing" distributed system inside a single machine. There are no global mutexes protecting partition logs. Core 0 owns its assigned partitions and never locks against Core 1.

The 500-Microsecond Rule

In a cooperative, non-preemptive runtime like Seastar, if one fiber executes a heavy CPU calculation for 10 milliseconds, the reactor thread cannot poll the network socket or service incoming disk completions. That introduces tail latency spikes across every client on that core.

Redpanda enforces a strict architectural rule: no single instruction block or task may block the thread for more than 500 microseconds.

If a task takes longer (such as parsing a massive batch or scanning an index), it must explicitly yield execution back to the reactor poller using cooperative scheduling primitives (seastar::yield()). During development and CI, if any operation holds the reactor for longer than 500 microseconds, Seastar dumps a full stack trace warning.


3. Communication Across Cores: Structured Message Passing (SMP)

A client connection can terminate on any CPU core. A Java producer might establish a TCP connection handled by Core 0, but the partition leader it wants to write to is owned by Core 1.

How does Core 0 hand off the batch to Core 1 without a mutex?

Redpanda uses Structured Message Passing (SMP) via lock-free Single Producer Single Consumer (SPSC) ring buffers:

  1. Core 0 has a dedicated outgoing ring buffer pointing to Core 1.
  2. Core 1 has a dedicated incoming ring buffer coming from Core 0.
  3. Core 0 drops an execution pointer into the ring buffer and notifies Core 1.
  4. Core 1 polls its queue during its normal reactor loop and executes the task in its own local memory space.

Because memory on NUMA hardware is physically wired to specific CPU sockets, memory allocated on Core 0 must be released back to Core 0. Redpanda uses custom memory allocators that track allocation origin, ensuring that cross-core tasks return their memory tokens to the originating core without memory leaks or cross-socket bus thrashing.


4. Zero-Copy Memory Management: struct iobuf

In network and storage engines, memory fragmentation is a major risk. If you continuously allocate variable-size byte buffers (e.g., a 1KB message, followed by a 400KB batch, followed by an 8KB payload), the standard C library allocator (ptmalloc or glibc) quickly fragments heap memory. In long-running systems, this leads to memory exhaustion and stalls.

To solve this, Redpanda avoids monolithic byte arrays and uses a custom data structure called iobuf.

An iobuf is a fragmented, reference-counted chain of fixed-size buffer chunks:

struct fragment {
    void* data;
    size_t ref_count;
    size_t capacity;
    size_t size;
    fragment* next;
    fragment* prev;
};

struct iobuf {
    fragment* head;
};
Enter fullscreen mode Exit fullscreen mode

When a network packet arrives from a Kafka client:

  1. The kernel network stack places incoming TCP frames into network buffers.
  2. Redpanda allocates fixed-size memory fragments from pre-allocated memory pools (ranging from 512 bytes up to 128KB chunks).
  3. The payload is represented as a linked list of fragments.
  4. If Redpanda needs to route headers to the metadata cache and message bodies to disk, it creates lightweight slice views that increment the reference count of the underlying fragments. No bytes are copied.
  5. When the disk write completes, the reference count decrements. When it hits zero, the fragment returns directly to the core's local free pool.

This keeps memory allocation deterministic. The allocator never has to search for large contiguous memory blocks, eliminating memory compaction stalls.


5. Storage Engine: Bypassing the Page Cache with O_DIRECT

The biggest divergence between Redpanda and Apache Kafka lies in disk I/O.

Kafka issues buffered write() calls and allows the Linux kernel page cache to handle flushes to disk. Redpanda opens partition log segment files with the O_DIRECT flag.

Kafka I/O Path:
[ Client Batch ] -> [ User Space JVM ] -> [ Linux Kernel Page Cache (write) ]
                                                        |
                                          (Dirty Page Flush / Locks)
                                                        v
                                             [ Physical NVMe SSD ]

Redpanda I/O Path:
[ Client Batch ] -> [ User Space C++ / iobuf ] 
                           |
            (DMA: Direct Memory Access)
                           v
                 [ Physical NVMe SSD ]
Enter fullscreen mode Exit fullscreen mode

Why Bypassing Page Cache Matters

When an application uses standard buffered I/O, every read and write passes through kernel page cache buffers. For random file access on slow disks, this helps. For an append-only commit log on high-speed NVMe storage, it introduces severe problems:

  • Unpredictable Flushes: When the volume of "dirty" pages in Linux exceeds kernel thresholds (vm.dirty_background_ratio), the kernel wakes up flusher threads. The kernel may throttle user space processes while it drains pages to disk, causing random 100ms+ latency spikes.
  • Double Data Copies: Data is copied from application buffers to kernel page cache, and then from page cache to the disk controller.
  • No Control Over Caching Priority: The kernel decides which pages to evict based on generic LRU algorithms. It does not know whether a page belongs to a real-time tailing consumer or a batch query from yesterday.

How Direct I/O Works in Redpanda

With O_DIRECT, Redpanda instructs the Linux kernel to bypass the page cache entirely. Disk transfers occur directly between the application memory buffer and the storage device controller via Direct Memory Access (DMA).

To make O_DIRECT work without performance degradation, Redpanda satisfies strict hardware alignment rules:

  1. Memory Alignment: Buffers written to disk must be aligned to physical sector boundaries (typically 4096 bytes on modern 4Kn NVMe drives).
  2. Filesystem Layout Optimization: Redpanda aligns log segments with XFS filesystem allocation groups. It dispatches concurrent large buffer writes to disk using sparse filesystem preallocations, followed by controlled fdatasync() calls.
  3. Internal Application Cache: Because the OS page cache is bypassed, Redpanda implements its own user-space cache inside its pre-allocated RAM. Tailing consumers read directly from Redpanda's in-memory iobuf buffers. When older data must be read, Redpanda issues aligned DMA reads into memory.

Because Redpanda controls its own cache, hot partitions can dynamically claim buffer space while idle partitions yield memory. The kernel never interferes with I/O scheduling.


6. Partition-Level Raft Consensus

In Apache Kafka, replication is coordinated at the cluster level:

  • In legacy Kafka, ZooKeeper elected a single broker as the Controller.
  • In modern Kafka (KRaft mode), an internal Raft quorum manages cluster metadata, but actual partition data replication still uses the legacy In-Sync Replicas (ISR) mechanism.
  • In the ISR model, the partition leader tracks which follower replicas are caught up. If a follower lags, the leader removes it from the ISR list. If a leader fails, an election occurs based on ISR membership.

Redpanda takes a decentralized approach: Every individual topic partition is an independent, self-contained Raft consensus group.

Cluster Topology:
Topic: "orders" (3 Partitions, Replication Factor 3)

[ Partition 0 Raft Group ] -> Node A (Leader), Node B (Follower), Node C (Follower)
[ Partition 1 Raft Group ] -> Node B (Leader), Node C (Follower), Node A (Follower)
[ Partition 2 Raft Group ] -> Node C (Leader), Node A (Follower), Node B (Follower)
Enter fullscreen mode Exit fullscreen mode

Each Raft group maintains its own replicated state machine:

  • Zero External Coordination: When a broker fails, there is no centralized controller or metadata quorum needed to fail over partition leadership. Each partition Raft group independently detects missed heartbeats and elects a new leader in milliseconds.
  • Strict Consensus Guarantees: An entry is committed once a quorum (majority) of replicas write and acknowledge the data according to the client's acks configuration (acks=all waits for quorum disk persistence).
  • Embedded Membership Changes: Adding or removing partition replicas uses joint consensus directly within the partition's Raft log, preventing split-brain scenarios and data loss during cluster rebalancing.

7. Architectural Comparison: Kafka vs Redpanda

Architectural Layer Apache Kafka (KRaft) Redpanda
Language & Runtime Java / Scala on JVM C++20 on Seastar
Threading Model Thread pools + shared mutexes Thread-per-core (pinned to hardware CPU)
Disk I/O Strategy Buffered I/O via Linux Page Cache Direct I/O (O_DIRECT) + NVMe DMA
Data Replication Leader-follower ISR mechanism Independent Raft consensus per partition
Memory Allocation JVM Garbage Collector (G1 / ZGC) Seastar NUMA-aware pooled allocators (iobuf)
Zero-Copy Mechanism Kernel sendfile() via Page Cache Userspace buffer slices + DMA network bypass
External Dependencies KRaft metadata quorum nodes None (single self-contained static binary)
p99 Tail Latency Sensitive to GC pauses and page cache flushes Deterministic sub-millisecond execution

8. Practical Trade-offs: When to Pick Which

Redpanda is not magic. Moving to bare-metal C++ comes with engineering trade-offs that you should evaluate before migrating production infrastructure.

When Redpanda Shines

  1. Strict p99 / p999 Latency SLAs: If you are building financial transaction routing, fraud detection, ad-tech auctions, or gaming backends where a 200ms latency spike breaches your SLA, Redpanda's deterministic thread-per-core execution eliminates JVM jitter.
  2. Simplified Kubernetes and Cloud Operations: Deploying Kafka in containers often requires fine-tuning JVM heap sizes, kernel swap parameters, and page cache limits. Redpanda runs as a single lightweight binary that allocates a fixed slice of host RAM and pins to available cores.
  3. High Resource Density: Because Redpanda does not waste RAM on JVM object overhead or duplicate OS page cache buffers, a single Redpanda node can push 1 GB/sec of write throughput per core when paired with modern NVMe storage.

Where Kafka Still Has the Advantage

  1. Massive Ecosystem of Connectors and Extensions: Apache Kafka has over a decade of community-built plugins, specialized tiering storage adapters, and custom security integrations. While Redpanda supports the Kafka client protocol and Kafka Connect, complex third-party JVM-specific broker plugins do not run natively on Redpanda.
  2. Large Shared Host Multitenancy: The thread-per-core model expects dedicated CPU cores and predictable memory allocations. If you run dozens of lightweight services on a shared, oversubscribed virtual machine with fluctuating vCPU allocations, Seastar's CPU-pinning model can struggle with CPU starvation.
  3. Hardware Sizing Constraints: Redpanda recommends at least 2GB of RAM per core and a 2:1 core-to-NVMe-disk ratio for high-throughput production clusters. Running Redpanda on slow spinning disks or networked storage with high random-seek latency removes its primary architectural advantage.

Summary

The difference between Kafka and Redpanda is not a syntax preference or a framework debate. It is a fundamental shift in how distributed systems interface with computer hardware.

Kafka was designed around 2011 hardware constraints: spinning disks, relatively small core counts, and the convenience of the Java runtime. Redpanda was designed for 2026 hardware: superscalar CPUs with dozens of cores, terabytes of fast memory, and NVMe drives capable of saturating gigabytes per second over PCI Express.

By pinning threads to cores, using structured message passing, avoiding cross-core locking, and writing directly to NVMe storage through O_DIRECT, Redpanda shows what happens when a streaming engine treats the modern Linux kernel and hardware as first-class citizens.


Primary References & Architecture Documentation

Top comments (0)