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

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.
Start the journey7 sections· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When an application calls `read(fd, buf, len)` followed by `write(sock, buf, len)`, the Linux kernel performs two D, traditional read()+write() pays 4 buffer copies and 4 context switches per chunk; sendfile() eliminates user-space copies, and io_uring eliminates per-I/O syscall overhead.

TL;DR30-second simplified summary
▾

Standard POSIX read() + write() incurs 4 context switches and 4 buffer copies (2 DMA, 2 CPU). sendfile() reduces this to 2 context switches and 0 CPU copies by attaching page-cache descriptors directly to sk_buff for NIC scatter-gather DMA.

When you must transform bytes in user space or run hundreds of thousands of random async I/O operations per second, io_uring replaces per-operation syscalls with lock-free mmap() Submission (SQ) and Completion (CQ) ring buffers, cutting syscall overhead dramatically.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
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.
API Gateway & Layer 7 Protocols
An API gateway terminates external Layer 7 traffic (HTTP/1.1, HTTP/2, gRPC, WebSockets) at the edge, centralizing TLS termination, rate limiting, auth verification, and protocol translation before routing to internal services.
Full walkthrough · 7 stages
01
STAGE 01 · THE BOTTLENECKfoundation

Why Traditional read() + write() Saturates CPU and Memory Bandwidth.

Why this matters: Trace the four buffer copies and four context switches incurred by standard POSIX read()+write() file serving.

When an application calls read(fd, buf, len) followed by write(sock, buf, len), the Linux kernel performs two DMA transfers and two CPU-driven memcpy() passes across the user/kernel boundary.

  1. DMA Read: Disk controller copies blocks into the Kernel Page Cache.
  2. CPU Copy 1: Kernel copies bytes from Page Cache into the User-Space Buffer, incurring a context switch back to user mode.
  3. CPU Copy 2: User process calls write(), switching to kernel mode and copying bytes into the Kernel Socket Buffer (sk_buff).
  4. DMA Write: NIC reads from sk_buff onto the wire.

Traditional POSIX read() + write() Data Path

NVMe DiskPage CacheUser BufferSocket Buffer
02
STAGE 02 · KERNEL BYPASSfoundation

sendfile() and DMA Scatter-Gather Mechanics.

Why this matters: Understand how sendfile() eliminates user-space buffer copies using page descriptors and hardware scatter-gather.

Introduced in Linux 2.1 and refined with scatter-gather DMA (NETIF_F_SG), sendfile(out_fd, in_fd, &offset, count) instructs the kernel to transfer bytes directly from a file descriptor to a socket without returning to user space.

Instead of copying payload bytes into sk_buff, the kernel attaches page descriptors (memory address, offset, and length) pointing directly to the Kernel Page Cache frames. The NIC's DMA engine reads those non-contiguous pages directly from RAM.

Zero-Copy sendfile() with Scatter-Gather DMA

NVMe DiskPage Cachesk_buff DescriptorsNIC Scatter-Gather
Engineering Decision Framework
Problem
How to implement Zero-Copy I/O, sendfile & io_uring 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
When an application calls read(fd, buf, len) followed by write(sock, buf, len), the Linux kernel performs two D, traditional read()+write() pays 4 buffer copies and 4 context switches per chunk; sendfile() eliminates user-space copies, and io_uring eliminates per-I/O syscall overhead.
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 Zero-Copy I/O, sendfile & io_uring experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · ALTERNATIVESintermediate

splice(), mmap(), and Page-Fault Traps.

Why this matters: Compare sendfile(), splice(), and mmap() so you avoid hidden page-fault stalls and SIGBUS crashes.

Engineers often consider mmap() a universal zero-copy silver bullet, but mmap() introduces subtle hazards on large or concurrent workloads:

  • mmap() + write(): Avoids the user-space copy on read(), yet still triggers minor/major page faults on first access, TLB shootdowns on munmap(), and SIGBUS if the underlying file is truncated concurrently.
  • splice(fd_in, ..., fd_out, ...): Moves page references between any two file descriptors via an internal kernel pipe buffer, enabling zero-copy proxying between two sockets (socket -> pipe -> socket).
  • Rule of thumb: Use sendfile() for file-to-socket streaming, splice() for socket-to-socket proxies, and io_uring when you need async random I/O or buffer transformation.
Request & State Flow

splice(), mmap(), and Page-Fault Traps

CallerService EntryCore ProcessorState Store1. Submit bounded request2. Apply domain invariant3. Persist or read state4. Return verified response
04
STAGE 04 · ASYNC RINGSintermediate

io_uring Shared Submission & Completion Ring Buffers.

Why this matters: Learn how io_uring eliminates per-operation syscall overhead using lock-free single-producer/single-consumer ring buffers.

Even with zero-copy data movement, issuing millions of small epoll_wait(), recv(), and pread() syscalls per second burns significant CPU—especially after Spectre/Meltdown syscall mitigations.

io_uring solves this by sharing two lock-free ring buffers between user space and the kernel via mmap():

io_uring Shared Memory Ring Architecture

Event LoopSQ Ring (SQEs)CQ Ring (CQEs)Kernel / SQPOLLWrite SQEs (no syscall)Batch submit / pollPost CQEsReap completions
05
STAGE 05 · PRODUCTION CODEintermediate

Bounded sendfile() Loop with Partial-Write & EAGAIN Handling.

Why this matters: Implement a production-safe non-blocking sendfile() loop with explicit EAGAIN backoff, EINTR retry, and bounded fallback.

On non-blocking sockets, sendfile() can return fewer bytes than requested (partial write) or fail with EAGAIN/EINTR. Never assume a single call transfers the entire file; track the offset explicitly, retry on EINTR, yield to epoll/io_uring on EAGAIN, and bound retries on transient errors.

#include <errno.h>
#include <sys/sendfile.h>
#include <unistd.h>
Component Topology

Bounded sendfile() Loop with Partial-Write & EAGAIN Handling

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
06
STAGE 06 · REAL-WORLD GOTCHASadvanced

Why User-Space TLS Breaks Zero-Copy (and How kTLS Restores It).

Why this matters: Understand why OpenSSL user-space encryption forces copies back, and how Linux kTLS restores sendfile().

If your server terminates TLS in user space (standard OpenSSL SSL_write()), the application must read plaintext into user memory to encrypt it—completely defeating sendfile().

Two production workarounds exist:

  1. Linux Kernel TLS (kTLS): User space performs the TLS handshake, then passes the negotiated symmetric session keys to the kernel via setsockopt(SOL_TLS, TLS_TX, ...). Subsequent sendfile() calls encrypt directly inside the kernel (or offload encryption to a SmartNIC).
  2. Internal Plaintext Backbone: Keep sendfile() on trusted VPC/mTLS-offloaded sidecar paths while terminating public TLS at an edge proxy.
Design Trade-Off

Why User-Space TLS Breaks Zero-Copy (and How kTLS Restores It)

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
07
STAGE 07 · FAILURE MODESadvanced

Page Cache Thrashing, Head-of-Line Blocking & io_uring Security.

Why this matters: Identify production failure modes when deploying zero-copy I/O and io_uring at scale.

Zero-copy I/O shifts bottlenecks from CPU memcpy() to kernel memory and syscall boundaries:

  • Page Cache Miss Stalls: sendfile() blocks the calling thread on disk I/O if the target file segment was evicted from the page cache. High-throughput brokers mitigate this with posix_fadvise(POSIX_FADV_WILLNEED) or io_uring async IORING_OP_READ.
  • Cold-Tail Eviction: Sequential cold reads can evict hot tail segments from the page cache; use O_DIRECT or POSIX_FADV_DONTNEED for cold backfill scans.
  • io_uring Kernel Attack Surface: Unprivileged io_uring has historically exposed kernel use-after-free CVEs; many container platforms disable io_uring by default via seccomp unless explicitly allowlisted for trusted data-plane pods.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

A Kafka broker serves 20 Gbps of plain-text consumer traffic from hot log segments in RAM, and CPU profiling shows 65% of time spent in `copy_user_enhanced_fast_string`. Which change addresses this directly?

Recommended Learning Flow