--- title: 5. The Transport Layer collection: computer networks author: Akash Kadlag updated: 2026-09-17 source: https://docs.chaicode.com/networking/transport-layer --- # 5. The Transport Layer ![Transport Layer TCP and UDP](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/1bfb4e4be4c2a8dc19e535730a7eb796e71798eda8f42b3252b36e73c10ce42d.png) Transport Layer TCP and UDP — Chap 5 Two Workhorses of the Internet. ![Port Numbers](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/ccf04cf5dc16adc55b02b03d34c93e5fd91fe27c3546f3f1b275cfcffcdb961c.png) Port Numbers — Port Numbers are like special codes that help devices know which specific application or service to send data to. Just like a house has a unique address, an application or service has its special port number. When you send data to someone, you include their IP address and a port number. It's like telling the postal service not just which house to deliver to but also which person inside the house should receive the package. PORT is 16-bit number. So the total PORT Numbers possible are = 2^16 = 65535. ![Port Numbers](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/c155c75e47901af7d208260927984e331057f84e52d5712686daa706087dff31.png) Port Numbers — Some of the most commonly used ports : Port 20 and 21: File Transfer Protocol (FTP). FTP is for transferring files between a client and a server. Port 22: Secure Shell (SSH). SSH is one of many tunnelling protocols that create secure network connections. Port 25: Simple Mail Transfer Protocol (SMTP). SMTP is used for email. Port 53: Domain Name System (DNS). DNS is an essential process for the modern Internet; it matches human-readable domain names to machine-readable IP addresses. Port 80: Hypertext Transfer Protocol (HTTP). HTTP is the protocol that makes the World Wide Web possible. ![Port Numbers](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/bf45d30263e92f431fcccf3f054657ccae7b4ab806d32e7647659983325e0e10.png) Port Numbers — Some of the most commonly used ports : Port 123: Network Time Protocol (NTP). NTP allows computer clocks to sync with each other, a process that is essential for encryption. Port 443: HTTP Secure (HTTPS). HTTPS is the secure and encrypted version of HTTP. Network services that use HTTPS for encryption, such as DNS over HTTPS, also connect at this port. Port 500: Internet Security Association and Key Management Protocol (ISAKMP), which is part of the process of setting up secure IPsec connections. Port 587: Modern, secure SMTP that uses encryption. Port 3389: Remote Desktop Protocol (RDP). RDP enables users to remotely connect to their desktop computers from another device. ![Port Numbers](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/8100e07c304b48a1857c97e5182040e9d57dec7a291327dad1773e9bc4f065ed.png) Port Numbers — PORT Numbers from 0-1023 are reserved. You’ll not be able to use those for personal usage PORT Numbers from 1024-4915 are reserved for some applications like MongoDB, MySQL etc. Example → every MongoDB server you run, has a PORT of 27017. PORT Numbers after 4916 are not reserved & can be used publicly. ![User Datagram Protocol (UDP)](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/295e5ab9e66a20ac167dd5f76582ade1f5fc8f9c863c2d42ea11be692d96f414.png) User Datagram Protocol (UDP) — UDP is a fundamental protocol used widely in network communications. It operates at Layer 4 of the OSI model, sitting directly on top of the Internet Protocol (IP) layer. Stateless Protocol: UDP is stateless, meaning that it doesn't maintain a connection between the sender and receiver. Each datagram (packet) is sent independently, without knowing if the destination is ready or even exists. No Prior Communication Required: Since it’s stateless, UDP doesn’t require any prior communication before sending data. This allows for faster transmission compared to connection-oriented protocols like TCP. Simple and Minimal Header: UDP's header is only 8 bytes long, much smaller than TCP's header. This simplicity contributes to its low overhead and efficiency. ![A network diagram illustrating multiplexing where multiple applications with different ports on host 10.0.0.2 are combined and transmitted to host 10.0.0.3, which demultiplexes the incoming data stream to separate destination applications with different ports.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/02de739b2dc692265393678273209f461ffb32479eb4e948f4084328eae4644f.png) Addressing with Ports — Each application on a host can be uniquely identified by its port number, facilitating communication between multiple applications. Multiplexing: Multiple data streams from different applications are combined into one stream to be sent over the network. Deultiplexing: The combined stream is then split back into original data streams at the receiving end, directing the data to the appropriate applications based on ports. Sender multiplexes all its apps into UDP. Receiver demultiplex UDP datagrams to each app. ![Use Cases of UDP](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/9ee983479d894c16eb1ee62652bce28aa52fafeb1c45a2e68b76bcdecb60ad2e.png) Use Cases of UDP — Video Streaming: Ideal for streaming where occasional data loss is acceptable. The protocol's efficiency outweighs the need for guaranteed delivery. VPN (Virtual Private Networks): Many VPN protocols use UDP for its efficiency and lower latency. DNS (Domain Name System): DNS uses UDP for quick, simple query-response communication. WebRTC (Web Real-Time Communication): Enables direct peer-to-peer communication for video and voice calls in web browsers. ![A network diagram illustrating a UDP packet containing source port 5432, source IP 10.0.0.2, data payload, destination IP 10.0.0.3, and destination port 27017 transmitted from Host A (App1) to Host B (AppZ).](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/b80d224c3dc024b52f57f8685ae807744978c979efd1f2b1981412cca4d7efbb.png) Example of UDP Communication — Let's consider an example where an application (App1) on Host A (IP: 10.0.0.2) sends data to an application (AppZ) on Host B (IP: 10.0.0.3) using UDP: App1 on Host A: Uses port 5432 to send data. AppZ on Host B: Listens on port 27017 (commonly used for MangoDB). ![A network diagram illustrating a UDP packet with source port 5432, source IP 10.0.0.2, data payload, destination IP 10.0.0.3, and destination port 27017 sent from Host A's App 1 to Host B's App Z.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/bbf2c8719a22b752c26e74ebc92e4d01bdb16b280a089d68bae20243f72bdeb7.png) Example of UDP Communication — Packet Structure: Source IP: 10.0.0.2 Source Port: 5432 Destination IP: 10.0.0.3 Destination Port: 27017 The packet is sent from App1 to AppZ without any prior setup. If AppZ responds, it will swap the source and destination IPs and ports, ensuring the response reaches App1 correctly. ![UDP Datagram Anatomy](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/1b0c71c7a6776b2e57c02fe7763dd5eb8d3607ce5dbc364dc3e58eeb064bfda6.png) UDP Datagram Anatomy — A UDP header is simple and compact, consisting of only 8 bytes (64 bits) for IPv4. Source Port (16 bits): Identifies the port of the sending application. This is used by the recipient to know where to send a response. Destination Port (16 bits): Identifies the port of the receiving application. This tells the recipient's system which application should process incoming datagram. Length (16 bits): Specifies the total length of the UDP datagram, including both the header and the data. This helps in determining the boundaries of the datagram Checksum (16 bits): Used for error-checking of the header and data. This ensures the integrity of the data during transmission. Data Section: The actual payload of the message. This is the information being transported, such as a DNS query or a video stream packet. ![A diagram showing the structure of a UDP datagram consisting of an 8-byte Header and the Data payload.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/992fb95954b8d48c823c4dd4ecfa8e7a84d7bdfd7fa69f61291f945d707996ba.png) UDP Datagram Anatomy — Header 8 Bytes Data Payload ![A diagram illustrating the anatomy of a UDP packet across 32 bits, divided into four bytes showing fields for Source Port, Destination Port, Length, Checksum, and Data.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/dbe804a41237f204927e49992d2d2fa5179cba4e6ac9e6338d6f0963be5e5aa1.png) UDP Packet Anatomy — First Byte Third Byte Second Byte Fourth Byte 0 3 7 11 15 19 23 27 31 Source Port Destination Port Length Checksum Data ![UDP Pros](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/6469e6c47456c882c55679fcf40384ace6673cc12baa8cef54ea10fcd96fd302.png) UDP Pros — Simplicity: It does exactly what developers want without adding unnecessary complexity. Ideal for applications like multiplayer gaming where simplicity & control are crucial Low Overhead: The header size is small (only 8 bytes), making the datagrams small & efficient. This low overhead results in better performance in terms of bandwidth usage. Statelessness: Being stateless means UDP doesn’t retain session information, which reduces memory usage on servers. It scales well since it doesn’t need to keep track of connection states. ![UDP Pros](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/d22e40142d3fa17f6fc2264bb485189df3880866aa35b3c5a23de13233bc3a33.png) UDP Pros — Low Latency: There is no handshake process, so data is sent immediately without waiting for connection setup. Ideal for applications where latency is critical, such as live video streaming or online gaming. No Congestion Control: Applications can control the flow of data without being hindered by the protocol’s own congestion control mechanisms. Useful in controlled environments where the developer can manage network conditions. ![UDP Cons](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/c7cdf4888892d79d20748561b17450eb1bd959d9695f1bcbe621230bcc7e115a.png) UDP Cons — No Acknowledgement: There’s no guarantee that a sent message will reach its destination. This can be problematic for applications that require reliable data transfer. No Guaranteed Delivery: Packets may be lost, duplicated, or delivered out of order. Security Issues: Since there’s no connection, there's no authentication, making it susceptible to various types of attacks. UDP is often used in denial-of-service (DoS) attacks because servers must process each incoming packet. ![UDP Cons](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/64c91f149bab68b126f1d818746a3677c8a97645ecbafe920cef2feb5db8f74a.png) UDP Cons — No Flow Control: There’s no mechanism to manage the rate of data transmission based on network conditions. This can lead to network congestion and packet loss, as the sending application has no feedback on the network’s capacity. No Congestion Control: Unlike TCP, UDP doesn’t adjust its transmission rate based on network congestion. This can exacerbate congestion problems, particularly in shared or congested networks. ![Transmission Control Protocol](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/68c75a2fce6b816591a0ca0b959fd891b8d1537e8f347fa13bd1d315981a3bfe.png) Transmission Control Protocol — TCP is one of the most widely used protocols in networking, essential for reliable communication. Reliable: Ensures that data is delivered accurately and in order. Uses checksums to detect errors and mechanisms like retransmission to correct them. Connection-Oriented: Establishes a connection using SYN, SYN-ACK, and ACK packets to synchronize and acknowledge the connection between client and server. Maintains the state of the connection, allowing for consistent and reliable communication. Port-Based Communication: Uses ports to identify different applications on the same host, enabling multiple concurrent connections. ![TCP Connection](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/96762977819bfba36601c458e76a22f4387c035d7a17c5056d167c85c1cfa2a2.png) TCP Connection — Connection is an agreement between client and server. Must create a connection to send data. Connection is identified by 4 properties SourceIP-SourcePort DestinationIP-DestinationPort Sometimes called socket or file descriptor. Requires a 3-way TCP handshake Segments are sequenced and ordered. Segments are acknowledged and Lost segments are retransmitted ![A network diagram illustrating the TCP three-way handshake showing packet headers (ports, IP addresses, and SYN, SYN-ACK, ACK flags) exchanged between a client at 10.0.0.2 on port 5432 and a server at 10.0.0.3 on port 22.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/850aa33fa8727c0bca7fbe4bc1c5b87864346118ff50f16b53147ca6f93ec7e3.png) Three-Way Handshake — 1. SYN (Synchronize): The client sends a SYN packet to the server to initiate a connection. 2. SYN-ACK (Synchronize-Acknowledge): The server responds with a SYN-ACK packet, acknowledging receipt of SYN packet & synchronizing its own sequence no. 3. ACK (Acknowledge): The client sends an ACK packet, completing the handshake and establishing a connection. ![A network diagram illustrating TCP segmentation, sequence numbers, and acknowledgement between a Client at 10.0.0.2 (Port 5432) sending packets Seq1, Seq2, and Seq3, and a Server at 10.0.0.3 (SSH Port 22) responding with ACK3.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/2b7f5ea676d8a6c0491bbd18646b7e160b7f4b942e2dde23453be35d67c808b7.png) Sequence Numbers and ANK — Sequence Numbers: Used to keep track of the order of segments. Acknowledgements (ACK): Sent by the receiver to confirm the receipt of segments. Segmentation: Divides data into smaller segments, each with a sequence number. Reassembly: Receiver reassembles segments in correct order based on sequence no ![A diagram illustrating TCP error handling and retransmission via timeout between a sender at 10.0.0.2 (Port 5432) and a receiver at 10.0.0.3 (SSH Port 22), where a lost sequence segment (Seq3) triggers an ACK2, a timeout, retransmission of Seq3, and final receipt of ACK3.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/b555fa4d0de50713af4fbb687d27d166904b52a71e108d27764c4f812ea5f741.png) Error Handling — If a segment is lost, the receiver will not acknowledge it, prompting the sender to retransmit the missing segment. Timeouts: If an acknowledgement is not received within a certain timeframe, the sender will retransmit the data. ![A diagram illustrating the TCP four-way handshake for connection termination between a client (10.0.0.2, port 5432) and a server (10.0.0.3, port 22), showing the sequential exchange of FIN, ACK, FIN, and ACK packets.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/d7241f7d384e3bd325ba5a30efbaa19504558547da4ee171e07ef262058b8173.png) Connection Termination (Four-way handshake) — 1. FIN (finish): One end sends a FIN packet to initiate the closing process. 2. ACK (acknowledge): The other end acknowledges the FIN. 3. FIN (finish): The other end sends a FIN packet to confirm closure. 4. ACK (acknowledge): The first end acknowledges final FIN, completing the closure ![TCP Use Case](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/e7c05ee63ee3e7911872e732a776887d1d7eb7d92916b924d2b14989cdcf5626.png) TCP Use Case — Chat Applications: Ensures messages are delivered in correct order without errors. Remote Shells and Database Connections: Guarantees the integrity of commands and queries. Web Communication HTTP/1.1 and HTTP/2: Both protocols rely on TCP for reliable data transfer. HTTP/3, however, uses QUIC, which is built on UDP for enhanced performance. Any bidirectional communication. ![TCP Segment Anatomy](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/fde5591ff13f09d820c101e731e9086cafddf45025ab09912295cf6fb04fb909.png) TCP Segment Anatomy — The TCP segment is encapsulated within an IP packet as its payload. The segment itself consists of a header followed by data. The header can be as short as 20 bytes or extend up to 60 bytes if options are used. Source Port (16 bits): Identifies the port of the sending application. Destination Port (16 bits): Identifies the port of the receiving application. Sequence Number (32 bits): Ensures data is reassembled in correct order. Acknowledgment Number (32 bits): Indicates next expected byte from sender. Data Offset (4 bits): Specifies the size of the TCP header in 32-bit words. Reserved (3 bits): Reserved for future use; should be set to zero. ![TCP Segment Anatomy](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/7e96bc898e1c35aaeb0528847a5bb3c5a3afef568591632dadc318ab0fcc10c4.png) TCP Segment Anatomy — Flags (9 bits): Control flags, including: URG: Urgent pointer field significant. ACK: Acknowledgment field significant. PSH: Push function RST: Reset the connection. SYN: Synchronize sequence numbers to initiate a connection.. FIN: No more data from the sender. ECE (ECN Echo): allows routers to inform the TCP endpoints that their transmit buffers are filling due to congestion so that they will slower data transmission. CWR (Congestion Window Reduced): bit is used by the sending host to indicate that it received a packet with the ECE flag set. NS (Nonce sum): experimental flag used to help protect against accidental or malicious concealment of marked packets from the sender. ![TCP Segment Anatomy](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/7200a7e372a1c2aff855cd89be06ecd2ea323f13d2f52a22d9df533545adf7bd.png) TCP Segment Anatomy — Window Size (16 bits): Size of the receive window, which specifies the number of bytes the receiver is willing to accept. The default maximum is 65,535 bytes, but this can be scaled using the window scale option to handle more data. Checksum (16 bits): Used for error-checking the header and data. Urgent Pointer (16 bits): Points to the urgent data (if URG flag is set). Options (variable): Additional options (if any), padded to ensure the header ends on a 32-bit boundary. Padding (variable): Added to ensure the header is a multiple of 32 bits. ![A diagram illustrating the anatomy of a TCP segment divided into a Header section measuring 20-60 Bytes and a Data section measuring 1500 Bytes.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/c42bee4253eeb6c0f49b61098b19c1824362b58aa235593cd395179293409615.png) TCP Segment Anatomy — Header 20-60 Bytes Data 1500 Bytes ![A structural diagram showing the field layout and bit positions of a TCP segment header and data payload.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/ad7adc62d27c847d9a36e4e4b9bf011d7f4b89b114ccf0b152c143e643a7b7ef.png) TCP Segment Anatomy — First Byte Second Byte Third Byte Fourth Byte 0 3 7 11 15 19 23 27 31 Source Port Destination Port Sequence Number Acknowledgment Number (if ACK set) Data Offset Reserved 000 NS CWR ECE URG ACK PSH RST SYN FIN Window Size Checksum Urgent Pointer (if URG set) Options Data ![Maximum Segment Size](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/2f75e8e207ab3493904c34b1eb08f1df6e70edfc92fb46487319beaa50686dea.png) Maximum Segment Size — MSS plays a vital role in optimizing network performance & avoiding fragmentation. Calculation of MSS MSS is determined based on Maximum Transmission Unit (MTU) of network. The MTU is largest size of a packet that can be transmitted over a network. For Ethernet, the typical MTU is 1500 bytes. To calculate the MSS, the sizes of the IP header and TCP header must be subtracted from the MTU: For standard headers (without options): IP header size: 20 bytes TCP header size: 20 bytes So, the typical MSS for Ethernet is: 1500 - 20 -20 = 1460 bytes This means the data portion of each TCP segment can be up to 1460 bytes. ![A sequence diagram showing message exchange with dashed arrows between two vertical timelines, both labeled ESTABLISHED.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/68a4b0583c18e8039ced68d2bc869d1edff343bccfcfee05633d9e45be41ea43.png) TCP Connection States — TCP is a stateful protocol, meaning it needs to maintain the state of a connection. This involves both the client and the server keeping track of various states such as window size, sequence numbers, and the state of the connection itself. 1. ESTABLISHED: This state means the connection is open and data can be sent and received. Both client and server are in this state during data transfer. ESTABLISHED ESTABLISHED ![A sequence diagram illustrating the left side transitioning from ESTABLISHED to FIN_WAIT_1 after sending a FIN message to the right side, which remains in the ESTABLISHED state.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/93ba15d9e3f746a373e56013bb58f2db1cb447ddca044b8ad96382a17e2c7006.png) TCP Connection States — 2. FIN-WAIT-1: This state is entered when one side (e.g. client) wants to close the connection and sends a FIN (finish) segment to the other side. The side that sent the FIN waits for an acknowledgment (ACK). ![A sequence diagram illustrating TCP connection state transitions, showing one side moving from ESTABLISHED to FIN_WAIT_1 upon sending a FIN message, while the other side transitions from ESTABLISHED to CLOSE_WAIT upon receiving it and replying with an ACK.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/fa981dbc20d2239696f1c88544f337ed8c8af5817a554167d895eedb0b9977cc.png) TCP Connection States — 3. CLOSE-WAIT: When the side receiving the FIN (e.g. server) gets the FIN, it sends an ACK back and enters the CLOSE-WAIT state. This state indicates that the connection is still open but will soon be closed. ![A sequence diagram illustrating TCP connection teardown where one endpoint transitions from ESTABLISHED to FIN_WAIT_1 upon sending a FIN packet, and then to FIN_WAIT_2 upon receiving an ACK, while the opposing endpoint transitions from ESTABLISHED to CLOSE_WAIT.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/a5e54660320cf2cc09a7458ce4eceac32cf2ea346a422777d63bc16d836bbbeb.png) TCP Connection States — 4. FIN-WAIT-2: The side that sent the initial FIN (e.g. client) enters this state after receiving the ACK for its FIN. It waits for a FIN from the other side (e.g server). ![A sequence diagram illustrating TCP connection termination states transitioning between ESTABLISHED, FIN_WAIT_1, and FIN_WAIT_2 on the left, and ESTABLISHED, CLOSE_WAIT, and LAST_ACK on the right through exchanged FIN and ACK packets.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/39ba09b6250d164bffcd87a3568ff2860b83832981574d03a35eb510b6bd7b67.png) TCP Connection States — 5. LAST-ACK: After the server sends its own FIN to the client, it enters the LAST-ACK state. In this state, the server waits for an ACK from the client to acknowledge its FIN. ![A sequence diagram illustrating TCP teardown message exchanges (FIN and ACK) and connection states transitioning to TIME_WAIT.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/ebd71e5aa512f9c888347539102e7339d69525fddeba5e512ff1afdfc14c26a3.png) TCP Connection States — 6. TIME-WAIT: Once the client receives the FIN from the server, it sends an ACK back and enters the TIME-WAIT state. The client remains in this state for a certain period (typically 2*MSL, where MSL is the Maximum Segment Lifetime, usually 2 minutes). This wait ensures that any delayed packets are properly handled and prevents issues like session hijacking. ![A sequence diagram illustrating the TCP connection termination process between two hosts, showing transitions through states from ESTABLISHED to CLOSED via FIN and ACK packet exchanges.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/f1ecbd738de9eb7b9d04491b63cd5b0909e976f2aa9d0779829318fbb52406d1.png) TCP Connection States — 7. CLOSED: Both sides enter this state once the connection is completely terminated, and all resources are freed. ![TCP Flow Control](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/5b7f94378d548ecb2050cd0b4a72cf8fcd205e2e4513b53ad838483aef187e3b.png) TCP Flow Control — Flow control in TCP ensures that the sender does not overwhelm the receiver with more data than it can handle at a time. It's distinct from congestion control, which deals with managing data transmission across the network to avoid congestion and ensure smooth communication. Receiver’s Capacity: Flow control answers the question: How much data can the receiver handle at a time? The receiver's capacity can vary based on its processing power, memory, and current load. TCP Segments: Data in TCP is sent in units called segments. The sender needs to manage how many segments it sends before waiting for an acknowledgment from the receiver. ![A diagram illustrating the sliding window protocol, depicting a queue of numbered packets from 10 down to 1 with packets 1 through 4 inside a window of size 4, alongside a packet exchange diagram between Sender and Receiver showing segments 1 through 4 sent before an acknowledgment is returned.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/2f3872c7a2ce9c57eb998a84f6879e8bc9e2a619758f2dc1842425a7b495b9d0.png) TCP Flow Control — Receiver Buffer: The receiver has a buffer where incoming data is temporarily stored before being processed Receiver Window (rwnd): Determines the amount of data that can be sent before receiving an acknowledgment. It's a dynamic value that changes based on the current state of the receiver's buffer. Window Size = 4 Sliding Window Protocol: This protocol allows the sender to send multiple segments before needing an acknowledgment, but the amount of data sent must be within the limits of the receiver window. ![A sliding window diagram highlighting packets 2 through 5 out of a sequence from 1 to 10, accompanied by a packet transmission timeline between a Sender and Receiver illustrating the flow of packets 1 to 5 and their acknowledgments.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/a0f3af830730fbdd898ce1f12ac9694dac65bf0d55b17825a4a0e64a09cacff4.png) TCP Flow Control — Sliding Window Protocol: Adjusts the window size dynamically based on network conditions to prevent congestion. Window Size = 4 ![A sliding window diagram showing a buffer with segments numbered 1 through 10, highlighting a window size of 4 covering segments 4 to 7, paired with a sender-receiver message sequence chart showing packet transmission and acknowledgments.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/c5c06537c6f10aeac7549984dc6fe355d1c57e8b6cb7228926a06dc92ccdbe88.png) TCP Flow Control — Sliding Window Protocol: Adjusts the window size dynamically based on network conditions to prevent congestion. Window Size = 4 ![TCP Flow Control](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/6edeed33512a764d9d5020f6b1221b6a4a60708141d530a7a1c08673d6a85dbc.png) TCP Flow Control — To accommodate larger data transfers, TCP includes a Window Scaling option, which allows for a much larger receiver window size. Scaling Factor is between 0-14. So Window Size can go up to 1 GB [(2^16-1) * 2^14] This scaling factor is negotiated during the TCP handshake. ![TCP Congestion Control](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/c3e9470807ab7fb550af513cb6c8ebaa586721bd4df85488f4a28194a610aaf2.png) TCP Congestion Control — Congestion control is about how much the network can handle and how fast data can be sent through the network. This involves considering the capacity of middleboxes (like routers) that IP packets pass through. We can't send a single segment and wait, because that's inefficient due to latency. Instead, it's better to send as much data as the receiver and network can handle at once to maximize data flow and reduce the impact of roundtrip times. While the receiver might handle the load, the middleboxes might not. Think of it as flow control for the routers. ![TCP Congestion Control](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/e90e34d23af0fedf9353728f2f5b0bf5d292efabc6c30549bb2f36e65cc9a435.png) TCP Congestion Control — We need to avoid congesting the network with data, and this is managed using a congestion window (CWND), which is a property of the sender. If you send too much data, routers might drop it, leading to retransmissions and reduced network performance. There are two primary congestion control algorithms: TCP Slow Start Congestion Avoidance ![TCP Slow Start](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/e23ae13d9b8c423597f3994670569ad0194816a65c69d80ef5fd8bb25b2d8daf.png) TCP Slow Start — Why is it called Slow Start? It's called "Slow Start" because we begin with a congestion window (cwnd) of just one Maximum Segment Size (MSS). This means we start very slowly, but don't let the name fool you - the increase in the window size is quite aggressive. How does it work? Initially, the cwnd is set to one MSS. For every acknowledgment (ACK) received, we increase the cwnd by one MSS. This exponential growth continues until a certain threshold is reached. ![A diagram illustrating the TCP slow start process between host A and host B via a network router, showing congestion window expansion as packet 1 is sent and acknowledged with ANK1, followed by packets 2 and 3 with acknowledgments ANK2 and ANK3, leading to the transmission of packets 4 through 7.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/c1b1d02bffeb219ed7d98412b112e03fe9f1d62e0804dbdcacb51ee7d8d37a08.png) TCP Slow Start — CWND + 1 CWND + 2 ![Congestion Avoidance](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/6925540a2071dd0d19823ff7cada1ed6ce581ee2e59c356fcef504c66cee7dab.png) Congestion Avoidance — Once the cwnd hits the threshold (ssthresh), we switch from Slow Start to Congestion Avoidance. Here, CWND increases linearly rather than exponentially. For each round trip time (RTT), the CWND is increased by 1 MSS, regardless of the number of ACKs received during that RTT. An RTT is the time it takes for a packet to travel from the sender to the receiver and back. This linear growth is slower compared to the exponential growth of Slow Start but helps to avoid congestion more effectively. ![A diagram illustrating the TCP congestion avoidance algorithm between host A and host B via a router, demonstrating how the congestion window (CWND) increases linearly by one with each round trip time as packets are transmitted and acknowledged.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/ec52815a5bbd18720288d0b1d557567b498d6c2ae3ffacb6b1e43bb809af6a24.png) Congestion Avoidance — CWND + 1 CWND + 1 ![Congestion Notification](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/1c8bf4388abc618eaa706c4778781b8cf418d10eba385179158586801d02f1a5.png) Congestion Notification — We don’t want routers dropping packets Can Routers let us know when congestion hit? Meet ECN (Explicit Congestion Notification) Routers and middle boxes can tag IP packets with ECN The receiver will copy this bit back to the sender CN is IP Header bit So Routers don’t drop packets just let me know you are reaching your limit ![Congestion Detection](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/1426252e1ea2dee68d69911a69b238be80c13c6e6acf77422db85901227bf513.png) Congestion Detection — Congestion is usually detected by packet loss, indicated by a timeout or by receiving duplicate ACKs. Actions Taken: ▪ Reduce ssthresh: The ssthresh is set to half of the current flight size (the number of unacknowledged packets). ▪ Reset cwnd: The cwnd is reset to one MSS. This means we start over, but since the ssthresh is now lower, we’ll hit the threshold quicker than before, transitioning back to Congestion Avoidance sooner. It's important to note that the minimum value for ssthresh is two MSS. This ensures that the cwnd doesn’t shrink to zero, which would halt communication. ![A line graph plotting CWND versus Time, illustrating phases of exponential Slow Start followed by linear Congestion Avoidance, with sharp drops when congestion is triggered down to a minimum threshold.](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/ba5ed17849ccdedf06295e192282acb8c3ddfb3e70bbbecef1e9d2edc8543bac.png) Slow Start & Congestion Avoidance — Slow Start Congestion Avoidance CWND Congestion Triggered 1 MSS 2 * MMS (Can’t go lower) Time ![TCP Pros](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/992679212753439cc2117015f6d7bb84ceb3870cf76173d2f375da444054a19b.png) TCP Pros — Guaranteed Delivery: TCP ensures that data packets are delivered reliably. If packets are lost, TCP will retransmit them until they are successfully received. Connection Establishment: Before any data is sent, a connection must be established, preventing spoofing and ensuring that both parties are ready to communicate. Flow Control and Congestion Control: TCP uses mechanisms to control the flow of data and manage network congestion, making sure the network isn't overwhelmed with too much data at once. ![TCP Pros](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/4fb96341b08df516a7eb1187aba2bd175bdbb548f1a31d99be412b9ec0acb72a.png) TCP Pros — Ordered Packets: Data packets are delivered in the same order they were sent, eliminating the need for reordering at the application level. Security: TCP's requirement for connection establishment and its built-in checks make it more resistant to certain types of attacks, such as IP spoofing. ![TCP Cons](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/5ddee4b57b338489540a9c36ec66146186bbd2bfa85e3c3e2b7c7c3496aa7ffa.png) TCP Cons — Large Header Overhead: TCP headers can be quite large (20 to 60 bytes), consuming more bandwidth compared to UDP, which has a smaller header. Stateful Nature: TCP connections maintain state information, which consumes memory and system resources. The TIME-WAIT state, for example, keeps connections open for a while to prevent old packets from causing issues, but this can use up a lot of resources. ![TCP Cons](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/059658a68d229718261d334bfe81b558c03078d9de92f14b1ae51973e27eac7a.png) TCP Cons — Latency: TCP's mechanisms, like slow start and congestion control, can introduce latency. Each data packet needs to be acknowledged, which can slow down communication, especially in high-latency networks. Head-of-Line Blocking: In TCP, if a single packet is lost, subsequent packets must wait until the lost packet is retransmitted and received. This can delay the entire stream of data, even if the missing packet is not crucial. Complexity: TCP's complexity can be a drawback. Managing connections, ordering packets, and handling retransmissions add overhead to the network stack. ![Addressing TCP Limitations](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/9764cbf7edd2d913db422624f32e22173ce2c12e1448788d536f4fcf0a04e2b4.png) Addressing TCP Limitations — Head-of-Line Blocking: TCP can block subsequent packets if one is lost, which can delay processing. This is known as head-of-line blocking. In protocols like QUIC, this issue is addressed by allowing multiple streams within a single connection, each stream independently retransmitting lost packets without blocking others. Single Connection Limitations: Using a single TCP connection for multiple streams of data can lead to inefficiencies. If one packet is lost, it can delay all streams. To avoid this, you can use techniques like connection pooling, where multiple connections are used to manage different streams independently. ![The Transport Layer - TCP, UDP](https://docs.chaicode.com/cdn-cgi/image/width=1600,format=auto,fit=scale-down/assets/2e9345f8619c2188ad4df3578358d07131d21bccd9dbc72639f5149160eb52dc.png) The Transport Layer - TCP, UDP — Two Workhorses of the Internet. Port Numbers UDP Protocol Datagram Anatomy TCP Protocol Segment Anotomy TCP Connection States Flow Control Congestion Control In the next chapter, we’ll study application layer protocols.