🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10
Deep DiveSystems Engineering14 min read

High-Concurrency Backend Patterns: Zero-Copy Networking and Memory Management

C
ChatWhole AI Team|2026-09-23

High-Concurrency Backend Patterns: Zero-Copy Networking and Memory Management

High-concurrency backend patterns cut tail latency by pairing zero-copy networking primitives (sendfile, splice, MSG_ZEROCOPY, io_uring) with memory reuse strategies such as buffer pooling and arena allocation instead of per-request heap churn. Add SO_REUSEPORT, lock-free queues, and backpressure, and p99 latency stays flat while connection counts climb past 100,000.

Advertisement

Zero-Copy Networking Primitives for High-Concurrency Backends

What zero-copy actually means

Zero-copy networking means the kernel moves payload bytes between a socket and a file or another socket without first copying them into a userspace buffer. The application still pays for control messages, but the expensive per-megabyte copy disappears. On a 25 GbE link, a single unassisted copy path can burn more than one full core just shuffling bytes.

The four primitives most teams reach for first:

  1. sendfile — streams a file descriptor straight to a socket; classic for static assets and TLS termination offload.
  2. splice — pipes bytes between two sockets or a pipe and a socket with zero payload copies; ideal for proxies.
  3. MSG_ZEROCOPY — pins userspace pages and lets the NIC DMA from them; completion arrives via a notification queue, so batch it.
  4. io_uring with registered buffers — submission queues remove per-call syscall overhead, and fixed buffers remove repeated pin/unpin work.

epoll and kqueue are readiness notifiers, not copy-avoidance tools: they tell you when a socket is writable, then you still copy. Treat them as the control plane, not the data plane.

Syscall and primitive comparison

PrimitiveWhat it avoidsCopy count per directionBest fitAvailable since
read / writenothingone full copygeneric low-QPS socketsalways
sendfileuserspace payload copyzero on Linux with suitable NICsfile-to-socket streamingLinux 2.2
spliceuserspace payload copyzeroproxies, load balancers, teeLinux 2.6.17
MSG_ZEROCOPY sendtransmit-side payload copyzero (page pins instead)bulk sends above roughly 1 MBLinux 4.14
io_uring fixed bufferssyscall overhead plus repeated map workoften zero with registered buffers50k+ operations per secondLinux 5.1
epoll / kqueuebusy polling onlystill one copy after readinessclassic event loopsLinux 2.6 / BSD

Rule of thumb: messages below a few kilobytes rarely justify MSG_ZEROCOPY because notification and pinning overhead exceed the saved copy. Above 8-16 MB per connection, zero-copy paths routinely remove 20-40 percent of CPU time in proxy workloads.

Key Takeaways

💡

  • Zero-copy networking eliminates payload copies with sendfile, splice, MSG_ZEROCOPY, and io_uring registered buffers, not with epoll alone.
  • Buffer pooling typically removes 30-60 percent of allocator pressure at sustained load above 50k requests per second.
  • Go GC pauses above 1 millisecond under memory churn are the usual cause of p99 spikes; arenas and sync.Pool shrink both.
  • MSG_ZEROCOPY pays off above roughly 1 MB transfers; below that, pinning overhead loses.
  • Bounded queues with backpressure keep p99 flat; unbounded queues convert latency spikes into out-of-memory crashes.
  • Pick the pattern by message size, core count, and object lifetime — not by novelty.

Buffer Pooling vs Allocation Churn

Every request that allocates a fresh buffer churns the allocator, dirties cache lines, and — in GC languages — creates garbage the collector must later scan. At 100k requests per second with 64 KB read buffers, naive allocation generates 6.4 GB per second of garbage. Buffer pooling returns the same memory to a free list after each request.

Rust with a fixed-size pool:

use bytes::BytesMut;
use std::collections::VecDeque;

pub struct BufferPool {
    free: VecDeque<BytesMut>,
    buf_size: usize,
    max_idle: usize,
}

impl BufferPool {
    pub fn new(capacity: usize, buf_size: usize) -> Self {
        let mut free = VecDeque::with_capacity(capacity);
        for _ in 0..capacity {
            free.push_back(BytesMut::with_capacity(buf_size));
        }
        Self { free, buf_size, max_idle: capacity }
    }

    pub fn acquire(&mut self) -> BytesMut {
        self.free
            .pop_front()
            .unwrap_or_else(|| BytesMut::with_capacity(self.buf_size))
    }

    pub fn release(&mut self, mut buf: BytesMut) {
        buf.clear();
        if self.free.len() < self.max_idle {
            self.free.push_back(buf);
        }
    }
}

// Naive alternative: one fresh heap allocation per read
async fn read_naive(stream: &mut tokio::net::TcpStream) -> std::io::Result<Vec<u8>> {
    let mut buf = vec![0u8; 64 * 1024];
    let n = stream.read(&mut buf).await?;
    buf.truncate(n);
    Ok(buf)
}

The same pattern in Go with sync.Pool:

var bufPool = sync.Pool{
    New: func() any {
        return make([]byte, 32*1024)
    },
}

func handleConn(conn net.Conn) {
    buf := bufPool.Get().([]byte)
    defer func() {
        // clear length so reused capacity starts empty
        bufPool.Put(buf[:0])
    }()

    n, err := conn.Read(buf)
    if err != nil {
        return
    }
    process(buf[:n])
    _ = n
}

Two practical constraints decide whether pooling wins:

  • Size variance — pools shine when frame sizes cluster (network packets, fixed records). Payloads that swing from 200 bytes to 8 MB defeat fixed-size pools; use size-class pools instead.
  • Escape lifetime — a pooled buffer handed to a background task that outlives the request corrupts reuse. Keep pooled memory request-scoped, or promote escaped buffers to owned Bytes with refcounting.

For service-boundary payload schemas that interact with these buffers, see declarative data contracts for microservices.

GC Pause Impact vs Arena Allocation

Go's garbage collector is concurrent and typically targets sub-millisecond pauses, but allocation churn raises heap scan work. A proxy allocating 6 GB per second frequently shows 2-5 ms GC assist stalls on the allocating goroutines, which surface directly as p99 latency cliffs. Three mitigations, in ascending effort:

  1. sync.Pool / buffer reuse — cheapest, removes most short-lived garbage.
  2. Arena-style regions — allocate every object for one request from a bump-allocated slab, then free the slab in one call; Rust's bumpalo and C++'s std::pmr monotonic_resource do this natively.
  3. Manual lifetime design — Rust ownership and arenas make the compiler enforce reuse; C++ custom allocators do it by convention.

Arenas are a poor fit for long-lived objects (connection state, caches) and a perfect fit for per-request parse trees, response frames, and query plans. Teams running memory-heavy inference on prem see the same allocator math in model serving — see SLM quantization and on-premise benchmarking for the memory-footprint side of that tradeoff.

Object Pooling and Lock-Free Queues

Object pooling extends buffer reuse to whole structs: connection wrappers, parser state, message envelopes. The win appears when constructor cost is non-trivial (TLS session setup, decompression contexts) or when construction alone costs 100-500 ns.

Lock-free queues connect producer and consumer cores without mutex handoffs:

  • SPSC ring buffers — one producer, one consumer, power-of-two capacity; the workhorse for pipeline stages inside a single process.
  • MPMC bounded queues — needed when multiple workers share a work queue; consider crossbeam or LMAX-style rings before raw compare-and-swap loops.
  • Mutex + condvar — genuinely fine below roughly 10k operations per second; contention rarely appears on profiles.

Hand-rolled lock-free code is where correctness bugs hide: ABA problems, forgotten memory ordering, and lost wakeups. Prefer a battle-tested library ring and spend complexity budget on backpressure instead.

SO_REUSEPORT and Multi-Core Accept Scaling

A single accept() loop pins connection acceptance to one core. SO_REUSEPORT lets every worker thread bind the same ip:port and run its own accept loop; the kernel distributes new connections across sockets, often with reuseport locality selection that favors the least-loaded CPU.

Deployment notes:

  • Requires Linux 3.9 or newer; verify kernel support before relying on it in container images.
  • Each worker needs its own listen socket — do not share one fd across threads and expect scaling.
  • Combine with busy-poll avoidance: leave the default scheduler, or dedicate cores explicitly with cpusets.

Combined with io_uring, accept scaling removes the two classic event-loop ceilings: one core for accepts, one for syscalls.

Backpressure and Latency Under Load

Latency under load is almost always queueing latency. Little's Law bounds the math: average latency equals queue depth divided by throughput, so an unbounded inbound queue doubles latency every time depth doubles, regardless of how fast workers are.

Illustrative numbers from a 64-byte echo benchmark on an 8-vCPU Linux box:

Concurrent connectionsNaive alloc p99Pooled buffers p99Observed Go GC stallQueue behavior
2,0001.2 ms0.9 msunder 1 msdrain immediately
20,0003.4 ms1.5 ms1-2 msbrief bursts
100,00018 ms2.8 ms4-6 msnaive path saturates
100,000 with backpressure6.1 ms2.5 ms2-3 msbounded, shed above 90 percent

Backpressure mechanics that work in practice:

  1. Bound every queue between pipeline stages with an explicit capacity.
  2. Signal saturation upstream — TCP flow control, HTTP 429, or credit-based tokens for internal RPC.
  3. Shed or sample before queues overflow; dropping cheap work beats stalling critical work.
  4. Track queue depth as a first-class metric alongside p99, because depth rises seconds before latency does.

Wasted CPU from unbounded queues shows up on the cloud bill — the cost angle is covered in cloud FinOps and GPU compute cost drains.

Pattern Selection: Which Technique When

PatternWhen to useSkip it when
Buffer pool (BytesMut, sync.Pool)fixed or bimodal frame sizes, above 10k RPSpayload sizes vary across three orders of magnitude
Size-class poolsmixed small and large messagesworkload is uniform — one pool suffices
Arena / bump allocationmany short-lived objects sharing one request lifetimeobjects escape the request
Object poolingexpensive constructors such as TLS or compression stateconstruction costs under 50 ns
SPSC lock-free ringsingle-producer single-consumer stagelow throughput — a mutex is simpler
SO_REUSEPORTmulti-core accept scaling on Linuxolder kernels or single-threaded servers
MSG_ZEROCOPYbulk sends above roughly 1 MBsmall messages where notifications dominate
splice / sendfileproxies and static file servingpayload must be inspected in userspace
io_uring fixed bufferssyscall-bound paths above 50k ops per secondsimple low-throughput services
Bounded queue plus backpressureany stage that can grow without limitpure offline batch jobs with slack

Production Rollout Checklist

Roll the patterns out incrementally so regressions stay attributable:

  1. Baseline p50, p99, GC pause histograms, and context-switch rates under realistic load.
  2. Add buffer pooling to the hottest read path; measure allocator pressure before and after.
  3. Move GC-heavy services to arenas or pooled objects for per-request state only.
  4. Enable SO_REUSEPORT across worker threads and confirm per-core accept distribution.
  5. Bound every inter-stage queue and wire saturation signals to admission control.
  6. Adopt splice, sendfile, or MSG_ZEROCOPY only for paths above 1 MB or file streaming.
  7. Switch syscall-heavy loops to io_uring with registered buffers once profiling shows syscall time above 15 percent.
  8. Re-run load tests at 2x peak and confirm p99 stays inside the agreed error budget.
Sponsored

Common Mistakes in High-Concurrency Paths

Common Mistakes

Enabling MSG_ZEROCOPY on every send because zero-copy sounds strictly faster

Fix: Gate it on payload size above roughly 1 MB: page pinning and completion notifications lose to a plain send on small messages.

Handing a pooled buffer to a background task that outlives the request

Fix: Keep pooled memory request-scoped, or promote escaped buffers to a refcounted type — reuse after free corrupts the next request that acquires the slot.

Scaling workers while every queue between stages stays unbounded

Fix: Bound each queue and propagate saturation upstream with flow control or 429s, because Little's Law makes queue depth, not worker count, the latency driver.

Frequently Asked Questions

What is zero-copy networking?

Zero-copy networking is a set of kernel mechanisms that move payload bytes between sockets, files, and devices without copying them through userspace buffers. Linux provides it through sendfile, splice, MSG_ZEROCOPY, and io_uring registered buffers. It reduces CPU cost per byte but does not eliminate control-plane syscalls.

When does buffer pooling outperform normal allocation?

Buffer pooling outperforms normal allocation when message sizes are consistent, request rates exceed roughly 10k per second, and buffers never outlive their request. Under those conditions teams commonly report 30-60 percent less allocator and GC pressure. Skip pooling when payload sizes vary enormously or buffers escape into background tasks.

How does GC pause affect high-concurrency backends in Go?

GC pause affects high-concurrency backends by adding assist time exactly when allocation rate spikes, which is usually under peak load. Go's collector is concurrent, but heavy churn still produces multi-millisecond stalls that appear as p99 outliers. Reusing buffers with sync.Pool and arena-style region allocation are the standard fixes.

What is backpressure in a backend system?

Backpressure is the explicit propagation of overload from a saturated stage to its producers, keeping queues bounded and latency stable. Common mechanisms include bounded channels, TCP flow control, HTTP 429 responses, and credit-based internal RPC. Without it, queues grow until latency degrades or the process runs out of memory.

Is MSG_ZEROCOPY always faster than a normal send?

No. MSG_ZEROCOPY pins user pages and incurs notification overhead, so it typically loses to ordinary sends for small messages and wins above roughly 1 MB per write. For file streaming, sendfile or splice usually beats both. Measure with your own message-size distribution before committing.


Last updated: September 23, 2026

Explore More Articles

Search across 3100+ tutorials and news articles.