Chapters

Sockets, Nagle & keepalives: TCP from your code

Chapters 16-20 described TCP from the network's side. This chapter looks at the same things from kade-api's code: the calls your app makes, the queues it can overflow, a 40 ms delay hiding in small writes, and the timeouts that quietly kill idle connections.

Layers, routing and transport · chapter 21 of 34 · 8 min read

A socket is your app's handle

Apps never build segments themselves. They ask the OS for a socket, a handle for one endpoint of communication, and call a few functions on it. Each call maps to something you already know from the wire:

#CallSideWhat the OS doesIn Node.js
1socket()bothCreates the handle (TCP or UDP)done for you
2bind(ip, port)serverClaims the port (443)server.listen(443) does bind + listen
3listen(backlog)serverState → LISTEN; creates the queues (section 3)backlog defaults to 511
4connect(ip, port)clientPicks an ephemeral port, sends SYN, waits for the handshakenet.connect(), fetch(), a pg pool
5accept()serverTakes one finished connection from the queue and returns a new socket for itthe 'connection' event
6write() / read()bothCopy bytes into the send buffer / out of the receive buffer (chapter 19)socket.write(), 'data' events
7close()bothSends FIN (chapter 16)socket.end(); destroy() may send RST

One listening socket, many connected sockets

kade-api has one listening socket on port 443. Every accepted connection gets its own new socket, told apart by the 4 values from chapter 1. So thousands of clients can all talk to port 443 at once: the server port is never "used up".

$ ss -tn state all '( sport = :443 )'
State       Local Address:Port    Peer Address:Port
LISTEN      0.0.0.0:443           0.0.0.0:*
ESTAB       10.10.1.10:443        203.0.113.45:40001     ← your laptop (after home NAT)
ESTAB       10.10.1.10:443        203.0.113.45:40003     ← your phone, same public IP
ESTAB       10.10.1.10:443        198.51.100.20:40117    ← the office front desk PC
Port limits (chapter 10) only hit the client side: each outgoing connection needs its own ephemeral port toward the same destination.

The two queues behind listen()

Between the SYN arriving and your code seeing a connection, it waits in two kernel queues:

ClientsSYN, then ACKSYN queuehalf-open: SYN-RECEIVEDwaiting for the final ACKACKAccept queueESTABLISHED, not yet takensize = backlogaccept()Node apphandles itFull SYN queue: SYN flood (chapter 16).Full accept queue: the app is not calling accept() fast enough.

Wide by design - scroll it sideways.

If kade-api's event loop is blocked (a big synchronous JSON parse, say), it stops accepting. The accept queue fills up to the backlog, and the kernel then ignores new handshakes. Clients see slow connects and timeouts, even though the VM looks fine. Two things to know:

  • The backlog you ask for is capped by the OS (net.core.somaxconn, 4096 on current Linux).
  • ss -lnt shows it live: on a LISTEN line, Recv-Q is how many connections are waiting now, Send-Q is the backlog. Recv-Q near Send-Q means the app is falling behind.

"Address already in use"

You restart kade-api and get EADDRINUSE. Two possible causes:

Old connections in TIME-WAITConnections the old process closed are still in TIME-WAIT (chapter 16) on port 443. Without the SO_REUSEADDR socket option, the OS refuses to bind the port again for up to a minute. Node sets this option for you on listening sockets, so this is mostly a problem in other languages.
Something is still listeningThe usual cause in Node: the old process has not exited yet, or a second copy is running. Check with lsof -iTCP:443 -sTCP:LISTEN.
SO_REUSEPORT is different: it lets several processes listen on the same port on purpose, and the kernel spreads connections between them.

Nagle's algorithm and the 40 ms mystery

Nagle's algorithm was built to stop apps from flooding networks with tiny packets (each 1-byte write would otherwise cost 40 bytes of headers). The rule: while any sent data is still unacknowledged, hold new small writes and send them together later.

On its own that is fine. Combined with delayed ACK on the other side (chapter 17), it creates a classic stall. kade-api sends a request to a service as two small writes, headers then body:

kade-api (client)order service0 ms · write 1: headers (200 bytes)write 2 (body, 100 bytes) is called at once, but Nagle holds it: write 1 is not ACKed yetthe service waits for more data before ACKing (delayed ACK)≈ 40 ms · ACK (delayed-ACK timer fired)≈ 40 ms · write 2 finally sentresponseevery small two-part request pays ~40 ms

The fix is the TCP_NODELAY socket option, which turns Nagle off, or writing each message in one go. In Node:

socket.setNoDelay(true);   // raw net sockets: Nagle is on by default
// Node's http module, and most database drivers (e.g. pg), already turn it off for you.

TCP keepalive (not HTTP keep-alive)

Two features with nearly the same name do completely different things:

TCP keepalive

After a connection sits idle for a while, the OS sends a tiny empty probe to check the other side is alive, and keeps NAT and firewall rows fresh.

Off by default. Linux defaults when on: first probe after 2 hours (!), then every 75 s, give up after 9.

HTTP keep-alive

Reusing one TCP connection for many HTTP requests instead of opening a new one each time (chapter 16's handshake cost).

An HTTP feature. Sends nothing while idle.

The Linux default of 2 hours is far longer than any NAT or firewall timeout (next section), so on its own it saves nothing. Set a short delay per socket:

socket.setKeepAlive(true, 60_000);          // first probe after 60 s idle
new pg.Pool({ keepAlive: true, keepAliveInitialDelayMillis: 60_000 });

Who drops idle connections

An idle TCP connection passes through many boxes that each forget it after their own timeout. When one forgets, the next packet gets a RST or silence (chapters 10 and 16). For Kadé:

#WhereIdle timeout (defaults)Affects
1Home / office routers (NAT)varies: minutes to hoursLong-lived connections from laptops and PCs
2GCP firewall connection trackingabout 10 minutes for established TCPkade-api ⇄ kade-db, and anything through VPC firewall rules
3Cloud NAT (planned)20 minutes for established TCP (chapter 10)kade-api → PayGate after the load balancer arrives
4GCP external application load balancer (planned)keeps idle client and backend connections about 10 minutes (610 s at the time of writing)Browsers and apps → api.kade.lk
5Node HTTP serverserver.keepAliveTimeout = 5 skade-api closes idle HTTP connections after 5 s
6node-postgres poolidleTimeoutMillis = 10 skade-api's idle DB connections
Cloud defaults change; confirm current values in GCP's documentation before relying on them.

Connection pools

Everything in Section 2 argues for reusing connections: every new connection costs a handshake (and TLS), starts in slow start (chapter 20), uses an ephemeral port and leaves a TIME-WAIT behind. So kade-api keeps pools of open connections:

const db = new pg.Pool({
  max: 20,                          // at most 20 connections to kade-db
  idleTimeoutMillis: 30_000,          // close idle ones well before the ~10 min firewall timeout
  keepAlive: true,
});

const payGate = new https.Agent({ keepAlive: true, maxSockets: 50 });  // reuse connections to PayGate
Node 19 and later turn HTTP keep-alive on by default for the global agent. Fetch (undici) pools connections by default too.

Errors you will see, and what they mean

#ErrorWhat happened on the wireUsual cause
1ECONNREFUSEDSYN answered with RSTNothing listening on that port (chapter 16)
2ETIMEDOUTSYNs, or data, got no answerFirewall dropping packets; host down; full accept queue
3ECONNRESETRST arrived on an open connectionPeer crashed or closed abruptly; a NAT or firewall forgot an idle connection
4EPIPEWriting to a connection the other side already closedSame as above, noticed while writing
5EADDRINUSEbind() refusedAnother process listening; old process not dead (section 4)
6Steady ~40 ms extra on small requestsNagle + delayed ACKTCP_NODELAY off (section 5)
7Random 502s behind a load balancerLB reused a connection the server had just closedServer keep-alive timeout shorter than the LB's (section 7)
8First query after a quiet period hangs, then failsMiddlebox forgot the idle connectionPool idle timeout or keepalive too long (sections 6-7)

Section 2 complete

This chapter closes Section 2. One request from your laptop to kade-api is now explained end to end below HTTP, from both the network's side and your code's side:

  1. Layersch 11
  2. Routingch 12
  3. ICMPch 13
  4. UDPch 14-15
  5. TCPch 16-20
  6. TCP in codech 21
  7. Section 3DNS, WebSocket …

Summary

#IdeaIn one lineNew terms
1Socketssocket, bind, listen, connect, accept, read/write, closesocket
2Many connectionsOne listening socket; a new socket per connection
3QueuesSYN queue, accept queue (backlog); a slow app overflows the secondbacklog, somaxconn
4EADDRINUSETIME-WAIT or a live listener; SO_REUSEADDR, SO_REUSEPORTSO_REUSEADDR
5NagleHolds small writes; with delayed ACK = ~40 ms stalls; fix with TCP_NODELAYNagle, TCP_NODELAY
6KeepaliveTCP keepalive probes idle connections; HTTP keep-alive reuses themTCP keepalive
7Idle timeoutsClose or ping before the middlebox forgets; server outlives the LB
8PoolsReuse connections: fewer handshakes, warm windows, fewer portsconnection pool
9ErrorsREFUSED, TIMEDOUT, RESET, EPIPE, ADDRINUSE mapped to the wire

Try it yourself

Listening sockets and their queues

ss -lnt

Accept queue overflows since boot

nstat -az TcpExtListenOverflows TcpExtListenDrops

Who holds the port

lsof -iTCP:443 -sTCP:LISTEN -n -P

Connections with their timers

ss -tno state established

System keepalive defaults

sysctl net.ipv4.tcp_keepalive_time net.ipv4.tcp_keepalive_intvl net.ipv4.tcp_keepalive_probes

Time between packets

sudo tcpdump -n -ttt -i lo port 9000

Spotted a mistake, or something unclear? Suggest an edit on GitHub