Sub topic 10
Flow control and the receive window
This chapter assumes you know the TCP header fields, sequence numbers, and acknowledgments from the earlier chapters on reliable delivery. It also assumes you can read basic Python socket code.
Reliable delivery makes sure every byte arrives. It does not stop a fast sender from sending faster than the receiving application can read. Flow control fixes that problem. It lets a receiver tell the sender how much data it can accept right now.
The problem: a fast sender and a slow reader
Each TCP connection has a receive buffer in the operating system's kernel. Arriving data waits there until the application calls recv. If the application is slow, the buffer fills. Without a limit, new segments would have to be dropped. The sender would then retransmit them, wasting bandwidth on data the receiver could never store.
Flow control is the mechanism that stops this. The receiver tells the sender how much free buffer space it has, and the sender keeps its unacknowledged data within that amount. Flow control protects the receiving host. It does not protect the network between the two hosts. That is the job of congestion control, covered in the next chapter.
The receive window
Every TCP segment sent after the handshake carries a 16-bit window field in its header. It holds the receive window (often written rwnd). This is the number of bytes the sender of that segment is willing to accept, counted from the acknowledgment number in the same segment.
In practice:
- The receiver's advertised window is roughly its free buffer space: total buffer size minus the bytes received but not yet read by the application.
- Each ACK carries the current value, so the window is updated continuously.
- The sender may have at most rwnd bytes of unacknowledged data in flight.
For example, suppose the receiver's buffer holds 64 KB and the application has read nothing. After 40 KB arrives, the receiver advertises about 24 KB. If the application then reads 10 KB, the next ACK advertises about 34 KB.
The window is a sliding range of sequence numbers. Its left edge is the last acknowledged byte. Its right edge is the left edge plus rwnd. The left edge moves right as data is acknowledged. The right edge moves right as the application drains the buffer.
A window shrinking to zero and reopening
The sequence below shows a receiver that stalls and then recovers.
Three details from this exchange matter in practice.
- A zero window stops the sender. When the receiver advertises a window of 0, the sender sends no new data. It may still retransmit lost data and send certain control segments.
- The persist timer prevents deadlock. A window update is an ordinary ACK, and ACKs can be lost. If the update that reopens the window is lost, the sender waits for it and the receiver waits for data. To break this, the sender starts a persist timer and periodically sends a zero-window probe, a segment carrying one byte or none. The receiver's reply reports the current window. Probes are repeated with growing intervals for as long as the window stays at zero.
- Zero window is not an error. It means the application on the other side is not reading fast enough. Long zero-window periods in a packet capture point to a slow or blocked reader, not to a network fault.
Window scaling
The window field is 16 bits, so the largest value is 65,535 bytes. That is far too small on fast, long links. The data a sender needs in flight to keep a path full is the bandwidth-delay product: bandwidth times round-trip time (RTT).
For a 100 Mbit/s path with an 80 ms RTT:
- 100,000,000 bits/s ÷ 8 × 0.08 s = 1,000,000 bytes in flight.
- With a 65,535-byte window, the sender can send only 65,535 bytes per RTT. That is about 819 KB/s, or roughly 6.5 Mbit/s, about 6.5% of the link.
The window scale option (RFC 7323) fixes this. During the handshake, each side may include a scale factor in its SYN. A factor of n means the 16-bit window value is shifted left by n bits, which allows windows up to about 1 GB. Scaling is agreed only in the SYN and SYN-ACK segments. If either side omits it, scaling is off for the whole connection. A middlebox that strips TCP options from SYN segments can therefore silently cap throughput at the 64 KB limit.
Seeing it from the sockets API
The kernel's buffer sizes decide how large the window can grow. You can request sizes with SO_RCVBUF and SO_SNDBUF. Linux adjusts these values (it doubles the number you ask for to allow for bookkeeping overhead), and it also auto-tunes buffers unless you set them yourself. Treat any value you set as a hint.
The script below makes a deliberately slow receiver. The server accepts a connection, sleeps for three seconds without calling recv, and then drains the data. The client uses a non-blocking socket and sends until the kernel refuses more. At that point, the receiver's buffer and the client's own send buffer are both full.
import select
import socket
import threading
import time
PORT = 9002
def slow_server(ready):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Set before listen() so the accepted socket inherits it.
srv.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096)
srv.bind(("127.0.0.1", PORT))
srv.listen()
ready.set()
conn, _ = srv.accept()
with conn:
time.sleep(3) # the application is not reading
total = 0
while True:
data = conn.recv(65536)
if not data:
break
total += len(data)
print(f"server read {total} bytes")
ready = threading.Event()
t = threading.Thread(target=slow_server, args=(ready,))
t.start()
ready.wait()
cli = socket.create_connection(("127.0.0.1", PORT))
cli.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096)
cli.setblocking(False)
sent = 0
start = time.time()
try:
while True:
sent += cli.send(b"x" * 1024)
except BlockingIOError:
print(f"send stalled after {sent} bytes")
select.select([], [cli], []) # wait until the socket is writable again
print(f"writable again after {time.time() - start:.1f} s")
cli.close()
t.join()Expected behavior: the client reports a stall after a small number of bytes. The exact figure depends on your operating system and buffer tuning, and it is usually tens of kilobytes. About three seconds later, once the server starts reading, the window reopens and the client becomes writable again. Nothing was lost. The sender was simply held back by the receiver's window.
A blocking send or sendall would behave the same way, except that the call would pause instead of raising BlockingIOError. This is why a slow consumer can freeze a producer in code that looks as though it never waits.
Silly window syndrome
Flow control has a known failure mode called silly window syndrome. Suppose a slow application reads only a few bytes at a time. Each read frees a tiny amount of buffer space, so the receiver advertises a tiny window, and the sender sends a tiny segment. The connection then carries 20 or more bytes of header for every few bytes of data.
TCP avoids this from both ends:
- Receiver side. The receiver does not advertise a small increase in the window. It keeps advertising the old value until the free space reaches the smaller of one maximum segment size (MSS) or half the buffer.
- Sender side. Nagle's algorithm holds back small writes while earlier data is still unacknowledged, so tiny writes are merged into fuller segments. Latency-sensitive programs often disable it with the
TCP_NODELAYsocket option. Doing so accepts more small segments in exchange for lower delay.
Flow control versus congestion control
The two mechanisms limit the same sender, but they protect different things and learn their limits differently.
| Row | Flow control | Congestion control |
|---|---|---|
| Protects | The receiving host's buffer | The network between the hosts |
| Limit comes from | The receiver, in the window field of each ACK | The sender's own estimate, from loss and delay signals |
| Variable | Receive window (*rwnd*) | Congestion window (*cwnd*) |
| Typical cause of a limit | A slow application | Overloaded routers and links |
The sender obeys both at once. The amount of unacknowledged data it may have in flight is the smaller of the two values: min(cwnd, rwnd). Whichever limit is lower at that moment is the one slowing the transfer.
Common errors
- Assuming a bigger
SO_RCVBUFalways helps. A bigger buffer only matters if the path's bandwidth-delay product exceeds the current window. Setting it also turns off Linux auto-tuning for that socket, which can make performance worse. - Blaming the network for a stall. A capture full of "TCP ZeroWindow" markers means the receiving application is the bottleneck. Fix the reader, not the path.
- Setting buffer sizes after the connection starts. Window scaling is negotiated in the handshake. To get a large scale factor, set the receive buffer before
connecton the client and beforelistenon the server. - Ignoring backpressure in your own code. If you copy data between two sockets, a slow destination should make you stop reading from the source. Ignoring the signal means unbounded memory growth in your process.
Exercise
A sender's last acknowledgment number is 10000. The receiver advertised a window of 8000 bytes, and the sender's congestion window is 12000 bytes. The sender has already sent bytes 10000 to 13999 and none of them are acknowledged. How many more bytes can it send now, and which limit applies? Then, for a path with a 50 ms RTT and a 65,535-byte window with no scaling, what is the maximum throughput in bytes per second?
Show answer
In-flight data is 4000 bytes. The allowed amount is min(rwnd, cwnd) = min(8000, 12000) = 8000, so rwnd is the limit and the sender may send 8000 - 4000 = 4000 more bytes. Without scaling, throughput is at most one window per RTT: 65,535 bytes / 0.05 s = about 1,310,700 bytes per second, roughly 10.5 Mbit/s, regardless of the link's capacity.
Exercise
A capture shows a receiver advertising window 0, followed by a one-byte segment from the sender every few seconds, each answered with window 0. Is the connection broken? What is the sender doing, and where should you look for the cause?
Show answer
The connection is working as designed. The sender is sending zero-window probes driven by its persist timer, and the receiver is correctly reporting that its buffer is still full. The cause is the receiving application not calling recv fast enough (blocked, busy, or waiting on something else), so look at the receiver's code and host load.