Systemd Socket Tuning for High Load
If you've run busy Linux web stacks for a few years, you recognize this outage immediately. Traffic jumps for twenty seconds after an email blast, a webhook storm, or a cache stampede. CPU sits at 35%. Memory has gigabytes free. Application logs look calm. Yet Nginx spits out waves of 502 Bad Gateway errors, and your error log fills with Resource temporarily unavailable or abrupt upstream timeouts.
Almost nobody checks the kernel listen queue first. People blame PHP, Go, Python, the firewall, or noisy hypervisor neighbors. What actually happened is far more mundane: your worker pool saturated for 200 milliseconds, incoming connections stacked up in the accept queue, and Linux quietly truncated that queue at 128 or 511 slots. On hosts where systemd manages service lifecycles and socket activation, mismatched sysctl defaults, unit files, and daemon configs keep that cap invisible until burst load hits.
The Silent Clamp Behind 128 and 511
When a daemon calls listen(fd, backlog), Linux never takes that argument at face value. Inside __sys_listen(), the kernel silently clamps the queue to min(backlog, net.core.somaxconn). No EINVAL, no warning in dmesg, and your service boots up looking completely healthy.
Two legacy defaults collide here. Before Linux 5.4, net.core.somaxconn defaulted to 128. Newer kernels raised it to 4096, convincing many teams the issue was gone. It isn't. Older LTS images, container runtimes, and vendor sysctl baselines still carry 128. Even with somaxconn at 4096, userland software still asks for less:
- Nginx defaults
listentobacklog=511on Linux unless overridden. - PHP-FPM packages frequently set
listen.backlog = 511(older builds defaulted to128). - Redis, Gunicorn, and older systemd binaries built against pre-2.32 glibc headers often request
128or511.
Don't guess what Linux is enforcing. Check ss and read the Send-Q column. On a socket in LISTEN state, the headers are counterintuitive: Recv-Q shows queued connections waiting for accept4(), while Send-Q is the effective maximum backlog.
$ ss -lnt sport = :9000
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 129 128 127.0.0.1:9000 0.0.0.0:*
$ ss -xl src /run/php/php8.3-fpm.sock
Netid State Recv-Q Send-Q Local Address:Port
u_str LISTEN 512 511 /run/php/php8.3-fpm.sock 48291
Once Recv-Q hits Send-Q + 1, the queue is full. On TCP listeners, confirm historical drops with nstat:
$ nstat -az TcpExtListenOverflows TcpExtListenDrops
#kernel
TcpExtListenOverflows 1482 0.0
TcpExtListenDrops 1482 0.0
If those counters climb during spikes, the kernel is shedding traffic before your app sees it. Raising the backlog won't rescue an undersized worker pool, though. Size your workers properly using Linux PHP-FPM max children sizing practices and server concurrency sizing rules first. A wider queue absorbs micro-bursts; it doesn't invent CPU cores.
Unix Domain Sockets vs. 127.0.0.1 TCP Loopback
Once you start chasing 502 bursts, the transport question always surfaces: should Nginx talk to local upstreams over Unix domain sockets or 127.0.0.1 TCP loopback? Both plug into Nginx's epoll loop, yet they fail in completely different ways under load.
Overflow Behavior Under Burst Load
A TCP loopback listener maintains two queues: the SYN queue for half-open handshakes (bounded by net.ipv4.tcp_max_syn_backlog) and the accept queue for completed handshakes waiting on accept4() (bounded by min(backlog, somaxconn)). When the accept queue fills and net.ipv4.tcp_abort_on_overflow stays at 0, Linux silently drops the final ACK. The server resends SYN-ACK on an exponential timer starting at 1 second. To Nginx, requests hang for 1s, 3s, or until fastcgi_connect_timeout fires. Tail latency cliffs hit before the 502s even start.
A stream Unix socket (AF_UNIX, SOCK_STREAM) bypasses TCP/IP completely. There's no handshake and no SYN queue, just one accept queue bounded by sk_max_ack_backlog. Because Nginx calls connect() on non-blocking descriptors inside epoll, a full Unix socket immediately returns EAGAIN:
connect() to unix:/run/php/php8.3-fpm.sock failed (11: Resource temporarily unavailable)
Nginx returns a 502 on the spot instead of stalling for a full second. Under bursts, failing fast beats hoarding half-open TCP states, provided the backlog is wide enough that normal jitter never trips EAGAIN.
Ephemeral Port Starvation and TIME_WAIT
TCP loopback hides a second trap on busy proxies: TIME_WAIT exhaustion. Every short-lived connection from Nginx to 127.0.0.1:9000 consumes a local ephemeral port. Whichever side sends the first FIN holds that four-tuple in TIME_WAIT for 60 seconds, hardcoded in Linux.
Default net.ipv4.ip_local_port_range is 32768 60999, just 28,232 ports. Push 500 unpooled FastCGI requests per second over loopback and you run dry in 57 seconds:
connect() to 127.0.0.1:9000 failed (99: Cannot assign requested address)
Run ss -s during load; if timewait passes 24,000, you're starving loopback. Upstream keepalive pools fix this cleanly for HTTP/1.1 services like Go or Node, though persistent FastCGI connections in PHP-FPM can pin idle workers to specific Nginx worker processes and skew load balancing.
Unix domain sockets skip TIME_WAIT entirely. No ephemeral ports, no IP routing, no TCP checksums. In my single-host benchmarks at 4,000 req/s, switching a local PHP-FPM pool from 127.0.0.1 to AF_UNIX cuts 25 to 40 microseconds off connect-and-dispatch latency and drops kernel CPU by 6% to 9%. You also get clean per-site filesystem permissions, which matters when designing OpenLiteSpeed versus Nginx PHP isolation on multi-tenant hosts.
Where TCP Loopback Still Wins
Unix sockets aren't magic on high-core hardware. On 32-core or 64-core nodes where dozens of Nginx workers hammer one .sock inode, contention builds on the socket's receive queue lock. Linux doesn't support SO_REUSEPORT for AF_UNIX stream sockets, whereas TCP loopback with SO_REUSEPORT gives each worker its own accept queue and cuts epoll wakeup contention. Loopback also lets you run tcpdump -i lo instead of reaching for strace or eBPF. My rule: run Unix sockets on single-host stacks up to roughly 8,000 req/s (or shard across two to four socket paths), and use TCP loopback with keepalive plus SO_REUSEPORT for multi-queue scaling or future multi-node splits.
Kernel Sysctls Worth Setting
Old tuning posts still recommend net.ipv4.tcp_tw_recycle = 1, which broke NAT traffic for years and was removed in Linux 4.12. Skip cargo-cult configs and place only verifiable settings in /etc/sysctl.d/99-socket-tuning.conf:
# Cap for TCP and AF_UNIX accept queues
net.core.somaxconn = 8192
# Packet backlog between NIC driver and network stack
net.core.netdev_max_backlog = 16384
# Incomplete TCP handshake queue
net.ipv4.tcp_max_syn_backlog = 8192
# Wider ephemeral port range for 127.0.0.1 upstreams
net.ipv4.ip_local_port_range = 10240 65535
# Safe TIME_WAIT reuse for outbound client sockets
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_tw_reuse = 1
Apply it with sysctl --system. Leave net.ipv4.tcp_abort_on_overflow at 0 unless you want immediate RST packets to trigger failover to another node. Also watch what sits downstream: queuing 4,000 requests instead of dropping them at 128 pushes a denser query wave into your database as workers drain. If DB limits don't match, you'll trade 502s for database lockups, a chain reaction I examined while solving MySQL 1040 too many clients errors.
Tuning Systemd Socket and Service Units
Here is the trap that catches veteran admins every time: sysctl --system does not resize the accept queue of sockets already in LISTEN state. Under systemd socket activation, systemd binds the socket and calls listen() using the unit's Backlog= directive before your daemon starts. Bump somaxconn without updating and restarting the .socket unit, and Send-Q stays frozen.
Add a drop-in via systemctl edit your-app.socket so package updates won't clobber it:
[Socket]
Backlog=4096
ListenStream=/run/app/backend.sock
SocketUser=www-data
SocketGroup=www-data
SocketMode=0660
Accept=no
For TCP loopback units, add three directives that pay off immediately under load:
[Socket]
ListenStream=127.0.0.1:9000
Backlog=4096
NoDelay=yes
ReusePort=yes
DeferAcceptSec=2
NoDelay=yes sets TCP_NODELAY, avoiding 40ms Nagle and delayed-ACK stalls on small loopback frames. ReusePort=yes splits accept queues across workers. Keep Accept=no untouched: flipping it to yes turns systemd into an inetd per-connection spawner that will fork-bomb a web box in seconds.
Pair this with a service override via systemctl edit your-app.service. Raising Backlog=4096 buys nothing if your daemon hits the legacy 1024 file descriptor soft limit and fails accept4() with EMFILE:
[Service]
LimitNOFILE=65536
When a daemon opens its own listener without socket activation, match the setting inside its config too (listen 443 ssl backlog=4096; in Nginx, listen.backlog = 4096 in PHP-FPM). Every layer must agree because min() enforces the smallest value.
Don't set
Backlog=65535just because the kernel allows it. Queuing 30,000 requests ahead of a backend draining 500 req/s makes tail requests wait 60 seconds, long after clients timed out and retried. Aim for 2 to 5 seconds of peak drain rate;2048to4096fits most production nodes.
Production Rollout and Verification Checklist
Never trust a config reload until the kernel confirms it. After systemctl daemon-reload and restarting your .socket and .service units during a maintenance window, verify four things:
- Run
ss -lnt(TCP) orss -xl(Unix) and verifySend-Qreads4096, not128or511. - Check live descriptor limits in
/proc/$(systemctl show -p MainPID --value php8.3-fpm.service)/limitsunderMax open files. - Baseline drops with
nstat -az TcpExtListenOverflows TcpExtListenDrops, fire a shortwrkorheyburst against staging, and confirm both stay flat. - On
127.0.0.1upstreams, watchss -sduring the burst sotimewaitstays well under half ofip_local_port_range.
Once Send-Q aligns across kernel, systemd, and daemon configs, and your transport matches your request rate, those mysterious 20-second 502 storms vanish. Real saturation will surface cleanly in worker metrics where you can scale it, instead of hiding as silent kernel drops.
Comments
Post a Comment