Recipe

Zero-copy I/O primer

Moving bytes without copying them is the difference between a hot path that scales and one that buckles at the first thousand RPS. This recipe walks through the three primitives Meridian uses to keep large payloads off the CPU and out of userland buffers, so your gateway can saturate a 10 GbE link without melting a core.

1.Map, do not read

The classic read(2)syscall pulls bytes from the page cache into a userland buffer, doubling memory pressure. Replace it with mmap(2) and you get a pointer straight into the cache. The kernel handles paging, you handle pointers.

2.Splice between descriptors

When you need to shuttle data from a file to a socket, splice(2)and sendfile(2) move pages through a kernel pipe without ever crossing the userland boundary. Meridian uses this for large artifact streaming and signed-URL proxying.

3.io_uring for batched submissions

For high-fanout workloads, submit reads and writes in batches viaio_uring. A single shared ring buffer between kernel and userland eliminates per-op syscall overhead and lets the scheduler coalesce work. Pair it with registered buffers for true zero-copy submission.

example.c
int src = open(path, O_RDONLY);
struct stat st;
fstat(src, &st);

// map the file into our address space
void *buf = mmap(NULL, st.st_size,
                 PROT_READ, MAP_PRIVATE,
                 src, 0);

// splice straight to the socket
ssize_t sent = sendfile(client_fd,
                        src, NULL,
                        st.st_size);

munmap(buf, st.st_size);
close(src);