How We Made OTP's socket Module 1.5x Faster
Erlang/OTP ships with two distinct TCP stacks. The legacy stack is inet_drv, a port driver written in C that has powered Erlang networking for decades. The modern alternative is the socket module: a thin NIF layer over the OS socket API, paired with a compatibility shim that allows gen_tcp to run on top of it.
For an RTB bidder whose sole job is to process incoming HTTP requests and return bids within tight millisecond budgets, the TCP stack is not an abstract implementation detail. It defines your baseline throughput and latency floor. We spent several weeks investigating the socket NIF to see how much performance was left on the table.
The results: after our changes, the raw socket backend drains bulk TCP streams 1.5x faster than the legacy driver and handles connection churn 1.6x faster. It still trails slightly on small-message request/response workloads, and the underlying reason turned out to be the most interesting discovery of all. It is not slower per request. It simply leaves schedulers idle more often.
This post walks through the bottlenecks we found, the optimizations we upstreamed to Erlang/OTP, and what the runtime is actually doing under the hood.
Where the socket module came from
Much of the advice about Erlang’s socket module online predates the releases that made it production-ready. Here is where the backend stands across OTP versions:
| Release | What landed |
|---|---|
| OTP 22.0 | socket introduced as an experimental module in ERTS |
| OTP 23.0 | Moved into Kernel; first experimental gen_tcp backend |
| OTP 24.0 | Stabilized as inet_backend = socket |
| OTP 26.0 | Windows IOCP support; Unix API marked non-experimental |
| OTP 27.0 | Windows backend rework and stabilization |
It took six years from the initial commit for the OTP team to mark the Unix API as non-experimental, and it remains opt-in rather than the default. Because applications must explicitly request it per socket, it has seen only a fraction of the production traffic that inet_drv has weathered over the decades. Code that has not been run hard at scale usually has straightforward performance wins waiting in it. That was our working hypothesis going in.
Enabling the socket backend in gen_tcp looks like this. Note that {inet_backend, socket} must be the first option in the list; placed anywhere else, gen_tcp:listen treats it as an unknown option and fails with badarg:
{ok, L} = gen_tcp:listen(Port, [{inet_backend, socket}, binary]).
How we measured
We report two types of numbers in this post. Per-change deltas compare the tip of our branch against the same branch with that specific optimization reverted, isolating the impact of each patch. Cross-backend comparisons evaluate complete HTTP servers built on each stack, pinned to dedicated CPU cores and driven by wrk from outside the VM. All benchmarks were run against OTP master (as of 30 September 2026).
To eliminate host drift and CPU frequency throttling artifacts, every run was paired and interleaved across five to seven repeats, reporting the median delta. When fewer than 70% of runs agreed on direction, we discarded the result as noise. All tests ran inside a Linux container on aarch64 with 10 dedicated CPUs.
The two highest-impact bottlenecks surfaced immediately: one affecting bulk throughput, and the other crippling connection churn.
Bottleneck 1: The receive buffer read in 8 KB sips
When you call socket:recv(S, 0), you are telling the runtime to return whatever data is currently available in the socket buffer. On Unix, the NIF historically allocated a fixed 8 KB buffer for this call. As a result, draining a large incoming payload required dozens of 8 KB reads, invoking a separate recv syscall for each chunk regardless of how many megabytes were waiting in the OS kernel buffer.
We updated the NIF to adapt its buffer dynamically:
- A read that completely fills the buffer doubles its capacity for the next call.
- A read that leaves the buffer mostly empty halves its capacity, but only after an exponentially weighted moving average of read sizes drops below one quarter of the current size (ensuring a single partial packet does not discard accumulated buffer growth).
- The floor is the configured
rcvbufsetting, and the ceiling is capped at 256 KB, a limit we arrived at through empirical sweep testing rather than guessing.
Here is what happens when draining 4 GB of data over loopback:
| Build | MB/s | recv calls | Bytes per recv |
|---|---|---|---|
| master | 7,840 | 526,532 | 8,157 |
| with adaptation | 11,304 | 16,738 | 256,599 |
Throughput jumped by 44% while slashing syscall count by 97%. In paired repeat runs, the throughput advantage ranged between 51% and 60%, showing unanimous agreement across all test iterations.
The hidden memory trap
Our initial implementation had a subtle memory leak of the kind that pure throughput benchmarks never expose. The receive buffer was stored as a persistent scratch binary on the socket resource, deallocated only when the socket was garbage collected. If a connection briefly transferred a large payload, scaled its buffer up to 256 KB, and then transitioned to an idle keep-alive state, it retained that full 256 KB allocation indefinitely. Across 4,000 idle connections, that pinned 866 MB of uncollected memory.
We resolved this by releasing the scratch buffer whenever the socket enters a waiting state (when recv returns EAGAIN). The adapted capacity setting is preserved, since EAGAIN simply means the immediate stream drained, not that the connection is permanently dead. With this fix, memory across those same 4,000 idle connections dropped to 7.2 MB (compared to master’s baseline of 41.1 MB).
Bottleneck 2: Adding acceptors made listening sockets slower
On high-traffic servers, standard practice is to spin up multiple acceptor processes on a shared listening socket to distribute connection setup across schedulers. When benchmarking connection churn on the socket NIF, we ran into an unexpected anomaly: adding more acceptors caused throughput to collapse.
In the original NIF implementation, only one process, designated as the “current acceptor”, was permitted to execute the underlying accept() syscall. Every additional acceptor process was enqueued on an internal wait list. When a connection arrived, the active acceptor handled it and passed a baton to wake up the next acceptor in queue.
With multiple acceptors running, every single incoming connection had to pay the full price of this serialized handover: re-arm the poll set, wait for the OS wakeup, process the internal '$socket' message, reschedule the BEAM process, re-enter the NIF, and only then issue accept().
The bottleneck was not lock contention; it was total scheduler starvation. With 32 acceptor processes, scheduler utilization plummeted to just 3.6%. The CPUs were completely idle because every process was waiting in line for the baton.
The solution is straightforward: allow processes to attempt accept() immediately before falling back to the wait queue. In modern Unix kernels, calling accept() concurrently from multiple processes on the same listening descriptor is safe; the kernel guarantees each caller receives a distinct socket descriptor. If a racing process claims the connection first, the original acceptor simply encounters EAGAIN, which the NIF already handles seamlessly.
| Acceptors on one socket | Before | After |
|---|---|---|
| 1 | 22,425/s | 19,302/s (noise) |
| 8 | 3,926/s | 59,483/s |
| 32 | 3,925/s | 61,019/s |
At 8 and 32 acceptors, throughput surged from under 4,000 connections/sec to over 60,000 connections/sec.
Note that we preserved the serialized queue for reader and writer processes. For reads and writes, strict serialization is necessary to prevent concurrent operations from interleaving payload bytes. accept() is the single operation where the kernel naturally handles concurrent callers independently.
Three smaller syscall optimizations
The remaining patches focused on eliminating unnecessary syscalls across the socket lifecycle:
- Eliminating redundant
fcntlcalls: Every newly created socket was issuing twofcntlcalls to configure non-blocking flags that modern kernels can set atomically insidesocket()andaccept4(). Theaccept4code path already existed in the C source but was guarded behind aHAS_ACCEPT4macro that no autoconf check ever defined. Adding the configure probe enabledaccept4across Linux, eliminating both syscalls. Combined with the socket closing optimization below, connection churn that previously cost fourfcntlcalls per socket now costs zero. - Avoiding dirty schedulers on close: Sockets previously dispatched
close()to a dirty I/O scheduler unconditionally while resetting the file descriptor back to blocking mode. Neither step is necessary unlessSO_LINGERis active with a non-zero timeout. Bypassing dirty schedulers for non-lingering sockets kept the dirty scheduler pool idle during connection churn; reverting this change pegged dirty scheduler utilization at 85%. - Removing no-op
epoll_ctlcalls: When re-arming a descriptor for reads in the scheduler poll set (which OTP 28 made zero-cost), the NIF still fell through to anepoll_ctl(MOD)call with an empty event mask. This burned one useless syscall on every single wakeup. Removing eleven lines of redundant code eliminated it completely.
The SO_LINGER optimization highlights an important operational detail. If a socket is configured to linger on close, it must execute on a dirty scheduler because the close syscall can block. Because the dirty I/O pool (+SDio) is small by default, enabling SO_LINGER {true, 5} on our benchmark server caused throughput to drop from 109,015 req/s to 35,305 req/s, driving dirty pool utilization above 99%. At that point, throughput stops scaling with CPU cores and becomes strictly bound by +SDio:
+SDio threads | 1 | 4 | 8 | 16 |
|---|---|---|---|---|
| req/s | 32,216 | 35,530 | 39,480 | 43,375 |
If you enable SO_LINGER on a high-throughput server, that setting alone will dominate your connection teardown latency.
Where socket stands against inet
With these optimizations in place, we benchmarked the new socket NIF directly against the legacy inet_drv driver across three distinct workload profiles:
- Connection churn: The server accepts a connection, processes one HTTP request, sends the response, and closes.
- Keep-alive: Standard HTTP request/response over long-lived connections.
- Bulk upload: Draining 1 MB request bodies over active connections.
Each test was evaluated at saturation load (256 concurrent connections for churn and keep-alive, 64 for bulk upload):
| Workload | inet | gen_tcp + socket | raw socket |
|---|---|---|---|
| Connection churn (server closes) | 67,650/s | 24,379/s | 110,348/s |
| Request/response (keep-alive) | 405,023/s | 295,863/s | 345,290/s |
| Bulk drain (1 MB uploads) | 6,262 MB/s | 7,067 MB/s | 9,727 MB/s |
Raw socket wins bulk upload throughput by 1.55x and connection churn by 1.63x. inet_drv retains a 1.17x edge on keep-alive request/response.
Two numbers in this table warrant a deeper look: why the middle column (gen_tcp + socket) trails both alternatives, and why inet_drv still leads on keep-alive.
The cost of the gen_tcp compatibility shim
The middle column (gen_tcp + socket) and the right column (raw socket) use the exact same NIF implementation. The performance gap comes entirely from the compatibility layer.
Under the hood, gen_tcp_socket is implemented as a gen_statem process: one extra BEAM process for every active socket. This process takes ownership of the socket descriptor, executes recv, and implements in Erlang what inet_drv handles directly in C: stream buffering, packet framing ({packet, N} and HTTP header parsing), delivery mode conversions, and active-mode credit tracking.
In active mode, a single packet delivery requires:
- An internal
'$socket'message from the NIF to thegen_statemprocess. - A
recvcall and Erlang-level packet framing. - A second message forwarding the formatted payload to the controlling process.
inet_drv performs all of this logic inside the C port driver, delivering the final term directly to the controlling process mailbox in a single hop. For perspective, inet_drv.c contains 15,879 lines of C; the gen_tcp_socket shim is 3,455 lines of Erlang.
Running through the shim imposes a measurable tax: 27% lower throughput on bulk transfers, 14% on keep-alive, and 78% on connection churn. Spawning and tearing down an extra gen_statem process per connection heavily penalizes short-lived connections. This also impacts tail latency: p99 latency on the 1 MB bulk upload workload reached 1.64 seconds through the shim versus 82 milliseconds on the raw socket.
Our patches optimize the NIF layer below the shim. Closing that 78% gap will require revisiting the architecture of gen_tcp_socket itself.
The remaining gap: Scheduler idleness, not execution cost
The most intriguing question is why inet_drv still beats raw socket on keep-alive request/response (405k vs 345k req/s).
Profiling the keep-alive workload revealed that the socket backend was executing 1.3 sched_yield syscalls per request, compared to zero for inet_drv. There are no explicit yield calls in the socket NIF and no calls to enif_consume_timeslice. Every single yield originated from inside ERTS, specifically from the busy-wait spin loop a BEAM scheduler executes before entering sleep state.
The socket backend was exhausting scheduler run queues roughly once per request. Because each incoming request parks an Erlang process waiting for a '$socket' notification, schedulers briefly run out of runnable processes between requests. inet_drv avoids this because its internal I/O operations are queued directly on schedulers as port tasks, keeping run queues continuously primed.
This is the exact same starvation pattern we observed with acceptors, occurring one layer down. Acceptor processes were waiting for a baton; here, schedulers are waiting for message notifications.
Microstate accounting (msacc) confirms this diagnosis. Summing the sleep and other state counters reveals the percentage of time schedulers had zero work to execute: 18.9% for socket versus 7.2% for inet_drv.
Increasing connection concurrency does not eliminate this difference. Sweeping connections from 32 to 2,048 reduced idle time from 57.8% down to 10.1%, but inet_drv maintained a steady 1.00x to 1.12x lead across the entire range.
However, holding load constant and varying the scheduler count (+S) dramatically changes the outcome:
Schedulers (+S) | socket ran dry | socket vs inet throughput |
|---|---|---|
| 1 | 3.6% | 1.24x |
| 2 | 6.9% | 0.97x |
| 4 | 17.9% | 0.90x |
On a single scheduler, the socket backend runs dry as rarely as inet_drv and outperforms it by 24%. On four schedulers, it cannot keep all cores consistently saturated, trailing by 10%.
HTTP pipelining proves the same point from the opposite angle. At a pipeline depth of 8 (where a single recv returns eight requests, allowing one wakeup to service all of them), raw socket delivers 1,505,767 req/s compared to 706,862 req/s for inet_drv, cutting latency in half.
Per unit of active CPU time, the socket NIF is roughly 24% faster than inet_drv. The limitation is that a strict request/response pattern over keep-alive cannot keep four or more schedulers fed without encountering brief idle gaps. The gap is not a per-request compute overhead; it is unutilized scheduler time.
A brief note on Nagle and pipelining
While setting up the pipelining benchmark, our initial test registered a surprisingly poor 44,728 req/s at 27 ms latency, with the server 95% idle. The culprit was TCP_NODELAY: because Nagle’s algorithm was enabled, the TCP stack held the second response of every batch waiting for the client’s delayed ACK. Setting nodelay: true produced an immediate 27-fold throughput increase. In strict ping-pong request/response flows, Nagle rarely triggers, making this an easy trap to overlook when testing batched or pipelined streams.
Upstream patches
All of these optimizations have been submitted upstream to the Erlang/OTP repository:
- #11490: Accept and close optimizations
- #11491: Adaptive receive buffer sizing
- #11525: Poll set re-arm optimization (queued by the OTP core team for OTP 28 and 29 maintenance releases)
- #11537: Concurrent acceptor fast path
You can find the rest of our open-source tools and infrastructure libraries on our open source page.

Working on something in this space? We help teams ship ad tech infrastructure that holds up under production load.
Get in touch