Computer Network 📂 Transport Layer · 1 of 4 60 min read

Transport Layer Explained

Master the Transport Layer — from port-based multiplexing and UDP's 8-byte simplicity to TCP's full machinery: 3-way handshake with teardown, flow control via sliding window (rwnd), and congestion control (Slow Start, Congestion Avoidance, Fast Recovery). Features three animated diagrams, TCP vs UDP comparison, QUIC and SCTP, real incidents from the 1986 ARPANET collapse to Starlink 2022.

Section 01

The Transport Layer — The Invisible Courier Between Applications

The Royal Mail vs a Motorbike Courier
Imagine you need to send documents across a city. You have two options:

Royal Mail (TCP) — tracked delivery, signed receipt, guaranteed order, returned if undelivered. Slower, more overhead, but nothing gets lost. Your solicitor uses this for legal contracts.

Motorbike Courier (UDP) — no tracking, no receipt, no guarantee. But it's fast and cheap. Your pizza delivery app uses this for GPS location updates — if one position message is lost, the next one arrives anyway and nobody cares.

Both services sit on top of the same road network (the Internet / IP layer). Neither cares how the roads are laid out — they just use them. That is the Transport Layer: a service on top of IP that gives applications the delivery guarantee (or lack thereof) they need.

The Transport Layer (Layer 4) in the OSI model sits between the Network Layer (IP routing) and the Application Layer (HTTP, DNS, FTP). Its job is to provide logical communication between application processes running on different hosts — not just between hosts themselves. It does this using port numbers to identify which application on a machine should receive each packet.

📌
The Critical Distinction: Host-to-Host vs Process-to-Process

IP (Network Layer) delivers packets to the correct machine using IP addresses. It has no idea which application on that machine should receive the data.

Transport Layer delivers data to the correct application process on that machine using port numbers. When your browser and Spotify both run on your laptop simultaneously, transport layer multiplexing ensures HTTP traffic goes to Chrome and audio streams go to Spotify — not the other way around.

Transport Layer — Core Responsibilities

🔌
Multiplexing / Demultiplexing
Port numbers — the address within a host
Multiplexing: at the sender, gathers data from multiple sockets and adds transport headers. Demultiplexing: at the receiver, delivers segments to the correct socket using (src IP, src port, dst IP, dst port) as a 4-tuple identifier.
📊
Segmentation & Reassembly
Breaking big data into segments
Application data may be megabytes long. The transport layer breaks it into segments (TCP) or datagrams (UDP) sized to fit inside IP packets. At the destination, segments are reassembled in order before delivery to the application.
📋
Error Detection
Checksum on every segment
Both TCP and UDP include a 16-bit checksum covering the header and data. UDP merely detects errors and discards. TCP detects errors, discards, and triggers retransmission. Neither corrects — they detect and react.

Port Numbers — The Addressing System

🔎 Port Number Ranges
0 – 1023
Well-Known Ports — assigned by IANA. HTTP=80, HTTPS=443, SSH=22, DNS=53, SMTP=25, FTP=21. Require root/admin privileges to bind.
1024 – 49151
Registered Ports — registered by vendors but not reserved. MySQL=3306, PostgreSQL=5432, Redis=6379, HTTP-alt=8080.
49152 – 65535
Ephemeral Ports — dynamically assigned by the OS to client connections. Your browser uses one of these as its source port when connecting to port 443.

Section 02

UDP — User Datagram Protocol

UDP (RFC 768, 1980) is the minimalist of the transport layer. It provides almost nothing beyond IP — just port-based demultiplexing and an optional checksum. No connection, no ordering, no retransmission, no flow control. What it lacks in reliability, it makes up in speed and simplicity.

📋 UDP Header — Just 8 Bytes
FieldSizePurpose
Source Port16 bitsSender's port (optional, can be 0)
Destination Port16 bitsReceiver's application port
Length16 bitsHeader + data length in bytes
Checksum16 bitsError detection (optional in IPv4)

Total overhead: 8 bytes vs TCP's 20+ bytes. No connection state maintained anywhere.

🌐 Where UDP Is Used
ApplicationWhy UDP
DNS (port 53)One request, one reply — no connection needed
Video streamingLate packet is useless — better to skip
VoIP / GamingLow latency beats perfect delivery
DHCP (port 67/68)Broadcast-based — TCP can't broadcast
QUIC (HTTP/3)Reliability built in user space over UDP
SNMP (port 161)Polling protocol; loss tolerable
💡
UDP Is Not Unreliable — It Is Deliberately Simple

Applications that need reliability on top of UDP build it themselves — with exactly the semantics they need. QUIC (used by HTTP/3 and YouTube) reimplements TCP-like reliability with better performance because it can avoid head-of-line blocking, deploy faster (no OS kernel update needed), and use 0-RTT connection resumption. UDP is the canvas; reliability is the painting the application chooses to draw.


Section 03

TCP — Transmission Control Protocol

TCP (RFC 793, 1981) is the backbone of the web. It guarantees that every byte sent by the application arrives at the destination in order, exactly once, without corruption. It achieves this through connection management, sequence numbers, acknowledgements, retransmission, flow control, and congestion control — all working together transparently beneath every HTTP, HTTPS, SSH, and SMTP session you use.

📋 TCP Header — 20 Bytes Minimum (up to 60 with options)
Src / Dst Port
16-bit each. Identifies source and destination applications. Core of demultiplexing.
Sequence Number
32-bit. Byte number of the first byte in this segment's data. Enables ordering and gap detection.
Acknowledgement No.
32-bit. Next byte the receiver expects. Implicitly ACKs all bytes up to this number (cumulative ACK).
Flags (6 bits)
SYN setup · ACK acknowledgement · FIN teardown · RST abort · PSH push · URG urgent
Window Size
16-bit. Receiver's advertised buffer space (rwnd). Sender must not have more than this many bytes in-flight unacknowledged — this is flow control.
Checksum
16-bit. Covers header + data + pseudo-header (src IP, dst IP, protocol, length). Mandatory in TCP.
Options
Variable. MSS (maximum segment size), Window Scale, SACK (selective ACK), Timestamps. Negotiated during the handshake.

🏭 Interactive: TCP Header — Every Field Explained

The TCP header is a masterpiece of 1981 engineering that still underpins the entire web. It is 20 bytes minimum (160 bits) with up to 40 bytes of options — compared to UDP's flat 8 bytes. Every bit is there for a reason. Click any field in the diagram below to see a deep explanation.

📋 TCP Header — Interactive Field-by-Field Diagram
👉 Click any field in the diagram above
Each coloured field in the TCP header has a specific job. Click to explore them — from the port numbers that identify applications to the flags that control the connection lifecycle.

💡 TCP header is drawn to scale in bit-widths. One row = 32 bits. The minimum header is 5 rows × 32 bits = 160 bits = 20 bytes. Options can add up to 40 more bytes (max header = 60 bytes).

TCP Options — Deep Dive

📈
MSS — Max Segment Size
Type 2 · Negotiated in SYN
Each side announces the largest payload it can accept. On Ethernet: MTU (1500) − IP header (20) − TCP header (20) = 1460 bytes. Both sides use the smaller of the two announced values. Prevents fragmentation. Without MSS, TCP would default to 536 bytes (RFC 879).
🔄
Window Scale
Type 3 · RFC 7323
The raw Window Size field is 16 bits → max 65535 bytes. On a 100ms RTT link that caps throughput at ~5 Mbps. Window Scale shifts the window by 0–14 bits, enabling windows up to 1 GB. Negotiated in SYN. Both sides must support it. Essential for satellite and intercontinental links.
SACK — Selective ACK
Types 4 & 5 · RFC 2018
Without SACK, TCP uses cumulative ACK — a lost packet forces retransmission of all subsequent packets (Go-Back-N). With SACK, the receiver reports up to 4 non-contiguous received ranges, so the sender retransmits only what is truly missing. Boosts throughput by ~50% on lossy links.
🕑
TCP Timestamps Option (Type 8) — Two Hidden Powers

The Timestamps option carries two 32-bit values in every segment: the sender's current clock (TSval) and an echo of the peer's most recent timestamp (TSecr). This enables two critical features:

1. Accurate RTT Measurement — even when retransmissions make it ambiguous which ACK corresponds to which send (Karn's algorithm problem).

2. PAWS — Protection Against Wrapped Sequence Numbers — a 32-bit sequence number wraps after 4 GB. At 10 Gbps that takes 3 seconds. Without PAWS, an old segment from a previous connection could be mistakenly accepted. Timestamps let the receiver reject segments with timestamps older than recent ones.

FieldBitsPurposeKey Value / Range
Source Port16Sending application identifier0–65535 (ephemeral: 49152–65535)
Destination Port16Receiving application identifierWell-known: 0–1023 · Registered: 1024–49151
Sequence Number32Byte offset of first data byte0 – 2³²−1 (wraps at ~4 GB)
Acknowledgement No.32Next expected byte from peerCumulative ACK — acks all prior bytes
Data Offset4Header length in 32-bit words5 (=20B min) – 15 (=60B max)
Reserved3Future use — must be 0Partially used by ECN (RFC 3168)
Flags9Connection control bitsNS CWR ECE URG ACK PSH RST SYN FIN
Window Size16Receive buffer space (rwnd)0–65535 bytes (× scale factor if WS option)
Checksum16Error detection (mandatory)One's complement of header + data + pseudo-hdr
Urgent Pointer16Offset of urgent data (if URG=1)Rarely used — Telnet era legacy
Options0–320Extensions (MSS, WScale, SACK, TS)Padded to 32-bit boundary

Section 04

🏭 Animated: TCP 3-Way Handshake — Connection Establishment

Before a single byte of application data is exchanged, TCP establishes a connection — a shared understanding of initial sequence numbers, window sizes, and supported options. This takes exactly 1.5 RTT (one-and-a-half round trips) and is called the 3-way handshake.

▶ TCP 3-Way Handshake + Connection Teardown (4-Way)
Click Play or Step to begin

💡 The Initial Sequence Number (ISN) is chosen randomly — not starting at 0 — to prevent old duplicate segments from a previous connection being mistakenly accepted. Each side picks its own ISN independently.

⚠️
SYN Flood Attack — Weaponising the Handshake

An attacker sends thousands of SYN packets with spoofed source IPs. The server replies with SYN-ACK and allocates a half-open connection entry — waiting for the final ACK that never comes. The server's connection table fills up, and legitimate connections are refused. This is a SYN Flood DDoS attack.
Defence: SYN Cookies — the server encodes connection state in the sequence number of the SYN-ACK, eliminating the need to store half-open state. The 2016 Dyn DNS attack that took down Twitter, Netflix, and Reddit used SYN floods as one of its vectors. Source: Cloudflare, October 2016.


Section 05

TCP Flow Control — Receiver Protects Its Own Buffer

What if the sender is blazingly fast but the receiver is a slow mobile device? Without flow control, the receiver's buffer would overflow and packets would be silently dropped — then retransmitted — wasting bandwidth. TCP's flow control prevents this using the Receiver Window (rwnd) advertised in every ACK.

Filling a Glass from a Fire Hose
Imagine someone trying to fill your glass of water using a fire hose. Even if the fire hose can deliver 1000 litres per minute, your glass holds only 500ml. The solution: the person holding the glass shouts "STOP!" when it's nearly full, and "GO!" when they've drunk some. The fire hose operator — however powerful — must obey.

TCP flow control works identically. The receiver shouts its current buffer space in every ACK (window=X bytes). The sender must never have more than X bytes outstanding. When the receiver drains its buffer (the application reads the data), it sends a larger window and the sender speeds up again.
▶ TCP Flow Control — Sliding Window Animation
Ready

💡 When rwnd=0, the sender stops completely. It sends 1-byte window probe segments periodically to check if the receiver has freed space. This prevents permanent deadlock if the window-update ACK is lost.


Section 06

TCP Congestion Control — Slow Start & Congestion Avoidance

Flow control protects the receiver. Congestion control protects the network. The sender also self-limits with a Congestion Window (cwnd), and the effective sending rate is:

Effective Send Rate
send ≤ min(cwnd, rwnd)
The sender cannot exceed either the receiver's buffer limit (rwnd from flow control) or the network limit (cwnd from congestion control). The smaller constraint wins.
Slow Start — per ACK
cwnd += 1 MSS
Every ACK grows cwnd by one MSS → window doubles each RTT. Exponential growth probes for available bandwidth quickly after connection start or timeout.
Congestion Avoidance — per RTT
cwnd += MSS²/cwnd
Approximately +1 MSS per full RTT regardless of window size. Linear growth. Careful probing once near the capacity limit, after ssthresh is reached.

The Slow Start Threshold (ssthresh)

⚙ How cwnd and ssthresh Interact
Start
cwnd = 1 MSS  |  ssthresh = 65535 bytes (or rwnd, whatever is smaller). Begin Slow Start.
cwnd < ssthresh
Slow Start — exponential growth. cwnd doubles every RTT. Fast probe of available bandwidth.
cwnd ≥ ssthresh
Congestion Avoidance — linear growth. +1 MSS per RTT. Careful approach to the capacity ceiling.
3 Dup ACKs (Reno)
ssthresh = cwnd/2  ·  cwnd = ssthresh + 3 MSS  ·  Enter Fast Recovery. Retransmit immediately.
Timeout
ssthresh = cwnd/2  ·  cwnd = 1 MSS  ·  Restart Slow Start from scratch. Severe congestion assumed.

Section 07

🏭 Animated: Slow Start → Congestion Avoidance → Loss → Recovery

▶ TCP Congestion Window (cwnd) Live Simulation — Reno Algorithm
Click Play to simulate TCP Reno

💡 The sawtooth pattern is the hallmark of TCP Reno — probe until loss, back off, probe again. This constant probing means TCP is always slightly congesting the network to find the maximum throughput. BBR avoids this by modelling the pipe capacity directly.


Section 08

TCP vs UDP — Full Comparison

FeatureTCPUDP
ConnectionConnection-oriented (3-way handshake)Connectionless — fire and forget
ReliabilityGuaranteed delivery & orderingNo guarantee — packets may be lost or reordered
Header size20–60 bytes8 bytes (minimal overhead)
Flow controlYes — rwnd in every ACKNone
Congestion controlYes — cwnd, Slow Start, CUBIC/BBRNone (can congest the network)
SpeedSlower (ACKs, retransmission, setup)Faster (no handshake, no wait for ACK)
OrderingIn-order delivery guaranteedOut-of-order possible
Broadcast/MulticastNot supportedSupported
Use caseHTTP/S, SSH, FTP, SMTP, databasesDNS, VoIP, video, gaming, DHCP, QUIC
RFCRFC 793 (1981), RFC 9293 (2022)RFC 768 (1980)

Section 09

Beyond TCP and UDP — Other Transport Protocols

QUIC — The Future of Transport
Google's QUIC (now RFC 9000, 2021) is a transport protocol that runs over UDP. It combines TLS 1.3 encryption, TCP-like reliability, and HTTP/2 stream multiplexing — all without head-of-line blocking. A lost UDP packet stalls only its own stream, not all concurrent requests. Supports 0-RTT connection resumption for returning users. Powers HTTP/3. As of 2024, ~30% of all web traffic uses QUIC.
RFC 9000 | HTTP/3 | Google, Cloudflare, Meta
🔌
SCTP — Stream Control Transmission Protocol
SCTP (RFC 4960) combines features of both TCP and UDP. It supports multi-streaming (multiple independent streams in one connection — no HOL blocking), multi-homing (a connection can span multiple IP addresses for failover), and message-oriented delivery. Used in telecom signalling (SS7 over IP / SIGTRAN), WebRTC data channels, and some IETF protocols.
RFC 4960 | Telecom / WebRTC | Multi-homing
📈
DCCP — Datagram Congestion Control Protocol
DCCP (RFC 4340) provides unreliable, unordered delivery like UDP, but adds congestion control — solving the problem that UDP streams can congest the network with no backoff. Designed for streaming media (voice, video) where perfect delivery is unnecessary but being a "good citizen" to other flows matters. Rarely deployed in practice; QUIC replaced its niche.
RFC 4340 | Congestion-aware UDP alternative

Section 10

Real-World Cases — Transport Layer in the News

💥
1986 — ARPANET Congestion Collapse (TCP's Origin Story)
Before TCP had congestion control, every sender transmitted at full speed regardless of network load. In 1986, the ARPANET link between Berkeley and MIT collapsed from 32 Kbps to 40 bps — a 99.9% throughput loss. All packets were being dropped and immediately retransmitted by uncontrolled senders. Van Jacobson invented Slow Start, Congestion Avoidance, and Fast Retransmit in 1988 and deployed them in BSD Unix. The Internet stabilised overnight. Source: V. Jacobson, "Congestion Avoidance and Control", ACM SIGCOMM 1988.
Protocol: TCP | Root Cause: No congestion control | Fixed: 1988
🔥
2016 — Dyn DNS DDoS (SYN Flood at Scale)
The October 2016 Mirai botnet attack on Dyn DNS used SYN floods as a primary vector — millions of IoT devices (cameras, routers) each sending thousands of SYN packets per second with spoofed source addresses. Dyn's servers exhausted their TCP connection tables accepting half-open connections. Twitter, Reddit, Netflix, and Spotify were unreachable for hours across the US East Coast. Peak attack traffic: 1.2 Tbps. Source: Dyn post-mortem report, October 2016; Wired Magazine.
Protocol: TCP SYN flood | Impact: Major Internet outage | Fixed: SYN Cookies
🌐
2022 — Starlink & TCP Congestion Control Mismatch
SpaceX Starlink's LEO satellite internet has highly variable RTTs (20–40ms normally, spikes to 500ms+). TCP Reno and CUBIC interpret high RTT as congestion and throttle cwnd — dramatically reducing throughput on Starlink. Academic research in 2022 showed CUBIC achieved only 40% of available bandwidth on Starlink, while BBR reached 90%+. SpaceX now recommends BBR for high-performance Starlink applications, and this drove widespread adoption of BBR on cloud platforms. Source: IEEE INFOCOM 2022; ArXiv 2205.12561.
Protocol: TCP CUBIC vs BBR | Context: Satellite Internet RTT variance

Section 11

Golden Rules — Transport Layer Engineering

📌 Non-Negotiable Rules for Every Network Engineer
1
Choose TCP for correctness, UDP for speed — never mix up the decision. If a single lost byte causes data corruption (file transfer, API calls, database queries) → TCP. If a delayed retransmission is worse than missing data (live video, VoIP, GPS updates) → UDP. Using TCP for live video adds 200–500ms latency from head-of-line blocking when packets are retransmitted.
2
Enable SYN Cookies on all public-facing TCP servers. Linux: sysctl -w net.ipv4.tcp_syncookies=1. Without SYN cookies, a 10 Mbps SYN flood can exhaust the connection table of a 40 Gbps server. SYN cookies eliminate the need to store half-open connection state.
3
Deploy BBR on servers with high-BDP or lossy paths. Linux: sysctl -w net.ipv4.tcp_congestion_control=bbr. BBR outperforms CUBIC dramatically on satellite, mobile, and intercontinental links. CUBIC is better on wired low-latency paths where its cubic growth more efficiently fills the pipe.
4
Enable TCP SACK (Selective ACK) on all endpoints. Linux enables SACK by default. Without it, TCP must retransmit all segments from the lost one onwards (Go-Back-N behaviour). With SACK, only lost segments are retransmitted. On a link with 1% loss, SACK can increase throughput by 50%.
5
Tune TCP buffer sizes for high-bandwidth-delay-product paths. The throughput ceiling is min(cwnd, rwnd) / RTT. On a 100ms RTT link, the default 87KB socket buffer limits throughput to ~7 Mbps. Set: net.core.rmem_max=134217728 and net.core.wmem_max=134217728 on Linux for multi-gigabit long-distance paths.
6
Consider QUIC for new application protocols. QUIC eliminates head-of-line blocking, encrypts by default, and enables 0-RTT connection resumption. For applications with many concurrent small requests (APIs, microservices, CDN assets), QUIC + HTTP/3 can reduce latency by 30–50% compared to TLS 1.3 + TCP + HTTP/2.
7
Never firewall block TCP RST — it causes silent connection hangs. RST tells a peer that a connection is dead — allowing it to clean up immediately. Blocking RST means the peer waits for a timeout (2+ minutes for TCP timeout). Applications appear to hang with no error message. Always allow RST through firewalls on established sessions.
🎓
The Complete Picture

The Transport Layer is where the Internet becomes reliable. IP delivers packets between machines with no guarantees — it is the transport layer that adds ordering, error recovery, flow control, and congestion management.

TCP's 3-way handshake establishes the shared state that makes reliable communication possible. Flow control (rwnd) ensures the receiver is never overwhelmed. Congestion control (cwnd, Slow Start, Congestion Avoidance) ensures the network is never overwhelmed — making TCP's sawtooth behaviour the self-regulating heartbeat of the Internet.

UDP strips all of this away for applications that know better than the transport layer what guarantees they actually need — and modern protocols like QUIC rebuild exactly the right guarantees, in user space, with none of the legacy constraints of a 1981 standard.