Nagle's algorithm
/ NAY-gul /
Imagine mailing one playing card per envelope. Each tiny card needs a full envelope, stamp, and trip — enormous overhead for almost no content. Nagle's algorithm is TCP's way of avoiding that waste: instead of firing off a network packet for every tiny write, it gathers small bits of data together and sends them as one fuller packet, so the network is not flooded with mostly-header, almost-no-payload packets.
The rule, from John Nagle in 1984, is simple: if there is already unacknowledged data in flight on a TCP connection, hold any new small data in a buffer until either the outstanding data is acknowledged or you have accumulated a full segment's worth, then send. A 40-byte TCP/IP header carrying a single 1-byte keystroke wastes 40 bytes of overhead per byte of content, so on slow links coalescing many such writes into one packet was a big win. Crucially, the buffered bytes still arrive — Nagle delays them slightly, it does not drop them — and a full-sized write or an arriving acknowledgment releases the held data right away.
Why it matters: Nagle's algorithm interacts badly with some interactive, request-reply applications. The classic trap is its collision with delayed acknowledgments: the sender holds a small request waiting for an ack, while the receiver holds the ack waiting for more data or a timer, and both sit stalled for tens of milliseconds. This shows up as mysterious latency in chatty protocols, and the standard fix is to set the TCP_NODELAY socket option, which disables Nagle so small writes go out immediately. Honest caveat: do not disable it reflexively — Nagle still protects the network from floods of tiny packets, so it is right to turn off only when your application genuinely needs low latency for small messages and already batches its own writes sensibly.
A remote shell sends each keystroke as a 1-byte write. With Nagle on, several quick keystrokes can be merged into one packet, and a tiny write may pause until the previous byte is acknowledged. Setting TCP_NODELAY makes each keystroke go out at once, trading a little efficiency for snappier typing.
Nagle batches tiny writes; TCP_NODELAY turns batching off for low latency.
Nagle never loses data — it only delays small writes slightly. The infamous stalls come from its interaction with delayed ACKs. Disable it with TCP_NODELAY only when low latency on small messages truly matters.