← Concepts

阅读中文版本

Zero-Copy I/O

Zero-copy I/O moves data kernel-to-socket or file-to-socket without copying into user space, using sendfile, splice, or mmap, cutting CPU and memory bandwidth per byte served.

runtime

Definition

Zero-copy techniques eliminate redundant data copies and context switches on the I/O path. Classic read-then-write copies kernel buffer to user buffer and back; sendfile and splice keep data in kernel space, transferring between descriptors directly. mmap shares pages between kernel and user space with copy-on-write semantics.

Context and scope

Used by web servers serving static files, Kafka transporting log segments, storage proxies, and CDNs. TLS interplays with kernel zero-copy via kTLS.

Common misconceptions

  • Zero-copy removes all copies — it removes the user-space round trip; checksum and crypto stages still touch data
  • It speeds up every transfer — gains appear on large sequential sends; small chatty transfers pay setup costs
  • TLS forbids zero-copy — kernel TLS offload re-enables it after the handshake, keeping sendfile usable on encrypted flows

Anti-patterns

  • Streaming uploads through user-space buffers in chunked loops where splice would do
  • Enabling sendfile on dynamic small responses and paying per-call overhead
  • Assuming zero-copy with compression pipelines compose without measuring copies reintroduced by the compressor

Related concepts

Authoritative source

https://man7.org/linux/man-pages/man2/sendfile.2.html

What it is

Serving a file traditionally copies it twice through user space: kernel page cache to user buffer, user buffer back to socket buffer. Zero-copy delegates the transfer to the kernel — descriptors in, bytes moved — removing both copies and two context switches from every send.

How it works

sendfile copies between an input file descriptor and an output socket inside the kernel. splice moves data through a pipe joining two descriptors. mmap maps file pages into the address space, letting the application read them without an explicit copy. kTLS installs keys in the kernel so encryption applies to kernel-resident data.

When to use it

Static asset serving, log replication, and bulk transfer at high throughput. Measure with strace and perf counters: the copy count per byte is visible as CPU sys time dropping.

Pitfalls

Dynamic content negates the path unless cached as files. User-space TLS historically forced a copy back for encryption — kTLS addresses it, but key lifecycle and cipher support vary. Memory-mapped files require page-fault awareness under first-touch latency.