β‘ Module 02: TCP vs UDP & Transport Layer Mastery
Core Focus: 3-Way Handshake, 4-Way Termination,
TIME_WAITvsCLOSE_WAITSockets, Flow Control (Sliding Window), Congestion Control (Slow Start, AIMD, Fast Retransmit/Recovery, BBR), TCP Header Anatomy, and Low-Latency Tuning for Payment Gateways.
π Table of Contents
- Transport Layer Overview & Core Responsibilities
- Definitive Comparison: TCP vs UDP
- TCP 3-Way Handshake (Connection Establishment)
- TCP 4-Way Handshake (Connection Termination)
- Flow Control: The Sliding Window Protocol
- Congestion Control: Protecting the Global Network
- UDP Internals & When to Use It
- Juspay & Payment Systems Real-World Context
- High-Yield Interview Questions & Verbatim Answers
1. Transport Layer Overview & Core Responsibilities
The Transport Layer (OSI Layer 4) is responsible for Process-to-Process delivery (end-to-end communication) using Port Numbers.
Layer 7: Application -> Generates HTTP / JSON Data
Layer 4: Transport -> Port multiplexing, Reliability, Segmentation (TCP/UDP)
Layer 3: Network -> Host-to-Host routing via IP Addresses
Layer 2: Data Link -> Hop-to-Hop framing via MAC AddressesA network connection is uniquely identified by a 5-Tuple: $$\text{Socket Connection} = (\text{Source IP}, \text{Source Port}, \text{Destination IP}, \text{Destination Port}, \text{Protocol})$$
2. Definitive Comparison: TCP vs UDP
| Metric | TCP (Transmission Control Protocol) | UDP (User Datagram Protocol) |
|---|---|---|
| Connection Type | Connection-oriented (requires 3-way handshake) | Connectionless (fire-and-forget) |
| Reliability | Guaranteed: ACKs, Retransmissions, Checksum verification | Unreliable: Best-effort; packets may drop |
| Ordering | Guaranteed: Uses byte Sequence Numbers | Unordered: Packets can arrive in any sequence |
| Header Size | 20 β 60 Bytes (Options, Window size, Flags) | 8 Bytes (Fixed: Src Port, Dst Port, Length, Checksum) |
| Flow Control | Yes (Sliding window prevents receiver buffer overflow) | No (Receiver can be overwhelmed) |
| Congestion Control | Yes (Slow start, AIMD prevents network collapse) | No (Transmits at application rate) |
| Transmission Type | Byte Stream (no boundary preservation) | Datagram Message (preserves packet boundaries) |
| Speed / Latency | Higher overhead (~1.5 RTT setup + state tracking) | Extremely fast (0 RTT setup, minimal CPU overhead) |
| Primary Use Cases | HTTP/HTTPS, WebSockets, SSH, FTP, Payment APIs | DNS, VoIP (Zoom/WhatsApp call), Video streaming, Gaming, QUIC |
3. TCP 3-Way Handshake (Connection Establishment)
Before any data is exchanged, client and server must agree on Initial Sequence Numbers (ISN) and establish buffer parameters.
CLIENT (Initiator) SERVER (Listener)
State: CLOSED State: LISTEN
β β
β βββ 1. [SYN] Seq = x ββββββββββββββββββββββββββββββββββββββββββ> β (SYN_RCVD)
β (Client allocates socket buffer & sets ISN=x) β
β β
β <ββ 2. [SYN + ACK] Seq = y, Ack = x + 1 ββββββββββββββββββββββββ β
β (Server acknowledges x and sets its own ISN=y) β
β β
β βββ 3. [ACK] (Seq = x + 1), Ack = y + 1 βββββββββββββββββββββββ> β (ESTABLISHED)
β (Client completes handshake; CAN attach first HTTP payload)β
βΌ βΌ
State: ESTABLISHED State: ESTABLISHED3.1 Step-by-Step Packet Flow & Sequence Numbers
- Packet 1 (
SYN): Client sends a packet withSYN=1, random Initial Sequence Number $\text{Seq} = x$, and options (MSS, Window Scale). State changes fromCLOSED$\rightarrow$SYN_SENT. - Packet 2 (
SYN-ACK): Server receives SYN, allocates TCB (Transmission Control Block) buffer, sends backSYN=1, ACK=1, $\text{Ack} = x+1$, and its own sequence number $\text{Seq} = y$. State changes fromLISTEN$\rightarrow$SYN_RCVD. - Packet 3 (
ACK): Client receives SYN-ACK, acknowledges server sequence number with $\text{Ack} = y+1$. State changes toESTABLISHED. Server receives ACK and entersESTABLISHED.
[!NOTE] Why random ISN?
If sequence numbers always started at 0, an attacker could predict sequence numbers and inject malicious packets into an active TCP connection (TCP sequence prediction attack). Furthermore, delayed duplicate packets from a previous closed connection could corrupt a new connection.
3.2 SYN Flood Attack & SYN Cookies Mitigation
ATTACKER SERVER
β βββ SYN (Spoofed IP 1) βββ> [Allocates TCB Buffer in Half-Open Queue]
β βββ SYN (Spoofed IP 2) βββ> [Allocates TCB Buffer in Half-Open Queue]
β βββ SYN (Spoofed IP 3) βββ> [Allocates TCB Buffer in Half-Open Queue]
β (Never sends final ACK) [QUEUE OVERFLOW! Drops legitimate users]- Vulnerability: Server allocates memory in the SYN Queue for every SYN received while waiting for the final ACK. A flood of fake SYNs exhausts memory and prevents legitimate users from connecting.
- Solution β SYN Cookies:
- The server does not allocate memory in the backlog queue upon receiving a SYN.
- Instead, the server encodes the connection state inside the server's Initial Sequence Number $y$: $$y = \text{Hash}(\text{Client IP}, \text{Client Port}, \text{Server Secret}, \text{Timestamp}) + \text{MSS Index}$$
- When the client sends the 3rd packet (
ACKwith $\text{Ack} = y+1$), the server extracts $y$, re-computes the cryptographic hash, verifies its authenticity, and only then allocates the connection memory!
4. TCP 4-Way Handshake (Connection Termination)
TCP is full-duplex (data flows both directions independently). Closing a connection requires closing both channels independently.
CLIENT (Active Closer) SERVER (Passive Closer)
State: ESTABLISHED State: ESTABLISHED
β β
β βββ 1. [FIN] Seq = u ββββββββββββββββββββββββββββββββββββββββββ> β (CLOSE_WAIT)
β (Client says: "I have no more data to send") β
β β
β <ββ 2. [ACK] Ack = u + 1 βββββββββββββββββββββββββββββββββββββββ β
β (Server says: "I acknowledge your close; I can still send")β
β β
β [Server finishes flushing remaining outgoing data] β
β β
β <ββ 3. [FIN] Seq = w, Ack = u + 1 ββββββββββββββββββββββββββββββ β (LAST_ACK)
β (Server says: "I am also done sending data") β
β β
β βββ 4. [ACK] Ack = w + 1 ββββββββββββββββββββββββββββββββββββββ> β (CLOSED)
β β
βΌ βΌ
State: TIME_WAIT (Starts 2MSL Timer ~ 60s) State: CLOSED
β (Timer expires)
βΌ
State: CLOSED4.2 The TIME_WAIT State & 2MSL Timer Rationale
The endpoint that performs the Active Close (usually the client, or a reverse proxy like Nginx) must enter the TIME_WAIT state and remain there for $2 \times \text{MSL}$ (Maximum Segment Lifetime, typically 60 to 120 seconds).
WHY 2MSL IS MANDATORY
ββββββββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Reason 1: Graceful Teardown β Reason 2: Prevent Old Duplicate Confusion β
ββββββββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β If the final ACK (Packet 4) is lost, β Packets can get delayed in router queues. If a new β
β the server will retransmit its FIN. β connection immediately reuses the exact same 5-tuple β
β Client MUST remain in TIME_WAIT to β (IP:Port), an old delayed packet from the previous β
β re-send the ACK. Otherwise, the β connection could arrive and corrupt the new data stream.β
β server receives RST (connection resetβ Waiting 2MSL guarantees all stale packets have died in β
β error). β the network. β
ββββββββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ4.3 Production Disasters: TIME_WAIT vs CLOSE_WAIT Socket Leaks
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β DIAGNOSING SOCKET LEAKS IN PRODUCTION β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β 1. `TIME_WAIT` Accumulation: β
β - Symptoms: Server runs out of ephemeral ports (`EADDRNOTAVAIL`), drops connections.β
β - Root Cause: Server/Proxy is making high volumes of short-lived connections and β
β actively initiating the close on each request without HTTP Keep-Alive. β
β - Fix: Enable Connection Pooling, HTTP/1.1 Keep-Alive, reuse TCP sockets, tune β
β `tcp_tw_reuse` in Linux kernel sysctl. β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β 2. `CLOSE_WAIT` Accumulation (Dangerous Application Bug!): β
β - Symptoms: File descriptor limit hit (`Too many open files`), server crashes. β
β - Root Cause: The remote client closed the socket (sent FIN), the OS replied with β
β ACK, but the **application code forgot to call `socket.close()` / `resp.Body.Close()`β
β - Fix: Pure application bug! Ensure all HTTP response bodies and DB connections β
β are closed in a `finally` block or Go `defer`. β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ5. Flow Control: The Sliding Window Protocol
Flow Control ensures a fast sender does not overwhelm a slow receiver's memory buffer.
SENDER BUFFER RECEIVER BUFFER
ββββββββββββββ¬βββββββββββββββ¬βββββββββββββββ ββββββββββββββββββββββββββββββββ
β Sent & ACK β Sent, No ACK β Unsent (Can) β β Received Data β Free Space β
ββββββββββββββ΄βββββββββββββββ΄βββββββββββββββ βββββββββββββββββ΄βββββββββββββββ
β² β² β² β²
βββββββ Window Size (rwnd) ββββ βββ rwnd size ββ5.1 Window Size (rwnd) Mechanics
- In every ACK packet, the receiver advertises its available buffer space via the Receive Window (
rwnd) header field. - The sender is mathematically constrained: $$\text{Bytes In-Flight} \le \text{rwnd}$$
- If the receiver's application is slow reading data from the buffer,
rwnddrops towards 0.
5.2 Zero Window Probe & Silly Window Syndrome
- Zero Window: When
rwnd = 0, sender halts data transmission. The sender starts a Persist Timer and periodically transmits a 1-byte Zero Window Probe to prompt the receiver to advertise its updatedrwnd. - Silly Window Syndrome:
- Occurs when receiver application reads data 1 byte at a time and advertises a window of 1 byte, causing sender to transmit tiny packets with huge header overhead (40 bytes header for 1 byte payload = 2.5% efficiency).
- Receiver Solution (Clark's Algorithm): Receiver does not advertise a non-zero window until free space is $\ge \min(\text{MSS}, \text{Buffer}/2)$.
- Sender Solution (Nagle's Algorithm): Sender buffers small outgoing messages until a full MSS segment is ready or until an ACK for previous data is received.
6. Congestion Control: Protecting the Global Network
While Flow Control protects the receiver, Congestion Control protects the intermediate network routers and switches from being overwhelmed.
The sender computes the effective sending window: $$\text{Max Send Window} = \min(\text{cwnd}, \text{rwnd})$$ Where $\text{cwnd}$ is the sender's dynamically calculated Congestion Window.
Congestion Window (cwnd in MSS)
β²
32 β€ * (Packet Loss -> Tahoe drops to 1,
β * * Reno halves cwnd to ssthresh)
16 β€ * * β
β * * β
8 β€ * * (Linear: AIMD) β
β * (ssthresh = 8) β
4 β€ * β
2 β€ * (Exponential: Slow Start) β
1 β€βββ*ββββββββββββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββΊ Time (RTTs)6.1 The 4 Phases:
- Slow Start:
- Starts with $\text{cwnd} = 1$ (or 10 in modern Linux).
- For every ACK received, $\text{cwnd} = \text{cwnd} + 1 \implies \text{cwnd}$ doubles every RTT ($1 \rightarrow 2 \rightarrow 4 \rightarrow 8 \dots$).
- Continues until $\text{cwnd} \ge \text{ssthresh}$ (Slow Start Threshold).
- Congestion Avoidance (AIMD β Additive Increase Multiplicative Decrease):
- When $\text{cwnd} \ge \text{ssthresh}$, growth switches from exponential to linear.
- Increases $\text{cwnd}$ by 1 MSS per RTT ($\text{cwnd} = \text{cwnd} + \frac{1}{\text{cwnd}}$ per ACK).
- Fast Retransmit:
- If a single packet is lost while subsequent packets arrive, the receiver sends Duplicate ACKs.
- Upon receiving 3 Duplicate ACKs, the sender retransmits the missing segment immediately without waiting for the slow Retransmission Timeout (RTO) timer.
- Fast Recovery:
- Instead of dropping $\text{cwnd}$ back to 1 (like legacy Tahoe), TCP Reno sets $\text{ssthresh} = \frac{\text{cwnd}}{2}$ and $\text{cwnd} = \text{ssthresh}$, staying in Congestion Avoidance.
6.2 TCP Tahoe vs TCP Reno vs Modern Google BBR
- TCP Tahoe: On any loss (Timeout or 3 Dup ACKs), drops $\text{cwnd} = 1$ and enters Slow Start. (Severe throughput collapse).
- TCP Reno: Drops $\text{cwnd} = 1$ on Timeout; on 3 Dup ACKs, cuts $\text{cwnd}$ in half (Fast Recovery).
- Google BBR (Bottleneck Bandwidth and RTT):
- Loss-based algorithms (Reno/Cubic) falsely interpret any dropped packet as network congestion, causing bufferbloat and performance degradation on high-speed fiber/mobile networks.
- BBR measures real-time maximum delivery rate and minimum round-trip time to model the physical bottleneck, maximizing throughput without filling router buffers.
7. UDP Internals & When to Use It
UDP HEADER (8 BYTES FIXED)
0 15 16 31
ββββββββββββββββββββββββ¬βββββββββββββββββββββββ
β Source Port (16b) β Destination Port (16bβ
ββββββββββββββββββββββββΌβββββββββββββββββββββββ€
β Length (16b) β Checksum (16b) β
ββββββββββββββββββββββββ΄βββββββββββββββββββββββ- Why UDP Wins in Real-Time Applications:
- Zero handshake overhead (immediate data transmission).
- No Head-of-Line (HoL) blocking β if packet 2 drops, packet 3 is delivered to the app immediately.
- Custom congestion control: Applications can decide their own retransmission policy (e.g., in WebRTC, drop old video frames instead of retransmitting them).
- Basis for HTTP/3 (QUIC).
8. Juspay & Payment Systems Real-World Context
PAYMENT GATEWAY LATENCY OPTIMIZATIONS
[ Merchant Backend ]
β
Persistent TCP Pool
(Keep-Alive, TCP_NODELAY)
βΌ
[ Juspay Ingress ]
β
mTLS Persistent Mesh
βΌ
[ Core Banking ]TCP_NODELAY(Disabling Nagle's Algorithm):- By default, Nagle's algorithm buffers small TCP packets. For payment APIs (where JSON payloads are small, e.g., 500 bytes), Nagle can introduce an artificial 40ms delay waiting for ACKs.
- Juspay disables Nagle via
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, 1)to transmit transaction payloads instantly.
- Persistent Connection Pooling:
- Creating a new TCP connection takes 1 RTT (3-way handshake) + 2 RTTs (TLS 1.2 handshake) = 3 RTTs (~150ms over cellular networks).
- Juspay maintains warm, long-lived TCP connection pools to merchant servers and banking APIs, eliminating connection handshake latency on payment critical paths.
- Socket Exhaustion Protection:
- High TPS payment bursts can exhaust local ephemeral ports (65,535 max). Juspay uses multiple outbound NAT gateways and IP-binding configurations to scale past single-interface port limitations.
9. High-Yield Interview Questions & Verbatim Answers
Q1: "Explain the TCP 3-Way Handshake. Why is it 3 steps and not 2?"
Spoken Answer:
*"The TCP 3-way handshake establishes a reliable, full-duplex byte stream connection.
- The client sends a
SYNpacket with an initial sequence number $x$.- The server acknowledges $x$ by sending
ACK = x + 1and synchronizes its own channel by sendingSYNwith sequence number $y$.- The client responds with
ACK = y + 1to confirm receipt of the server's sequence number.It cannot be 2 steps because TCP is bidirectional. With only 2 steps, the client knows the server received its SYN, but the server has no confirmation that the client received the server's SYN. Both sides must independently announce their sequence numbers and receive an explicit acknowledgment to guarantee synchronization."*
Q2: "What is the TIME_WAIT state in TCP? Why does it wait for 2MSL?"
Spoken Answer:
*"TheTIME_WAITstate is entered by the endpoint that initiates the active close after sending the final ACK. It lasts for $2 \times \text{MSL}$ (Maximum Segment Lifetime), which is typically 60 to 120 seconds.
It exists for two fundamental reasons:
- To ensure graceful termination: If the final ACK is lost in the network, the remote server will retransmit its FIN. The active closer must remain in
TIME_WAITto resend the ACK; otherwise, it would reply with an RST error.- To drain stale packets from the network: It ensures that delayed duplicate packets from this connection expire in intermediate router queues before a new connection reuses the same 5-tuple socket, preventing data corruption."*
Q3: "What is the difference between Flow Control and Congestion Control in TCP?"
Spoken Answer:
*"Flow Control is end-to-end between sender and receiver. It prevents a fast sender from overwhelming a slow receiver's memory buffer. It is implemented using the Sliding Window Protocol, where the receiver advertises its available buffer space (rwnd) in every ACK.In contrast, Congestion Control is global between the sender and the intermediate network. It prevents excessive data injection from causing router buffer overflows and network collapse. It is managed by the sender dynamically adjusting its Congestion Window (
cwnd) using algorithms like Slow Start, AIMD, and Fast Retransmit."*
Q4: "What is a SYN Flood attack and how do SYN Cookies mitigate it?"
Spoken Answer:
*"A SYN flood is a Denial of Service attack where an attacker sends a high volume of TCPSYNrequests with spoofed IP addresses and never sends the completingACK. The server allocates memory in its SYN backlog queue for each half-open connection, quickly exhausting RAM and denying service to legitimate users.SYN Cookies solve this by removing the need for server-side state allocation during the SYN phase. The server cryptographically encodes the connection parameters into the server's Initial Sequence Number ($y$) using a hash of the client IP, port, server secret, and timestamp. The server only allocates memory after receiving the client's final ACK and validating the decoded sequence number."*