TCP Notes

Created by Qiwei on 7/18/2020 · Edited on 9/7/2025

  1. Segment Structure
  2. Connection Management
  3. Reliable Data Transfer
  4. Flow Control
  5. CONGESTION CONTROL
  6. TCP vs UDP

Revision of TCP basics

1. Segment Structure

tcp segment unsw

tcp-seg-wiki

FieldsUsage
Sequence numberIf the SYN flag is set (1), then this is the initial sequence number. The sequence number of the actual first data byte and the acknowledged number in the corresponding ACK are then this sequence number plus 1. If the SYN flag is clear (0), then this is the accumulated sequence number of the first data byte of this segment for the current session.
Acknowledgment numberIf the ACK flag is set then the value of this field is the next sequence number that the sender of the ACK is expecting. This acknowledges receipt of all prior bytes (if any). The first ACK sent by each end acknowledges the other end's initial sequence number itself, but no data.
Data offsetSpecifies the size of the TCP header in 32-bit words. The minimum size header is 5 words and the maximum is 15 words thus giving the minimum size of 20 bytes and maximum of 60 bytes, allowing for up to 40 bytes of options in the header. This field gets its name from the fact that it is also the offset from the start of the TCP segment to the actual data.
Reserved (3 bits)For future use and should be set to zero.
Window sizeThe size of the receive window, which specifies the number of window size units that the sender of this segment is currently willing to receive.
ChecksumThe 16-bit checksum field is used for error-checking of the TCP header, the payload and an IP pseudo-header.
OptionsThe length of this field is determined by the data offset field. Options have up to three fields: Option-Kind (1 byte), Option-Length (1 byte), Option-Data (variable).

Common TCP options: tcp-options

FlagsUsage
NSECN-nonce - concealment protection (Experimental)
CWRCongestion window reduced (CWR) flag is set by the sending host to indicate that it received a TCP segment with the ECE flag set and had responded in congestion control mechanism.
ECEECN(explicit congestion notification)-Echo has a dual role, depending on the value of the SYN flag. If the SYN flag is set (1), that the TCP peer is ECN capable. If the SYN flag is clear (0), that a packet with Congestion Experienced flag set (ECN=11) in the IP header was received during normal transmission.[b] This serves as an indication of network congestion (or impending congestion) to the TCP sender.
URGIndicates that the Urgent pointer field is significant
ACKIndicates that the Acknowledgment field is significant. All packets after the initial SYN packet sent by the client should have this flag set.
PSHPush function. Asks to push the buffered data to the receiving application.
RSTReset the connection.
SYNSynchronize sequence numbers. Only the first packet sent from each end should have this flag set. Some other flags and fields change meaning based on this flag, and some are only valid when it is set, and others when it is clear.
FINLast packet from sender

mss

2. Connection Management

3way

At this point, both the client and server have received an acknowledgment of the connection. The steps 1, 2 establish the connection parameter (sequence number) for one direction and it is acknowledged. The steps 2, 3 establish the connection parameter (sequence number) for the other direction and it is acknowledged.

4way

A connection can be "half-open", in which case one side has terminated its end, but the other has not. The side that has terminated can no longer send any data into the connection, but the other side can. The terminating side should continue reading the data until the other side terminates as well.

It is also possible to terminate the connection by a 3-way handshake, when host A sends a FIN and host B replies with a FIN & ACK (merely combines 2 steps into one) and host A replies with an ACK

3. Reliable Data Transfer

Reliability is achieved by the sender detecting lost data and retransmitting it. TCP uses two primary techniques to identify loss. Retransmission timeout (abbreviated as RTO) and duplicate cumulative acknowledgements (DupAcks).

3.1 Sequence Number

TCP uses a sequence number to identify each byte of data. The sequence number identifies the order of the bytes sent from each computer so that the data can be reconstructed in order, regardless of any packet reordering, or packet loss that may occur during transmission. The sequence number of the first byte is chosen by the transmitter for the first packet, which is flagged SYN. This number should be unpredictable to defend against TCP sequence prediction attacks.

seq-ack

3.2 Acknowledgements

  1. Positive Acknowledgement: the receiver explicitly notifies the sender which packets, messages, or segments were received correctly. Positive Acknowledgement therefore also implicitly informs the sender which packets were not received and provides detail on packets which need to be retransmitted.

  2. Negative Acknowledgment (NACK): the receiver explicitly notifies the sender which packets, messages, or segments were received incorrectly and thus may need to be retransmitted. Not NACK in TCP

  3. Cumulative: the receiver acknowledges that it correctly received a packet, message, or segment in a stream which implicitly informs the sender that the previous packets were received correctly.

  4. Selective Acknowledgment (SACK): the receiver explicitly lists which packets, messages, or segments in a stream are acknowledged (either negatively or positively).

3.3 Timeout-based Retransmission

When a sender transmits a segment, it initializes a timer with a conservative estimate of the arrival time of the acknowledgement. The segment is retransmitted if the timer expires prematurely, with a new timeout threshold of twice the previous value, resulting in exponential backoff behavior.

Typical RTT calculation (Jacobson / Karels):

  • SampleRTT: measured time from segment transmission until ACK receipt, ignore retransmission

  • EstimatedRTT = (1- a) * EstimatedRTT + a * SampleRTT (typically, a = 0.125)

  • DevRTT = (1-b) * DevRTT + b * |SampleRTT-EstimatedRTT| (typically, b = 0.25)

  • TimeoutInterval = EstimatedRTT + 4*DevRTT

3.4 DupAcks-based Retransmission (Fast Retransmission)

Timeout period is usually long, fast retransmission is an optimisation that uses duplicated ACKs to trigger early retransmission.

If a single segment (say segment 100) in a stream is lost, then the receiver cannot acknowledge packets above no.100 because it uses cumulative ACKs. Hence the receiver acknowledges packet 99 again on the receipt of another data packet. This duplicate acknowledgement is used as a signal for packet loss. If the sender receives three duplicate acknowledgements, it's likely that unAcked segment is lost, so don't wait for timeout, it retransmits the last unacknowledged packet. A threshold of three is used because the network may reorder segments causing duplicate acknowledgements. This threshold has been demonstrated to avoid spurious retransmissions due to reordering.

Sometimes selective acknowledgements (SACKs) are used to provide explicit feedback about the segments that have been received. This greatly improves TCP's ability to retransmit the right segments.

3.5 Checksum (for error detection)

https://en.wikipedia.org/wiki/Transmission_Control_Protocol#Checksum_computation

Error correction unnecessary, coz we have periodic messages.

4. Flow Control

Whereas congestion control prevents senders from overwhelming the network, flow control prevents the sender from overwhelming the receiver.

TCP uses an end-to-end flow control protocol to avoid having the sender send data too fast for the TCP receiver to receive and process it reliably. Having a mechanism for flow control is essential in an environment where machines of diverse network speeds communicate.

4.1 Sliding Window (for efficiency and flow control)

Increased utilization when we use sliding window.

sliding window

TCP uses a sliding window flow control protocol. In each TCP segment, the receiver specifies in the receive window field the amount of additionally received data (in bytes) that it is willing to buffer for the connection. The sending host can send only up to that amount of data before it must wait for an acknowledgement and window update from the receiving host.

flow-control

Two generic forms of pipelined (sliding window) protocal: go-Back-N (GBN), Selective Repeat (SR). The TCP uses a variant of GBN to ensure reliable transmission, it may also use SR when SACK is set.

GBN

Note: 在传输过程中,receiver 和 sender 协商接收窗口 rwnd,再结合拥塞控制窗口 cwnd 计算滑动窗口 swnd。在 Linux 内核实现中,滑动窗口 cwnd 是以包为单位,所以在计算 swnd 时需要乘上 MSS(最大分段大小)。

swnd = min(rwnd, cwnd * MSS)

5. Congestion Control

Congestion: too many senders sending too much data too fast for network to handle.

Cost of Congestion:

cost-of-congestion

LossCause
Duplicate ACKs: isolated lossdup ACKs indicate network capable of delivering some segments
Timeout: more seriousNot enough dup ACKs, must have suffered several losses

Need to adjust rate differently for each case.

tcp-rate

How? Basic structure:

  • Upon receipt of ACK (of new data): increase rate
  • Upon detection of loss: decrease rate

5.1 Three Phases

  1. Slow start phase

    When connection begins, increase rate exponentially until first loss event:

    • initially cwnd = 1 MSS
    • double cwnd every RTT (full ACKs)
    • Simpler implementation achieved by incrementing cwnd for every ACK received
      • cwnd += 1 for each ACK

    "Slow start" stops when cwnd reaches ssthresh (slow start threshold)

  2. Congestion avoidance phase

    TCP uses Additive Increase Multiplicative Decrease (AIMD).

    Additive increase: increase cwnd by 1 MSS every RTT until loss detected

    • For each successful RTT (all ACKS), cwnd = cwnd + 1
    • Simple implementation: for each ACK, cwnd = cwnd + 1/cwnd

    Multiplicative decrease: cut cwnd in half after loss

    sawtoth

  3. Fast Recovery

    The problem is that fast retransmission is slow when recovering from an isolated loss.

    (BSD 初始版本) 当检测到丢包时,TCP 会触发快速重传并进入降窗状态。该状态下 cwnd 会通过快速恢复算法降至一个合理值。

    1. 收到 3 次重复 ACK,ssthresh 设为 cwnd/2,cwnd = cwnd / 2 + 3;

    2. 每收到一个重复 ACK,窗口值加 1;

    3. 收到非重复 ACK,窗口设为 ssthresh,退出。

    fast-recovery

    优点:在快速恢复期间,可以尽可能多的发送数据。

    缺点:由于快速恢复未完成,尽可能多发送可能会加重拥塞。

5.2 Other Flavours

There are many other flavours of TCP congestion control.

https://en.wikipedia.org/wiki/TCP_congestion_control

https://arxiv.org/pdf/1903.03852.pdf

https://zhuanlan.zhihu.com/p/144273871

6. TCP differs from UDP

The Transmission Control Protocol differs in several key features from the User Datagram Protocol:

  • Ordered data transfer: the destination host rearranges segments according to a sequence number
  • Retransmission of lost packets: any cumulative stream not acknowledged is retransmitted
  • Error-free data transfer
  • Flow control: limits the rate a sender transfers data to guarantee reliable delivery. The receiver continually hints the sender on how much data can be received (controlled by the sliding window). When the receiving host's buffer fills, the next acknowledgment contains a 0 in the window size, to stop transfer and allow the data in the buffer to be processed.
  • Congestion control

udf-tcp