Notes › Computer Networks
TCP vs UDP and the 3-Way Handshake
Both are transport-layer protocols: they deliver data between processes (not just machines) using ports.
- A socket = IP address + port, e.g.
142.250.183.14:443. - A TCP connection is identified by 4 values: source IP, source port, destination IP, destination port.
- Ports 0–1023 are well-known (80 HTTP, 443 HTTPS, 22 SSH, 53 DNS); your browser uses a random high "ephemeral" port.
TCP — Transmission Control Protocol
Connection-oriented, reliable, ordered byte stream. How it's reliable:
- Sequence numbers on every byte → the receiver puts data back in order.
- Acknowledgements (ACKs) → the receiver confirms what arrived.
- Retransmission → if no ACK arrives before a timeout (or 3 duplicate ACKs arrive), resend.
- Checksum → detect corrupted segments.
- Flow control and congestion control (below).
The 3-way handshake (opening a connection)
Client Server (LISTEN)
| ---- SYN, seq = x ------------------> | 1. "I want to connect, my number is x"
| <--- SYN-ACK, seq = y, ack = x+1 ---- | 2. "OK, my number is y, I expect x+1"
| ---- ACK, ack = y+1 ----------------> | 3. "Got it, I expect y+1"
| ESTABLISHED — data flows |
Why 3 and not 2? Both sides must agree on each other's starting sequence number (random, for security), and the server must know the client actually received its SYN-ACK. Two messages would leave the server unsure; it also protects against old, delayed SYNs creating ghost connections.
SYN flood attack: an attacker sends many SYNs and never sends the final ACK, filling the server's half-open queue. Defence: SYN cookies, rate limiting.
The 4-way teardown (closing)
Client Server
| ---- FIN --------------> | client is done sending
| <--- ACK --------------- |
| <--- FIN --------------- | server is done sending
| ---- ACK --------------> |
TIME_WAIT (2 × MSL) then CLOSED
Four messages because TCP is full-duplex — each direction is closed separately (the server may still send data after the client's FIN). TIME_WAIT: the side that closes first waits ~2 × maximum segment lifetime so the last ACK can be resent if lost and stray old packets die out. A RST segment aborts a connection immediately.
Flow control — don't overwhelm the receiver
The receiver advertises a window size (rwnd): "I have buffer space for N more bytes". The sender never has more than that unacknowledged. Window 0 → sender pauses. This is the sliding window protocol.
Congestion control — don't overwhelm the network
The sender keeps a congestion window (cwnd):
- Slow start: start small (e.g. 10 segments), double cwnd every round trip.
- Congestion avoidance: after a threshold, grow by ~1 segment per round trip (linear).
- On loss: 3 duplicate ACKs → halve cwnd (fast recovery); timeout → back to slow start.
This is AIMD — additive increase, multiplicative decrease. Sender sends
min(cwnd, rwnd).
UDP — User Datagram Protocol
Connectionless, unreliable, message-oriented. Just adds ports and a checksum to IP.
- No handshake, no ACKs, no retransmission, no ordering, no congestion control.
- Header is only 8 bytes (TCP: 20–60).
- Supports broadcast and multicast. Great when speed matters more than perfection: a lost video frame is better skipped than waited for.
TCP vs UDP
| TCP | UDP | |
|---|---|---|
| Connection | yes (handshake) | no |
| Reliability | guaranteed delivery, retransmits | best effort, may lose packets |
| Order | in order | may arrive out of order |
| Speed / overhead | slower, 20+ byte header | faster, 8-byte header |
| Flow & congestion control | yes | no |
| Data | byte stream | individual datagrams |
| Broadcast/multicast | no | yes |
| Used by | HTTP/1.1 & 2, HTTPS, SSH, FTP, SMTP, databases | DNS, video calls, live streaming, online games, VoIP, DHCP |
Why DNS uses UDP: a query and its answer each fit in one small packet; a handshake would double the time. (DNS falls back to TCP for large answers and zone transfers.)
Socket code (Node.js)
// TCP server
import net from 'node:net';
net.createServer(sock => sock.on('data', d => sock.write('echo: ' + d))).listen(4000);
// UDP server
import dgram from 'node:dgram';
const udp = dgram.createSocket('udp4');
udp.on('message', (msg, rinfo) => udp.send('got it', rinfo.port, rinfo.address));
udp.bind(4001);
QUIC and HTTP/3
QUIC runs on UDP but rebuilds reliability, ordering and encryption itself:
- Connection + TLS setup in 1 round trip (0-RTT on reconnect) vs TCP+TLS's 2–3.
- No head-of-line blocking between streams — one lost packet doesn't stall the others.
- Connections survive network changes (Wi-Fi → mobile data). HTTP/3 = HTTP over QUIC.
Interview one-liners
- TCP: reliable, ordered, connection-oriented; UDP: fast, connectionless, best effort.
- Handshake: SYN → SYN-ACK → ACK; teardown: FIN, ACK, FIN, ACK.
- Flow control protects the receiver (rwnd); congestion control protects the network (cwnd).
- DNS, games and video calls prefer UDP; web, email and file transfer use TCP.
- Related: OSI and TCP/IP Models, HTTP and HTTPS.