Skip to content

Ports, Sockets & Connections: Ephemeral Ports, TIME_WAIT, Keepalive, Backlog, conntrack; ss, lsof, tcpdump, nc, curl, dig ​

"When a connection is closed actively, it MUST linger in the TIME-WAIT state for a time 2xMSL (Maximum Segment Lifetime) (MUST-13)." — RFC 9293, Transmission Control Protocol (TCP), Section 3.6

Summary: A connection is a pair of sockets named by a 5-tuple; ports, file descriptors, kernel queues and timers are the finite resources behind every "connection refused", "too many open files" and "cannot assign requested address". Focus: Ports and ephemeral ranges, sockets as file descriptors, every TCP state you see in ss, TIME_WAIT and CLOSE_WAIT, backlog queues, keepalive and timeouts, conntrack, fd limits, SO_REUSEPORT, Unix and UDP sockets, and the tools (ss, lsof, tcpdump, nc, curl, dig, mtr, iperf3) with real output. Learning goal: Read ss output and an errno and say what is wrong, then fix it in Go and Laravel with pools, keep-alive, timeouts and limits instead of kernel folklore.

This page is the complete reference for the socket layer as a developer meets it: on a laptop, in Docker, behind a NAT gateway and in a busy service. It owns ports, sockets, connection states, the kernel queues and timers, and the command-line tools. It does not re-teach three neighbours: the protocol-level comparison of TCP and UDP (headers, congestion control, when to pick which) is in TCP vs UDP; how a pool sizes and recycles database connections is in Connection Pooling; and how a packet climbs the layers is in Network Models. NAT internals are in NAT, PAT & Port Forwarding, Docker's port publishing in Docker Networking, and the step-by-step incident flow in the Network Troubleshooting Playbook.

Page map ​

If you are looking forGo to
Tables you can memorise in one minuteEverything in one minute
Why sockets, ports and states exist at allWhy it exists
RFC 793/9293, RFC 768, RFC 6335, BSD socketsWhere it comes from
Port ranges and the well-known ports tablePorts
socket/bind/listen/accept/connect, the 5-tupleSockets are file descriptors
What each state in ss meansConnection states
TIME_WAIT, 2MSL, tcp_tw_reuseTIME_WAIT
"cannot assign requested address"Ephemeral port exhaustion
Connections stuck in CLOSE_WAITCLOSE_WAIT leaks
somaxconn, SYN queue, accept queue, SYN cookiesBacklog and the accept queue
TCP keepalive vs HTTP keep-alive vs heartbeatsKeepalive
TCP_NODELAY, Nagle, delayed ACKNagle and delayed ACK
SO_RCVBUF, tcp_rmem, windowBuffers and the window
Connect vs read vs write vs idle timeoutsTimeouts and half-open connections
nf_conntrack: table full, dropping packetconntrack
"too many open files"File descriptor limits
Two processes on one port, zero-downtime restartsSO_REUSEADDR and SO_REUSEPORT
php-fpm, PostgreSQL, Redis, Docker socketsUnix domain sockets
UDP drops and no backpressureUDP sockets
Every sysctl, every errno, hex dumpsMechanics
ss, lsof, netstat, nc, curl, telnet, tcpdump, dig, mtr, iperf3, macOSThe tools
Fixes in Go and Laravel, troubleshooting tableSolving the classic problems
Which fix for which symptomChoosing
Monolith to distributed systemIn architecture
Reproduce everything in DockerLab
Wrong beliefs, cheat sheet, every termMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The resources. Each row is unpacked in the concept catalogue.

ResourceIn plain wordsLimit you hitSymptom
PortA 16-bit number that picks a process on a host65 535 per IP and protocol; about 28 000 ephemeral ports on LinuxEADDRINUSE (server), EADDRNOTAVAIL (client)
SocketA kernel object you hold through a file descriptorulimit -n per process, fs.file-max per hostEMFILE "too many open files"
5-tupleProtocol + source IP:port + destination IP:port names one connectionOnly the source port varies towards one serverPort exhaustion on busy clients and NAT
Accept queueFinished handshakes waiting for accept()min(backlog, somaxconn)SYN retries, slow connects, ListenOverflows
TIME_WAITA closed connection's tuple kept for 2MSL by the side that closed first60 s on Linux, 30 s on macOSThousands of TIME-WAIT lines, then port exhaustion
CLOSE_WAITPeer has closed, your app has notGrows until fds run outEMFILE, leaked goroutines/workers
conntrack entryNAT/firewall memory of one flownf_conntrack_maxnf_conntrack: table full, dropping packet
Idle timer in a middleboxA NAT or load balancer forgets idle flowsAWS NAT gateway 350 s, AWS ALB 60 s defaultNext write gets ECONNRESET or hangs

The states you will see in ss.

StateWhat it means when you see manyUsually caused by
LISTENA server socket waiting for connectionsNormal; check Recv-Q vs Send-Q for a full accept queue
SYN-SENTWe sent SYN, no answer yetFirewall dropping, server accept queue full, wrong IP
SYN-RECVServer got SYN, sent SYN/ACK, waits for ACKSYN flood or lossy path
ESTABOpen connectionNormal; huge counts mean no pooling limit
FIN-WAIT-1 / FIN-WAIT-2We closed, waiting for the peer's ACK / FINPeer slow to close; orphans end after tcp_fin_timeout
CLOSE-WAITPeer closed, we have not called close()A bug in our code: missing Close() / defer
LAST-ACKWe closed after the peer, waiting for the final ACKBrief; many means a lossy path
TIME-WAITWe closed first; tuple kept for 2MSLMany short connections without keep-alive

The errors.

errno / messageMeaningFirst move
ECONNREFUSED "connection refused"The host answered with RST: nothing listens on that portIs the service up, on that port, on that interface (127.0.0.1 vs 0.0.0.0)?
ETIMEDOUT / connect timeoutNo answer at all: packets droppedFirewall/security group, wrong IP, full SYN or accept queue
EADDRINUSE "address already in use"Another socket holds this local addressOld process still running; or set SO_REUSEADDR
EADDRNOTAVAIL "cannot assign requested address"No free ephemeral port for this destinationKeep-alive and pools; widen ip_local_port_range
EMFILE "too many open files"This process hit its fd limitFind leaks (lsof -p), then raise ulimit -n
ECONNRESET "connection reset by peer"We received a RST mid-conversationPeer crashed, middlebox idle timeout, peer closed with unread data
EPIPE "broken pipe"We wrote after the connection was already closedSame causes; handle as "peer gone" and retry safely

Why it exists ​

A host has one network interface (or a few) and runs hundreds of programs. IP addresses get a packet to the host; something has to get it to the right program and to the right conversation inside that program. Ports pick the program, the 5-tuple picks the conversation, and a socket is the program's handle on it. TCP then has to make a reliable byte stream out of a network that drops, duplicates and reorders packets, so each connection carries state (sequence numbers, windows, timers), and that state cannot vanish the moment you call close(), because a late packet from the old connection could corrupt a new one with the same tuple. Every limit on this page follows from those two facts: names are finite, and state outlives your code.

Cheap and statelessReliable and stateful
UDP: no handshake, no connection state, no backpressureTCP: handshake, per-connection state, flow control
Nothing to clean up after a datagramTIME_WAIT, CLOSE_WAIT, FIN_WAIT linger after close
Lost data is the application's problemThe kernel retransmits, and timers decide when to give up
A NAT keeps a short timer per flow (30 s for UDP in conntrack)A NAT keeps established flows for days, or for 350 s in a cloud NAT
Scales with packetsScales with connections: ports, fds, memory, conntrack entries

The analogy we reuse on this page: a hotel switchboard. The hotel's street address is the IP. The room number is the port: the front desk (well-known port 80 or 5432) is always the same room; guests calling out get a temporary extension (an ephemeral port) for the length of the call. A call is identified by both extensions and both hotels (the 5-tuple). Each open line uses a jack on the switchboard (a file descriptor); the switchboard has a fixed number of jacks. After a caller hangs up first, the operator keeps that extension reserved for a minute in case a late "are you still there?" arrives (TIME_WAIT). If the other side hung up but the receptionist never puts the handset down, the line stays busy forever (CLOSE_WAIT). Callers who ring while every receptionist is busy wait in a short hold queue; when it is full they hear nothing and redial (the accept queue and SYN retries).

Three common misunderstandings, up front ​

  1. "TIME_WAIT is a problem to tune away." TIME_WAIT is TCP working correctly. Thousands of TIME_WAIT sockets are a symptom of opening a new connection per request; the fix is keep-alive and pools, not kernel flags.
  2. "Connection refused and connection timed out are the same failure." Refused means a host answered with RST in milliseconds: the network is fine, the port is closed. Timeout means nothing answered: a firewall, a wrong address, or a full queue dropped your packets. They point at different teams.
  3. "An ESTABLISHED socket means the peer is alive." TCP sends nothing on an idle connection. A peer that crashed, or a NAT that forgot the flow, leaves you with a socket that looks fine until you write to it. Only keepalive, heartbeats or a read timeout tell you.

Where it comes from ​

TCP was specified in RFC 793 (1981) and re-issued as RFC 9293 in 2022, which consolidates decades of updates. Its state diagram is the source of every state name ss prints, and it defines MSL as "the time a TCP segment can exist in the internetwork system. Arbitrarily defined to be 2 minutes." Linux does not wait 2 × 2 minutes: its kernel header defines TCP_TIMEWAIT_LEN (60*HZ) "about 60 seconds", and macOS sets net.inet.tcp.msl to 15 000 ms, so 30 s.

UDP is RFC 768 (1980), three pages long: "delivery and duplicate protection are not guaranteed." Port numbers are governed by RFC 6335, which splits them into "the System Ports, also known as the Well Known Ports, from 0-1023", "the User Ports, also known as the Registered Ports, from 1024-49151" and "the Dynamic Ports, also known as the Private or Ephemeral Ports, from 49152-65535 (never assigned)". Linux ignores the last range and uses 32768–60999 by default (ip_local_port_range); macOS follows the RFC with 49152–65535. RFC 6056 discusses how stacks pick an ephemeral port so that it is hard to guess.

Keepalive comes from RFC 1122 (1989), which allowed it reluctantly: keep-alives "MUST default to off" and the interval "MUST default to no less than two hours" — which is why Linux's tcp_keepalive_time is still 7200 s. Nagle's algorithm is RFC 896 (1984): "inhibit the sending of new TCP segments when new outgoing data arrives from the user if any previously transmitted data on the connection remains unacknowledged."

The programming interface is the BSD sockets API from 4.2BSD (1983): socket, bind, listen, accept, connect, send/recv, close, and setsockopt for the knobs. Every language wraps it: Go's net package, PHP's streams and ext/sockets, libcurl under Guzzle, libpq under PDO. Linux documents the behaviour in socket(7), tcp(7), ip(7), udp(7), unix(7) and listen(2); the sysctl list lives in the kernel's ip-sysctl and nf_conntrack-sysctl documents. The conntrack table is part of Linux netfilter; it exists because NAT and stateful firewalls must remember flows.

The concept catalogue ​

Every block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, per-product behaviour, and the fix in Go and Laravel (full code in Solving the classic problems).

Ports and port ranges Must-know ​

In plain words: a port is a 16-bit number (0–65535) that, together with an IP address and a protocol, picks one socket on a host. Servers listen on a fixed, known port; clients get a random temporary one.

Common misunderstanding: "Ports below 1024 need root." On a classic Linux host, yes, but the threshold is net.ipv4.ip_unprivileged_port_start (default 1024) or the CAP_NET_BIND_SERVICE capability, and Docker sets it to 0 inside containers, which is why an unprivileged nginx in a container can bind port 80. Another one: "TCP port 53 and UDP port 53 are the same port." They are separate namespaces; DNS uses both.

Definition: RFC 6335 ranges: System/Well-Known 0–1023, User/Registered 1024–49151, Dynamic/Ephemeral 49152–65535. The kernel picks a client's local port from ip_local_port_range (Linux default 32768 60999, about 28 232 ports) when you connect() without bind(). The kernel docs add: "If possible, it is better these numbers have different parity" and the range "Must be greater than or equal to ip_unprivileged_port_start."

text
1  server: socket(); bind(0.0.0.0:5432); listen()     -> fixed, well-known port
2  client: socket(); connect(10.0.1.9:5432)           -> kernel picks 10.0.0.5:41516 from 32768-60999
3  the connection is (tcp, 10.0.0.5, 41516, 10.0.1.9, 5432)
4  client closes; port 41516 is free again only after TIME_WAIT (60 s) for THAT destination

Real scenario: a node whose ip_local_port_range had been widened to 1024 65535 for a busy proxy: a Kubernetes NodePort (30000–32767) now sits inside the ephemeral range, an outbound connection takes that local port, and the NodePort bind fails — the reason to set ip_local_reserved_ports before widening. A Laravel worker hard-codes 127.0.0.1:6379 but Redis in Compose listens on the redis service name: refused. A second copy of a Go service started on the same port fails with listen tcp :8080: bind: address already in use (captured in the lab).

Ports a backend developer must know.

PortProtocolServiceNote
22TCPSSHSee VPNs & Tunnels for ssh -L
53UDP and TCPDNSTCP for large answers and zone transfers
80 / 443TCP (443 also UDP for HTTP/3)HTTP / HTTPSQUIC is UDP 443
3306TCPMySQL / MariaDB33060 is MySQL X Protocol
5432TCPPostgreSQLPgBouncer often 6432
6379TCPRedis26379 Sentinel, 16379 cluster bus
5672 / 15672TCPRabbitMQ AMQP / management UI5671 AMQP over TLS
9092TCPKafka broker9093 often the controller or TLS listener
27017TCPMongoDB
9042TCPCassandra / ScyllaDB CQL7000 inter-node
8080TCPConventional alternative HTTP (Octane uses 8000 by default)Not reserved; just a habit
9000TCPphp-fpm FastCGI (also MinIO)Never publish it on the host
11211TCP/UDPMemcached
2375 / 2376TCPDocker API plain / TLSPlain 2375 exposed = root on the host

Per OS:

SettingLinuxmacOS (measured on this machine)
Ephemeral rangenet.ipv4.ip_local_port_range = 32768 60999net.inet.ip.portrange.first/last = 49152 65535
Privileged portsbelow ip_unprivileged_port_start (1024 on a host; 0 measured inside Docker)below 1024
Reserve ports from the ephemeral poolnet.ipv4.ip_local_reserved_ports—

Fix / how to use it: bind servers to a port outside the ephemeral range; in containers listen on 0.0.0.0 (not 127.0.0.1) so the published port can reach you; put dependency ports in config (DB_PORT, REDIS_PORT) not code. The Laravel command net:probe and Go's dialerrors check each dependency's port.

Sockets are file descriptors Must-know ​

In plain words: a socket is a kernel object; your program holds it as a small integer, the file descriptor, the same kind of handle as an open file. A server has one listening socket and one more socket per accepted connection.

Common misunderstanding: "A server on port 8080 can only have one connection per client port, so it runs out at 65 535 connections." The server's side of every connection uses port 8080; what makes each connection unique is the client's IP and port. A server can hold millions of connections on one port; the limits are fds and memory, not ports.

Definition: the system calls, in order:

CallSideWhat it doesCommon error
socket(AF_INET, SOCK_STREAM, 0)bothCreates the object, returns an fdEMFILE, ENFILE
setsockopt(...)bothSO_REUSEADDR, SO_REUSEPORT, SO_KEEPALIVE, TCP_NODELAY, buffersEINVAL
bind(addr:port)server (client optional)Claims a local addressEADDRINUSE, EACCES (privileged port)
listen(backlog)serverMarks it passive; creates the accept queue
accept()serverPops one finished connection, returns a NEW fdEMFILE (then the queue keeps filling)
connect(addr:port)clientPicks an ephemeral port, runs the handshakeECONNREFUSED, ETIMEDOUT, EADDRNOTAVAIL, ENETUNREACH
read/write (recv/send)bothMoves bytes through the kernel buffersECONNRESET, EPIPE, EAGAIN
shutdown(SHUT_WR)bothSends FIN but keeps reading (half-close)
close()bothReleases the fd; sends FIN (or RST if unread data is pending)
text
     server process                        kernel                             client
1    fd3 = socket(); bind(:9000); listen()  LISTEN *:9000 (fd3)
2                                           <- SYN 172.21.0.6:51198            connect()
3                                           -> SYN+ACK, <- ACK: queued in accept queue
4    fd4 = accept(fd3)                      ESTAB 172.21.0.2:9000 <-> 172.21.0.6:51198 (fd4)
5    fd5 = accept(fd3)                      ESTAB 172.21.0.2:9000 <-> 172.21.0.6:51200 (fd5)
6    fd3 still listening; fd4 and fd5 are independent connections on the SAME local port

The 5-tuple (protocol, source IP, source port, destination IP, destination port) is the identity of a connection. Two sockets can share four of the five fields; they cannot share all five. That is the whole reason ephemeral ports run out: towards one database at 10.0.1.9:5432, from one client IP, only the source port can vary.

container A172.17.0.2:41516container B172.17.0.3:41516host / NAT gatewaySNAT (MASQUERADE) + conntrackA: 172.17.0.2:41516 → 10.0.0.5:41516B: 172.17.0.3:41516 → 10.0.0.5:52007same port taken? NAT picks anothernf_conntrack_max; full table ="table full, dropping packet"database10.0.1.9:5432The 5-tuple names one connection: (protocol, src IP, src port, dst IP, dst port)(tcp, 10.0.0.5, 41516, 10.0.1.9, 5432) and (tcp, 10.0.0.5, 52007, 10.0.1.9, 5432) are two connections.For one destination ip:port only the source port varies: about 28 000 ports (32768–60999) per source IP.Each closed connection keeps its tuple in TIME_WAIT for 60 s on the side that closed first, so the limit isroughly 28 000 / 60 ≈ 470 new connections per second per destination. Pools and keep-alive remove the limit;more source IPs or more destination IPs/ports raise it.

Real scenario: lsof -p <pid> on a Go API shows fd 3 as TCP *:8080 (LISTEN) and fds 4…900 as ESTABLISHED; each is one client. A php-fpm child holds one fd for the FastCGI socket and one per DB/Redis connection it opened. A Go response body that is never closed keeps its connection, and its fd, busy for good.

RuntimeListening socketPer-connectionHow you see the fd
Go netnet.Listen → *net.TCPListenerAccept() → net.Conn, one goroutine eachlsof -p, /proc/<pid>/fd
php-fpmmaster holds the listen socket, children inherit iteach child accept()s one FastCGI request at a timess -xlp for the socket, lsof -p per child
Octane (Swoole/RoadRunner/FrankenPHP)server process listens (8000 by default)workers keep app state, DB/Redis sockets between requestsss -tnp
nginxeach worker inherits listeners (or reuseport)event loop, thousands per workerss -tnp
PostgreSQLpostmaster listens on 5432 and a Unix socketone backend PROCESS per connectionpg_stat_activity

Fix / how to use it: always close what you open (defer conn.Close(), resp.Body.Close()); bound connection counts with pools; watch the fd count as a metric. Go code: labserver.

Connection states Must-know ​

In plain words: TCP is a state machine. Opening takes three messages; closing takes four (each direction is closed separately). The side that closes first walks through FIN_WAIT to TIME_WAIT; the side that closes second walks through CLOSE_WAIT to LAST_ACK.

Common misunderstanding: "TIME_WAIT is on the server." It is on whichever side called close() first. With HTTP/1.1 keep-alive the client usually closes first; with Connection: close or an idle timeout, the server does. In the lab, short client-closed connections left 20 000 TIME_WAIT on the client and none on the server.

Definition: RFC 9293 Figure 5 names eleven states: LISTEN, SYN-SENT, SYN-RECEIVED, ESTABLISHED, FIN-WAIT-1, FIN-WAIT-2, CLOSE-WAIT, CLOSING, LAST-ACK, TIME-WAIT, CLOSED. ss prints them with dashes (TIME-WAIT), netstat and lsof with underscores (TIME_WAIT).

Active side (client, closes first)Passive side (server)connect() … close()listen() accept() … close()CLOSEDLISTENSYN_SENTSYN_RECVESTABLISHEDESTABLISHEDFIN_WAIT_1CLOSE_WAITFIN_WAIT_2LAST_ACKTIME_WAITCLOSEDCLOSEDSYNSYN+ACKACK (handshake done)data both ways, 5-tuple fixedFIN (client called close)ACKFIN (server finally called close)ACKapp got EOF but has notcalled close(): a CLOSE_WAITpile-up is an app bugwaits 2×MSL (Linux: 60 s, macOS: 30 s)and holds the local ephemeral portorphan FIN_WAIT_2 ends after tcp_fin_timeout

The real capture from the lab, client 172.21.0.6 sends ping to the echo server 172.21.0.2:9000 and closes first:

text
1  .6.51198 > .2.9000: Flags [S],  seq 2720448920                    client SYN_SENT
2  .2.9000 > .6.51198: Flags [S.], seq 2986156317, ack 2720448921    server SYN_RECV
3  .6.51198 > .2.9000: Flags [.],  ack 2986156318                    both ESTABLISHED
4  .6.51198 > .2.9000: Flags [P.], seq 2720448921:2720448926, length 5   "ping\n"
5  .6.51198 > .2.9000: Flags [F.], seq 2720448926                    client FIN_WAIT_1
6  .2.9000 > .6.51198: Flags [P.], seq 2986156318:2986156323, length 5   echo arrives anyway (half-close)
7  .2.9000 > .6.51198: Flags [F.], seq 2986156323                    server CLOSE_WAIT -> LAST_ACK
8  .6.51198 > .2.9000: Flags [.],  ack 2986156324                    client TIME_WAIT, server CLOSED

(Flags: S SYN, . ACK, P PUSH, F FIN, R RST.)

StateSideLeaves whenTimer / knob
SYN-SENTclientSYN/ACK arrives, or retries exhaustedtcp_syn_retries (6), tcp_syn_linear_timeouts (4)
SYN-RECVserverfinal ACK arrivestcp_synack_retries (5)
ESTABLISHEDbothsomeone closeskeepalive, TCP_USER_TIMEOUT
FIN-WAIT-1active closerACK of FINretransmission
FIN-WAIT-2active closerpeer's FINorphaned sockets: tcp_fin_timeout (60 s)
CLOSE-WAITpassive closerYOUR app calls close()none: no timer at all
LAST-ACKpassive closerACK of its FINretransmission
CLOSINGboth closed at onceACK of FINrare
TIME-WAITactive closer2MSL passes60 s fixed on Linux; tcp_max_tw_buckets caps the count

Fix / how to use it: read the states as symptoms with the table in Everything in one minute; count them per state as a metric with the Go sockstat program or ss -s.

TIME_WAIT Must-know ​

In plain words: after you close first, the kernel keeps the connection's tuple for 2MSL so that late packets from the old connection die out and so that a lost final ACK can be resent. The socket holds no fd and almost no memory, but it does hold the local port towards that destination.

Common misunderstanding: "Set tcp_tw_recycle or tcp_fin_timeout to make TIME_WAIT shorter." tcp_tw_recycle broke clients behind NAT and is gone (it no longer appears in the kernel's ip-sysctl document). tcp_fin_timeout controls orphaned FIN-WAIT-2, not TIME_WAIT; tcp(7) says it is "how many seconds to wait for a final FIN packet before the socket is forcibly closed." On Linux, TIME_WAIT is the compile-time TCP_TIMEWAIT_LEN of 60 s.

Definition: RFC 9293: an actively closed connection "MUST linger in the TIME-WAIT state for a time 2xMSL". Two reasons: (1) if the final ACK is lost, the peer resends FIN and we must answer with ACK, not RST; (2) a delayed duplicate segment from the old connection must not be accepted by a new connection with the same 5-tuple. tcp_tw_reuse lets an outgoing connect() take over a TIME_WAIT tuple "when it is safe from protocol viewpoint" (TCP timestamps prove the new segments are newer). The kernel docs list 0 disable, 1 global enable, 2 "enable for loopback traffic only", with default 2 (older tcp(7) pages still say "disabled"), and tcp_tw_reuse_delay (1000 ms on the lab kernel) as the minimum age before reuse.

text
     client (closes first)                                  server
1    connect() from :32768; send request; read reply
2    close()  -> FIN                                         CLOSE_WAIT -> close() -> LAST_ACK
3    FIN_WAIT_2 <- FIN ; send ACK -> TIME_WAIT              CLOSED (no state left)
4    port 32768 towards server:9000 is reserved for 60 s
5    repeat 20 000 times in 1.2 s -> 20 000 TIME_WAIT on the CLIENT, 0 on the server

Real output from the lab (twgen -mode short, 20 000 exchanges):

text
mode=short ok=20000 eaddrnotavail=0 refused=0 other=0 elapsed=1.184s
TCP:   20082 (estab 0, closed 20081, orphaned 0, timewait 20000)
172.21.0.3:32768   172.21.0.2:9000 timer:(timewait,58sec,0)

Real scenario: a PHP script calling an internal API with Connection: close in a loop; a Go service that builds a new http.Client{} (and Transport) per request; a health checker opening a TCP connection every second to 500 targets; a load test client with keep-alive off. In all of them TIME_WAIT is harmless until it covers the whole ephemeral range for one destination.

PlatformTIME_WAIT lengthReuse knobCount cap
Linux60 s (TCP_TIMEWAIT_LEN)net.ipv4.tcp_tw_reuse 0/1/2, default 2; tcp_tw_reuse_delaytcp_max_tw_buckets (excess sockets are destroyed immediately)
macOS / FreeBSD2 × net.inet.tcp.msl = 2 × 15 000 ms = 30 snone for outgoing—
Docker containerown network namespace: own TIME_WAIT table and its own tcp_tw_reuse--sysctl net.ipv4.tcp_tw_reuse=1

Fix / how to use it: reuse connections (HTTP keep-alive, http.Transport shared, DB pools, Redis client pools); let the server close first only when it must; as a second line, tcp_tw_reuse=1 for outgoing connections on clients (it does not help a burst younger than tcp_tw_reuse_delay: in the lab a 5 000-connection burst over 1 000 ports still failed, while a second burst 2 s after the first succeeded). Never use SO_LINGER with timeout 0 to "avoid" TIME_WAIT on a normal path: it turns every close into a RST and the peer sees ECONNRESET.

Ephemeral port exhaustion Must-know ​

In plain words: a client that opens new connections to the same server faster than TIME_WAIT releases them runs out of local ports. connect() then fails at once with EADDRNOTAVAIL, "cannot assign requested address".

Common misunderstanding: "We have 65 535 ports, so we can open 65 535 connections per second." Linux uses about 28 000 ports by default, and each one is blocked for 60 s after a client-side close: roughly 28 000 / 60 ≈ 470 new connections per second per destination IP:port, from one source IP. And it is per destination: the same port can be reused at the same time towards a different server.

Definition: connect(2): EADDRNOTAVAIL "(Internet domain sockets) The socket referred to by sockfd had not previously been bound to an address and, upon attempting to bind it to an ephemeral port, it was determined that all port numbers in the ephemeral port range are currently in use."

text
1  ip_local_port_range = 50000 50999 (1 000 ports, narrowed for the lab)
2  burst of 5 000 short connections, client closes first
3  ok=999   eaddrnotavail=4001        (999 ports in TIME_WAIT)
4  run again within 60 s: ok=0 eaddrnotavail=5000
5  same work with ONE kept-alive connection per worker: ok=20000 eaddrnotavail=0 elapsed=77ms

Real scenario: a PHP-FPM fleet calling a payment API through one NAT gateway: the NAT's ports (not the servers') run out, because all servers share the NAT's public IP; AWS's troubleshooting page lists it as "Cannot initiate more connections". A Go service behind Docker's default bridge: every container's connection is SNAT-ed to the host IP, so containers compete for the host's ports. A Laravel queue worker that dispatches 10 000 webhooks with a fresh client each.

Where the ports run outWho shares the portsDetectFix
The client hostAll processes on that IPss -s timewait count, EADDRNOTAVAILKeep-alive, pools, tcp_tw_reuse=1
Docker host (bridge SNAT)All containers on the hostconntrack count, errors in many containers at oncePools; --network host for heavy clients
Cloud NAT gatewayAll instances in the subnetAWS: "Cannot initiate more connections"; each NAT IPv4 address "can support up to 55,000 concurrent connections"Pools, close idle connections, more NAT IPs
Kubernetes node SNATAll pods on the nodeconntrack insert_failedPools; see Kubernetes Networking

Fix / how to use it: a shared http.Transport with MaxIdleConnsPerHost raised from its default of 2 (httpclient); in Laravel the keepAlive macro under Octane or queue workers (HttpKeepAliveServiceProvider); database pools and PgBouncer (Connection Pooling). Widen ip_local_port_range to 1024 65535 only after reserving your listen ports with ip_local_reserved_ports.

CLOSE_WAIT leaks Must-know ​

In plain words: the peer closed its side and the kernel told your program (a read returned EOF), but your program never called close(). The socket stays in CLOSE_WAIT forever, holding an fd.

Common misunderstanding: "CLOSE_WAIT will time out like TIME_WAIT." There is no CLOSE_WAIT timer. The kernel is waiting for your application. Only close(), process exit, or ss -K (kill) ends it.

Definition: RFC 9293: in CLOSE-WAIT the connection is "waiting for a connection termination request from the local user". The fix is always in application code.

text
     client                                   server (bug: no Close on EOF)
1    connect, send "hi\n", read "hi\n"
2    close() -> FIN                           read() returns EOF; handler returns WITHOUT conn.Close()
3    FIN_WAIT_2 (orphan; dies after 60 s)     CLOSE_WAIT ... forever, fd 7 still open
4    after 10 000 such clients                accept: too many open files

Real output from the lab (labserver -leak):

text
$ ss -tanp state close-wait
0 0 [::ffff:172.21.0.5]:9200 [::ffff:172.21.0.6]:46034 users:(("labserver",pid=1,fd=7))
$ lsof -nP -p 1 -a -i
labserver 1 root 7u IPv6 270543 0t0 TCP 172.21.0.5:9200->172.21.0.6:46034 (CLOSE_WAIT)

Real scenario: Go: an early return before defer conn.Close() or a resp.Body never closed; PHP: a long-running Octane worker or ReactPHP loop that drops the stream reference without fclose; Java/Node: connection pool bugs where an evicted connection is never closed; any proxy whose upstream closed while the downstream is still idle.

Language / runtimeWhere CLOSE_WAIT comes fromGuard
Gomissing conn.Close(), resp.Body.Close(), rows.Close()defer right after the error check; bodyclose linter
PHP-FPMrare: process state dies with the request—
PHP long-running (Octane, workers, Swoole)streams kept in static propertiesclose in finally; --max-requests / --max-jobs recycles
Proxies (nginx, Envoy)upstream closed, client idleidle timeouts on both sides

Fix / how to use it: close in the same function that opened it; set read deadlines so a handler that waits forever ends (labserver); export CLOSE_WAIT count as a metric and alert when it only grows.

Backlog and the accept queue Important ​

In plain words: the kernel completes TCP handshakes for you and parks the finished connections in a queue until your program calls accept(). If your program is slower than the arrivals, the queue fills and new clients wait or time out, even though the process is "up".

Common misunderstanding: "listen(fd, 65535) gives me a 65 535-deep queue." listen(2): "If the backlog argument is greater than the value in /proc/sys/net/core/somaxconn, then it is silently capped to that value. Since Linux 5.4, the default in this file is 4096; in earlier kernels, the default value is 128." Also: a bigger queue only hides a slow server; requests wait longer instead of failing fast.

Definition: Linux keeps two queues per listener. The SYN queue holds half-open connections (SYN-RECV), bounded by tcp_max_syn_backlog ("The maximum number of queued connection requests which have still not received an acknowledgement"). The accept queue holds completed connections, bounded by the listen() backlog capped at somaxconn. When the SYN queue overflows, SYN cookies (tcp_syncookies=1) let the kernel answer without storing state — tcp(7) calls them a last resort that "attempts to protect a socket from a SYN flood attack". When the accept queue is full, the kernel drops the SYN or the final ACK (or sends RST if tcp_abort_on_overflow=1), and the client retransmits.

clientsSYNSYN queuehalf-open, state SYN_RECVtcp_max_syn_backlogAccept queuehandshake done, ESTABLISHEDmin(backlog, somaxconn)your appaccept()Overflow (app too slow to accept)accept queue full: SYN or final ACK dropped, ListenOverflows/ListenDrops count upclient retransmits SYN (1 s, 1 s, 1 s … then backoff) and finally ETIMEDOUTSYN queue full: SYN cookies (tcp_syncookies=1) answer without storing stateSYNACKfdss -ltn on a listener:Recv-Q = connections waiting in the accept queue nowSend-Q = the accept queue limit (effective backlog)Go net.Listen and nginx: backlog follows somaxconn / listen … backlog=php-fpm: listen.backlog (511 on Linux), capped by somaxconn
text
1  server: listen() with somaxconn=4, never calls accept()   ss: LISTEN Recv-Q 0 Send-Q 4
2  10 clients connect at once
3  5 handshakes complete -> accept queue                       ss: LISTEN Recv-Q 5 Send-Q 4
4  5 clients stay SYN-SENT; their SYNs are dropped
5  client SYN retries at +1 s, +1 s, +1 s, +1 s, then 2 s, 4 s ... (tcp_syn_linear_timeouts=4)
6  nstat: TcpExtListenOverflows 20, TcpExtListenDrops 20
7  client with a 2 s connect timeout: "TIMEOUT"; with none: 133 s (measured) then ETIMEDOUT

Real scenario: a php-fpm pool with pm.max_children all busy: nginx's connections queue in the fpm socket backlog, then nginx's connect() to the socket fails with EAGAIN and the user gets 502s. A Go server whose handlers block on a saturated DB: Go's accept loop keeps up, so the queue is not the issue — the goroutine count is. A Node.js server with a CPU-bound event loop: accept stalls, the queue overflows, clients see slow connects. A deploy where the new process listens only after a 30 s warm-up: the old one is gone, connections are refused.

ServerBacklog settingDefault
Linux kernelnet.core.somaxconn cap; tcp_max_syn_backlog4096 (since 5.4); 1024 or more
Go net.Listenno parameter; reads somaxconnfollows somaxconn (4096 in the lab)
nginxlisten 80 backlog=N"511 on other platforms" (-1 on FreeBSD, macOS)
php-fpmlisten.backlog511 on Linux, -1 (max) on BSD
PostgreSQLno knob; max_connections limits backends100
Redistcp-backlog511 (redis.conf)

Fix / how to use it: accept fast and do work elsewhere (Go does this by design); size worker pools (pm.max_children, Octane --workers) to the load; watch ListenOverflows; set a short client connect timeout so a full queue fails fast and the client retries another instance.

Keepalive: TCP keepalive, HTTP keep-alive and app heartbeats Must-know ​

In plain words: three different things share one name. TCP keepalive is the kernel sending empty probes on an idle connection to detect a dead peer and to keep NAT entries warm. HTTP keep-alive (persistent connections) means reusing one TCP connection for many HTTP requests. Application heartbeats (AMQP heartbeats, WebSocket ping/pong, Redis PING) are messages your protocol sends to prove the other process, not just the kernel, is alive.

Common misunderstanding: "I set Connection: keep-alive, so idle connections survive the NAT." HTTP keep-alive sends nothing while idle; a NAT gateway or load balancer with an idle timeout still drops the flow. And "TCP keepalive is on by default": RFC 1122 says it "MUST default to off", and Linux waits tcp_keepalive_time = 7200 s (2 h) before the first probe, long after any cloud NAT forgot you.

Definition: Linux knobs from tcp(7): tcp_keepalive_time 7200 s ("Keep-alives are sent only when the SO_KEEPALIVE socket option is enabled"), tcp_keepalive_intvl 75 s, tcp_keepalive_probes 9: a dead peer is detected after about 2 h 11 min by default. Per socket: SO_KEEPALIVE, TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT. RFC 9112: HTTP/1.1 defaults to the use of “persistent connections”; Connection: close ends one.

text
1    t=0      app sends query on pooled connection; idle afterwards
2    t=350s   AWS NAT gateway drops the idle flow (no FIN, no RST to anyone)
3    t=600s   app writes the next query on the "ESTABLISHED" socket
4    NAT has no entry -> "returns an RST packet" -> app: ECONNRESET / "server closed the connection unexpectedly"
     with TCP keepalive every 60 s: the NAT sees traffic, the flow never goes idle

Real scenario: Laravel queue workers lose their PostgreSQL connection overnight behind a NAT; a RabbitMQ consumer is silently disconnected by an LB after 1 hour of quiet; a WebSocket through an ALB dies after 60 s without pings; nginx closes an upstream keep-alive connection exactly when the Go client reuses it (race at the server's idle timeout).

ComponentIdle timeout / keepalive defaultSource
Linux TCP keepalive7200 s idle, 75 s interval, 9 probes; off unless SO_KEEPALIVEtcp(7)
Go net.Dialer / ListenConfigkeepalive on: 15 s idle, 15 s interval, 9 probes (KeepAliveConfig defaults)go doc net.KeepAliveConfig
Go http.TransportIdleConnTimeout 90 s in DefaultTransport, MaxIdleConnsPerHost 2Go source transport.go
AWS NAT gatewaydrops idle flows after 350 s, sends RSTAWS VPC docs
AWS ALBconnection idle timeout 60 s defaultELB docs
nginx (client side)keepalive_timeout 75snginx core module
nginx (upstream)keepalive 32 idle connections per worker by default since 1.29.7nginx upstream module
Redistimeout 0 (never close idle clients); tcp-keepalive 300 since 3.2Redis client handling docs, redis.conf
MySQLwait_timeout 28 800 s (8 h)MySQL 8.4 server variables
PostgreSQL / libpqclient keepalives_idle etc.; 0 = system defaultlibpq docs
PgBouncerserver_idle_timeout closes idle server connectionsPgBouncer config

The rule: each hop's idle timeout must be longer than the hop in front of it, and keepalive/heartbeat intervals must be shorter than the shortest idle timeout on the path. AWS puts it directly: configure "the idle timeout of your application to be larger than the idle timeout configured for the load balancer."

Fix / how to use it: Go KeepAliveConfig{Idle: 60s} on dialers and listeners (labserver, httpclient); Laravel pgsql keepalives_idle => 60 (database.php); client idle timeouts below server idle timeouts (Go IdleConnTimeout 50 s against nginx's 75 s).

Nagle and delayed ACK Good to know ​

In plain words: Nagle's algorithm holds back small writes while earlier data is unacknowledged, to avoid sending many tiny packets. The receiver's delayed ACK waits a little before acknowledging. Together, a "write, write, read" pattern can stall for up to tens of milliseconds per request.

Common misunderstanding: "My Go service needs TCP_NODELAY." Go already sets it: SetNoDelay doc says the "default is true (no delay)". PHP streams, many C clients and Java sockets leave Nagle on.

Definition: tcp(7) TCP_NODELAY: "If set, disable the Nagle algorithm. This means that segments are always sent as soon as possible, even if there is only a small amount of data." TCP_CORK is the opposite: collect until uncorked. Delayed ACK is per-stack (Linux: TCP_QUICKACK turns it off temporarily).

text
1  client: write(header 20 B)     -> sent immediately (nothing unacked)
2  client: write(body 30 B)       -> HELD by Nagle: header not yet ACKed
3  server: got header, waits for body; delays its ACK (delayed ACK)
4  ~40 ms later the server's delayed ACK fires -> client sends body
5  fix: one write (buffer header+body) or TCP_NODELAY
Stack / clientNagle by defaultTurn off
Go netoff (NoDelay true)(*TCPConn).SetNoDelay(true) (already)
PHP streamsonstream context socket option tcp_nodelay => true
libcurl (Guzzle)off: CURLOPT_TCP_NODELAY "is set by default" (since 7.50.2)—
Redis, PostgreSQL serversset TCP_NODELAY on their sockets—

Fix / how to use it: buffer a request and write it once (bufio.Writer.Flush); in PHP raw sockets, set tcp_nodelay.

Buffers and the window Good to know ​

In plain words: each socket has a send buffer and a receive buffer in the kernel. The receiver advertises how much free space it has (the window); a slow reader shrinks the window and the sender's write blocks. That is TCP's backpressure.

Common misunderstanding: "write() returned, so the peer has the data." It means the bytes are in YOUR kernel's send buffer. The peer may never get them if the connection dies; only an application-level reply confirms receipt.

Definition: SO_SNDBUF / SO_RCVBUF set per-socket sizes; socket(7): "The kernel doubles this value (to allow space for bookkeeping overhead)". tcp_rmem / tcp_wmem are min default max vectors for autotuning (lab: 4096 131072 33554432 and 4096 16384 4194304), limited by net.core.rmem_max/wmem_max. The window scale option (wscale 10 in the capture) multiplies the 16-bit window by 2^10. ss -tm shows per-socket memory (skmem), ss -ti shows rtt, cwnd, rcv_space.

text
1  producer writes 1 MiB; consumer reads 1 KiB per second
2  consumer's receive buffer fills -> advertised window 0
3  producer's send buffer fills -> write() blocks (or EAGAIN for non-blocking)
4  sender probes with zero-window probes (ss -o: timer:(persist,...))
5  with a write deadline: Go returns "i/o timeout"; without: blocks until the consumer reads
SymptomBuffer causeLook at
Large Recv-Q on an ESTAB socketapp not reading fast enoughthe reader
Large Send-Q on an ESTAB socketpeer not reading, or network slowthe peer, ss -ti rtt/retrans
Throughput capped on a long fat linktcp_rmem max too small for bandwidth × RTTiperf3, raise rmem_max
UDP drops (UdpRcvbufErrors)receive buffer too small for burstsSO_RCVBUF, faster reader

Fix / how to use it: set write deadlines so a stuck peer cannot block a goroutine forever; leave autotuning alone unless iperf3 shows a bandwidth-delay problem.

Timeouts and half-open connections Must-know ​

In plain words: every network call needs a deadline, and there are several kinds: how long to wait for the handshake (connect), for a reply to start (response header / first byte), for data between reads (read), for the whole request (total), and how long an idle pooled connection may sit (idle).

Common misunderstanding: "My HTTP client has a 30 s timeout, so a dead server costs me at most 30 s." Only if that timeout is a total deadline. Go's http.Client has Timeout: 0 (none) by default; net.Dial without a timeout waits for the kernel's SYN retries (an untimed nc against the full queue in the lab gave up after 133 s, with tcp_syn_retries=6). A half-open connection (the peer vanished without FIN or RST) never errors on read; it waits for data that will never come.

Definition:

TimeoutProtects againstGoLaravel / PHP
Connectdropped SYNs, dead hostsnet.Dialer.Timeout, DialContext with deadlineHttp::connectTimeout() (10 s default), PDO::ATTR_TIMEOUT, stream_socket_client($t, timeout)
TLS handshakeslow or hostile TLS peerTransport.TLSHandshakeTimeoutcURL inside connect timeout
Response header / TTFBserver accepted but hangsTransport.ResponseHeaderTimeoutHttp::timeout() covers it
Total requestanythinghttp.Client.Timeout, context.WithTimeoutHttp::timeout() (30 s default)
Read / write (raw socket)stuck peer, zero windowconn.SetReadDeadline / SetWriteDeadlinestream_set_timeout
Server read headerslowlorishttp.Server.ReadHeaderTimeoutnginx client_header_timeout
Server writeslow readershttp.Server.WriteTimeoutnginx send_timeout, fpm request_terminate_timeout
Idle keep-alive (server)idle clients holding socketshttp.Server.IdleTimeoutnginx keepalive_timeout
Idle pooled (client)reusing a conn the server just closedTransport.IdleConnTimeoutGuzzle/cURL reuse; DB::disconnect() on idle
Unacked datadead peer while sendingTCP_USER_TIMEOUT via Controllibpq tcp_user_timeout
text
1  t=0    client sends request on pooled connection
2  t=0.1  server host loses power (no FIN, no RST)
3  t=0.1… client waits in read(); the kernel retransmits the request (tcp_retries2)
4         without a deadline: tcp_retries2=15, "approximately between 13 to 30 minutes" until ETIMEDOUT
5         with Client.Timeout 10 s: error at t=10 s, connection discarded, retry elsewhere

Real scenario: a payment call with no timeout blocks all 40 php-fpm children; a Go service with the zero http.Server keeps 50 000 slowloris connections open; a queue job hangs forever on a Redis read after a failover.

Fix / how to use it: set all of them explicitly (httpserver, httpclient, PaymentGatewayClient); keep connect timeouts short (1–3 s inside a data centre) and total timeouts tied to the caller's own deadline via context.

conntrack Important ​

In plain words: when a Linux host does NAT or stateful firewalling (Docker, Kubernetes kube-proxy in iptables mode, any iptables -m state rule), it remembers every flow in the connection-tracking table. The table has a maximum size; when it is full, new connections are dropped.

Common misunderstanding: "conntrack only matters on firewalls." Every Docker host and every Kubernetes node is a NAT. And entries outlive the socket: an established TCP entry lives 432 000 s (5 days) by default if no FIN or RST is seen, and TIME_WAIT entries 120 s.

Definition: nf_conntrack_max "Maximum number of allowed connection tracking entries"; default equals nf_conntrack_buckets (memory / 16384, between 1024 and 262144). Timers: nf_conntrack_tcp_timeout_established 432000, nf_conntrack_tcp_timeout_time_wait 120, nf_conntrack_udp_timeout 30, nf_conntrack_udp_timeout_stream 120. When the table is full the kernel logs, verbatim from nf_conntrack_core.c: nf_conntrack: table full, dropping packet (or table full in netns N, dropping packet).

text
1  Docker host, nf_conntrack_max = 262144
2  1 000 containers each open 300 short connections per second through the bridge NAT
3  each closed flow stays 120 s in TIME_WAIT inside conntrack
4  300 000 entries needed > 262 144 -> dmesg: nf_conntrack: table full, dropping packet
5  new SYNs dropped silently -> clients see connect TIMEOUTS, not refusals
CommandShows
cat /proc/sys/net/netfilter/nf_conntrack_countcurrent entries (lab: 0 in a fresh namespace)
sysctl net.netfilter.nf_conntrack_maxlimit (lab: 262144)
conntrack -L -p tcp --dport 5432entries for one service (needs CAP_NET_ADMIN)
conntrack -Sper-CPU insert_failed, drop, early_drop
dmesg | grep conntrackthe "table full" message

Fix / how to use it: fewer, longer connections (pools) shrink the table; raise nf_conntrack_max and hashsize on busy NAT nodes; for heavy internal traffic use --network host or a CNI that bypasses conntrack. Details of the iptables rules Docker writes are in Docker Networking and Firewalls.

File descriptor limits Must-know ​

In plain words: every socket, file and pipe a process holds uses one file descriptor. The process has a soft and a hard limit; the host has a total. A busy server hits them with "too many open files".

Common misunderstanding: "Raise ulimit -n and the problem is solved." If the count grows forever, you have a leak (CLOSE_WAIT, unclosed bodies) and a higher limit only delays the outage. Also: Go raises its own soft limit to just under the hard limit (Max − 1) at start-up (the runtime comment: "Go does not use select, so it should not be subject to these limits"), so a Go program ignores a lowered soft limit; the lab needed --ulimit nofile=256:256 to see EMFILE.

Definition: RLIMIT_NOFILE soft/hard per process (ulimit -n, ulimit -Hn, systemd LimitNOFILE=, Docker --ulimit nofile=), fs.nr_open (max any process may set; 1 048 576 in the lab), fs.file-max (host-wide; 1 608 922 in the lab). EMFILE = per-process limit; ENFILE = system-wide.

text
1  docker run --ulimit nofile=256:256 ... /lab/fdlimit
2  RLIMIT_NOFILE soft=256 hard=256
3  each dial uses 1 fd client-side and 1 fd server-side (same process here)
4  accept: accept tcp 127.0.0.1:46339: accept4: too many open files
5  dial #126: dial tcp 127.0.0.1:46339: socket: too many open files (EMFILE=true)
Where setLinuxmacOSDocker / Kubernetes
Per processulimit -n, /etc/security/limits.conf, systemd LimitNOFILEulimit -n, launchctl limit maxfiles; kern.maxfilesperproc (92160 here)--ulimit nofile=soft:hard; container runtime default (1 048 576 in the lab)
Systemfs.file-max, fs.nr_openkern.maxfilesnode's kernel
Inside the appGo raises soft to hard − 1 automaticallysamesame
PgBouncerneeds max_client_conn + pool sizes worth of fds

Fix / how to use it: find the leak first (ls /proc/<pid>/fd | wc -l, lsof -p <pid> grouped by type/state); then size the limit to peak connections × 2 plus files; in Go, back off on EMFILE in the accept loop instead of spinning (labserver).

SO_REUSEADDR and SO_REUSEPORT Important ​

In plain words: SO_REUSEADDR lets a restarted server bind its port even though old connections from the previous run are still in TIME_WAIT. SO_REUSEPORT lets several sockets (in one or several processes) listen on the same port, and the kernel spreads new connections across them.

Common misunderstanding: "SO_REUSEADDR lets two servers listen on one port." Not on Linux: socket(7) says a socket "may bind, except when there is an active listening socket bound to the address." That is SO_REUSEPORT, and it requires every socket to set it and to belong to the same effective UID ("To prevent port hijacking").

Definition: socket(7) SO_REUSEPORT (since Linux 3.9): "Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. This option must be set on each socket (including the first socket) prior to calling bind(2)". For TCP it "allows accept(2) load distribution in a multi-threaded server to be improved by using a distinct listener socket for each thread". Go's net.Listen already sets SO_REUSEADDR on Unix.

text
1  old process A listens on :8080 with SO_REUSEPORT
2  new process B starts, also SO_REUSEPORT, binds :8080 -> both LISTEN (ss shows two lines)
3  kernel hashes new connections across A and B
4  A gets SIGTERM: stops accepting (closes listener), drains in-flight requests, exits
5  B serves everything; no connection was refused during the switch
   caveat: connections already queued in A's accept queue when A closes its listener are reset

Real scenario: zero-downtime Go deploys without a proxy; nginx listen 443 reuseport for per-worker accept queues; Envoy and HAProxy hot restarts; UDP DNS servers spreading load across cores.

ProductOption
LinuxSO_REUSEPORT since 3.9; BPF can steer (SO_ATTACH_REUSEPORT_EBPF)
macOS / BSDSO_REUSEPORT exists, but does not load-balance TCP like Linux
Gonet.ListenConfig{Control: ...} with unix.SO_REUSEPORT
nginxlisten ... reuseport
php-fpmnot needed: one master listener, children inherit it

Fix / how to use it: the Go reuseport server; for most teams a load balancer or systemd socket activation is simpler.

Unix domain sockets Important ​

In plain words: a socket that is a file on disk instead of an IP:port. Only processes on the same host (or sharing the directory through a volume) can use it, access is controlled by file permissions, and the kernel skips the whole TCP/IP stack.

Common misunderstanding: "Unix sockets are a legacy thing." They are the default local transport for php-fpm, PostgreSQL (/var/run/postgresql/.s.PGSQL.5432), MySQL (mysqld.sock), Redis (unixsocket), Docker (/var/run/docker.sock) and systemd. And "a Unix socket is safe because it is local": docker.sock with mode 0666, or mounted into a container, gives root on the host.

Definition: unix(7): types SOCK_STREAM, SOCK_DGRAM (reliable, ordered on Linux) and SOCK_SEQPACKET; pathname sockets are bound to a filesystem path; Linux also supports an abstract namespace (a name starting with a NUL byte) "which is independent of the filesystem". Connecting "requires write permission on that socket". No ports, no TIME_WAIT, no conntrack, no Nagle.

text
1  php-fpm master: bind("/run/php/php-fpm.sock"), chmod 0660, chown www-data:nginx
2  nginx worker (group nginx): connect("unix:/run/php/php-fpm.sock") -> allowed
3  a process as user "deploy": connect -> EACCES (permission denied)
4  fpm restarts while an old socket file exists -> unlink first, else EADDRINUSE

Real output from the lab's PostgreSQL container:

text
srwxrwxrwx    1 postgres postgres         0 Nov 25 17:47 .s.PGSQL.5432
-rw-------    1 postgres postgres        68 Nov 25 17:47 .s.PGSQL.5432.lock
ServiceDefault Unix socketLaravel / Go
php-fpmlisten = /run/php/php-fpm.sock (distro-specific)nginx fastcgi_pass unix:...
PostgreSQL/var/run/postgresql/.s.PGSQL.5432 (unix_socket_directories)Laravel 'host' => '/var/run/postgresql'; pgx host=/var/run/postgresql
MySQL/var/run/mysqld/mysqld.sockLaravel 'unix_socket'
Redisoff by default; unixsocket /run/redis.sockLaravel 'scheme' => 'unix', 'path' => ...; go-redis Network: "unix"
Docker/var/run/docker.sockDocker SDK; never mount casually

Fix / how to use it: use Unix sockets when client and server share a host (nginx + fpm, app + local PgBouncer): lower latency, no port or conntrack use; set mode 0660 and a shared group (www.conf, unixsock).

UDP sockets Good to know ​

In plain words: UDP sends independent datagrams with no connection, no retransmission and no backpressure. If the receiver is slow, the kernel drops datagrams when its buffer is full, and the sender never knows.

Common misunderstanding: "sendto returned success, so the datagram arrived." It left your host (or not even that). And "UDP has no ports to exhaust": a UDP client socket still takes an ephemeral port, and conntrack still tracks UDP flows (30 s, or 120 s for streams).

Definition: RFC 768: "delivery and duplicate protection are not guaranteed". connect() on a UDP socket only fixes the default peer (and lets ICMP port-unreachable come back as ECONNREFUSED on the next call). Drops show in nstat as UdpRcvbufErrors / UdpInErrors.

text
1  receiver: SO_RCVBUF 8 KiB (kernel doubles it), reads one datagram per 20 µs
2  sender: 20 000 datagrams of 512 B as fast as possible
3  sent=20000 send_errors=0 received=548 lost=19452
4  nstat: UdpRcvbufErrors 19452
UsesPortWhat protects against loss
DNS53client retries; TCP fallback for large answers
QUIC / HTTP/3443QUIC itself retransmits
StatsD / metrics8125nothing: loss is accepted
Syslog514nothing (use TCP/TLS 6514 for audit logs)
WireGuard51820inner TCP

Fix / how to use it: accept loss (metrics) or add retries/acks in the protocol; raise SO_RCVBUF and net.core.rmem_max for bursty receivers (udpdrop). The protocol-level comparison is in TCP vs UDP.

Mechanics ​

Every knob, with the value measured in the lab Must-know ​

Values read from /proc/sys in a Docker Desktop container on kernel 7.0.14-linuxkit. Network sysctls are per network namespace, so a container can change most of them for itself with docker run --sysctl without touching the host.

SysctlLab valueWhat it controls
net.ipv4.ip_local_port_range32768 60999Ephemeral ports for outgoing connections
net.ipv4.ip_unprivileged_port_start0 (Docker sets it; host default 1024)Lowest port a non-root process may bind
net.ipv4.tcp_tw_reuse2 (loopback only)Reuse TIME_WAIT tuples for outgoing connects
net.ipv4.tcp_tw_reuse_delay1000 msMinimum TIME_WAIT age before reuse
net.ipv4.tcp_fin_timeout60Orphaned FIN-WAIT-2 lifetime
net.core.somaxconn4096Cap on every listen() backlog
net.ipv4.tcp_max_syn_backlog1024Half-open (SYN-RECV) queue
net.ipv4.tcp_syncookies1SYN cookies when the SYN queue overflows
net.ipv4.tcp_abort_on_overflow01 = RST instead of silent drop when the accept queue is full
net.ipv4.tcp_syn_retries / tcp_synack_retries6 / 5How long a connect keeps trying
net.ipv4.tcp_syn_linear_timeouts4First SYN retries at 1 s intervals, then exponential
net.ipv4.tcp_keepalive_time / _intvl / _probes7200 / 75 / 9Keepalive defaults for sockets with SO_KEEPALIVE
net.ipv4.tcp_rmem / tcp_wmem4096 131072 33554432 / 4096 16384 4194304Buffer autotuning min/default/max
net.netfilter.nf_conntrack_max262144conntrack table size
fs.file-max / fs.nr_open1608922 / 1048576Host-wide fds / per-process maximum
ulimit -n (container)1048576Soft limit given by the runtime

Error codes decoded Must-know ​

errno (Linux / macOS number)MessageReturned byWhat happened on the wireRetry?
ECONNREFUSED (111 / 61)Connection refusedconnectSYN answered by RST (nothing listening), or ICMP port unreachable for UDPYes, another instance; the service is down
ETIMEDOUT (110 / 60)Connection timed out / Operation timed outconnect, readNo reply to SYN, or retransmissions exhaustedYes, with backoff; check firewall
EHOSTUNREACH / ENETUNREACHNo route to host / Network is unreachableconnectICMP unreachable or no routeFix routing
EADDRINUSE (98 / 48)Address already in usebind, listennone: local conflictNo: find the other process
EADDRNOTAVAIL (99 / 49)Cannot assign requested addressconnect, bindnone: no ephemeral port free, or binding an IP the host does not haveNot immediately: reuse connections
EMFILE (24) / ENFILE (23)Too many open files (in system)socket, accept, opennoneAfter closing something
ECONNRESET (104 / 54)Connection reset by peerread, writeWe received RSTIdempotent requests only
EPIPE (32)Broken pipewriteWe wrote after the connection closed (Go returns the error instead of dying on SIGPIPE for sockets)Idempotent requests only
EAGAIN / EWOULDBLOCKResource temporarily unavailablenon-blocking callsbuffer full / queue empty / Unix socket backlog fullRuntime handles it
EACCES (13)Permission deniedbind, connect (Unix)privileged port, socket file permissionsFix permissions
cURL 7 / 28 / 6 / 52 / 56Couldn't connect / Timeout / Couldn't resolve / Empty reply / Recv failureGuzzle, Laravel Httprefused-or-unreachable / timeout / DNS / peer closed / resetas above

"Connection reset by peer" vs "broken pipe": both mean the peer is gone. Reset is reported when a RST arrives (often on read); broken pipe when you write after the kernel already knows the connection is closed (often the second write after a reset). Closing a socket that still has unread data sends a RST instead of a FIN — RFC 9293 says the TCP implementation "SHOULD send a RST to show that data was lost" — which is how a client that drops a large unread HTTP body resets the server.

Bytes on the wire: SYN, data and RST in hex Good to know ​

tcpdump -X prints the IPv4 header (20 bytes) then the TCP header. The lab SYN from 172.21.0.7:41516 to 172.21.0.2:9000:

text
0x0000:  4500 003c 7e4a 4000 4006 643e ac15 0007   45=IPv4,hdr 20 B  003c=60 B total  06=TCP  ac15 0007=172.21.0.7
0x0010:  ac15 0002 a22c 2328 cbe8 aa04 0000 0000   dst 172.21.0.2  a22c=41516 (src port)  2328=9000 (dst port)  seq
0x0020:  a002 faf0 5862 0000 0204 05b4 0402 080a   a0=hdr 40 B  02=SYN  faf0=window 64240  0204 05b4=MSS 1460  0402=SACK ok
0x0030:  d973 8bfd 0000 0000 0103 030a             timestamps, 0103 030a=window scale 10

The data segment carries ping\n as 70 69 6e 67 0a with flags 0x18 (PSH+ACK); the RST from a closed port is a 40-byte packet with flags 0x14 (RST+ACK), window 0:

text
0x0020:  8018 003f 585f 0000 0101 080a d973 8bfd   80=hdr 32 B  18=PSH|ACK
0x0030:  2b2c 23ac 7069 6e67 0a                    ... payload "ping\n"
RST:     ... 270f 8d5c 0000 0000 4809 206c 5014 0000   270f=9999  8d5c=36188  5014: hdr 20 B, flags 14=RST|ACK, window 0

/proc/net/tcp (which ss and the Go sockstat program read) prints IPv4 addresses as a little-endian 32-bit word: 0B00007F:A2F1 is 7F.00.00.0B reversed, i.e. 127.0.0.11, port 0xA2F1 = 41713 — Docker's embedded DNS listener. The state column is hex: 01 ESTABLISHED, 06 TIME_WAIT, 08 CLOSE_WAIT, 0A LISTEN.

The tools Must-know ​

ss (iproute2) — the first tool. It reads sockets from the kernel via netlink; netstat (net-tools) reads /proc and is slower and deprecated on Linux.

CommandShowsReal output (lab)
ss -tulpnlistening TCP/UDP with processtcp LISTEN 0 4096 *:8080 *:* users:(("httpserver",pid=7,fd=3))
ss -stotals per stateTCP: 20082 (estab 0, closed 20081, orphaned 0, timewait 20000)
ss -tan state time-waitTIME_WAIT sockets172.21.0.3:32768 172.21.0.2:9000
ss -tano state time-waitwith timerstimer:(timewait,58sec,0)
ss -tanp state close-waitleak ownersusers:(("labserver",pid=1,fd=7))
ss -ltnaccept queue: Recv-Q now, Send-Q limitLISTEN 5 4 *:9100 (queue overflowing)
ss -tno state established '( sport = :9000 )'keepalive timertimer:(keepalive,59sec,0)
ss -ti / ss -tmrtt, cwnd, retrans / socket memory (skmem)per-socket internals
ss -xlpUnix listeners with processphp-fpm, PostgreSQL, Docker sockets
ss -K dst 10.0.0.9kill sockets (root, kernel support)

The others.

ToolUse it forExampleWhat you learn
lsof -nP -i :8080which process holds a port (Linux and macOS)httpserve 7 root 3u IPv6 ... TCP *:8080 (LISTEN)PID, fd, state
lsof -nP -p PID -a -ione process's socketslines ending (CLOSE_WAIT)leaks per process
netstat -an -p tcp (macOS) / netstat -tanp (legacy Linux)same as sstcp4 0 0 127.0.0.1.64586 127.0.0.1.18080 TIME_WAITmacOS has no ss
nc -zv host portis the port open?Connection to psc-srv ... 9000 port [tcp/*] succeeded! / ... failed: Connection refusedrefused vs timeout (-w 2)
nc -l 9000 / nc -lu 5353throwaway TCP/UDP listenerdoes traffic arrive at all
curl -v --connect-timeout 2 --max-time 5HTTP with separate connect and total budgetscurl: (28) Connection timed out after 2001 milliseconds, curl: (7) Failed to connect ... Could not connect to serverexit 28 = timeout, 7 = refused
curl -w '%{time_connect} %{local_port}'timing and our ephemeral portconnect=0.000081s total=0.000399s local_port=40718where the time goes
telnet host porttype a protocol by handConnected to psc-srvinteractive check
tcpdump -i any port 5432 -nnpackets: SYN, RST, retransmitsFlags [R.], seq 0, ack 1208557676, win 0the truth on the wire
dig +short name / dig +noall +answer +statsDNS answer and which server answeredpsc-iperf. 600 IN A 172.21.0.6, SERVER: 127.0.0.11#53name vs network problem
traceroute -T -p 443 / mtr -T -P 443 -r -c 3path and loss per hop with TCP probes1.|-- 172.21.0.2 0.0% 3 0.1where packets die
iperf3 -s / iperf3 -c host -t 3raw throughput and retransmits96079 Mbits/sec 4190 retr (veth, same VM)bandwidth, not the app
nstat -az TcpExtListenOverflowskernel countersTcpExtListenOverflows 20accept queue drops
conntrack -L, conntrack -SNAT flowstable pressure

macOS vs Linux.

TaskLinuxmacOS
Listening portsss -tulpnlsof -nP -iTCP -sTCP:LISTEN
Sockets by statess -tan state time-waitnetstat -an -p tcp | grep TIME_WAIT
Live per-process trafficss -tpi, nethogsnettop -m tcp -p PID
Ephemeral rangesysctl net.ipv4.ip_local_port_rangesysctl net.inet.ip.portrange.first net.inet.ip.portrange.last
TIME_WAIT length60 s fixedsysctl net.inet.tcp.msl × 2 (15000 ms → 30 s)
fd limitsulimit -n, fs.file-maxulimit -n, kern.maxfilesperproc
Packet capturetcpdump -i anytcpdump -i en0 / -i lo0
Docker's published portss -ltnp shows docker-proxylsof shows Docker Desktop's process (com.docker.backend)

On macOS the Docker VM is another kernel: ss inside a container shows the container's sockets, lsof -nP -iTCP:18080 -sTCP:LISTEN on the Mac shows only Docker Desktop's forwarder (com.docke ... TCP 127.0.0.1:18080 (LISTEN)), and the TIME_WAIT of your curl to that port appears in netstat on the Mac.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
TIME_WAIT pile-up, EADDRNOTAVAILConnection reuseShared HTTP transport, DB/Redis pools, keep-aliveRemoves the cause; faster (no handshake, no TLS)Must handle stale pooled connections
tcp_tw_reuse=1sysctl on the clientOne lineOnly outgoing; only after tcp_tw_reuse_delay; masks the design issue
More source IPs / NAT IPsSecondary IPs, more NAT gatewaysLinear headroomMoney; ops work
CLOSE_WAIT leakClose in the same scopedefer conn.Close(), resp.Body.Close()Fixes the bugNeeds code review / linter
Accept queue overflowFaster accept, more workersSize pm.max_children, Octane workers, replicasReal capacityMemory per worker
Fail fastShort client connect timeouts, LB health checksLoad moves elsewhereErrors instead of latency
Idle connection killed by NAT/LBKeepalive / heartbeatsKeepAliveConfig, libpq keepalives_idle, AMQP heartbeatsFlow stays warm, dead peers detectedA few packets per minute
Shorter client idle timeoutIdleConnTimeout below server/LB idle timeoutNever reuse a half-dead connSlightly more reconnects
EMFILEFind leaks, then raise limitslsof -p, --ulimit, LimitNOFILEHeadroomHides leaks if done first
EADDRINUSE on restartSO_REUSEADDR (Go default) or SO_REUSEPORT handoverListenConfig ControlZero-downtimeLinux-specific behaviour
Slow clients hold socketsServer timeoutsReadHeaderTimeout, IdleTimeout, nginx timeoutsBounded resourcesLegit slow uploads need exceptions
conntrack fullFewer flows; bigger tablePools; nf_conntrack_max; host networkingNo silent dropsMemory

Connection reuse for outbound HTTP ​

Go: one http.Client for the whole process, MaxIdleConnsPerHost above the default 2, idle timeout below the upstream's, and the body read to EOF. The lab output proves reuse: with -drain=false against a 1 MiB body, every request opened a new connection.

go
// Command httpclient shows an outbound HTTP client that reuses connections:
// a tuned Transport, explicit timeouts, and httptrace proving reuse.
// Run with -drain=false to see the classic bug: an unread body stops reuse.
package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"net/http/httptrace"
	"time"
)

func newClient() *http.Client {
	dialer := &net.Dialer{
		Timeout: 2 * time.Second, // connect timeout (SYN -> SYN/ACK)
		KeepAliveConfig: net.KeepAliveConfig{
			Enable: true, Idle: 30 * time.Second, Interval: 10 * time.Second, Count: 3,
		},
	}
	tr := &http.Transport{
		Proxy:                 http.ProxyFromEnvironment,
		DialContext:           dialer.DialContext,
		MaxIdleConns:          200,              // idle pool across all hosts
		MaxIdleConnsPerHost:   50,               // default is 2: too low for one busy upstream
		MaxConnsPerHost:       100,              // hard cap: protects the upstream and your ports
		IdleConnTimeout:       50 * time.Second, // below the upstream's keep-alive timeout
		TLSHandshakeTimeout:   3 * time.Second,
		ResponseHeaderTimeout: 5 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
		ForceAttemptHTTP2:     true,
	}
	// Client.Timeout bounds the whole exchange, body included.
	return &http.Client{Transport: tr, Timeout: 10 * time.Second}
}

func main() {
	url := flag.String("url", "http://127.0.0.1:8080/", "target")
	n := flag.Int("n", 5, "requests")
	drain := flag.Bool("drain", true, "read the body to EOF before Close")
	flag.Parse()

	client := newClient() // create ONCE and share; never per request
	for i := 0; i < *n; i++ {
		trace := &httptrace.ClientTrace{
			GotConn: func(info httptrace.GotConnInfo) {
				fmt.Printf("req %d: reused=%v local=%s\n", i, info.Reused, info.Conn.LocalAddr())
			},
		}
		ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
		req, err := http.NewRequestWithContext(httptrace.WithClientTrace(ctx, trace), http.MethodGet, *url, nil)
		if err != nil {
			log.Fatal(err)
		}
		resp, err := client.Do(req)
		if err != nil {
			cancel()
			log.Fatal(err)
		}
		if *drain {
			_, _ = io.Copy(io.Discard, resp.Body) // EOF lets the conn return to the pool
		}
		resp.Body.Close()
		cancel()
	}
}
text
req 0: reused=false local=127.0.0.1:44002
req 1: reused=true local=127.0.0.1:44002
-- drain=false
req 0: reused=false local=127.0.0.1:44010
req 1: reused=false local=127.0.0.1:44016

Laravel: the HTTP client creates a new Guzzle client per request (PendingRequest::buildClient() returns $this->client ?? $this->createClient(...)), so separate Http::get() calls never share a connection. A shared CurlHandler keeps cURL handles, and libcurl's curl_easy_reset "does not change ... live connections", so connections survive between requests. This pays off in Octane and queue workers; under php-fpm only within one request.

php
<?php

namespace App\Providers;

use GuzzleHttp\Handler\CurlFactory;
use GuzzleHttp\Handler\CurlHandler;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\ServiceProvider;

/**
 * Laravel's HTTP client builds a new Guzzle client (and so new cURL handles)
 * for every request, so two Http::get() calls never share a TCP connection.
 * Sharing ONE handler keeps idle cURL handles, and cURL keeps their live
 * connections across curl_reset(), so later requests skip the handshake.
 *
 * Under php-fpm the process state dies with the request, so this only helps
 * within one request. Under Octane and queue workers the singleton lives for
 * thousands of requests or jobs: that is where keep-alive really pays.
 */
class HttpKeepAliveServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Keep up to 20 idle handles (Guzzle's default is 3).
        $this->app->singleton(CurlHandler::class, fn () => new CurlHandler([
            'handle_factory' => new CurlFactory(20),
        ]));
    }

    public function boot(): void
    {
        Http::macro('keepAlive', function () {
            return Http::setHandler(app(CurlHandler::class))
                ->connectTimeout(2)   // SYN -> SYN/ACK budget
                ->timeout(5)          // whole request budget
                ->withHeaders(['Connection' => 'keep-alive']);
        });
    }
}
php
<?php

namespace App\Services;

use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Throwable;

class PaymentGatewayClient
{
    public function charge(string $idempotencyKey, int $amountMinor): Response
    {
        return Http::keepAlive()
            ->baseUrl(config('services.gateway.url'))
            ->withHeaders(['Idempotency-Key' => $idempotencyKey])
            // Retry only failures where the request surely never arrived,
            // or that the idempotency key makes safe to repeat.
            ->retry([100, 300, 900], when: function (Throwable $e, PendingRequest $request) {
                return $e instanceof ConnectionException;
            })
            ->post('/v1/charges', ['amount' => $amountMinor]);
    }

    /**
     * Turn a ConnectionException into the socket-level reason, using the
     * cURL errno Guzzle attaches: 7 = could not connect (ECONNREFUSED,
     * unreachable), 28 = timed out (connect or transfer), 6 = DNS failed,
     * 52 = empty reply (peer closed), 56 = receive failure (often ECONNRESET).
     * Guzzle throws ConnectException for 6/7/28/35/52 and RequestException
     * for the rest; both carry the handler context.
     */
    public static function reason(ConnectionException $e): string
    {
        $previous = $e->getPrevious();
        $errno = $previous instanceof ConnectException || $previous instanceof RequestException
            ? ($previous->getHandlerContext()['errno'] ?? null)
            : null;

        $reason = match ($errno) {
            6 => 'dns',
            7 => 'refused_or_unreachable',
            28 => 'timeout',
            52 => 'empty_reply',
            56 => 'reset_by_peer',
            default => 'other',
        };

        Log::warning('gateway connection failed', ['errno' => $errno, 'reason' => $reason]);

        return $reason;
    }
}

Server timeouts and graceful shutdown ​

go
// Command httpserver is a net/http server with every timeout set. The zero
// value of http.Server has none, so one slow client can hold a socket forever.
package main

import (
	"context"
	"errors"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("ok\n"))
	})
	big := make([]byte, 1<<20) // 1 MiB: big enough that an unread body matters
	mux.HandleFunc("GET /big", func(w http.ResponseWriter, r *http.Request) {
		w.Write(big)
	})

	srv := &http.Server{
		Addr:              ":8080",
		Handler:           mux,
		ReadHeaderTimeout: 5 * time.Second,   // slowloris guard
		ReadTimeout:       15 * time.Second,  // whole request incl. body
		WriteTimeout:      30 * time.Second,  // from end of headers to end of response
		IdleTimeout:       120 * time.Second, // keep-alive idle; above the LB's idle timeout
		MaxHeaderBytes:    1 << 20,
	}

	go func() {
		if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
			log.Fatal(err)
		}
	}()

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()
	<-ctx.Done()

	// Shutdown closes the listener, closes idle keep-alive connections and
	// waits for in-flight requests: no RST for clients mid-request.
	shCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	if err := srv.Shutdown(shCtx); err != nil {
		log.Printf("shutdown: %v", err)
	}
}

For php-fpm the equivalents live in nginx (client_header_timeout, keepalive_timeout, fastcgi_read_timeout) and in the pool (request_terminate_timeout).

The CLOSE_WAIT leak and a well-behaved TCP server ​

labserver is both the bug and the fix: -leak drops the defer conn.Close(); the normal path closes, sets read/write deadlines, enables keepalive on accepted sockets and backs off on EMFILE.

go
// Command labserver is the TCP server used in the lab. It can behave well
// (accept, echo, close) or reproduce three classic bugs on purpose:
//
//	-leak      never close accepted connections (CLOSE_WAIT pile-up)
//	-noaccept  never call Accept (accept queue fills, SYNs get dropped)
//	-closefirst close right after the reply (TIME_WAIT lands on the server)
package main

import (
	"bufio"
	"context"
	"errors"
	"flag"
	"log"
	"net"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"
)

func main() {
	addr := flag.String("addr", ":9000", "listen address")
	leak := flag.Bool("leak", false, "never close accepted connections (bug)")
	noAccept := flag.Bool("noaccept", false, "listen but never accept (bug)")
	closeFirst := flag.Bool("closefirst", false, "server closes after one reply")
	flag.Parse()

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	// ListenConfig lets us set TCP keepalive on every accepted socket.
	// Go has no backlog argument: Linux uses net.core.somaxconn.
	lc := net.ListenConfig{
		KeepAliveConfig: net.KeepAliveConfig{
			Enable:   true,
			Idle:     60 * time.Second, // below every NAT/LB idle timeout we meet
			Interval: 10 * time.Second,
			Count:    3,
		},
	}
	ln, err := lc.Listen(ctx, "tcp", *addr)
	if err != nil {
		log.Fatal(err) // EADDRINUSE lands here: "bind: address already in use"
	}
	log.Printf("listening on %s (pid %d)", ln.Addr(), os.Getpid())

	if *noAccept {
		<-ctx.Done()
		return
	}

	var wg sync.WaitGroup
	go func() { <-ctx.Done(); ln.Close() }() // unblocks Accept on shutdown

	for {
		conn, err := ln.Accept()
		if err != nil {
			if errors.Is(err, net.ErrClosed) {
				break
			}
			// EMFILE ("too many open files") arrives here; back off, do not spin.
			log.Printf("accept: %v", err)
			time.Sleep(100 * time.Millisecond)
			continue
		}
		wg.Add(1)
		go func() {
			defer wg.Done()
			handle(conn, *leak, *closeFirst)
		}()
	}
	wg.Wait()
}

func handle(conn net.Conn, leak, closeFirst bool) {
	if !leak {
		defer conn.Close() // the one line whose absence creates CLOSE_WAIT
	}
	r := bufio.NewReader(conn)
	for {
		// Idle timeout: a silent peer must not hold a goroutine and an fd forever.
		_ = conn.SetReadDeadline(time.Now().Add(30 * time.Second))
		line, err := r.ReadString('\n')
		if err != nil {
			return // io.EOF: the peer sent FIN; we are now in CLOSE_WAIT until Close
		}
		_ = conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
		if _, err := conn.Write([]byte(line)); err != nil {
			return // EPIPE / ECONNRESET: the peer is gone
		}
		if closeFirst {
			return
		}
	}
}

TIME_WAIT generator: short connections vs reuse ​

go
// Command twgen opens many short TCP connections (the client closes first, so
// the client keeps TIME_WAIT) or reuses one connection for the same work.
//
//	twgen -addr server:9000 -n 20000 -mode short   # TIME_WAIT climbs
//	twgen -addr server:9000 -n 20000 -mode reuse   # one socket, no pile-up
package main

import (
	"bufio"
	"errors"
	"flag"
	"fmt"
	"net"
	"sync"
	"sync/atomic"
	"syscall"
	"time"
)

func main() {
	addr := flag.String("addr", "127.0.0.1:9000", "server address")
	n := flag.Int("n", 20000, "number of request/response exchanges")
	mode := flag.String("mode", "short", "short | reuse")
	workers := flag.Int("c", 50, "concurrent workers")
	flag.Parse()

	var ok, exhausted, refused, other atomic.Int64
	start := time.Now()
	jobs := make(chan struct{})
	var wg sync.WaitGroup

	for w := 0; w < *workers; w++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			var conn net.Conn
			var r *bufio.Reader
			for range jobs {
				if conn == nil {
					c, err := net.DialTimeout("tcp", *addr, 2*time.Second)
					switch {
					case errors.Is(err, syscall.EADDRNOTAVAIL):
						exhausted.Add(1) // no free ephemeral port for this 4-tuple
						continue
					case errors.Is(err, syscall.ECONNREFUSED):
						refused.Add(1)
						continue
					case err != nil:
						other.Add(1)
						continue
					}
					conn, r = c, bufio.NewReader(c)
				}
				if _, err := conn.Write([]byte("ping\n")); err != nil {
					other.Add(1)
					conn.Close()
					conn = nil
					continue
				}
				if _, err := r.ReadString('\n'); err != nil {
					other.Add(1)
					conn.Close()
					conn = nil
					continue
				}
				ok.Add(1)
				if *mode == "short" {
					conn.Close() // active close: THIS side enters TIME_WAIT
					conn = nil
				}
			}
			if conn != nil {
				conn.Close()
			}
		}()
	}
	for i := 0; i < *n; i++ {
		jobs <- struct{}{}
	}
	close(jobs)
	wg.Wait()

	fmt.Printf("mode=%s ok=%d eaddrnotavail=%d refused=%d other=%d elapsed=%s\n",
		*mode, ok.Load(), exhausted.Load(), refused.Load(), other.Load(),
		time.Since(start).Round(time.Millisecond))
}

Classifying dial errors ​

go
// Command dialerrors dials a list of targets with a context deadline and
// prints which classic error each one produced, using errors.Is on the errno
// rather than matching strings.
package main

import (
	"context"
	"errors"
	"fmt"
	"net"
	"os"
	"syscall"
	"time"
)

func classify(err error) string {
	var ne net.Error
	switch {
	case err == nil:
		return "OK (handshake completed)"
	case errors.Is(err, syscall.ECONNREFUSED):
		return "ECONNREFUSED: host answered with RST, nothing listening on that port"
	case errors.Is(err, context.DeadlineExceeded), errors.As(err, &ne) && ne.Timeout():
		return "TIMEOUT: no answer at all; packets dropped (firewall, wrong IP, full SYN queue)"
	case errors.Is(err, syscall.EHOSTUNREACH), errors.Is(err, syscall.ENETUNREACH):
		return "UNREACHABLE: no route, or an ICMP unreachable came back"
	case errors.Is(err, syscall.EADDRNOTAVAIL):
		return "EADDRNOTAVAIL: no free local ephemeral port for this destination"
	case errors.Is(err, syscall.EMFILE):
		return "EMFILE: this process hit its file descriptor limit (ulimit -n)"
	default:
		var dnsErr *net.DNSError
		if errors.As(err, &dnsErr) {
			return "DNS: " + dnsErr.Err
		}
		return "OTHER: " + err.Error()
	}
}

func main() {
	targets := os.Args[1:]
	if len(targets) == 0 {
		targets = []string{"127.0.0.1:9000", "127.0.0.1:1", "10.255.255.1:80", "no-such-host.invalid:80"}
	}
	var d net.Dialer
	for _, t := range targets {
		ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
		start := time.Now()
		conn, err := d.DialContext(ctx, "tcp", t)
		cancel()
		if conn != nil {
			conn.Close()
		}
		fmt.Printf("%-26s %-8s %s\n", t, time.Since(start).Round(time.Millisecond), classify(err))
	}
}

// IsPeerGone reports the two errors a write or read returns when the other
// side has vanished mid-conversation: ECONNRESET ("connection reset by peer",
// we received a RST) and EPIPE ("broken pipe", we wrote after the peer closed
// and the kernel already knows it).
func IsPeerGone(err error) bool {
	return errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE)
}
text
psc-srv:9000               1ms      OK (handshake completed)
psc-srv:9999               0s       ECONNREFUSED: host answered with RST, nothing listening on that port
psc-bl:9100                2.001s   TIMEOUT: no answer at all; packets dropped (firewall, wrong IP, full SYN queue)
172.21.0.250:80            2.001s   TIMEOUT: no answer at all; packets dropped (firewall, wrong IP, full SYN queue)
no-such-host.invalid:80    3ms      DNS: no such host

A dependency probe in Laravel ​

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

/**
 * php artisan net:probe db:5432 redis:6379 rabbitmq:5672
 *
 * The nc -zv of a Laravel app: opens a TCP connection to each dependency
 * with a short timeout and reports how it failed. A refusal comes back in
 * milliseconds (RST); a timeout takes the full budget (packets dropped).
 */
class ProbeDependencies extends Command
{
    protected $signature = 'net:probe {targets* : host:port pairs} {--timeout=2 : seconds}';

    protected $description = 'Check TCP reachability of dependencies';

    public function handle(): int
    {
        $rows = [];
        $failed = false;

        foreach ($this->argument('targets') as $target) {
            $start = hrtime(true);
            $socket = @stream_socket_client(
                "tcp://{$target}",
                $errno,
                $errstr,
                (float) $this->option('timeout'),
            );
            $ms = (int) ((hrtime(true) - $start) / 1_000_000);

            if ($socket === false) {
                $failed = true;
                // errno is the OS value: Linux 111 ECONNREFUSED, 110 ETIMEDOUT;
                // macOS 61 and 60. errstr is the portable text.
                $rows[] = [$target, 'FAIL', "{$errno} {$errstr}", "{$ms} ms"];

                continue;
            }

            $local = stream_socket_get_name($socket, false); // our ephemeral port
            fclose($socket);
            $rows[] = [$target, 'OK', "from {$local}", "{$ms} ms"];
        }

        $this->table(['target', 'result', 'detail', 'time'], $rows);

        return $failed ? self::FAILURE : self::SUCCESS;
    }
}

The same stream_socket_client call from PHP 8.5 in the lab:

text
psc-srv:9000   OK from 172.21.0.8:35520 0 ms
psc-srv:9999   FAIL 111 Connection refused 0 ms
psc-bl:9100    FAIL 110 Operation timed out 2002 ms

Socket state as a metric ​

go
// Command sockstat reads /proc/net/tcp and /proc/net/tcp6 (Linux) the way ss
// does without netlink: it counts sockets per TCP state and decodes the hex
// addresses, so a service can export "how many CLOSE_WAIT do I have" as a metric.
package main

import (
	"bufio"
	"encoding/binary"
	"encoding/hex"
	"fmt"
	"net"
	"os"
	"sort"
	"strconv"
	"strings"
)

// States as numbered in the kernel's include/net/tcp_states.h.
var states = map[string]string{
	"01": "ESTABLISHED", "02": "SYN_SENT", "03": "SYN_RECV", "04": "FIN_WAIT1",
	"05": "FIN_WAIT2", "06": "TIME_WAIT", "07": "CLOSE", "08": "CLOSE_WAIT",
	"09": "LAST_ACK", "0A": "LISTEN", "0B": "CLOSING",
}

// decodeAddr turns "0100007F:2328" into 127.0.0.1:9000. The IPv4 word is
// printed in host byte order (little-endian on x86-64 and arm64); the port is
// printed already in readable order.
func decodeAddr(s string) (string, error) {
	hostHex, portHex, ok := strings.Cut(s, ":")
	if !ok {
		return "", fmt.Errorf("bad address %q", s)
	}
	raw, err := hex.DecodeString(hostHex)
	if err != nil {
		return "", err
	}
	port, err := strconv.ParseUint(portHex, 16, 16)
	if err != nil {
		return "", err
	}
	ip := make(net.IP, len(raw))
	for i := 0; i+4 <= len(raw); i += 4 { // each 32-bit word is little-endian
		binary.BigEndian.PutUint32(ip[i:], binary.LittleEndian.Uint32(raw[i:]))
	}
	return net.JoinHostPort(ip.String(), strconv.Itoa(int(port))), nil
}

func main() {
	counts := map[string]int{}
	for _, path := range []string{"/proc/net/tcp", "/proc/net/tcp6"} {
		f, err := os.Open(path)
		if err != nil {
			fmt.Fprintln(os.Stderr, "not Linux or no procfs:", err)
			os.Exit(1)
		}
		sc := bufio.NewScanner(f)
		sc.Scan() // header line
		for sc.Scan() {
			fields := strings.Fields(sc.Text())
			if len(fields) < 5 {
				continue
			}
			st := states[fields[3]]
			counts[st]++
			if st == "LISTEN" {
				local, _ := decodeAddr(fields[1])
				// fields[4] is tx_queue:rx_queue; for a listener rx_queue is
				// the number of connections waiting in the accept queue.
				q := strings.SplitN(fields[4], ":", 2)
				backlog, _ := strconv.ParseUint(q[1], 16, 32)
				fmt.Printf("LISTEN %-22s raw=%s accept_queue=%d\n", local, fields[1], backlog)
			}
		}
		f.Close()
	}
	keys := make([]string, 0, len(counts))
	for k := range counts {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	for _, k := range keys {
		fmt.Printf("%-12s %d\n", k, counts[k])
	}
}
text
LISTEN 127.0.0.11:41713       raw=0B00007F:A2F1 accept_queue=0
LISTEN [::]:9200              raw=00000000000000000000000000000000:23F0 accept_queue=0
CLOSE_WAIT   4
LISTEN       2

Idle connections, keepalive and long-lived PHP workers ​

Database side: PostgreSQL counts every connection as a backend process, so the first question is how many sockets your fleet opens. max_connections "is typically 100"; the lab set it to 6 and the seventh client got FATAL: sorry, too many clients already.

sql
-- PostgreSQL: who holds connections, and in which state
SHOW max_connections;
SELECT backend_type, state, count(*)
FROM pg_stat_activity
GROUP BY 1, 2
ORDER BY 3 DESC;

-- idle-in-transaction sockets are the dangerous ones (locks + a pool slot)
SELECT pid, client_addr, client_port, now() - state_change AS idle_for
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY idle_for DESC;

-- MySQL equivalent
SHOW GLOBAL STATUS LIKE 'Threads_connected';
SHOW VARIABLES LIKE 'wait_timeout';

client_port is the client's ephemeral port: match it with ss -tnp on the app host to find the process. Laravel settings for timeouts, keepalive and persistent connections:

php
<?php

// config/database.php (excerpt): connection-level settings that matter for sockets.

return [
    'connections' => [
        'pgsql' => [
            'driver' => 'pgsql',
            'url' => env('DB_URL'),
            // Same host? A Unix socket directory skips TCP entirely:
            // 'host' => '/var/run/postgresql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'laravel'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => env('DB_CHARSET', 'utf8'),
            'prefix' => '',
            'search_path' => 'public',
            'sslmode' => env('DB_SSLMODE', 'prefer'),
            // libpq TCP keepalive, passed through by Laravel's PostgresConnector.
            // Probe after 60 s idle: below a NAT gateway's 350 s and an LB's 60-350 s.
            'keepalives' => 1,
            'keepalives_idle' => 60,
            'keepalives_interval' => 10,
            'keepalives_count' => 3,
            'options' => [
                // pdo_pgsql turns this into libpq connect_timeout (default 30 s).
                PDO::ATTR_TIMEOUT => 3,
                // Persistent PDO keeps the socket after the request, together
                // with any open transaction, temp table or session setting.
                // Prefer PgBouncer or Octane's long-lived connection instead.
                PDO::ATTR_PERSISTENT => false,
            ],
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            // 'unix_socket' => '/var/run/mysqld/mysqld.sock',
            'unix_socket' => env('DB_SOCKET', ''),
            'database' => env('DB_DATABASE', 'laravel'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'options' => [
                // pdo_mysql maps this to MYSQL_OPT_CONNECT_TIMEOUT.
                PDO::ATTR_TIMEOUT => 3,
            ],
        ],
    ],
];

PDO::ATTR_PERSISTENT pitfalls. PHP's manual: persistent connections "are not closed at the end of the script, but are cached and re-used", and "PDO does not perform any cleanup of persistent connections. Temporary tables, locks, transactions and other stateful changes may remain from previous usage". With php-fpm you get one connection per child per credential set, kept forever: 40 children × 10 servers = 400 PostgreSQL backends even when idle. Use PgBouncer or a pool instead; PgBouncer itself needs fds for max_client_conn + (max pool_size * total databases * total users).

Queue workers "are long-lived processes and store the booted application state in memory", so their sockets live for hours. Laravel reconnects once on a lost connection outside a transaction (handleQueryException rethrows when $this->transactions >= 1). WorkerIdle fires on every empty poll (Worker.php dispatches it, then sleeps --sleep seconds), so disconnecting on each event would recreate connection churn; disconnect once after a long quiet period:

php
<?php

namespace App\Providers;

use Illuminate\Queue\Events\WorkerIdle;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\ServiceProvider;

/**
 * Queue workers (and Octane workers) hold their DB, Redis and HTTP sockets
 * for hours. A NAT gateway or load balancer that silently drops an idle flow
 * leaves the worker with a dead socket that fails on the next job.
 *
 * WorkerIdle fires on EVERY empty poll (each --sleep interval), so never
 * disconnect on each event: that recreates the short-connection churn this
 * chapter warns about. Disconnect once, after a long quiet period. With the
 * "database" queue driver the poll itself uses the connection, so this only
 * makes sense for the redis / sqs drivers.
 */
class QueueConnectionHygiene extends ServiceProvider
{
    private const IDLE_BEFORE_DISCONNECT = 300; // seconds; below a 350 s NAT idle timeout

    private ?int $idleSince = null;

    private bool $disconnected = false;

    public function boot(): void
    {
        // Never carry a half-open transaction into the next job.
        Queue::looping(function () {
            while (DB::transactionLevel() > 0) {
                DB::rollBack();
            }
        });

        // A job is starting: the worker is busy again.
        Queue::before(function () {
            $this->idleSince = null;
            $this->disconnected = false;
        });

        Event::listen(function (WorkerIdle $event) {
            $this->idleSince ??= time();

            if (! $this->disconnected && time() - $this->idleSince >= self::IDLE_BEFORE_DISCONNECT) {
                // Close the DB socket ourselves; Laravel reconnects lazily on the
                // next query. Outside a transaction Laravel also retries once on a
                // "lost connection" error (Connection::tryAgainIfCausedByLostConnection).
                DB::disconnect();
                $this->disconnected = true;
            }
        });
    }
}

Octane "boots your application once, keeps it in memory", so DB, Redis and HTTP connections made in one request are reused by the next — real pooling for free, and also real staleness: combine keepalive settings with --max-requests (500 by default) to recycle workers.

php-fpm: the socket between nginx and PHP ​

conf
; /usr/local/etc/php-fpm.d/www.conf  (php-fpm pool for a Laravel app)
[www]
user = www-data
group = www-data

; Same host as nginx: a Unix socket, no TCP port, no TIME_WAIT, no conntrack.
listen = /run/php/php-fpm.sock
listen.owner = www-data
listen.group = nginx
listen.mode = 0660
; listen(2) backlog; still capped by net.core.somaxconn on Linux.
listen.backlog = 511

; Separate containers instead? Use TCP and restrict who may connect:
; listen = 0.0.0.0:9000
; listen.allowed_clients = 172.20.0.10

; One request = one child. max_children is the concurrency ceiling AND the
; ceiling on DB connections this pool can open (one per busy child).
pm = dynamic
pm.max_children = 40
pm.start_servers = 8
pm.min_spare_servers = 4
pm.max_spare_servers = 12
pm.max_requests = 1000

; Kill a stuck child; keep it above the slowest legitimate request.
request_terminate_timeout = 60s

; Expose pm status (active/idle/listen queue) to the web server only.
pm.status_path = /fpm-status

The PHP manual's warning on listen: "An exposed FastCGI endpoint allows arbitrary code execution. When the web server runs on the same host, a Unix socket should be preferred". Note listen.backlog (511 on Linux) is capped by somaxconn, and when all pm.max_children are busy, requests wait in that backlog.

Zero-downtime restarts with SO_REUSEPORT ​

go
// Command reuseport starts an HTTP server whose listening socket sets
// SO_REUSEADDR and SO_REUSEPORT. Run it twice on the same port: the kernel
// spreads new connections across both processes, and either one can be
// stopped while the other keeps serving (the basis of zero-downtime restarts).
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"syscall"

	"golang.org/x/sys/unix"
)

func reusePort(network, address string, c syscall.RawConn) error {
	var serr error
	err := c.Control(func(fd uintptr) {
		// Both options must be set before bind(2), on every socket in the group.
		if serr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1); serr != nil {
			return
		}
		serr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
	})
	if err != nil {
		return err
	}
	return serr
}

func main() {
	addr := flag.String("addr", ":8080", "listen address")
	flag.Parse()

	lc := net.ListenConfig{Control: reusePort}
	ln, err := lc.Listen(context.Background(), "tcp", *addr)
	if err != nil {
		log.Fatal(err)
	}
	pid := os.Getpid()
	log.Printf("pid %d listening on %s with SO_REUSEPORT", pid, ln.Addr())

	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "served by pid %d\n", pid)
	})
	log.Fatal(http.Serve(ln, h))
}
text
LISTEN 0      4096               *:8080            *:*    users:(("reuseport",pid=7,fd=3))
LISTEN 0      4096               *:8080            *:*    users:(("reuseport",pid=6,fd=3))
served by pid 6
served by pid 7
-- without REUSEPORT:
listen tcp :8080: bind: address already in use

Unix sockets ​

go
// Command unixsock serves a tiny echo protocol on a Unix domain socket, the
// transport php-fpm, PostgreSQL, Redis and the Docker daemon use locally.
// Access is controlled by file permissions, not by ports or firewalls.
package main

import (
	"bufio"
	"errors"
	"fmt"
	"io/fs"
	"log"
	"net"
	"os"
	"path/filepath"
)

func main() {
	path := filepath.Join(os.TempDir(), "echo.sock")
	// A stale socket file from a crashed run makes bind fail with EADDRINUSE.
	if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
		log.Fatal(err)
	}
	ln, err := net.Listen("unix", path)
	if err != nil {
		log.Fatal(err)
	}
	defer ln.Close() // net.UnixListener unlinks the file on Close
	// Like php-fpm listen.mode = 0660: owner and group may connect, others not.
	if err := os.Chmod(path, 0o660); err != nil {
		log.Fatal(err)
	}

	go func() {
		c, err := ln.Accept()
		if err != nil {
			return
		}
		defer c.Close()
		line, _ := bufio.NewReader(c).ReadString('\n')
		fmt.Fprintf(c, "echo: %s", line)
	}()

	c, err := net.Dial("unix", path)
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
	fmt.Fprintln(c, "hello over", path)
	reply, _ := bufio.NewReader(c).ReadString('\n')
	fmt.Print(reply)
}

UDP drops ​

go
// Command udpdrop shows that UDP has no backpressure: a fast sender and a
// slow receiver with a small receive buffer lose datagrams silently. The
// kernel counts them as receive buffer errors (nstat UdpRcvbufErrors).
package main

import (
	"flag"
	"fmt"
	"net"
	"time"
)

func main() {
	n := flag.Int("n", 20000, "datagrams to send")
	rcvbuf := flag.Int("rcvbuf", 8192, "SO_RCVBUF bytes (kernel doubles it)")
	flag.Parse()

	rc, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
	if err != nil {
		panic(err)
	}
	defer rc.Close()
	_ = rc.SetReadBuffer(*rcvbuf)

	received := make(chan int)
	go func() {
		buf := make([]byte, 1500)
		count := 0
		for {
			_ = rc.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
			if _, _, err := rc.ReadFromUDP(buf); err != nil {
				received <- count
				return
			}
			count++
			time.Sleep(20 * time.Microsecond) // a "slow" consumer
		}
	}()

	sc, err := net.DialUDP("udp", nil, rc.LocalAddr().(*net.UDPAddr))
	if err != nil {
		panic(err)
	}
	defer sc.Close()
	payload := make([]byte, 512)
	sendErrs := 0
	for i := 0; i < *n; i++ {
		if _, err := sc.Write(payload); err != nil {
			sendErrs++ // sendto succeeds even when the receiver will drop it
		}
	}
	got := <-received
	fmt.Printf("sent=%d send_errors=%d received=%d lost=%d\n", *n, sendErrs, got, *n-sendErrs-got)
}

File descriptor limit ​

go
// Command fdlimit prints the RLIMIT_NOFILE soft and hard limits, then opens
// TCP connections to a local listener until accept or dial fails with EMFILE
// ("too many open files"). Every socket is a file descriptor.
package main

import (
	"errors"
	"fmt"
	"net"
	"syscall"
)

func main() {
	var lim syscall.Rlimit
	if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &lim); err == nil {
		// The Go runtime raises the soft limit to just under the hard limit at start-up,
		// so to see EMFILE set BOTH (docker run --ulimit nofile=256:256).
		fmt.Printf("RLIMIT_NOFILE soft=%d hard=%d\n", lim.Cur, lim.Max)
	}

	ln, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		panic(err)
	}
	defer ln.Close()
	go func() {
		var held []net.Conn // accepted sockets: one fd each, server side
		for {
			c, err := ln.Accept()
			if err != nil {
				if errors.Is(err, syscall.EMFILE) {
					fmt.Println("accept:", err)
					return
				}
				return
			}
			held = append(held, c)
		}
	}()

	var conns []net.Conn // dialled sockets: one fd each, client side
	for {
		c, err := net.Dial("tcp", ln.Addr().String())
		if err != nil {
			fmt.Printf("dial #%d: %v (EMFILE=%v)\n", len(conns)+1, err, errors.Is(err, syscall.EMFILE))
			break
		}
		conns = append(conns, c)
	}
	for _, c := range conns {
		c.Close()
	}
}

Troubleshooting table ​

SymptomCheckLikely causeFix
connection refused in msss -ltnp on the server; nc -zvService down, wrong port, listening on 127.0.0.1 inside a containerStart it; bind 0.0.0.0; fix port mapping
Connect hangs, then timeouttcpdump on both ends: SYN leaves, nothing returnsFirewall/security group, wrong IP, full accept queueOpen the rule; fix IP; scale the server
cannot assign requested addressss -s timewait; ss -tan state time-wait | wc -lEphemeral ports exhaustedKeep-alive and pools
too many open filesls /proc/PID/fd | wc -l; lsof -p PIDLeak or low limitFix leak; raise ulimit -n
Growing CLOSE_WAITss -tanp state close-waitMissing close()Fix code, read deadlines
Works for hours, then first request after idle failsCompare idle times with NAT/LB timeoutsMiddlebox dropped the idle flowKeepalive below the timeout; client idle timeout
Random 502 from nginx to upstream keep-alivenginx error log, upstream IdleTimeoutUpstream closes idle conns just as nginx reuses themUpstream idle timeout above nginx's
address already in use on deployss -ltnp 'sport = :8080'Old process still runningGraceful handover, SO_REUSEPORT
UDP metrics missingnstat -az UdpRcvbufErrorsReceive buffer overflowBigger SO_RCVBUF, faster reader
nf_conntrack: table full in dmesgnf_conntrack_count vs _maxToo many flows through NATPools; raise limit
sorry, too many clients already (PostgreSQL)pg_stat_activityNo pooling; persistent connectionsPgBouncer, smaller pools
Latency spikes of tens of ms on small requestsss -ti, captureNagle + delayed ACKOne write per message; TCP_NODELAY

Choosing ​

SituationRecommendationExtra techniqueReason
Service calls another service over HTTPOne shared client/transport with keep-aliveMaxIdleConnsPerHost ≈ expected concurrency; idle timeout below server'sHandshake and TLS once, no TIME_WAIT churn
App and DB on the same hostUnix socketMode 0660, shared groupLower latency; no ports, no conntrack
php-fpm with many app servers to one PostgreSQLPgBouncer (transaction mode)Small default_pool_sizeBounded backends; fpm children stay cheap
Octane / queue workersLong-lived connections + keepalive--max-requests, --max-jobs, one disconnect after long WorkerIdleReuse without staleness
Client behind cloud NATTCP keepalive idle below 350 s (AWS NAT)Pools; more NAT IPs at high fan-outNAT drops idle flows and limits ports per IP
Public HTTP serverAll server timeouts setLB idle timeout below app IdleTimeoutSlowloris and LB races
Very high connection rate from one client hostPools first; then tcp_tw_reuse=1, wider port rangeReserve listen portsEach tuple blocked 60 s
Multi-core accept-heavy server (proxy, DNS)SO_REUSEPORT per workerBPF steering if neededNo single accept bottleneck
Fire-and-forget metricsUDPBigger receive bufferLoss acceptable, no backpressure on the app
Debugging "it can't connect"nc -zv then tcpdumpdig first if a name is involvedRefused vs timeout vs DNS in one minute

In architecture: from a single process to a distributed system ​

Sockets are where architecture becomes resource counts. Every arrow in a diagram is a set of connections, each with two ports, two fds, maybe a conntrack entry and a TIME_WAIT afterwards. The everyday example through this section is a Laravel shop; the production example is a Go payments API.

Monolith: one process, one database ​

Everyday: nginx and php-fpm on one VM, PostgreSQL and Redis on the same VM. Use Unix sockets for nginx→fpm and app→DB/Redis; the only TCP ports exposed are 80/443 and 22. The connection count equals pm.max_children (each busy child opens one DB socket), so max_children must stay below PostgreSQL's max_connections minus admin slots. The first scaling incident is usually fpm saturation: requests wait in the fpm backlog, nginx returns 502/504.

Production: a single Go binary uses one database/sql pool (SetMaxOpenConns(20)), one shared http.Client, server timeouts set, and a /metrics endpoint that exports socket states from /proc/net/tcp.

Modular monolith and multiple databases ​

Modules share a process, so they must share pools: one http.Client per upstream, not per module; one DB pool per database. Two modules each creating their own Guzzle client or sql.DB double the sockets silently. Ownership of a connection (who closes it) is a module boundary decision: a module that receives a *sql.Tx must not close the connection under it.

Microservices ​

Every call is now a network call: a request through 5 services is 5 connection pools, 5 sets of timeouts and 5 places for TIME_WAIT. The rules that survive:

text
1  client -> ALB (idle 60 s) -> api-gateway (Go, IdleTimeout 120 s)
2  api-gateway -> orders (keep-alive pool, IdleConnTimeout 50 s < orders' 75 s)
3  orders -> payments: connect 1 s, total 3 s, derived from the incoming request's context deadline
4  payments -> PostgreSQL via PgBouncer (pool 20) ; -> card network over NAT (keepalive 60 s < 350 s)
5  each hop's idle timeout > the hop in front of it; each timeout < the caller's remaining deadline

Service meshes (Envoy sidecars) add two more sockets per call (app→sidecar on localhost, sidecar→sidecar) but make pooling and timeouts uniform; see Service Mesh. Retries after ECONNRESET are safe only with idempotency keys, as the Laravel PaymentGatewayClient sends.

Distributed data: replicas, caches, NAT and containers ​

Read replicas and caches multiply destinations, which multiplies pools but also spreads ephemeral ports (the limit is per destination). The dangerous places are the shared middle boxes: a cloud NAT gateway that every pod's egress goes through, a Docker host's bridge SNAT, a Kubernetes node's conntrack table. Ports and conntrack entries are shared there by everything behind them. Failovers create waves: when a Redis primary moves, every client reconnects at once, which can overflow the new primary's accept queue — jittered reconnect backoff matters. Ports inside a container are not ports on the host: -p 127.0.0.1:18080:8080 maps the host's 18080 to the container's 8080 through Docker's proxy/NAT; --network host removes the NAT (and its conntrack cost) but also the isolation. Details: Docker Networking, Kubernetes Networking.

Scaling path: 1×, 10×, 100× ​

LoadWhat breaks firstChange
1× (one VM)fpm children, max_connectionsUnix sockets, timeouts, size pm.max_children
10× (several app servers, one DB)DB connections (servers × children), TIME_WAIT on clients without keep-alivePgBouncer, shared HTTP clients, Octane or Go with pools
100× (containers, NAT egress, many services)NAT ports and conntrack, idle-timeout resets, accept queue during failoversPer-AZ NAT with more IPs, keepalive below NAT timeout, conntrack sizing, SO_REUSEPORT/more replicas, reconnect jitter

Lab ​

Everything runs in Docker; network sysctls are per container namespace, so nothing touches your host. Build the tools image and the Go binaries:

bash
cat > Dockerfile <<'EOT'
FROM alpine:3
RUN apk add --no-cache iproute2 iproute2-ss tcpdump netcat-openbsd curl bind-tools lsof iperf3 mtr busybox-extras net-tools conntrack-tools xxd bash python3
EOT
docker build -t psc-lab .
cd docs/snippets/foundations/ports-sockets-connections/go
for d in labserver twgen reuseport httpclient httpserver sockstat dialerrors fdlimit udpdrop unixsock; do
  CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o /tmp/psc/$d ./$d   # GOARCH=amd64 on Intel
done
docker network create psc-net
docker run -d --name psc-srv --network psc-net -v /tmp/psc:/lab:ro psc-lab /lab/labserver -addr :9000

1. 20 000 short connections, then keep-alive.

bash
docker run --rm --network psc-net --sysctl net.ipv4.tcp_tw_reuse=0 -v /tmp/psc:/lab:ro psc-lab sh -c '
  /lab/twgen -addr psc-srv:9000 -n 20000 -mode short; ss -s | head -2; ss -tano state time-wait | head -3'
# mode=short ok=20000 eaddrnotavail=0 refused=0 other=0 elapsed=1.184s
# TCP:   20082 (estab 0, closed 20081, orphaned 0, timewait 20000)
# 172.21.0.3:32768   172.21.0.2:9000 timer:(timewait,58sec,0)
docker exec psc-srv sh -c 'ss -tan state time-wait | tail -n +2 | wc -l'   # 0: the server did not close first
docker run --rm --network psc-net --sysctl net.ipv4.ip_local_port_range="50000 50999" -v /tmp/psc:/lab:ro psc-lab sh -c '
  /lab/twgen -addr psc-srv:9000 -n 5000 -mode short'
# mode=short ok=999 eaddrnotavail=4001 ...            <- ports exhausted
docker run --rm --network psc-net --sysctl net.ipv4.ip_local_port_range="50000 50999" -v /tmp/psc:/lab:ro psc-lab sh -c '
  /lab/twgen -addr psc-srv:9000 -n 20000 -mode reuse; ss -tan state time-wait | tail -n +2 | wc -l'
# mode=reuse ok=20000 eaddrnotavail=0 ... elapsed=77ms
# 50                                                  <- one per worker, at exit

2. tcp_tw_reuse and its delay. With --sysctl net.ipv4.tcp_tw_reuse=1, a second burst of 999 two seconds after the first succeeds (ok=999); with 0 it fails (ok=0 eaddrnotavail=999). A burst inside the same second fails either way: tcp_tw_reuse_delay is 1000 ms.

3. Fill the accept queue and watch SYN retries.

bash
docker run -d --name psc-bl --network psc-net --sysctl net.core.somaxconn=4 -v /tmp/psc:/lab:ro psc-lab /lab/labserver -addr :9100 -noaccept
docker exec -d psc-bl tcpdump -i eth0 -nn -w /tmp/syn.pcap "tcp port 9100 and tcp[tcpflags] & tcp-syn != 0"   # capture FIRST
docker run --rm --network psc-net psc-lab sh -c 'for i in $(seq 10); do (nc -w 8 psc-bl 9100 </dev/null >/dev/null 2>&1 &); done; sleep 4; ss -tan | grep 9100'
# ESTAB    0 0 172.21.0.5:50952 172.21.0.4:9100     (x5: accepted by the kernel, never by the app)
# SYN-SENT 0 1 172.21.0.5:50996 172.21.0.4:9100     (x5: SYNs dropped)
docker exec psc-bl sh -c 'ss -ltn; nstat -az TcpExtListenOverflows TcpExtListenDrops'
# LISTEN 5      4                  *:9100             *:*
# TcpExtListenOverflows           20
# TcpExtListenDrops               20
docker exec psc-bl sh -c 'pkill tcpdump; sleep 1; tcpdump -nn -r /tmp/syn.pcap'
# 18:18:22.915043 IP 172.21.0.8.39214 > 172.21.0.4.9100: Flags [S], seq 3199031753 ...
# 18:18:23.976279 IP 172.21.0.8.39214 > 172.21.0.4.9100: Flags [S], seq 3199031753 ...   (+1 s, same seq: retry)
# and again every second for the first 4 retries (tcp_syn_linear_timeouts=4), then 2 s, 4 s ...
docker run --rm --network psc-net psc-lab sh -c 'nc psc-bl 9100 </dev/null; echo exit=$?'   # no -w: gives up after 133 s

4. Leak CLOSE_WAIT and find it.

bash
docker run -d --name psc-leak --network psc-net -v /tmp/psc:/lab:ro psc-lab /lab/labserver -addr :9200 -leak
docker run --rm --network psc-net psc-lab sh -c 'for i in 1 2 3; do printf "hi\n" | timeout 2 nc -N -w 1 psc-leak 9200; done; ss -tano | grep 9200'
# FIN-WAIT-2 0 0 172.21.0.6:46034 172.21.0.5:9200 timer:(timewait,56sec,0)
docker exec psc-leak sh -c 'ss -tanp state close-wait; /lab/sockstat'
# 0 0 [::ffff:172.21.0.5]:9200 [::ffff:172.21.0.6]:46034 users:(("labserver",pid=1,fd=7))
# CLOSE_WAIT   4

Restart it without -leak: the count stays at 0.

5. Capture a handshake and a RST.

bash
docker exec -d psc-srv tcpdump -i eth0 -nn -S "tcp port 9000 or tcp port 9999" -w /tmp/c.pcap
docker run --rm --network psc-net psc-lab sh -c 'printf "ping\n" | nc -N -w 1 psc-srv 9000; nc -zv -w 2 psc-srv 9999'
# nc: connect to psc-srv (172.21.0.2) port 9999 (tcp) failed: Connection refused
docker exec psc-srv sh -c 'pkill tcpdump; sleep 1; tcpdump -nn -r /tmp/c.pcap'
# 172.21.0.3.37178 > 172.21.0.2.9000: Flags [S], seq 2933136187, win 64240, options [mss 1460 ...
# 172.21.0.2.9000 > 172.21.0.3.37178: Flags [S.], seq 1180098624, ack 2933136188, win 65160, ...
# 172.21.0.3.37178 > 172.21.0.2.9000: Flags [.], ack 1, win 63, ...            (relative numbers from here; -S keeps absolute)
# 172.21.0.3.37178 > 172.21.0.2.9000: Flags [P.], seq 1:6, ack 1, ...          ("ping\n")
# 172.21.0.3.37178 > 172.21.0.2.9000: Flags [F.], seq 6, ack 1, ...
# 172.21.0.2.9000 > 172.21.0.3.37178: Flags [P.], seq 1:6, ack 7, ...
# 172.21.0.2.9000 > 172.21.0.3.37178: Flags [F.], seq 6, ack 7, ...
# 172.21.0.3.37178 > 172.21.0.2.9000: Flags [.], ack 7, ...
# 172.21.0.3.47708 > 172.21.0.2.9999: Flags [S], seq 4203362739, ...
# 172.21.0.2.9999 > 172.21.0.3.47708: Flags [R.], seq 0, ack 4203362740, win 0, length 0

6. Hit the fd limit, drop UDP, publish a port.

bash
docker run --rm --ulimit nofile=256:256 -v /tmp/psc:/lab:ro psc-lab /lab/fdlimit
# RLIMIT_NOFILE soft=256 hard=256
# dial #126: dial tcp 127.0.0.1:46339: socket: too many open files (EMFILE=true)
docker run --rm --ulimit nofile=256:4096 -v /tmp/psc:/lab:ro psc-lab /lab/fdlimit
# RLIMIT_NOFILE soft=4095 hard=4096        <- Go raised the soft limit itself
docker run --rm -v /tmp/psc:/lab:ro psc-lab sh -c '/lab/udpdrop; nstat -az UdpRcvbufErrors'
# sent=20000 send_errors=0 received=548 lost=19452
# UdpRcvbufErrors                 19452
docker run -d --name psc-pub -p 127.0.0.1:18080:8080 -v /tmp/psc:/lab:ro psc-lab /lab/httpserver
docker port psc-pub                     # 8080/tcp -> 127.0.0.1:18080
docker exec psc-pub ss -ltn             # LISTEN 0 4096 *:8080   (inside: the container port)
lsof -nP -iTCP:18080 -sTCP:LISTEN       # on macOS: Docker Desktop's forwarder holds 127.0.0.1:18080

Clean up: docker rm -f psc-srv psc-bl psc-leak psc-pub; docker network rm psc-net.

Common misconceptions ​

BeliefReality
TIME_WAIT is a kernel problem to tune awayIt is correct TCP; many TIME_WAIT means no connection reuse
TIME_WAIT is on the serverIt is on whichever side closed first; in the lab it was all on the client
tcp_fin_timeout shortens TIME_WAITIt limits orphaned FIN-WAIT-2; Linux TIME_WAIT is a fixed 60 s
CLOSE_WAIT times out eventuallyIt has no timer; only your close() ends it
A server port limits the number of clients to 65 535The client's IP:port makes each connection unique; the limits are fds and memory
Refused and timed out are the sameRefused = RST from a live host; timeout = packets dropped
listen(fd, 100000) gives a 100 000 queueCapped silently at somaxconn (4096 since Linux 5.4)
HTTP keep-alive keeps idle connections alive through NATIt sends nothing while idle; only TCP keepalive or heartbeats do
TCP keepalive is on by defaultOff unless SO_KEEPALIVE; and the first probe is after 2 h (Go turns it on at 15 s)
write() succeeded, so the peer got the dataIt is in your kernel's send buffer
Raising ulimit -n fixes "too many open files"Only if there is no leak
SO_REUSEADDR lets two servers share a portThat is SO_REUSEPORT on Linux
A UDP send error tells you about lossUDP drops silently on the receiver (UdpRcvbufErrors)
PDO::ATTR_PERSISTENT is a connection poolIt is one cached connection per fpm child, with leftover session state

Cheat sheet ​

TopicRemember
Port ranges0–1023 system, 1024–49151 registered, ephemeral: Linux 32768–60999, macOS 49152–65535
5-tupleproto, src IP, src port, dst IP, dst port; towards one server only the src port varies
~470/s28 000 ports ÷ 60 s TIME_WAIT = new connections per second per destination without reuse
TIME_WAITactive closer, 2MSL, 60 s Linux, 30 s macOS; fix with keep-alive and pools
CLOSE_WAITyour bug: a missing close()
Accept queuess -ltn Recv-Q vs Send-Q; somaxconn 4096; ListenOverflows
Refused vs timeoutRST in ms vs silence until your connect timeout
EADDRNOTAVAILephemeral ports exhausted
EMFILEfd limit; lsof -p, ulimit -n; Go raises soft limit itself
KeepaliveTCP keepalive ≠ HTTP keep-alive ≠ heartbeat; probe below the shortest idle timeout (AWS NAT 350 s, ALB 60 s)
Timeoutsconnect, TLS, header, total, read/write, idle — set all; http.Server zero value has none
conntracknf_conntrack_max; "table full, dropping packet" = silent connect timeouts
Unix socketssame-host fpm/DB/Redis; 0660 permissions; docker.sock = root
First toolsss -tulpn, ss -s, nc -zv, curl -v --connect-timeout, tcpdump -nn port N, dig +short

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A Go service logs dial tcp 10.0.1.9:5432: connect: cannot assign requested address. What is exhausted, and what is the first fix? Must-know ​

Answer

Answer: Ephemeral ports towards that one destination: too many connections were opened and closed by this host, and their tuples sit in TIME_WAIT. Reuse connections: a bounded database/sql pool (or PgBouncer) instead of open/close per query. See Ephemeral port exhaustion.

2 — ss -s on an API server shows 30 000 TIME_WAIT. Is the server or the client misbehaving? Important ​

Answer

Answer: The server is closing first — for example Connection: close, keep-alive disabled, or a short server idle timeout. TIME_WAIT on a server does not exhaust its ports (they are all the listen port), so it is mostly harmless, but it signals that clients are not reusing connections. See TIME_WAIT.

3 — Why does CLOSE_WAIT never time out, and how do you find who owns it? Important ​

Answer

Answer: The kernel is waiting for the local application to call close(); there is no timer for that. ss -tanp state close-wait or lsof -nP -p PID -a -i shows the process and fd. See CLOSE_WAIT leaks.

4 — ss -ltn shows LISTEN 129 128 *:8080. What does it mean? Good to know ​

Answer

Answer: Recv-Q 129 connections are waiting in the accept queue, whose limit (Send-Q) is 128: the queue is full (Linux allows backlog+1). The app is not calling accept() fast enough; new SYNs are dropped and clients retry. See Backlog.

5 — A worker's first query after a quiet night fails with "server closed the connection unexpectedly". Name the mechanism and two fixes. Important ​

Answer

Answer: A middlebox (cloud NAT at 350 s, LB, firewall) dropped the idle flow and answered the next packet with RST. Fix: TCP keepalive below that timeout (libpq keepalives_idle, Go KeepAliveConfig), and/or disconnect yourself once after a long idle period (WorkerIdle counted to 300 s → DB::disconnect()). See Keepalive.

6 — What is the difference between ECONNRESET and EPIPE? Must-know ​

Answer

Answer: ECONNRESET: a RST arrived. EPIPE: you wrote after the connection was already known to be closed. Both mean "peer gone"; retry only idempotent work. See Error codes.

7 — Why did the Go fdlimit program need --ulimit nofile=256:256 rather than 256:4096 to fail at 256? Good to know ​

Answer

Answer: The Go runtime raises its soft RLIMIT_NOFILE to just under the hard limit (Max − 1) at start-up, so only the hard limit binds a Go program. See File descriptor limits.

8 — Laravel's Http::get() in a loop under Octane: does it reuse connections? How do you make it? Important ​

Answer

Answer: Not by default: each request builds a new Guzzle client and new cURL handles. Share one CurlHandler (singleton) via Http::setHandler(), as in the keepAlive macro; cURL keeps live connections across curl_reset. See Connection reuse.

9 — When is SO_REUSEPORT useful and what does SO_REUSEADDR actually do on Linux? Good to know ​

Answer

Answer: SO_REUSEPORT lets several sockets listen on the same address with kernel load distribution (per-worker accept queues, zero-downtime handover). SO_REUSEADDR lets you bind while old connections on that port are in TIME_WAIT, but not while another socket is listening. See SO_REUSEPORT.

10 — A UDP metrics receiver shows fewer events than were sent and no errors in the sender. Where do you look? Important ​

Answer

Answer: The receiver host's nstat -az UdpRcvbufErrors: datagrams dropped because the receive buffer was full. Raise SO_RCVBUF (and rmem_max) or read faster. See UDP sockets.

11 — Why prefer a Unix socket between nginx and php-fpm on the same host? Must-know ​

Answer

Answer: No TCP stack, no ports, no TIME_WAIT, no conntrack, lower latency, and access controlled by file permissions; an exposed FastCGI TCP port allows arbitrary code execution. See Unix domain sockets.

Glossary ​

TermMeaning
Port16-bit number selecting a socket on a host, per protocol
Well-known / system port0–1023 (RFC 6335)
Registered / user port1024–49151
Ephemeral / dynamic portTemporary client port; Linux ip_local_port_range 32768–60999
ip_unprivileged_port_startLowest port non-root may bind (1024; 0 in Docker)
SocketKernel endpoint object, held through a file descriptor
File descriptor (fd)Integer handle to a file, socket or pipe in a process
5-tupleProtocol, source IP, source port, destination IP, destination port
Listening socketSocket after listen(); produces new sockets via accept()
SYN / SYN+ACK / ACKThe three-way handshake segments
FINSegment that closes one direction
RSTReset: abort a connection; the answer of a closed port
SYN_SENT / SYN_RECVHandshake states of client / server
ESTABLISHEDOpen connection
FIN_WAIT_1 / FIN_WAIT_2Active closer waiting for ACK / peer's FIN
CLOSE_WAITPeer closed; local app has not
LAST_ACKPassive closer waiting for the final ACK
TIME_WAITActive closer keeps the tuple for 2MSL
MSL / 2MSLMaximum Segment Lifetime (RFC: 2 min); TIME_WAIT duration
tcp_tw_reuseReuse TIME_WAIT tuples for outgoing connects (0/1/2, default 2)
Port exhaustionNo free ephemeral port for a destination: EADDRNOTAVAIL
Half-closeshutdown(SHUT_WR): send FIN, keep reading
Half-open connectionOne side is gone without FIN/RST; the other still thinks it is open
Backloglisten() argument: accept queue size
SYN queueHalf-open connections; tcp_max_syn_backlog
Accept queueCompleted connections awaiting accept(); somaxconn cap
somaxconnKernel cap on any listen backlog (4096 since 5.4)
SYN cookiesStateless SYN/ACK when the SYN queue overflows
ListenOverflows / ListenDropsKernel counters for accept queue drops
TCP keepaliveKernel probes on idle connections (SO_KEEPALIVE, tcp_keepalive_time)
HTTP keep-alive / persistent connectionReusing one TCP connection for many HTTP requests
HeartbeatApplication-level liveness message (AMQP, WebSocket ping)
Idle timeoutTime after which a server, LB or NAT drops an unused connection
Nagle's algorithmHolds small writes while data is unacknowledged (RFC 896)
TCP_NODELAYSocket option disabling Nagle
Delayed ACKReceiver waits briefly before acknowledging
TCP_USER_TIMEOUTMax time sent data may stay unacknowledged before the connection is closed
SO_RCVBUF / SO_SNDBUFPer-socket buffer sizes (kernel doubles the value)
tcp_rmem / tcp_wmemAutotuning min/default/max buffer sizes
Window / window scaleReceiver's free buffer advertised to the sender; scale multiplies it
MSSMaximum Segment Size, in the SYN options (1460 on Ethernet)
conntrackNetfilter's table of tracked flows used by NAT and stateful firewalls
nf_conntrack_maxSize limit of the conntrack table
SNAT / MASQUERADERewriting the source address (and port) of outgoing traffic
RLIMIT_NOFILE / ulimit -nPer-process fd limit (soft/hard)
fs.file-maxHost-wide fd limit
EMFILE / ENFILEProcess / system out of fds
SO_REUSEADDRBind despite TIME_WAIT connections on the port
SO_REUSEPORTSeveral listening sockets on one address, kernel load-balanced
Unix domain socketLocal socket addressed by a file path, permission-controlled
Abstract socketLinux Unix socket name not on the filesystem (leading NUL)
UDPConnectionless datagrams, no retransmission, no backpressure
UdpRcvbufErrorsCounter of UDP datagrams dropped for a full receive buffer
ECONNREFUSEDRST in reply to SYN: nothing listening
ETIMEDOUTNo reply in time
EADDRINUSELocal address already bound
EADDRNOTAVAILNo usable local address/port
ECONNRESETConnection reset by peer
EPIPE / broken pipeWrite to a closed connection
Connection poolSet of reused open connections with a size limit
PgBouncerPostgreSQL connection pooler
PDO::ATTR_PERSISTENTPHP persistent DB connection cached per process
php-fpm pm.max_childrenMax PHP worker processes in a pool
OctaneLaravel app server keeping the app (and its connections) in memory
ssiproute2 socket statistics tool
lsofLists open files, including sockets, per process
netstatLegacy socket listing (net-tools; standard on macOS)
nettopmacOS live per-process network view
nc (netcat)Raw TCP/UDP client/listener; -z scan, -v verbose
tcpdumpPacket capture; -nn no name resolution, -X hex
digDNS query tool
traceroute / mtrPath and per-hop loss
iperf3Throughput tester

References ​

Built by Morteza Negahi