Linux Internals

Zero-Copy Networking in Linux: sendfile, splice, MSG_ZEROCOPY and io_uring

By NileVPS Team · Published · 5 min read

اقرأ المقال بالعربي

Serving a file over the network looks trivial: read it, then write it to a socket. Underneath, a naive implementation copies the same bytes several times, between the page cache, a user-space buffer, and the socket buffers, and switches between user and kernel mode on every call. At high throughput those copies cost real CPU time and memory bandwidth. Linux offers several "zero-copy" mechanisms that remove some or all of them. This article explains what each one does, where it helps, and how to use the most common one, nginx sendfile, on a VPS.

Where the copies come from

Consider the classic loop:

while ((n = read(fd, buf, sizeof buf)) > 0)
    write(sock, buf, n);

For each chunk, the kernel copies data from the page cache into buf in user space (copy one), then copies it from buf into the socket's kernel buffers (copy two). The NIC then reads those socket buffers by DMA (see our article on DMA). Two system calls per chunk mean two mode switches, and the CPU touches every byte twice even though the application never looked at the content.

"Zero-copy" usually means removing the copies done by the CPU. DMA transfers between memory and devices still happen; they are the efficient part.

sendfile: file to socket inside the kernel

sendfile(out_fd, in_fd, &offset, count) tells the kernel to send data from a file directly to a socket. The data never enters user space. On NICs that support scatter-gather and checksum offload, which virtually all modern ones do, including virtio-net, the kernel can hand references to page-cache pages to the network stack, and the NIC reads them by DMA. The CPU copy disappears entirely in that case.

sendfile is ideal for static content: images, downloads, video segments, and any file served as-is. Its limitation is also clear: the application cannot modify the data on the way out. Anything that transforms the payload, such as compression or user-space TLS encryption, forces the data back through user space.

splice and tee: moving data through pipes

splice() moves data between a file descriptor and a pipe without copying it to user space. Internally, a pipe is a ring of page references, so splicing from a socket into a pipe and from the pipe to a file (or another socket) can move pages rather than bytes. tee() duplicates pipe contents without consuming them, and vmsplice() maps user pages into a pipe.

These calls are useful for proxies and relays that forward data between two connections, or for receiving data from a socket and writing it to disk. They are more flexible than sendfile but more complex to use correctly, and the zero-copy benefit depends on the source and destination types.

MSG_ZEROCOPY: zero-copy for user-space buffers

Sometimes the data is generated by the application, not read from a file. MSG_ZEROCOPY, added for TCP in Linux 4.14, lets send() transmit directly from user memory:

int one = 1;
setsockopt(sock, SOL_SOCKET, SO_ZEROCOPY, &one, sizeof one);
send(sock, buf, len, MSG_ZEROCOPY);

The kernel pins the user pages and lets the NIC DMA from them. The catch is that the application must not reuse or free buf until the kernel says it is done. Completion notifications arrive on the socket's error queue and must be read with recvmsg(..., MSG_ERRQUEUE). Pinning pages and processing notifications has its own cost, so the kernel documentation notes that MSG_ZEROCOPY is generally effective only for larger writes, roughly above 10 KB; for small messages a normal copy is cheaper.

On the receive side, Linux also has TCP_ZEROCOPY_RECEIVE, which maps received pages into user memory using mmap, but it has strict alignment requirements and is mostly used in specialized, high-volume systems.

io_uring: asynchronous I/O with zero-copy send

io_uring is an asynchronous I/O interface built on shared submission and completion rings between user space and the kernel. Applications queue many operations and collect results without one system call per operation, which already reduces overhead significantly.

For networking, io_uring supports regular send and receive, splice, and since Linux 6.0 a zero-copy send operation (IORING_OP_SEND_ZC). It follows the same principle as MSG_ZEROCOPY, where the buffer must stay untouched until a notification arrives, but integrates the notification into the completion ring. Registered buffers can reduce the cost of pinning memory on every request. io_uring is powerful but young compared to the other APIs, and some environments restrict it for security reasons, so check that your kernel and container runtime allow it before relying on it.

Practical: nginx sendfile on a VPS

For most VPS owners, zero-copy networking means one line in nginx. A sensible block in http {}:

sendfile        on;
tcp_nopush      on;
tcp_nodelay     on;
sendfile_max_chunk 2m;
  • sendfile on serves static files through the kernel's sendfile.
  • tcp_nopush on (TCP_CORK on Linux) sends the response headers and the start of the file in full packets.
  • sendfile_max_chunk stops one large download from monopolizing a worker.

Keep these points in mind:

  1. TLS: with ordinary HTTPS, OpenSSL encrypts in user space, so nginx must read the file and sendfile does not apply. Kernel TLS (kTLS) changes that: with nginx 1.21.4 or newer built against OpenSSL 3.0 or newer, and the tls kernel module loaded, ssl_conf_command Options KTLS; lets the kernel encrypt and sendfile work again for supported ciphers.
  2. Compression: responses compressed on the fly with gzip on cannot use sendfile. Pre-compressed files with gzip_static on can.
  3. Network filesystems and some overlay setups: if files live on unusual storage and you see corrupted or stale downloads, test with sendfile off to rule it out.

To confirm what nginx is doing, trace a worker briefly:

sudo strace -f -e trace=sendfile,read,write,writev -p $(pgrep -f 'nginx: worker' | head -1)

If you are setting up a new web server, our deployment guide covers getting a VPS online first.

FAQ

Does zero-copy mean no data is copied at all?

No. It means the CPU avoids copying payload bytes between kernel and user buffers. The device still moves data to and from memory using DMA, and headers and metadata are still built by the CPU.

Should I always use MSG_ZEROCOPY instead of send?

No. It adds page pinning and completion handling, which costs more than a plain copy for small messages. It pays off mostly for large, frequent transmissions, and you should measure before and after enabling it.

Is sendfile useful if my site is HTTPS only?

Only with kernel TLS. Without kTLS, encryption happens in user space and nginx falls back to reading files normally. With kTLS enabled and a supported cipher, sendfile benefits return for static files.

Related guides