A 100 GbE service can exhaust memory bandwidth long before it runs out of application logic. The culprit is often not packet processing alone. It is copying large response buffers from user space into kernel socket memory, then touching those cache lines again as TCP segments are assembled. Zero copy sockets Linux support addresses that specific path, but it is not a universal throughput switch. It exchanges CPU copies for buffer-lifetime management, pinned-page pressure, and completion handling.

For services that stream large immutable objects, replication logs, media segments, model artifacts, or database snapshots, that exchange can be excellent. For APIs returning 2 KB JSON documents, it can be a self-inflicted reliability problem.

What Linux zero-copy socket paths actually remove

A traditional `send()` copies bytes from the application buffer into kernel-owned socket buffers. The kernel can then retain, segment, queue, retransmit, and eventually hand those bytes to the NIC independently of the process. This ownership transfer is convenient, but the initial copy consumes CPU cycles and memory bandwidth proportional to payload size.

Linux has several mechanisms that get called zero-copy, although they solve different parts of this problem. `sendfile()` moves file-backed data to a socket without first copying it through a user-space buffer. `splice()` can connect file descriptors through kernel pipes while avoiding a userspace round trip. `MSG_ZEROCOPY`, enabled through `SO_ZEROCOPY`, allows an application to submit user-space pages for socket transmission without copying payload bytes into kernel socket memory.

The last mechanism is what most engineers mean by zero-copy sockets. The kernel references the application’s pages while it constructs TCP packets and while the NIC performs DMA. The application cannot reuse or mutate those buffers until Linux reports that transmission ownership has ended.

That distinction matters. Zero-copy does not mean no data movement. Bytes still travel across the memory bus to the NIC, and receive-side processing still places incoming data into memory. It means Linux avoids one CPU-mediated copy between two memory regions.

The production cost is buffer ownership

`MSG_ZEROCOPY` turns what was previously an immediate buffer-release operation into an asynchronous lifecycle. After a successful `sendmsg()` call, the return value only says that the kernel accepted the request. It does not say the application can recycle the backing memory.

Completion notifications arrive through the socket error queue and are read with `recvmsg()` using `MSG_ERRQUEUE`. Linux reports ranges of completed zero-copy send IDs, allowing callers to release the associated buffers. A completion can also indicate that Linux copied a send rather than using the zero-copy path. Applications must treat both outcomes as a completed ownership transition.

This requirement is where many implementations fail. They enable `SO_ZEROCOPY`, observe lower CPU in a benchmark, and never drain the error queue under real traffic. Notifications accumulate, memory associated with in-flight sends cannot be reclaimed correctly, and the process eventually applies backpressure to itself or leaks its send-buffer bookkeeping.

The correct design has a distinct ownership model. A buffer should move through states such as application-owned, submitted, awaiting completion, and reusable. Do not attach that state to a raw pointer alone. Use an allocation ID or reference-counted buffer object because one page may participate in multiple sends, and completion notifications can cover a range rather than a single request.

TCP retransmission extends this lifetime. A packet that is delayed, lost, or held behind congestion control keeps its source pages relevant for longer. Under a clean local benchmark, completion latency may be tiny. Under WAN loss, a congested peer, or a stalled client, the outstanding buffer set can become large enough to dominate memory use.

The break-even point depends on payload size and concurrency

Zero-copy has fixed costs: pinning or referencing pages, building scatter-gather state, tracking send IDs, delivering completions, and adding cache pressure to the application’s allocation metadata. Small writes rarely amortize those costs.

There is no portable payload threshold because the answer depends on CPU generation, NIC driver behavior, MTU, kernel version, TLS use, allocator behavior, and traffic shape. Still, the practical pattern is consistent: large writes with high aggregate throughput are promising; small request-response messages are usually not.

A service emitting 64 KB to multi-megabyte chunks from a bounded object cache may benefit materially. A fan-out gateway serving millions of 1-8 KB responses per second is more likely to gain from batching writes, reducing serialization work, tuning TLS record sizing, and minimizing syscalls. `sendmmsg()`, `writev()`, TCP segmentation offload, and careful event-loop batching often produce a better risk-adjusted result.

The most dangerous workload is mixed traffic. If a connection alternates small control frames with large bulk payloads, selectively apply zero-copy only above a measured threshold. Preserve the ordinary copy path for small writes. This is not a fallback born of caution. It is usually the performance-optimal architecture.

File transmission should start with sendfile, not MSG_ZEROCOPY

If the source is a file, `sendfile()` is often the cleaner first choice. It avoids materializing file contents in a user-space buffer and uses kernel page cache references directly. For static assets, artifact distribution, and large immutable blobs, it reduces both copying and application memory management.

`splice()` is useful when the data already exists on a file descriptor boundary, such as a proxy pipeline or a kernel-mediated stream transformation. Its constraints are more operationally awkward, especially around pipes, error handling, and observability, but it can be the right primitive for specialized data paths.

`MSG_ZEROCOPY` is most compelling when the bytes originate in user space: generated replication records, encoded media, cache-resident objects, or application-owned buffers that would otherwise be copied into the socket layer. Treat the mechanisms as separate tools rather than interchangeable knobs.

io_uring changes the completion plumbing, not the trade-off

For systems already built around `io_uring`, `IORING_OP_SEND_ZC` can make zero-copy sends fit naturally into the submission and completion model. The key detail is that the normal completion queue entry may report submission progress before the buffer is safe to reclaim. A later notification completion, marked with `IORING_CQE_F_NOTIF`, closes the buffer-lifetime loop.

That is easy to miss when adapting an existing `send()` abstraction. If the application returns a pooled buffer after the first CQE, it can corrupt data still visible to the NIC or TCP stack. The ring makes notification delivery more uniform than per-socket error-queue polling, but it does not remove the need for explicit ownership states.

SQPOLL can further reduce submission overhead in the right deployment, yet it adds a polling thread and its own CPU-placement considerations. Do not combine every modern I/O feature because the benchmark looks impressive. First establish whether socket-copy CPU is a material fraction of end-to-end request cost.

TLS, memory pressure, and observability complicate the win

User-space TLS can erase much of the expected benefit because encryption still reads plaintext and writes ciphertext buffers. Kernel TLS can alter the path again, but the outcome depends on cipher support, NIC offloads, record framing, and the kernel version in production. Measure encrypted traffic, not an unencrypted synthetic benchmark, if customer traffic uses HTTPS.

Pinned or long-lived pages also change memory behavior. They can reduce allocator flexibility, increase working-set pressure, and worsen tail latency when an application allows too much outstanding zero-copy data. Set a per-connection and process-wide cap on bytes awaiting completion. When either cap is reached, apply backpressure or revert new writes to the copied path.

Instrument the system around decisions rather than only aggregate throughput. Track zero-copy attempts, copy fallbacks, completion delay percentiles, bytes awaiting completion, error-queue or notification drain rate, retransmissions, and connection-level stalls. Correlate those metrics with CPU cycles per byte and p99 response latency. A throughput gain that lengthens tail latency or increases memory headroom requirements may be a bad trade for a latency-sensitive service.

A deployment pattern that survives real traffic

Start with a single bulk endpoint and a conservative size threshold. Keep buffers immutable after submission, record every zero-copy send in a bounded ownership table, and drain completions in the same event-loop cadence as writable socket events. Add byte caps before enabling the feature broadly, then test with packet loss, slow readers, connection churn, and memory pressure.

Benchmark with realistic TLS, payload distributions, and network conditions. Then compare the outcome against simpler alternatives: larger application write batches, `sendfile()` for file-backed responses, response compression placement, or moving serialization off the critical core. Zero-copy earns its complexity only when it removes a measured bottleneck without creating a harder one.

The useful question is not whether a Linux socket can avoid copies. It is whether your service can afford to hold its output buffers until the network, not the application, decides they are done.

Fediverse reactions

Leave a Reply