Nagle’s algorithm and its consequences
Nagle’s algorithm aims to improve efficiency of TCP/IP communication by reducing the number of packets sent over the network. However in some cases, this behavior hurts the system’s performance instead of improving it.
Nagle’s algorithm. The background
Introduced way back in 1984, Nagle’s algorithm intends to reduce the number of packets sent over the network by grouping them into larger segments. The basic principle is, that for small messages, there is a delay before the data is actually sent over the network. If more messages are enqueued to be sent during this delay, they are grouped into one larger data segment. This reduces the overhead of TCP/IP headers – which is 40 bytes per packet (for IPv4), even if the data itself is just one byte.
For some applications, low latency of the communication is crucial. One example of such scenario is online gaming, another might be real time data processing. The Nagle’s algorithm however introduces additional delay that might cause problems in those scenarios.
There are ways to turn the Nagle’s algorithm off, however what you should do first, is to make sure this is actually source of the problem you are trying to solve. Making this configuration change will have a negative impact on overall throughput of the communication.
You can turn off the Nagle’s algorithm:
* at the OS level (on Windows – by editing adapter settings in the registry)
* if you work with the TcpClient, set `tcpClient.NoDelay = true` (also available on the `Socket`)
* if you use HTTP, set `ServicePointManager.UseNagleAlgorithm = false` (before making any HTTP calls)