Back to series
· 19 min read

TCP Protocol Explained: How Is Reliable Transmission Achieved?


I. What Is TCP?

TCP, short for Transmission Control Protocol, is the core transport layer protocol in the TCP/IP network architecture.

It mainly solves one problem:

How can reliable, ordered data transmission be achieved over an IP network that may lose packets, deliver them out of order, duplicate them, and introduce delays?

The IP protocol only makes a best-effort attempt to transmit packets; it does not guarantee that data will reach the destination device, nor that it will arrive in the order it was sent.

For example, an application sends:

Hello World

In the underlying network, the data may encounter:

  • Packet loss.
  • Packets arriving out of order.
  • Duplicate packets.
  • Varying network delay.
  • Insufficient processing speed at the receiver.
  • Network congestion.

If IP were used directly for transmission, applications would have to handle these problems themselves.

TCP encapsulates these complex mechanisms in the transport layer, providing applications with reliable communication capabilities.

1. Core Features of TCP

Feature Description
Connection-oriented A connection must be established before communication
Reliable transmission Handles packet loss through mechanisms such as acknowledgment and retransmission
Byte stream Treats application data as a continuous sequence of bytes
Ordered transmission The receiver reassembles data according to sequence numbers
Full-duplex Both sides can send and receive data simultaneously
Flow control Prevents the sending rate from exceeding the receiver's processing capacity
Congestion control Adjusts the sending rate according to network conditions
Point-to-point A TCP connection consists of two endpoints

2. TCP's Position in the Network Protocol Stack

TCP resides in the transport layer, runs on top of the IP protocol, and provides communication services to the application layer.

Layer Protocol or Technology Primary Responsibility
Application layer HTTP, HTTPS, SSH, SMTP Defines application communication rules
Transport layer TCP, UDP Provides end-to-end data transmission
Network layer IPv4, IPv6, ICMP Addressing and routing/forwarding
Data link layer Ethernet, Wi-Fi Local link data transmission
Physical layer Optical fiber, network cable, wireless signals Transmits bits

Relationship between typical application protocols and TCP:

Application Protocol Common TCP Port Purpose
HTTP 80 Web communication
HTTPS 443 Encrypted web communication
SSH 22 Remote login
SMTP 25, 587 Email sending
MySQL 3306 Database communication
PostgreSQL 5432 Database communication
Redis 6379 Caching service

Note: An application protocol using TCP does not mean that TCP understands the content of the application data. TCP is only responsible for reliably transmitting a byte stream; protocols such as HTTP and SSH are responsible for interpreting the business meaning of those bytes.


II. What Is the Difference Between TCP and UDP?

TCP and UDP are both transport layer protocols, but they have different design goals.

TCP emphasizes reliable, ordered byte-stream transmission; UDP emphasizes lightweight, low-overhead datagram transmission.

1. TCP vs. UDP Comparison

Comparison Item TCP UDP
Connection mode Connection-oriented Connectionless
Reliability Provides reliable transmission mechanisms Does not guarantee reliable delivery
Data form Byte stream Datagram
Data ordering Guarantees in-order delivery Does not guarantee order
Packet loss handling Mechanisms such as acknowledgments and retransmission Usually determined by the application
Flow control Yes No built-in mechanism
Congestion control Yes No general built-in congestion control
Header length Usually 20 bytes, maximum 60 bytes Fixed at 8 bytes
Broadcast and multicast Not supported Supported
Typical uses Web, databases, file transfer DNS, audio/video, real-time communication, etc.

2. Why does TCP need a connection?

The purpose of establishing a TCP connection is not just to confirm whether both parties are online.

During connection establishment, both parties need to negotiate and synchronize certain communication states, such as:

  • Initial sequence number.
  • Receive windows of both sides.
  • Parameters related to the maximum segment size.
  • Whether window scaling is supported.
  • Whether SACK is supported.
  • Whether options such as timestamps are supported.

Only after the connection is established can both parties transmit data according to the agreed sequence numbers and acknowledgment mechanism.

3. Why does UDP not need a three-way handshake?

UDP itself does not maintain connection state like TCP does.

The sender can directly construct and send a UDP datagram without first completing a TCP three-way handshake.

But this does not mean that UDP never requires connection management.

For example, QUIC implements connection management, reliable transmission, congestion control, and encrypted communication based on UDP.

Therefore:

UDP is a transport protocol; it does not mean that applications using UDP are necessarily unreliable.


3. TCP Segment Structure: How Does TCP Organize Data?

TCP transmits data over the network in TCP segments (TCP Segment).

A TCP segment mainly consists of two parts:

  1. TCP header.
  2. TCP data.

1. TCP Header Structure

The TCP header is at least 20 bytes and at most 60 bytes.

 0                   15                  31
 +-------------------+-------------------+
 |     Source Port   | Destination Port  |
 +-------------------+-------------------+
 |              Sequence Number          |
 +---------------------------------------+
 |           Acknowledgment Number        |
 +-------+-------+-----------------------+
 |Offset |Resv.  | Flags |   Window Size  |
 +-------+-------+-------+----------------+
 |      Checksum     |   Urgent Pointer   |
 +-------------------+-------------------+
 |          Options and Padding           |
 +---------------------------------------+
 |                  Data                 |
 +---------------------------------------+

2. TCP Header Field Description

Field Length Purpose
Source Port 16 bits Source port
Destination Port 16 bits Destination port
Sequence Number 32 bits Sequence number
Acknowledgment Number 32 bits Acknowledgment number
Data Offset 4 bits TCP header length
Reserved Reserved bits Used for protocol extensions
Flags Multiple flag bits Controls connection and transmission behavior
Window Size 16 bits Advertised receive window value
Checksum 16 bits Detects transmission errors in the header and data
Urgent Pointer 16 bits Urgent data pointer
Options Variable length TCP extension options
Data Variable length Application-layer data

3. TCP Flags

The TCP header contains multiple control flags.

Flag Full Name Purpose
SYN Synchronize Establish a connection, synchronize sequence numbers
ACK Acknowledgment The acknowledgment field is valid
FIN Finish Request to close the sending direction
RST Reset Reset the connection
PSH Push Prompt the receiver to deliver data to the application as soon as possible
URG Urgent The urgent pointer field is valid
ECE ECN-Echo Related to Explicit Congestion Notification
CWR Congestion Window Reduced Indicates the sender has responded to a congestion notification
NS Nonce Sum Historical ECN extension-related flag

The most common in daily use are SYN, ACK, FIN, and RST.

4. TCP Ports and Connection Identification

TCP uses port numbers to distinguish different application processes on the same host.

A TCP connection can usually be uniquely identified by the following four-tuple:

Source IP address
Source port
Destination IP address
Destination port

For example:

192.168.1.100:52000
        |
        | TCP
        |
93.184.216.34:443

This indicates:

  • Client IP: 192.168.1.100
  • Client port: 52000
  • Server IP: 93.184.216.34
  • Server port: 443

A server can use the same listening port to serve multiple clients simultaneously because each established connection has a unique four-tuple.

In real networks, factors such as NAT, IPv6 addresses, and network namespaces may also be involved, but the basic identification logic of TCP connections remains unchanged.


4. The Core of TCP Reliable Transmission: Sequence Numbers and Acknowledgment

The most important foundation of TCP reliable transmission is the sequence number and acknowledgment mechanism.

They solve two key problems:

  1. How does the receiver know which part of the data it has received?
  2. How does the sender know whether the data has been received?

1. What Is a TCP Sequence Number?

TCP uses 32-bit sequence numbers to identify data positions in the byte stream.

Note:

TCP sequence numbers represent byte numbering in the byte stream, not segment numbering.

Suppose the sender's initial sequence number is 1000.

Sending 100 bytes of data:

Data range: 1000 ~ 1099

The sequence number of the next byte is:

1100

If 200 bytes are then sent:

Data range: 1100 ~ 1299

The next sequence number is:

1300

TCP sequence numbers increase on a per-byte basis.

2. What Is the Acknowledgment Number ACK?

ACK, Acknowledgment Number, indicates the next byte sequence number that the receiver expects to receive.

For example:

The sender sends:

SEQ = 1000
Data length = 100

After successfully receiving these 100 bytes, the receiver returns:

ACK = 1100

This means:

Contiguous bytes with sequence numbers below 1100 have been received; the next expected byte starts at 1100.

This is TCP's cumulative acknowledgment mechanism.

3. Relationship Between Sequence Numbers and Acknowledgment Numbers

flowchart TD
    A["Sender sends 100 bytes"] --> B["SEQ = 1000"]
    B --> C["Receiver receives bytes 1000 to 1099"]
    C --> D["Receiver sends ACK = 1100"]
    D --> E["Sender confirms contiguous data has been received"]
    E --> F["Next segment starts at SEQ = 1100"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E9E2F8,stroke:#B9A5DF,color:#514078
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#FFF2CC,stroke:#E6C978,color:#765A18
    style E fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F

4. How Does TCP Handle Out-of-Order Data?

Suppose the sender sends three segments:

Segment Sequence Number Data Length
Segment A 1000 100
Segment B 1100 100
Segment C 1200 100

Under normal circumstances, the receiver receives A, B, and C in order.

But if packet reordering occurs on the network:

Receive order: A, C, B

The receiver has already received A and C, but has not yet received B.

At this point:

  • The byte range of A is 1000–1099.
  • The byte range of C is 1200–1299.
  • The byte range of B is 1100–1199.

Because there is a gap in the middle, the receiver cannot deliver the complete contiguous byte stream to the application.

If cumulative acknowledgment is used, the receiver can still acknowledge:

ACK = 1100

This means the currently contiguous bytes received only go up to 1099.

When B arrives, the receiver then has contiguous data from 1000 to 1299 and can continue delivering it.

5. How Does TCP Handle Duplicate Data?

Suppose the sender does not receive the ACK in time, so it retransmits data that the receiver has already received.

The receiver can identify duplicate data by sequence number.

For example:

First receipt:
SEQ = 1000, length = 100

Second receipt:
SEQ = 1000, length = 100

The second set of data is duplicate data.

The TCP receiver will not deliver duplicate bytes to the application again; instead, it continues sending acknowledgments according to the current receive state.

Therefore, TCP can prevent duplicate data from corrupting the byte stream seen by the application.


5. TCP Three-Way Handshake: How Is a Connection Established?

TCP is a connection-oriented protocol.

Before formally transmitting data, the two communicating parties need to complete the connection establishment process.

This process is called the TCP Three-Way Handshake.

1. Why Is the Three-Way Handshake Needed?

The three-way handshake is mainly used to:

  • Confirm that the client can send.
  • Confirm that the server can send and receive.
  • Confirm that the client can receive data from the server.
  • Synchronize the initial sequence numbers of both parties.
  • Negotiate TCP connection parameters.

It is not simply sending “hello” to each other three times.

2. The Three-Way Handshake Process

Assume:

Client initial sequence number:

Client ISN = 1000

Server initial sequence number:

Server ISN = 5000

The three-way handshake process:

Step Direction Flags Sequence Number Acknowledgment Number
First Client → Server SYN 1000 -
Second Server → Client SYN, ACK 5000 1001
Third Client → Server ACK 1001 5001

Note: The SYN flag consumes one sequence number, so the acknowledgment number needs to be increased by 1.

3. Three-Way Handshake Sequence Diagram

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: SYN, SEQ=1000
    S->>C: SYN+ACK, SEQ=5000, ACK=1001
    C->>S: ACK, SEQ=1001, ACK=5001
    Note over C,S: Both sides enter the ESTABLISHED state

4. First Handshake: The Client Sends SYN

The client actively initiates the connection.

Sends:

SYN = 1
SEQ = 1000

The client enters:

SYN-SENT

After the server receives the SYN, it knows:

  • A client wants to establish a connection.
  • The client can send data to the server.
  • The client has provided an initial sequence number of 1000.

5. Second Handshake: The Server Sends SYN + ACK

The server acknowledges the client's SYN and sends its own SYN.

SYN = 1
ACK = 1
SEQ = 5000
ACK = 1001

The server enters:

SYN-RECEIVED

This step means:

  • The server acknowledges that it received the client's SYN.
  • The server also provides its own initial sequence number.
  • The server wants the client to acknowledge receipt of its SYN.

6. Third Handshake: The Client Sends ACK

After the client receives the server's SYN + ACK, it returns:

ACK = 1
SEQ = 1001
ACK = 5001

After the server receives it, it confirms that the client has received its SYN.

Both sides enter:

ESTABLISHED

The TCP connection is formally established.

7. Why Can't There Be Only Two Handshakes?

Suppose there are only two handshakes:

  1. The client sends SYN.
  2. The server sends SYN + ACK.

Although the server knows that the client sent a request, it cannot confirm whether the client successfully received the server's response.

The third handshake is used to confirm that the SYN sent by the server has reached the client.

It can also reduce interference from stale delayed connection requests with the state of new connections.

8. The Three-Way Handshake and the Half-Open Connection Queue

After the server receives a SYN, before the third handshake is complete, the connection is in a half-open state.

The server usually needs to maintain the relevant state while waiting for the client to return an ACK.

Linux servers commonly involve:

  • SYN Queue: stores requests whose handshake has not yet completed.
  • Accept Queue: stores connections that have completed the handshake and are waiting to be accepted by the application.

When the server receives a SYN:

SYN arrives
    |
    v
Send SYN + ACK
    |
    v
Wait for client ACK
    |
    v
Handshake complete
    |
    v
Enter the completed connection queue

The actual queue management details are affected by mechanisms such as the Linux kernel version, TCP parameters, and SYN Cookies.

9. SYN Flood Attacks

A SYN Flood is a denial-of-service attack that exploits the TCP handshake process.

The attacker sends a large number of SYN requests but does not complete the subsequent handshake.

The server may need to reserve resources for these half-open connections.

Defensive measures include:

  • SYN Cookies.
  • Limit the rate of SYN requests.
  • Adjust connection queue parameters.
  • Use a firewall to filter abnormal traffic.
  • Deploy load balancing and DDoS protection.
  • Monitor the number of half-open connections.

6. TCP Four-Way Teardown: How Is the Connection Closed?

TCP is a full-duplex protocol.

After a connection is established, both the client and the server can send data independently.

Therefore, when closing a TCP connection, the data transmission in each direction must be closed separately.

This process is commonly called the four-way teardown.

1. Why Is a Four-Way Teardown Usually Needed?

A TCP connection contains two independent data transmission directions:

  • Client to server.
  • Server to client.

When the client sends FIN, it only indicates that the client will no longer send data.

The server may still have data left to send.

Therefore, the server needs to first confirm the client's FIN, and only then send its own FIN when it is ready to close its sending direction.

2. The Four-Way Teardown Process

Assume the client actively closes the connection.

Step Direction Flag Purpose
First Client → Server FIN The client requests to close its sending direction
Second Server → Client ACK Acknowledges receipt of the FIN
Third Server → Client FIN The server is also ready to close its sending direction
Fourth Client → Server ACK Acknowledges the server's FIN

3. Four-Way Teardown Sequence Diagram

sequenceDiagram
    participant C as Client
    participant S as Server
    C->>S: FIN
    S->>C: ACK
    Note over C,S: The server may continue sending remaining data
    S->>C: FIN
    C->>S: ACK
    Note over C: Closes after the TIME_WAIT timeout
    Note over S: Enters CLOSED after receiving the final ACK

4. TCP Closing States

The TCP closing process involves several states.

State Meaning
ESTABLISHED The connection is established
FIN-WAIT-1 FIN has been sent, waiting for acknowledgment
FIN-WAIT-2 The peer's acknowledgment of the FIN has been received
CLOSE-WAIT The peer's FIN has been received, waiting for the local application to close
LAST-ACK FIN has been sent, waiting for the final acknowledgment
TIME-WAIT The side that actively closed waits for a period of time
CLOSED The connection is closed

5. Why Is TIME_WAIT Needed?

The side that actively closes the connection usually needs to enter the TIME_WAIT state.

There are two main reasons.

First, to ensure the final ACK arrives reliably.

If the final ACK is lost, the server may retransmit its FIN.

During TIME_WAIT, the client can still resend the ACK.

Second, to prevent delayed packets from the old connection from affecting a new connection.

TIME_WAIT allows leftover packets from the old connection to gradually disappear from the network, reducing the chance that a new connection is disturbed by old packets.

In the traditional TCP design, TIME_WAIT usually lasts for 2MSL.

MSL stands for Maximum Segment Lifetime, the maximum time a packet can survive.

In real systems, the actual duration is determined by the operating system implementation and configuration.

6. Why Do Large Numbers of TIME_WAIT Appear?

If a server or client frequently actively closes short-lived connections, a large number of TIME_WAIT states can accumulate.

You can check with:

ss -ant state time-wait

Count them:

ss -ant state time-wait | wc -l

Common causes:

  • A large number of short connections.
  • HTTP connections are not reused.
  • The client creates connections frequently.
  • Services use a large number of short-lived TCP connections.
  • The connection pool is configured improperly.

Ways to optimize:

  • Use HTTP Keep-Alive.
  • Use connection pools.
  • Reuse database connections.
  • Adjust the client connection lifecycle.
  • Use long connections and load balancing appropriately.

You should not simply solve the problem by shortening the TIME_WAIT duration, because TIME_WAIT has a protocol-level safety significance.

7. Why Should CLOSE_WAIT Be a Concern?

CLOSE_WAIT means:

The peer has already sent a FIN and the local TCP has acknowledged it, but the local application has not yet closed the connection.

If the number of CLOSE_WAIT connections keeps growing, the usual cause is that the application is not releasing sockets properly.

For example:

import socket

server = socket.socket()
server.bind(("0.0.0.0", 9000))
server.listen()

while True:
    conn, addr = server.accept()

    try:
        data = conn.recv(1024)
        print(data)
    finally:
        conn.close()

If the business code omits close(), connection resources may leak.

Troubleshooting:

ss -ant state close-wait

VII. How Does TCP Achieve Reliable Transmission?

The three-way handshake is only responsible for establishing the connection.

During the actual data transfer, TCP also has to deal with packet loss, out-of-order delivery, duplication and network changes.

Its core mechanisms include:

  • Sequence number.
  • Acknowledgment.
  • Timeout retransmission.
  • Fast retransmission.
  • Selective acknowledgment.
  • Checksum.
  • Sliding window.

1. Acknowledgment Mechanism

After TCP sends data, the receiver returns an ACK.

For example:

Sender:
SEQ = 1000
Length = 100

Receiver:
ACK = 1100

After the sender receives the acknowledgment, it knows that the corresponding contiguous bytes have been acknowledged by the receiver.

2. Timeout Retransmission Mechanism

If the sender does not receive an acknowledgment within a certain period after sending data, it may consider the data lost and resend it.

For example:

sequenceDiagram
    participant A as Sender
    participant B as Receiver
    A->>B: SEQ=1000, Data
    Note over B: Segment lost
    Note over A: Waiting for acknowledgment timeout
    A->>B: Retransmit SEQ=1000
    B->>A: ACK=1100

Timeout retransmission solves the following:

How to recover data transmission when the sender does not receive a valid acknowledgment.

3. What Is RTO?

RTO, Retransmission Timeout, is the retransmission timeout interval.

TCP needs to dynamically estimate an appropriate timeout based on the network RTT.

RTT, Round-Trip Time, is the round-trip time for data to travel from the sender to the receiver and for the acknowledgment to return.

If RTO is set too short:

  • Even a slight network delay may trigger retransmission.
  • Unnecessary duplicate data may be generated.
  • Network load may increase further.

If RTO is set too long:

  • Recovery is too slow after actual packet loss occurs.
  • Application waiting time increases.

Therefore, TCP needs to dynamically adjust RTO according to network conditions.

4. How Is RTT Estimated?

TCP estimates RTT by measuring the time between sending a segment and receiving its acknowledgment.

The classic algorithm uses smoothed round-trip time SRTT and RTT variation estimate RTTVAR.

Common calculation approach:

SRTT_{new} = (1-\alpha)SRTT_{old}+\alpha RTT_{sample}
RTTVAR_{new} = (1-\beta)RTTVAR_{old} +\beta|SRTT_{old}-RTT_{sample}|

Common parameter values:

\alpha=\frac{1}{8},\quad \beta=\frac{1}{4}

RTO calculation usually also considers clock granularity, upper and lower bounds, and system implementation rules.

Classic form:

RTO=SRTT+\max(G,4\times RTTVAR)

where G represents clock granularity.

Actual TCP implementations also include mechanisms such as exponential backoff.

5. Why Can't RTO Be Calculated Directly from Each RTT?

Network latency is not a fixed value.

For example:

Measurement RTT
First 20 ms
Second 22 ms
Third 35 ms
Fourth 24 ms
Fifth 80 ms

If the latest RTT is used directly as the RTO, it is easily affected by transient network fluctuations.

TCP uses smoothed estimation and variation estimation to make the timeout mechanism more stable.

6. Fast Retransmission Mechanism

Timeout retransmission may wait for a relatively long time.

TCP therefore introduces the fast retransmission mechanism.

When the receiver detects a gap in the data, it can repeatedly send the same cumulative ACK.

For example:

Sender sends:
SEQ = 1000
SEQ = 1100
SEQ = 1200
SEQ = 1300

Receiver receives:
1000
1200
1300

The receiver is missing:

1100

So it sends repeatedly:

ACK = 1100

When the sender receives enough duplicate ACKs, it can infer that the intermediate data segment may be lost and retransmit it early.

Classic TCP fast retransmission usually uses three duplicate ACKs as the trigger condition.

7. Fast Retransmission Sequence Diagram

sequenceDiagram
    participant A as Sender
    participant B as Receiver
    A->>B: SEQ=1000
    A->>B: SEQ=1100
    Note over B: SEQ=1100 lost
    A->>B: SEQ=1200
    B->>A: ACK=1100
    A->>B: SEQ=1300
    B->>A: ACK=1100
    B->>A: ACK=1100
    B->>A: ACK=1100
    Note over A: Received three duplicate ACKs
    A->>B: Fast retransmit SEQ=1100
    B->>A: ACK=1400

This is a classic, easy-to-understand illustration. In real systems, the number of duplicate ACKs, the triggering behavior, and the recovery process are also affected by algorithms such as SACK and RACK and by the TCP implementation.

8. SACK: Selective Acknowledgment

SACK stands for Selective Acknowledgment.

Traditional cumulative acknowledgment can only tell the sender:

how far the continuously received data has reached.

However, if the receiver has already received multiple subsequent data segments, the sender may still be unable to know exactly which data has arrived.

SACK allows the receiver to report non-contiguous data blocks that have already been received.

For example:

Received:
1000 ~ 1099
1200 ~ 1399

Missing:
1100 ~ 1199

The receiver can report the non-contiguous data blocks it has received in the SACK option.

The sender can then prioritize retransmitting the missing part rather than blindly retransmitting the entire subsequent range.

9. TCP Checksum

The TCP header contains a 16-bit checksum.

The checksum covers:

  • The TCP header.
  • The TCP data.
  • Relevant fields in the IP pseudo-header.

The pseudo-header contains information such as the source address, destination address, protocol number, and TCP length, and is used to strengthen the checksum of transport-layer packets.

The checksum can detect some data errors during transmission.

However, it is not a cryptographic security mechanism and cannot prevent malicious tampering.


VIII. TCP Sliding Window: How to Improve Data Transmission Efficiency?

If TCP had to wait for the other side's acknowledgment after sending each data segment, transmission efficiency would be very low.

For example:

  • Sending one data segment takes 1 ms.
  • Round-trip acknowledgment takes 100 ms.

If only one data segment were allowed to be sent at a time, the sender would frequently have to wait.

TCP uses a sliding window mechanism, allowing the sender to continue sending multiple data segments while waiting for ACKs.

1. What Is a Sliding Window?

The sliding window is an important mechanism for TCP to achieve continuous data transmission.

It allows the sender to send data that has not yet been acknowledged within a certain range.

For example:

Sending window range:

Acknowledged | Sent but unacknowledged | Can send | Cannot send yet

As ACKs arrive, the sending window keeps moving forward.

This is the basic idea behind the sliding window.

2. Sliding Window Example

Assume the sending window size is 400 bytes.

The sender can currently send:

1000 ~ 1399

It sends the first 200 bytes:

1000 ~ 1199

But it has not yet received an ACK.

The sender can still continue sending:

1200 ~ 1399

When the receiver returns:

ACK = 1200

The left edge of the sending window moves to 1200.

If the window size is still 400 bytes, the new sendable range becomes:

1200 ~ 1599

As the window keeps moving forward, the sender can transmit data continuously.

3. Sliding Window Diagram

flowchart TD
    A["Initial window 1000 to 1399"] --> B["Send 1000 to 1199"]
    B --> C["Continue sending 1200 to 1399"]
    C --> D["Receive ACK = 1200"]
    D --> E["Window left edge moves"]
    E --> F["New window 1200 to 1599"]
    F --> G["Continue sending subsequent data"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#FFF2CC,stroke:#E6C978,color:#765A18
    style E fill:#E9E2F8,stroke:#B9A5DF,color:#514078
    style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F

4. Data States in the Sending Window

The sender's data can be divided into several regions:

Region Meaning
Sent and acknowledged The peer has confirmed receipt
Sent but not acknowledged Sent, waiting for ACK
Allowed to send Can be sent within the current window
Data outside the window Cannot be sent for now

TCP's sliding window does not mean that the receiver buffers all data at once.

The receiver needs to advertise the amount of data it can accept based on its own buffer space.

5. Why is window size important?

Window size directly affects TCP throughput capacity.

Suppose:

  • RTT is 100 ms.
  • The send window is 64 KB.

Ideally, the throughput limited by the window is approximately:

Throughput \leq \frac{WindowSize}{RTT}

Substituting:

\frac{64\times1024}{0.1} =655360\ bytes/s

Approximately:

640\ KB/s

This is only a simplified estimate; actual throughput is also affected by factors such as the congestion window, packet loss, protocol overhead, and receiver processing capacity.


IX. TCP Flow Control: How to Avoid Overwhelming the Receiver?

The sliding window solves the problem of continuous sending, but there is another important issue:

The sender may send too fast for the receiver to handle.

For example:

  • The sender sends 100 MB per second.
  • The receiver can process only 20 MB per second.

Without flow control, the receiver's buffer may fill up and even cause data loss.

TCP uses the receive window mechanism for flow control.

1. What is the receive window rwnd?

rwnd, Receive Window, indicates the amount of data the receiver is currently willing to receive.

The receiver advertises its receive window in the Window Size field of the TCP header.

For example:

Window Size = 32768

This indicates that the window advertised by the receiver is 32768 bytes.

The sender needs to control the amount of unacknowledged data according to the receive window.

2. How does the receive window change?

Assume the receiver's buffer capacity is 64 KB.

Initial state:

Receive buffer: 64 KB
Used: 0 KB
Available window: 64 KB

After receiving 40 KB of data:

Receive buffer: 64 KB
Used: 40 KB
Available window: 24 KB

After the application reads 20 KB:

Receive buffer: 64 KB
Used: 20 KB
Available window: 44 KB

The receiver can update the advertised window through subsequent ACKs.

3. What if the receive window is zero?

If the receiver's buffer is already full, it may advertise:

Window Size = 0

This indicates that the receiver cannot currently receive any new data.

The sender should pause regular data transmission.

However, if the sender keeps waiting for the window to reopen and the window update packet is lost, a deadlock-like wait may occur.

Therefore, TCP introduced Zero Window Probe, i.e., the zero window probing mechanism.

The sender sends probe packets at appropriate times to prompt the receiver to advertise the window again.

4. Flow control process

flowchart TD
    A["Sender prepares to send data"] --> B["Read receive window rwnd"]
    B --> C{"Is the receive window greater than zero?"}
    C -->|Yes| D["Send data within the allowed range"]
    D --> E["Receiver processes and buffers data"]
    E --> F["Update window and send ACK"]
    F --> B
    C -->|No| G["Pause regular data transmission"]
    G --> H["Perform zero window probe"]
    H --> I["Receiver advertises window update"]
    I --> C

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style C fill:#FFF2CC,stroke:#E6C978,color:#765A18
    style D fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style F fill:#E9E2F8,stroke:#B9A5DF,color:#514078
    style G fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style H fill:#FFF2CC,stroke:#E6C978,color:#765A18
    style I fill:#DCEFE5,stroke:#8EBFA5,color:#24563F

5. Window Scaling Option

The Window Size field in the TCP header is only 16 bits.

Therefore, it can represent at most:

2^{16}-1=65535

That is, 65535 bytes.

For high-speed, long-distance networks, a window of around 64 KB may be too small.

TCP uses the Window Scale option to extend the range of window representation.

For example:

Window Scale = 7

The actual window value can be calculated as follows:

ActualWindow=AdvertisedWindow\times 2^7

If the advertised window is 65535:

65535\times128

This can represent a larger receive window.

The window scale option needs to be negotiated during connection establishment.


10. TCP Congestion Control: How to Avoid Overwhelming the Network?

Flow control focuses on whether the receiver has the capacity to receive data.

But even if the receiver has sufficient buffer, the network itself may not be able to handle the sender's traffic.

For example:

  • Router queues become full.
  • Switching equipment becomes congested.
  • Network link bandwidth is insufficient.
  • Multiple senders transmit large amounts of data simultaneously.

In this case, congestion control is needed.

1. Difference Between Flow Control and Congestion Control

Comparison Item Flow Control Congestion Control
Focus Receiver Network
Main Goal Prevent receive buffer overflow Prevent network overload
Main Variable rwnd cwnd
Feedback Information Receive window advertisement Packet loss, ACK, ECN, and other signals
Main Adjustment Amount of data sent Sending rate

2. What Is the Congestion Window cwnd?

cwnd, Congestion Window, refers to the congestion window.

It indicates the amount of unacknowledged data that the sender is allowed to keep in the network based on network congestion status.

The sender's actual available send window is usually limited by the following factors:

SendWindow=\min(rwnd,cwnd)

Where:

  • rwnd: receive window.
  • cwnd: congestion window.

The sender can neither exceed the receiver's receiving capacity nor exceed the range allowed by congestion control.

3. Slow Start

Slow start is an important phase of TCP congestion control.

When a connection is first established, the sender does not know how much data the network can handle.

Therefore, it usually starts with a small congestion window and gradually increases the window based on acknowledgment feedback.

In the classic slow start model, for each valid ACK received, the congestion window grows according to certain rules, generally exhibiting roughly exponential growth overall.

Simplified illustration:

Initial window: 1 MSS
After the first RTT: 2 MSS
After the second RTT: 4 MSS
After the third RTT: 8 MSS
After the fourth RTT: 16 MSS

MSS stands for Maximum Segment Size, i.e., the maximum segment data length.

Modern TCP implementations may have different initial windows, growth rules, and algorithm details; the numbers above are only used to explain the growth characteristics of classic slow start.

4. Congestion Avoidance

When the congestion window reaches the slow start threshold ssthresh, TCP usually enters the congestion avoidance phase.

Classic congestion avoidance algorithms usually use additive increase:

For each RTT that passes, the congestion window increases by approximately one MSS.

For example:

16 MSS
17 MSS
18 MSS
19 MSS
20 MSS

This growth is more cautious than slow start.

5. Fast Recovery

When packet loss occurs, TCP needs to adjust the congestion window.

The traditional Reno algorithm usually considers network congestion to have occurred after detecting three duplicate ACKs.

It will:

  • Adjust the slow start threshold.
  • Fast retransmit the lost data.
  • Enter the fast recovery phase.
  • Avoid immediately returning to the initial slow start state.

However, retransmission timeout usually indicates a more severe congestion signal; traditional algorithms often significantly reduce the congestion window and re-enter slow start.

6. AIMD Algorithm

AIMD stands for Additive Increase Multiplicative Decrease, i.e., additive increase and multiplicative decrease.

It is an important concept in classic TCP congestion control.

  • When the network is normal, gradually increase the sending rate.
  • When congestion is detected, reduce the sending rate proportionally.

For example:

cwnd_{new}=cwnd_{old}+1

When congestion occurs:

cwnd_{new}=\frac{cwnd_{old}}{2}

This is a simplified expression; the specific rules of actual algorithms depend on the congestion control implementation.

7. TCP Congestion Control Process

flowchart TD
    A["TCP connection established"] --> B["Initialize congestion window"]
    B --> C["Slow start phase"]
    C --> D{"Slow start threshold reached"}
    D -->|No| C
    D -->|Yes| E["Congestion avoidance phase"]
    E --> F{"Congestion detected"}
    F -->|No| G["Gradually increase congestion window"]
    G --> E
    F -->|Fast retransmit signal| H["Fast retransmit and recovery"]
    F -->|Timeout signal| I["Reduce congestion window and restart slow start"]
    H --> E
    I --> C

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style C fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style D fill:#FFF2CC,stroke:#E6C978,color:#765A18
    style E fill:#E9E2F8,stroke:#B9A5DF,color:#514078
    style F fill:#FFF2CC,stroke:#E6C978,color:#765A18
    style G fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style H fill:#F6FAF7,stroke:#DCE9E0,color:#334155
    style I fill:#F6FAF7,stroke:#DCE9E0,color:#334155

8. Common TCP Congestion Control Algorithms

Different operating systems may use different congestion control algorithms.

Algorithm Core characteristics
Tahoe Classic algorithm; restarts slow start after congestion occurs
Reno Introduces the fast recovery mechanism
NewReno Improves recovery behavior in partial acknowledgment scenarios
CUBIC Adjusts the congestion window using a cubic function
BBR Estimates network state based on bandwidth and round-trip time models

CUBIC

CUBIC is a common TCP congestion control algorithm in systems such as Linux.

It adjusts the sending rate through a cubic function relationship between the congestion window and time.

Characteristics:

  • Suitable for networks with high bandwidth and relatively high RTT.
  • Responds to packet loss signals.
  • Delivers relatively good performance on some long-distance links.

View the current congestion control algorithm on Linux:

sysctl net.ipv4.tcp_congestion_control