Transport Layer: TCP and UDP

Learn how TCP delivers reliable ordered streams with handshakes, acknowledgements, flow and congestion control, and when lightweight UDP is the better choice.

Intermediate · about 6 hours · difficulty 3/5

Learn first: IP Addressing, Subnetting and Routing

The transport layer turns host-to-host delivery into process-to-process communication using ports. TCP vs UDP is one of the most predictable interview questions, but the follow-ups go deep, so understand the mechanisms.

TCP: reliable byte stream

  • Connection setup with the three-way handshake: SYN, SYN-ACK, ACK. Teardown uses FIN and ACK (four steps), and the side that closes first waits in TIME_WAIT.
  • Reliability: sequence numbers, acknowledgements, retransmission on timeout, and duplicate ACKs triggering fast retransmit.
  • Flow control: the receiver advertises a window so a fast sender does not overwhelm it (sliding window, the same idea as the DSA pattern).
  • Congestion control: slow start, congestion avoidance, and multiplicative decrease on loss, which protect the network as a whole.
  • Ordered delivery and no duplicates, at the cost of latency and head-of-line blocking.

UDP: fire and forget

  • No connection, no ordering, no retransmission. An 8-byte header.
  • Used for DNS queries, video calls, online games, live streaming, and as the base for QUIC (HTTP/3), which re-implements reliability in user space.

Choosing

  • Correctness of every byte matters (web pages, payments, file transfer): TCP.
  • Freshness matters more than completeness (voice, gaming): UDP.

Ports and sockets

Well-known ports: 80 HTTP, 443 HTTPS, 53 DNS, 22 SSH, 25 SMTP. A socket is identified by the 5-tuple (protocol, source IP, source port, destination IP, destination port), which is why one server port can serve thousands of clients.

Good enough to move on: you can draw the handshake, explain flow control vs congestion control, and justify TCP or UDP for five different applications.

Key concepts

  • Ports and sockets
  • Three-way handshake and teardown
  • Reliability: ACKs and retransmission
  • Flow control and sliding window
  • Congestion control
  • UDP and its use cases
  • TCP vs UDP comparison
  • QUIC and HTTP/3

Mini project

Write a TCP echo server and client and a UDP equivalent using sockets in Python or C++, then add a simple chat room to the TCP server. Capture the handshake in Wireshark and identify SYN, SYN-ACK and ACK packets.

Check yourself

What is the difference between flow control and congestion control, and which party (sender, receiver, network) each one protects?

Free resources