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.
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.
- DMA Read: Disk controller copies blocks into the Kernel Page Cache.
- CPU Copy 1: Kernel copies bytes from Page Cache into the User-Space Buffer, incurring a context switch back to user mode.
- CPU Copy 2: User process calls
write(), switching to kernel mode and copying bytes into the Kernel Socket Buffer (sk_buff). - DMA Write: NIC reads from
sk_buffonto the wire.
Traditional POSIX read() + write() Data Path
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
- 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 bywrite(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.
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?
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 onread(), yet still triggers minor/major page faults on first access, TLB shootdowns onmunmap(), andSIGBUSif 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, andio_uringwhen you need async random I/O or buffer transformation.
splice(), mmap(), and Page-Fault Traps
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>Bounded sendfile() Loop with Partial-Write & EAGAIN Handling
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:
- Linux Kernel TLS (
kTLS): User space performs the TLS handshake, then passes the negotiated symmetric session keys to the kernel viasetsockopt(SOL_TLS, TLS_TX, ...). Subsequentsendfile()calls encrypt directly inside the kernel (or offload encryption to a SmartNIC). - Internal Plaintext Backbone: Keep
sendfile()on trusted VPC/mTLS-offloaded sidecar paths while terminating public TLS at an edge proxy.
Why User-Space TLS Breaks Zero-Copy (and How kTLS Restores It)
- No backpressure on spikes
- Implicit shared state
- Cascading tail latency
- Explicit capacity budgets
- Isolated failure domains
- Predictable p99 latency
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 withposix_fadvise(POSIX_FADV_WILLNEED)orio_uringasyncIORING_OP_READ. - Cold-Tail Eviction: Sequential cold reads can evict hot tail segments from the page cache; use
O_DIRECTorPOSIX_FADV_DONTNEEDfor cold backfill scans. - io_uring Kernel Attack Surface: Unprivileged
io_uringhas historically exposed kernel use-after-free CVEs; many container platforms disableio_uringby default via seccomp unless explicitly allowlisted for trusted data-plane pods.
Practice: Make the trade-off yourself.
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?