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:
| # | Call | Side | What the OS does | In Node.js |
|---|---|---|---|---|
| 1 | socket() | both | Creates the handle (TCP or UDP) | done for you |
| 2 | bind(ip, port) | server | Claims the port (443) | server.listen(443) does bind + listen |
| 3 | listen(backlog) | server | State → LISTEN; creates the queues (section 3) | backlog defaults to 511 |
| 4 | connect(ip, port) | client | Picks an ephemeral port, sends SYN, waits for the handshake | net.connect(), fetch(), a pg pool |
| 5 | accept() | server | Takes one finished connection from the queue and returns a new socket for it | the 'connection' event |
| 6 | write() / read() | both | Copy bytes into the send buffer / out of the receive buffer (chapter 19) | socket.write(), 'data' events |
| 7 | close() | both | Sends 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
The two queues behind listen()
Between the SYN arriving and your code seeing a connection, it waits in two kernel queues:
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 -lntshows 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-WAIT | Connections 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 listening | The 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:
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é:
| # | Where | Idle timeout (defaults) | Affects |
|---|---|---|---|
| 1 | Home / office routers (NAT) | varies: minutes to hours | Long-lived connections from laptops and PCs |
| 2 | GCP firewall connection tracking | about 10 minutes for established TCP | kade-api ⇄ kade-db, and anything through VPC firewall rules |
| 3 | Cloud NAT (planned) | 20 minutes for established TCP (chapter 10) | kade-api → PayGate after the load balancer arrives |
| 4 | GCP 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 |
| 5 | Node HTTP server | server.keepAliveTimeout = 5 s | kade-api closes idle HTTP connections after 5 s |
| 6 | node-postgres pool | idleTimeoutMillis = 10 s | kade-api's idle DB connections |
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
Errors you will see, and what they mean
| # | Error | What happened on the wire | Usual cause |
|---|---|---|---|
| 1 | ECONNREFUSED | SYN answered with RST | Nothing listening on that port (chapter 16) |
| 2 | ETIMEDOUT | SYNs, or data, got no answer | Firewall dropping packets; host down; full accept queue |
| 3 | ECONNRESET | RST arrived on an open connection | Peer crashed or closed abruptly; a NAT or firewall forgot an idle connection |
| 4 | EPIPE | Writing to a connection the other side already closed | Same as above, noticed while writing |
| 5 | EADDRINUSE | bind() refused | Another process listening; old process not dead (section 4) |
| 6 | Steady ~40 ms extra on small requests | Nagle + delayed ACK | TCP_NODELAY off (section 5) |
| 7 | Random 502s behind a load balancer | LB reused a connection the server had just closed | Server keep-alive timeout shorter than the LB's (section 7) |
| 8 | First query after a quiet period hangs, then fails | Middlebox forgot the idle connection | Pool 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:
- Layersch 11
- Routingch 12
- ICMPch 13
- UDPch 14-15
- TCPch 16-20
- TCP in codech 21
- Section 3DNS, WebSocket …
Summary
| # | Idea | In one line | New terms |
|---|---|---|---|
| 1 | Sockets | socket, bind, listen, connect, accept, read/write, close | socket |
| 2 | Many connections | One listening socket; a new socket per connection | |
| 3 | Queues | SYN queue, accept queue (backlog); a slow app overflows the second | backlog, somaxconn |
| 4 | EADDRINUSE | TIME-WAIT or a live listener; SO_REUSEADDR, SO_REUSEPORT | SO_REUSEADDR |
| 5 | Nagle | Holds small writes; with delayed ACK = ~40 ms stalls; fix with TCP_NODELAY | Nagle, TCP_NODELAY |
| 6 | Keepalive | TCP keepalive probes idle connections; HTTP keep-alive reuses them | TCP keepalive |
| 7 | Idle timeouts | Close or ping before the middlebox forgets; server outlives the LB | |
| 8 | Pools | Reuse connections: fewer handshakes, warm windows, fewer ports | connection pool |
| 9 | Errors | REFUSED, TIMEDOUT, RESET, EPIPE, ADDRINUSE mapped to the wire |
Try it yourself
Listening sockets and their queues
- What to look for: For
:443: Recv-Q (waiting now) vs Send-Q (backlog). - Runs on: Linux, on kade-api
- From section: 3. The two queues behind listen()
ss -lntAccept queue overflows since boot
- What to look for: Anything above 0 and growing = the app is too slow to accept.
- Runs on: Linux
- From section: 3. The two queues behind listen()
nstat -az TcpExtListenOverflows TcpExtListenDropsWho holds the port
- What to look for: The PID of the old process, if it is still alive.
- From section: 4. "Address already in use"
lsof -iTCP:443 -sTCP:LISTEN -n -PConnections with their timers
- What to look for:
timer:(keepalive,…)on sockets with keepalive on. - Runs on: Linux
- From section: 6. TCP keepalive (not HTTP keep-alive)
ss -tno state establishedSystem keepalive defaults
- What to look for:
7200,75,9. - From section: 6. TCP keepalive (not HTTP keep-alive)
sysctl net.ipv4.tcp_keepalive_time net.ipv4.tcp_keepalive_intvl net.ipv4.tcp_keepalive_probesTime between packets
- What to look for: A ~40 ms gap before the second write with Nagle on; none with NODELAY.
- Runs on: while a test client writes twice to a local server
- From section: 5. Nagle's algorithm and the 40 ms mystery
sudo tcpdump -n -ttt -i lo port 9000