Nagle's Algorithm and TCP_NODELAY
w非全尺寸分组的发送条件
HTTP The Definitive Guide
TCP has a data stream interface that permits applications to stream data of any size to the TCP stack—
even a single byte at a time! But because each TCP segment carries at least 40 bytes of flags and
headers, network performance can be degraded severely if TCP sends large numbers of packets
containing small amounts of data.
[5]
[5]
Sending a storm of single-byte packets is called "sender silly window syndrome." This is inefficient, anti-
social, and can be disruptive to other Internet traffic.
Nagle's algorithm (named for its creator, John Nagle) attempts to bundle up a large amount of TCP
data before sending a packet, aiding network efficiency. The algorithm is described in RFC 896,
"Congestion Control in IP/TCP Internetworks."
Nagle's algorithm discourages the sending of segments that are not full-size (a maximum-size packet
is around 1,500 bytes on a LAN, or a few hundred bytes across the Internet). Nagle's algorithm lets
you send a non-full-size packet only if all other packets have been acknowledged. If other packets are
still in flight, the partial data is buffered. This buffered data is sent only when pending packets are
acknowledged or when the buffer has accumulated enough data to send a full packet.
[6]
[6]
Several variations of this algorithm exist, including timeouts and acknowledgment logic changes, but the
basic algorithm causes buffering of data smaller than a TCP segment.
Nagle's algorithm causes several HTTP performance problems. First, small HTTP messages may not
fill a packet, so they may be delayed waiting for additional data that will never arrive. Second, Nagle's
algorithm interacts poorly with disabled acknowledgments—Nagle's algorithm will hold up the
sending of data until an acknowledgment arrives, but the acknowledgment itself will be delayed 100-
200 milliseconds by the delayed acknowledgment algorithm.
[7]
[7]
These problems can become worse when using pipelined connections (described later in this chapter),
because clients may have several messages to send to the same server and do not want delays. HTTP applications often disable Nagle's algorithm to improve performance, by setting the
TCP_NODELAY parameter on their stacks. If you do this, you must ensure that you write large
chunks of data to TCP so you don't create a flurry of small packets.