What is the Nagle algorithm in TCP/IP?
Posted: (EET/GMT+2)
If you are developing TCP/IP applications that frequently send small amounts of data, you may occasionally notice unexpected delays even on a fast local network. One possible reason for such delays is the Nagle algorithm. It is specified in RFC 896.
TCP has considerable overhead compared with the amount of useful data in a very small transmission. If an application repeatedly writes only a few bytes at a time, sending every write immediately could result in a large number of small TCP segments. The Nagle algorithm reduces the number of packets sent by combining small writes when there is already unacknowledged data in transit.
Let's take an example.
Application writes: A B C D Without combining: [A] [B] [C] [D] With Nagle: [A] [BCD]
Text in square brackts [ ] is a single TCP package. As you can see, if the Nagle option is enabled, the protocol overhead is smaller per data byte and helps prevent applications from unnecessarily flooding.
However, the algorithm can sometimes introduce unwanted latency. This is especially noticeable in interactive applications that send small messages and expect responses immediately.
On a fast local area network, reducing the number of packets may be less important than obtaining the lowest possible response time.
WinSock applications can disable the Nagle algorithm for a TCP socket using the TCP_NODELAY socket option:
BOOL noDelay = TRUE;
setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&noDelay,
sizeof(noDelay));
This causes small writes to be sent without waiting for the Nagle algorithm to combine them.
For applications transferring larger amounts of data, the algorithm can reduce unnecessary network traffic. It is most useful to consider TCP_NODELAY when small, latency-sensitive messages are being transmitted.
For details, see the RFC document 896, which is titled "Congestion Control in IP/TCP Internetworks", by John Nagle from Ford.
Happy networkin'!