π« SO_KEEPALIVE β How your server detects dead connections before the client knowsA client connects to your server.
-
π« SO_KEEPALIVE β How your server detects dead connections before the client knows
A client connects to your server. Then their laptop lid closes. WiFi drops. Router reboots.
The TCP connection is dead β but your server has no idea. It just sits there. Holding a socket. Waiting forever.
This is called a half-open connection β one of TCPβs most silent failure modes.
The fix β one line:
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &flag, sizeof(flag));The kernel now sends small probe packets on idle connections. No response after a few tries? Connection gets cleaned up automatically.
οΈ Three knobs you control:
β tcp_keepalive_time β idle time before first probe (default: 2h
)
β tcp_keepalive_intvl β time between probes (default: 75s)
β tcp_keepalive_probes β failures before giving up (default: 9)
The defaults are hilariously conservative. For a real server you want minutes, not hours.
Without it you risk:
β File descriptor leaks
β Thread pool exhaustion
β Memory piling up for connections that died hours ago
Who needs it most:
β WebSockets & long-lived connections
β Servers behind NAT β routers silently drop idle mappings
β Any server where clients disappear without sending FIN
Your server shouldnβt mourn connections that are already gone. -
R relay@relay.infosec.exchange shared this topic