How We Handle 10M WebSocket Connections on a Single Server
We threw out the thread-per-connection model, pinned cores to NUMA nodes, and bypassed the kernel network stack. Here’s why your intuition about distributed systems might be backwards.
Most engineers, when you tell them you need to handle millions of concurrent connections, immediately reach for Kubernetes. Scale horizontally, they say. Add more nodes. I did too. I spent six months architecting a beautiful distributed system before I realized I was solving the wrong problem entirely.
We were rebuilding a real-time notification system that served mobile apps. Every connected user held a WebSocket open, waiting for updates. At peak, we’d hit 10 million concurrent connections — though honestly, most were idle at any given moment, maybe averaging 2–3 messages per second per connection. Our first architecture used Go services behind a load balancer, distributing connections across 50 nodes. It worked. It also cost $47,000 per month and had a 99.5% uptime — not bad, but every restart meant reconnection storms, and every deployment was a minor disaster where we’d watch Slack alerts pile up while services drained.
Then I read about how WhatsApp reported being able to push over 2 million TCP connections per tuned FreeBSD/Erlang server back in 2012, which showed that vertical scaling could go far further than most of us assumed. I thought: what if the problem isn’t scaling out, but scaling up? What if one properly tuned machine could handle what we’d been splitting across fifty?
Ah, but here’s where I got stuck for weeks. I kept trying to optimize our existing Go code. More goroutines, better scheduling, fancy connection pooling tricks I’d read about in blog posts. The profiler kept showing me syscall overhead and context switching costs. I thought the language was the bottleneck — maybe Go’s scheduler couldn’t handle this many concurrent operations, maybe the garbage collector was killing us. None of that was true.
The Moment Everything Changed
The breakthrough came when I stopped looking at the Go profiler and started looking at perf. The kernel was spending 60% of its time in network stack processing—specifically, interrupt handling and context switches between user space and kernel space. Every incoming packet triggered an interrupt, woke up a handler, copied data across the kernel boundary, and woke up a user-space thread.
For ten million connections receiving occasional messages, that’s billions of unnecessary trips across the privilege boundary every day. Each one tiny, but they add up like compound interest working against you.
I thought I needed better application code. What I actually needed was to bypass the kernel’s TCP/IP stack entirely.
DPDK Prerequisites: The Unglamorous Foundation
Before we get to the sexy architecture stuff, here’s what actually made this work — the operational setup that took us three weeks to get right:
Hugepages: DPDK needs 2MB or 1GB hugepages to reduce TLB misses. We allocated 10,240 2MB pages:
/sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
echo 10240 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages
echo 10240 > /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages
CPU Isolation: Reserve cores 2–95 for DPDK (leave 0–1 for kernel):
# Add to GRUB: isolcpus=2-95 nohz_full=2-95 rcu_nocbs=2-95
# Then: systemctl set-property --runtime user.slice AllowedCPUs=0-1
# Add to GRUB: isolcpus=2-95 nohz_full=2-95 rcu_nocbs=2-95
# Then: systemctl set-property --runtime user.slice AllowedCPUs=0-1
NIC Configuration: RSS to 96 queues, symmetric hashing:
ethtool -L eth0 combined 96
ethtool -X eth0 hfunc toeplitz equal 96
ethtool -L eth0 combined 96
ethtool -X eth0 hfunc toeplitz equal 96
VFIO Binding: Unbind NIC from kernel driver, bind to VFIO for user-space access:
dpdk-devbind.py --bind=vfio-pci 0000:3b:00.0
dpdk-devbind.py --bind=vfio-pci 0000:3b:00.0
This isn’t optional. Without it, DPDK won’t even initialize. I learned this the hard way after two days of “why isn’t rte_eal_init working” debugging.
Rust + DPDK: When You Take the Hardware Into Your Own Hands
DPDK (Data Plane Development Kit) lets you map network card buffers directly into user space using poll-mode drivers. No interrupts. No syscalls on the hot path. Your application polls the NIC directly and processes packets in tight loops. It’s what high-frequency trading firms and network appliance vendors have been using for years, but it felt like dark magic to someone who’d spent their career writing web services.
Rust made this approachable. Memory safety without garbage collection pauses. Zero-cost abstractions. Fearless concurrency without the constant fear of use-after-free bugs that would’ve haunted me in C.
Here’s the core event loop that processes incoming WebSocket frames:
<button data-code="use dpdk_sys::{rte_eth_rx_burst, rte_pktmbuf_free, rte_mbuf};
use crossbeam::channel::Sender;
fn process_socket_frames(
port_id: u16,
queue_id: u16,
connections: &mut HashMap,
senders: &[Sender]
) {
// Buffer to hold pointers to received packet mbufs
let mut bufs: [*mut rte_mbuf; 256] = [std::ptr::null_mut(); 256];
loop {
// Poll NIC RX queue for packets (never blocks)
let nb_rx = unsafe {
rte_eth_rx_burst(port_id, queue_id, bufs.as_mut_ptr(), 256)
} as usize;
for i in 0..nb_rx {
let mbuf = unsafe { &mut *bufs[i] };
// Extract connection ID from packet header
if let Some(conn_id) = parse_conn_id_from_mbuf(mbuf) {
// Hash to worker core that owns this connection
let core_id = conn_id % senders.len();
// Send to that core's channel (lock-free)
let _ = senders[core_id].try_send(Message::from_mbuf(mbuf));
}
// Free the mbuf back to mempool (critical!)
unsafe { rte_pktmbuf_free(bufs[i]); }
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use dpdk_sys::{rte_eth_rx_burst, rte_pktmbuf_free, rte_mbuf};
use crossbeam::channel::Sender;
fn process_socket_frames(
port_id: u16,
queue_id: u16,
connections: &mut HashMap<u32, Connection>,
senders: &[Sender<Message>]
) {
// Buffer to hold pointers to received packet mbufs
let mut bufs: [*mut rte_mbuf; 256] = [std::ptr::null_mut(); 256];
loop {
// Poll NIC RX queue for packets (never blocks)
let nb_rx = unsafe {
rte_eth_rx_burst(port_id, queue_id, bufs.as_mut_ptr(), 256)
} as usize;
for i in 0..nb_rx {
let mbuf = unsafe { &mut *bufs[i] };
// Extract connection ID from packet header
if let Some(conn_id) = parse_conn_id_from_mbuf(mbuf) {
// Hash to worker core that owns this connection
let core_id = conn_id % senders.len();
// Send to that core's channel (lock-free)
let _ = senders[core_id].try_send(Message::from_mbuf(mbuf));
}
// Free the mbuf back to mempool (critical!)
unsafe { rte_pktmbuf_free(bufs[i]); }
}
}
}
use dpdk_sys::{rte_eth_rx_burst, rte_pktmbuf_free, rte_mbuf};
use crossbeam::channel::Sender;
fn process_socket_frames(
port_id: u16,
queue_id: u16,
connections: &mut HashMap<u32, Connection>,
senders: &[Sender<Message>]
) {
// Buffer to hold pointers to received packet mbufs
let mut bufs: [*mut rte_mbuf; 256] = [std::ptr::null_mut(); 256];
loop {
// Poll NIC RX queue for packets (never blocks)
let nb_rx = unsafe {
rte_eth_rx_burst(port_id, queue_id, bufs.as_mut_ptr(), 256)
} as usize;
for i in 0..nb_rx {
let mbuf = unsafe { &mut *bufs[i] };
// Extract connection ID from packet header
if let Some(conn_id) = parse_conn_id_from_mbuf(mbuf) {
// Hash to worker core that owns this connection
let core_id = conn_id % senders.len();
// Send to that core's channel (lock-free)
let _ = senders[core_id].try_send(Message::from_mbuf(mbuf));
}
// Free the mbuf back to mempool (critical!)
unsafe { rte_pktmbuf_free(bufs[i]); }
}
}
}
This is the actual pattern we use, though simplified — real code handles backpressure when channels are full, tracks stats, and has error paths for malformed packets. The key is that rte_eth_rx_burst is just reading from mapped NIC memory; there’s no kernel involvement after setup.
Oh, and that WebSocket parsing? We had to implement RFC 6455 from scratch:
Result {
let data = unsafe {
std::slice::from_raw_parts(mbuf.buf_addr as *const u8, mbuf.data_len as usize)
};
// First byte: FIN (bit 7) + opcode (bits 0-3)
let fin = data[0] & 0x80 != 0;
let opcode = data[0] & 0x0F;
// Second byte: MASK (bit 7) + payload len (bits 0-6)
let masked = data[1] & 0x80 != 0;
let mut payload_len = (data[1] & 0x7F) as usize;
let mut offset = 2;
// Extended payload length (16 or 64 bits)
if payload_len == 126 {
payload_len = u16::from_be_bytes([data[2], data[3]]) as usize;
offset = 4;
} else if payload_len == 127 {
// 64-bit length for huge frames
payload_len = u64::from_be_bytes(data[2..10].try_into()?) as usize;
offset = 10;
}
// Client-to-server frames MUST be masked
let masking_key = if masked {
let key = [data[offset], data[offset+1], data[offset+2], data[offset+3]];
offset += 4;
Some(key)
} else { None };
// Unmask payload if needed
let mut payload = data[offset..offset+payload_len].to_vec();
if let Some(key) = masking_key {
for (i, byte) in payload.iter_mut().enumerate() {
*byte ^= key[i % 4]; // XOR unmask
}
}
// Return parsed frame based on opcode
match opcode {
0x01 => Ok(Frame::Text(payload)),
0x02 => Ok(Frame::Binary(payload)),
0x08 => Ok(Frame::Close),
0x09 => Ok(Frame::Ping),
0x0A => Ok(Frame::Pong),
_ => Err(WsError::InvalidOpcode)
}
}
// See full implementation: github.com/yourusername/dpdk-websocket” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn parse_websocket_frame(mbuf: &mut rte_mbuf) -> Result<Frame, WsError> {
let data = unsafe {
std::slice::from_raw_parts(mbuf.buf_addr as *const u8, mbuf.data_len as usize)
};
// First byte: FIN (bit 7) + opcode (bits 0-3)
let fin = data[0] & 0x80 != 0;
let opcode = data[0] & 0x0F;
// Second byte: MASK (bit 7) + payload len (bits 0-6)
let masked = data[1] & 0x80 != 0;
let mut payload_len = (data[1] & 0x7F) as usize;
let mut offset = 2;
// Extended payload length (16 or 64 bits)
if payload_len == 126 {
payload_len = u16::from_be_bytes([data[2], data[3]]) as usize;
offset = 4;
} else if payload_len == 127 {
// 64-bit length for huge frames
payload_len = u64::from_be_bytes(data[2..10].try_into()?) as usize;
offset = 10;
}
// Client-to-server frames MUST be masked
let masking_key = if masked {
let key = [data[offset], data[offset+1], data[offset+2], data[offset+3]];
offset += 4;
Some(key)
} else { None };
// Unmask payload if needed
let mut payload = data[offset..offset+payload_len].to_vec();
if let Some(key) = masking_key {
for (i, byte) in payload.iter_mut().enumerate() {
*byte ^= key[i % 4]; // XOR unmask
}
}
// Return parsed frame based on opcode
match opcode {
0x01 => Ok(Frame::Text(payload)),
0x02 => Ok(Frame::Binary(payload)),
0x08 => Ok(Frame::Close),
0x09 => Ok(Frame::Ping),
0x0A => Ok(Frame::Pong),
_ => Err(WsError::InvalidOpcode)
}
}
// See full implementation: github.com/yourusername/dpdk-websocket
fn parse_websocket_frame(mbuf: &mut rte_mbuf) -> Result<Frame, WsError> {
let data = unsafe {
std::slice::from_raw_parts(mbuf.buf_addr as *const u8, mbuf.data_len as usize)
};
// First byte: FIN (bit 7) + opcode (bits 0-3)
let fin = data[0] & 0x80 != 0;
let opcode = data[0] & 0x0F;
// Second byte: MASK (bit 7) + payload len (bits 0-6)
let masked = data[1] & 0x80 != 0;
let mut payload_len = (data[1] & 0x7F) as usize;
let mut offset = 2;
// Extended payload length (16 or 64 bits)
if payload_len == 126 {
payload_len = u16::from_be_bytes([data[2], data[3]]) as usize;
offset = 4;
} else if payload_len == 127 {
// 64-bit length for huge frames
payload_len = u64::from_be_bytes(data[2..10].try_into()?) as usize;
offset = 10;
}
// Client-to-server frames MUST be masked
let masking_key = if masked {
let key = [data[offset], data[offset+1], data[offset+2], data[offset+3]];
offset += 4;
Some(key)
} else { None };
// Unmask payload if needed
let mut payload = data[offset..offset+payload_len].to_vec();
if let Some(key) = masking_key {
for (i, byte) in payload.iter_mut().enumerate() {
*byte ^= key[i % 4]; // XOR unmask
}
}
// Return parsed frame based on opcode
match opcode {
0x01 => Ok(Frame::Text(payload)),
0x02 => Ok(Frame::Binary(payload)),
0x08 => Ok(Frame::Close),
0x09 => Ok(Frame::Ping),
0x0A => Ok(Frame::Pong),
_ => Err(WsError::InvalidOpcode)
}
}
// See full implementation: github.com/yourusername/dpdk-websocket
This parsing logic runs on every received packet. About 500 lines total when you add proper error handling, fragmented frame reassembly, and handshake logic. It took us two months to get right, mostly debugging edge cases with half-open connections and client implementations that slightly violated the spec.
The key insight that took me way too long to internalize: we process packets in batches and distribute work based on connection ID hashing. Every connection is consistently routed to the same core, which means we can eliminate basically all cross-core synchronization in the hot path.
Wait, but there’s a deeper thing happening here that wasn’t obvious to me at first. By controlling the entire packet flow from hardware to application logic, we could design data structures that matched the hardware’s actual behavior instead of fighting against kernel abstractions.
NUMA Awareness: The Performance Win I Didn’t See Coming
Our server had two Intel Xeon processors — 96 vCPUs total (48 cores with hyperthreading), 384GB RAM, dual 100Gb NICs, split across two NUMA nodes. NUMA (Non-Uniform Memory Access) means memory attached to one CPU socket is faster for cores on that socket. Access memory on the other socket? Remote NUMA memory access can cost roughly 30–50% more latency than local access on modern systems, which adds up under high load.
Initially, I ignored this. Computer science classes taught me to think of RAM as uniform. I let the kernel schedule threads wherever it wanted. Performance was… okay. We hit about 6 million connections before things got weird — high CPU usage but low throughput, lots of cache misses in perf.
Then I pinned worker threads to specific NUMA nodes and allocated their connection state from local memory:
<button data-code="use nix::sched::{CpuSet, sched_setaffinity};
use nix::unistd::Pid;
use std::alloc::{alloc, Layout};
fn spawn_worker(core_id: usize, numa_node: usize) {
std::thread::spawn(move || {
// Pin this thread to specific core using Linux affinity
let mut cpuset = CpuSet::new();
cpuset.set(core_id).unwrap();
sched_setaffinity(Pid::from_raw(0), &cpuset).unwrap();
// Bind to NUMA node for memory allocations
unsafe {
libc::numa_set_preferred(numa_node as i32);
}
// Allocate connection map from LOCAL NUMA memory
// (500k connections * ~200 bytes each = ~100MB per core)
let mut connections: HashMap =
HashMap::with_capacity(500_000);
loop {
// All memory touched here stays on THIS NUMA node
handle_messages(&mut connections);
}
});
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use nix::sched::{CpuSet, sched_setaffinity};
use nix::unistd::Pid;
use std::alloc::{alloc, Layout};
fn spawn_worker(core_id: usize, numa_node: usize) {
std::thread::spawn(move || {
// Pin this thread to specific core using Linux affinity
let mut cpuset = CpuSet::new();
cpuset.set(core_id).unwrap();
sched_setaffinity(Pid::from_raw(0), &cpuset).unwrap();
// Bind to NUMA node for memory allocations
unsafe {
libc::numa_set_preferred(numa_node as i32);
}
// Allocate connection map from LOCAL NUMA memory
// (500k connections * ~200 bytes each = ~100MB per core)
let mut connections: HashMap<u32, Connection> =
HashMap::with_capacity(500_000);
loop {
// All memory touched here stays on THIS NUMA node
handle_messages(&mut connections);
}
});
}
use nix::sched::{CpuSet, sched_setaffinity};
use nix::unistd::Pid;
use std::alloc::{alloc, Layout};
fn spawn_worker(core_id: usize, numa_node: usize) {
std::thread::spawn(move || {
// Pin this thread to specific core using Linux affinity
let mut cpuset = CpuSet::new();
cpuset.set(core_id).unwrap();
sched_setaffinity(Pid::from_raw(0), &cpuset).unwrap();
// Bind to NUMA node for memory allocations
unsafe {
libc::numa_set_preferred(numa_node as i32);
}
// Allocate connection map from LOCAL NUMA memory
// (500k connections * ~200 bytes each = ~100MB per core)
let mut connections: HashMap<u32, Connection> =
HashMap::with_capacity(500_000);
loop {
// All memory touched here stays on THIS NUMA node
handle_messages(&mut connections);
}
});
}
Throughput jumped 35% overnight. Just by being mindful about which memory we touched from which core. The CPU wasn’t working harder — it was working smarter, spending less time waiting for remote memory.
Oh, and here’s where it gets even better. Modern NICs support RSS (Receive Side Scaling) — you can configure the hardware to hash incoming packets into multiple RX queues. We pinned each queue to a specific core on the matching NUMA node so packets usually stayed local to the right CPU and memory.
Combined with NUMA pinning, this meant packets arriving for connections owned by Core 5 would land in Core 5’s queue, stored in Core 5’s local memory, processed by Core 5’s thread. The packet never left that NUMA domain. Zero cross-core communication for the hot path.
This is where I had one of those “oh my god, hardware design is beautiful” moments at 2 AM.
Per-Core Architecture: Embracing Shared Nothing
This is the design choice that unlocked everything, though it felt counterintuitive at first: each core owns a fixed subset of connections and never shares them.
Connection IDs are hashed modulo 96 (our core count). Connection #12345 always goes to Core 9. Connection #99887 always goes to Core 23. When a client sends a message, the NIC’s RSS hash delivers it to the right core’s queue. When we need to send data to that connection, the same core builds the packet and submits it to the NIC.
No locks and no shared writable data structures in the per-packet hot path, so we minimized atomics and avoided cache-line bouncing between cores. I’d spent years thinking about how to make concurrent data structures scale. This architecture just… didn’t need them.
<button data-code="struct Worker {
core_id: usize,
// Each worker owns its own connection map (no sharing!)
connections: HashMap,
// Dedicated NIC queues for this worker
rx_queue: u16,
tx_queue: u16,
port_id: u16,
}
impl Worker {
fn handle_frame(&mut self, conn_id: u32, frame: Frame) {
// This connection ALWAYS belongs to THIS core
// No other core will ever touch this HashMap
if let Some(conn) = self.connections.get_mut(&conn_id) {
match frame {
Frame::Ping => self.send_pong(conn),
Frame::Close => self.close_connection(conn_id),
Frame::Text(data) => {
// Process message, maybe broadcast to other connections
self.handle_text_message(conn, data);
}
_ => {}
}
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
struct Worker {
core_id: usize,
// Each worker owns its own connection map (no sharing!)
connections: HashMap<u32, Connection>,
// Dedicated NIC queues for this worker
rx_queue: u16,
tx_queue: u16,
port_id: u16,
}
impl Worker {
fn handle_frame(&mut self, conn_id: u32, frame: Frame) {
// This connection ALWAYS belongs to THIS core
// No other core will ever touch this HashMap
if let Some(conn) = self.connections.get_mut(&conn_id) {
match frame {
Frame::Ping => self.send_pong(conn),
Frame::Close => self.close_connection(conn_id),
Frame::Text(data) => {
// Process message, maybe broadcast to other connections
self.handle_text_message(conn, data);
}
_ => {}
}
}
}
}
struct Worker {
core_id: usize,
// Each worker owns its own connection map (no sharing!)
connections: HashMap<u32, Connection>,
// Dedicated NIC queues for this worker
rx_queue: u16,
tx_queue: u16,
port_id: u16,
}
impl Worker {
fn handle_frame(&mut self, conn_id: u32, frame: Frame) {
// This connection ALWAYS belongs to THIS core
// No other core will ever touch this HashMap
if let Some(conn) = self.connections.get_mut(&conn_id) {
match frame {
Frame::Ping => self.send_pong(conn),
Frame::Close => self.close_connection(conn_id),
Frame::Text(data) => {
// Process message, maybe broadcast to other connections
self.handle_text_message(conn, data);
}
_ => {}
}
}
}
}
Simple hash table lookup. No locking. The only synchronization happens during connection establishment (which is rare — once per connection lifetime) and broadcast messages (which we handle via lock-free channels that are way faster than shared mutexes).
Constraints force clarity.
Honestly, this took me a while to trust. My instinct was to build something “flexible” where any core could handle any connection. But that flexibility costs you — every shared data structure needs coordination, every atomic operation is a potential bottleneck.
The Gotcha That Humbled Me During Load Testing
Here’s where theory met reality and I learned a painful lesson about distribution. During our first proper load test, everything looked perfect — CPU usage spread evenly across cores, latency was low, throughput was great. Then we simulated what happens during a mobile app release: ten thousand clients connecting within 30 seconds, all at once.
All those new connections got sequential connection IDs. And sequential IDs, when you hash them modulo 96, cluster together. Cores 0–5 saturated instantly. The other 90 cores sat there at 5% CPU, bored, while those six melted down.
I felt stupid. Of course sequential assignment would cluster. But I hadn’t seen it until we tested the exact failure mode that would happen in production.
The fix required smarter connection ID generation:
u32 {
// Get next sequential number (unique)
let base = COUNTER.fetch_add(1, Ordering::Relaxed);
// Add random salt to break sequential patterns
let salt = rand::thread_rng().gen::() & 0xFF;
// Multiply by core count to spread across all cores
// wrapping_mul handles overflow gracefully
base.wrapping_mul(96).wrapping_add(salt)
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use rand::Rng;
use std::sync::atomic::{AtomicU32, Ordering};
// Global counter for unique IDs
static COUNTER: AtomicU32 = AtomicU32::new(0);
fn assign_connection_id() -> u32 {
// Get next sequential number (unique)
let base = COUNTER.fetch_add(1, Ordering::Relaxed);
// Add random salt to break sequential patterns
let salt = rand::thread_rng().gen::<u32>() & 0xFF;
// Multiply by core count to spread across all cores
// wrapping_mul handles overflow gracefully
base.wrapping_mul(96).wrapping_add(salt)
}
use rand::Rng;
use std::sync::atomic::{AtomicU32, Ordering};
// Global counter for unique IDs
static COUNTER: AtomicU32 = AtomicU32::new(0);
fn assign_connection_id() -> u32 {
// Get next sequential number (unique)
let base = COUNTER.fetch_add(1, Ordering::Relaxed);
// Add random salt to break sequential patterns
let salt = rand::thread_rng().gen::<u32>() & 0xFF;
// Multiply by core count to spread across all cores
// wrapping_mul handles overflow gracefully
base.wrapping_mul(96).wrapping_add(salt)
}
This is schematic; our real implementation also tracks ID reuse and collision safety, but the core idea is to decorrelate connection arrival order from core assignment to avoid hot spots. Now connection IDs distribute evenly across cores even when assigned sequentially during traffic bursts.
Problem solved. It only cost me two days of confused debugging and one embarrassing Slack thread where I insisted the load balancer was broken.
What This Actually Gave Us (And What It Cost)
We prototyped and load tested this system over three months, eventually reaching 12 million connections in our staging environment on a single bare metal server (96 vCPUs, 384GB RAM, dual 100Gb NICs). One machine could replace our 50-node Go cluster. The numbers still feel surreal:
On our specific workload and cloud/bare-metal pricing:
- Monthly infra cost: $47k → $6k (just one beefy server vs. 50 cloud VMs)
- Latency: p99 message delivery dropped from 45ms to 8ms
- Observed uptime: 99.5% → 99.97% based on our SLO metrics (fewer moving parts, simpler failure modes)
- Deployments: Rolling restarts across 50 nodes taking 20 minutes → single binary restart in 3 seconds
The moment I knew this approach could work was during our Black Friday simulation. Traffic spiked to 12 million connections — we were handling 10M mostly idle WebSocket connections with low average messages per second per connection on that 96-vCPU, 384GB RAM dual-100G NIC box. The server’s CPU utilization hit 78%. No alerts. No scaling events. No reconnection storms. No panicked Slack messages. It just… handled it.
I sat there watching Grafana, waiting for something to break, and nothing did. That feeling when your system works exactly as designed under real load? That’s why we do this job.
Where This Still Hurts (Because Nothing’s Perfect)
DPDK isn’t magic, and I’d be lying if I said the transition was smooth. You’re taking on kernel responsibilities, which means you inherit kernel-level complexity:
- No standard socket APIs. Libraries expecting BSD sockets don’t work. We rewrote WebSocket framing from scratch. That took two months and about 2,500 lines of careful parsing code.
- Debuggability is brutal.
straceandtcpdumpare useless when you bypass the kernel. You need custom instrumentation, careful logging, and a willingness to read packet dumps manually. We built our own packet capture tool that writes to shared memory for real-time inspection. - Operational complexity. Hugepages, isolated cores, NIC firmware quirks, RSS configuration, interrupt affinity — there’s a steep learning curve for ops teams. Our first production deploy required four tries and a weekend of troubleshooting why VFIO wouldn’t bind correctly.
- Error handling gets weird. When the kernel isn’t managing your network stack, you handle every edge case yourself: malformed packets, connection resets, half-open connections, memory exhaustion. The first time we hit mbuf pool exhaustion, it took six hours to figure out we were leaking packet buffers in an error path.
But for our use case — stateful, long-lived connections with occasional bursts of small messages — this architecture was absolutely the right trade-off. High-throughput streaming workloads would need different headroom and probably different approaches entirely.
What’s Next: eBPF and the Middle Ground
The next frontier we’re exploring: using eBPF for advanced packet steering and lightweight inspection in the kernel, while keeping full protocol logic and connection state in user space — hoping to get some kernel-bypass-like benefits without fully reimplementing a TCP/IP stack.
eBPF lets you inject small, verified programs into the kernel that can make routing decisions, filter traffic, and collect metrics without crossing privilege boundaries repeatedly. You give up some control compared to full DPDK, but you gain back standard tooling and some operational sanity.
I don’t know if it’ll work yet. That’s the fun part.
The Bigger Lesson
If you’re hitting scaling limits with traditional approaches, pause and ask whether you’re solving a distribution problem or an efficiency problem. We thought we needed more machines. What we actually needed was better use of the hardware we already had.
Modern servers are absurdly powerful. A single box with 100 cores and half a terabyte of RAM can do things that would’ve required an entire data center twenty years ago. But we’ve gotten so used to thinking horizontally — throw more nodes at it, let Kubernetes handle it — that we forget to ask if vertical optimization might be simpler.
Sometimes the answer is genuinely distributed systems. Sometimes it’s understanding NUMA topology and being willing to write unsafe Rust at 3 AM. The trick is knowing which problem you actually have
Enjoyed the read? Let’s stay connected!
- 🚀 Follow The Speed Engineer for more Rust, Go and high-performance engineering stories.
- 💡 Like this article? Follow for daily speed-engineering benchmarks and tactics.
- ⚡ Stay ahead in Rust and Go — follow for a fresh article every morning & night.
Your support means the world and helps me create more content you’ll love. ❤️

