Course contents

02. Networking and Internet Lesson 4 of 10

TCP and UDP

Watch the TCP handshake, ACKs and a fast retransmit after loss, compare UDP fire-and-forget, and see head-of-line blocking and how QUIC avoids it.

14 minBeginner7 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • TCP needs a one-round-trip handshake (SYN, SYN-ACK, ACK) before data flows.
  • Sequence numbers, cumulative ACKs and retransmission turn lossy IP into a reliable, ordered byte stream.
  • Three duplicate ACKs trigger a fast retransmit; until the gap is filled, later data waits in the receive buffer.
  • UDP adds only ports and a checksum: no handshake, no ordering, no retransmission.
  • One lost TCP segment blocks every stream on the connection; QUIC orders per stream, so only the affected stream waits.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

TCP and UDP are the two classic transport protocols on top of IP. Both add ports, so data reaches the right program, and a checksum. Beyond that they are opposites.

  • TCP (Transmission Control Protocol) gives applications a reliable, ordered byte stream over a connection. Everything sent arrives, once, in order, or the connection reports an error.
  • UDP (User Datagram Protocol) sends independent datagrams. Each one arrives intact or not at all, possibly out of order or duplicated, and nobody tells the sender.

QUIC is a newer transport built on UDP. It provides TCP-like reliability, but per stream, with TLS 1.3 built in. HTTP/3 runs on it.

Why it exists

IP is best effort: routers drop packets when queues overflow, links corrupt bits, and paths change so packets overtake each other. Most applications want something simpler to program against: send bytes, receive the same bytes in order. TCP provides that, along with flow control (do not overrun the receiver) and congestion control (do not overrun the network). Some applications care more about timeliness than completeness, or want to design their own reliability; UDP gets out of their way.

How it works

Handshake. A TCP client sends SYN with a random initial sequence number, the server answers SYN-ACK with its own and acknowledges the client's, and the client sends ACK. The client can put data right behind its ACK, so a new connection costs one round trip before the first request byte (TLS adds more, see the HTTPS lesson). TCP Fast Open can carry data in the SYN for repeat connections, but it is rarely deployed on the open internet.

Sequence numbers and ACKs. TCP numbers every byte. The receiver acknowledges cumulatively: "ACK 4001" means "I have every byte before 4001". The sender keeps a window of unacknowledged data in flight, sized by the receiver's advertised buffer and by the congestion window. Keeping several segments in flight is what lets TCP fill long, fast links instead of waiting a round trip per segment.

Retransmission. If a segment is lost, later segments still arrive and the receiver repeats its last ACK. Three duplicate ACKs tell the sender that one segment is missing while the network still delivers, so it retransmits immediately (fast retransmit). If ACKs stop entirely, a retransmission timeout (RTO, derived from measured round-trip times, with a floor that is often a few hundred milliseconds) fires instead. Selective acknowledgements (SACK) let the receiver report exactly which blocks it has, so only the gaps are resent. Modern stacks also use time-based loss detection (RACK).

In-order delivery and head-of-line blocking. The receiver hands data to the application only in order. Data after a gap waits in the receive buffer until the gap is filled, even if it belongs to a completely different request multiplexed on the same connection (HTTP/2 streams). On a lossy network that turns one lost packet into a stall for every stream.

Congestion control. TCP senders probe for available bandwidth and back off on loss or rising delay. Linux defaults to CUBIC; BBR models bandwidth and round-trip time instead of reacting to loss. Congestion control is why a new connection starts slowly (slow start) and why one flow does not starve others.

UDP. A UDP datagram is a header (source port, destination port, length, checksum) plus payload. No connection, no state, no ordering, no retransmission, no congestion control. The application decides what to do about loss: ignore it (voice codecs conceal a missing 20 ms frame), resend at its own level (DNS clients retry after a timeout), or implement a full protocol (QUIC).

QUIC. QUIC runs in user space over UDP. It combines the transport and TLS 1.3 handshakes into one round trip (zero for resumed connections, with replay caveats), encrypts almost all of its headers, numbers packets monotonically so retransmissions are never ambiguous, and keeps independent streams inside one connection: a lost packet only delays the streams whose data it carried. Connection IDs let a connection survive a client changing networks (Wi-Fi to mobile).

When to use it

  • TCP: anything that needs every byte in order and tolerates occasional extra latency: HTTP/1.1 and HTTP/2, database protocols, SSH, file transfer, most RPC and message brokers.
  • UDP: real-time media and games, where late data is worthless; DNS and other single request/response exchanges; telemetry where occasional loss is fine; and as the substrate for QUIC, WebRTC media and VPNs such as WireGuard.
  • QUIC / HTTP/3: web and API traffic to clients on lossy or mobile networks, many parallel streams, or frequent new connections.

When not to

  • Do not build your own reliable protocol on UDP unless the existing ones truly do not fit; reliability, congestion control and security are hard to get right. Use QUIC instead.
  • Do not use TCP for live media where retransmitted data arrives too late; the stall is worse than the loss.
  • Do not assume UDP is allowed everywhere: some enterprise and public networks block or throttle it, so QUIC clients keep a TCP fallback.

Trade-offs

Choice You gain You pay
TCP Reliable, ordered stream; universal support; kernel-optimised Handshake round trip; head-of-line blocking; connection state per client
UDP Lowest latency, no state, full control Loss, reordering and congestion are your problem
QUIC Reliable streams without cross-stream blocking, built-in TLS, fast setup, connection migration More CPU (user-space crypto and packet processing), UDP blocking on some networks, younger tooling
Many short TCP connections Simple A handshake per connection; use keep-alive and pooling instead

Alternatives

  • SCTP: message-oriented, multi-stream transport used in telecom signalling; rarely usable across the public internet because middleboxes do not pass it.
  • WebRTC data channels: SCTP over DTLS over UDP, configurable as reliable or unreliable, ordered or unordered, in the browser.
  • Application-level multiplexing on several TCP connections: what browsers did before HTTP/2 to soften head-of-line blocking.

Failure modes

  • Head-of-line blocking: one loss stalls every stream on a TCP connection.
  • Retransmission timeouts: when a whole window is lost, nothing triggers duplicate ACKs and the sender waits for the RTO, often hundreds of milliseconds, doubling on each repeat.
  • Half-open and idle connections: a peer or a NAT in the middle forgets a connection; the other side only notices on the next send or a keepalive.
  • Ephemeral port and TIME_WAIT exhaustion: a client opening and closing many connections to the same server runs out of source ports.
  • UDP amplification: spoofed small requests to open UDP services (DNS, NTP, memcached) trigger large responses aimed at a victim. Rate-limit and avoid exposing such services.
  • UDP blocked: QUIC fails on restrictive networks; without a TCP fallback, users cannot connect.

In production

Servers reuse connections (HTTP keep-alive, connection pools for databases and services) to avoid handshakes. Load balancers terminate TCP and TLS close to users. Large web properties serve HTTP/3 alongside HTTP/2 and see the biggest gains on mobile and lossy networks. Kernel tuning (buffer sizes, congestion control such as BBR) matters for high-bandwidth, long-distance transfers. Real-time products use WebRTC or custom UDP protocols with forward error correction and jitter buffers. Monitoring includes retransmission rates and connection errors, not just request latency.

Common misconceptions

  • "UDP is faster than TCP." It has no handshake and no waiting for retransmissions, but the bytes travel at the same speed. Over a clean network a warmed-up TCP connection is just as fast.
  • "TCP guarantees delivery." It guarantees ordered delivery or an error. If the network is down, data is not delivered; the application must handle the failure.
  • "HTTP/2 fixed head-of-line blocking." It fixed it at the HTTP layer; TCP still blocks all streams on loss. HTTP/3 over QUIC fixes it at the transport.
  • "QUIC over UDP is unreliable." QUIC is fully reliable; UDP is just its envelope.

Interview angle

Expect to justify transport choices: TCP (or HTTP over it) for APIs and data, UDP or WebRTC for real-time media and game state, WebSockets over TCP for chat. Be able to explain the handshake cost and why connection reuse matters, what happens on packet loss (duplicate ACKs, retransmission, buffered data), and why HTTP/3 helps on mobile networks. Mentioning head-of-line blocking precisely, and that QUIC still needs a TCP fallback, shows depth.

Model assumptions

This lesson is a scripted walk-through, not a simulation: every segment, acknowledgement and loss is placed by hand, and sequence numbers are labels. One-way latencies are illustrative (15 ms from client to router and 15 ms on to the server, 1 ms to forward, so a round trip is about 62 ms; 2 ms to hand data to the application). Segments are numbered 1, 2, 3 for readability, while real TCP numbers bytes and starts from a random value. Every segment is acknowledged individually; real receivers usually acknowledge every second segment (delayed ACKs). Congestion control, flow control, SACK and the QUIC handshake are described but not drawn. The QUIC step shows loss detection by packet threshold (three later packets acknowledged), as in RFC 9002.

The lesson as textEvery step of the simulation, written out.
  1. 1. TCP opens with a three-way handshake

    TCP gives applications a reliable, ordered byte stream on top of IP, which can lose, duplicate and reorder packets. Before any data flows, the two sides agree on starting sequence numbers: the client sends SYN, the server answers SYN-ACK, the client replies ACK.

    The client may send data right behind its ACK, so the handshake costs one round trip, about 62 ms here, before the first byte of the request. (A scripted illustration: segments are drawn by hand, not simulated.)

    Scene: The client sends SYN to the server through the router, the server answers SYN-ACK, and the client sends ACK. The exchange takes one round trip of about 62 ms before data can flow.

    Key idea: SYN, SYN-ACK, ACK: one round trip to agree on sequence numbers before data flows.

  2. 2. Numbered segments, acknowledged

    The client sends three segments back to back without waiting: the window allows several unacknowledged segments in flight. Each carries a sequence number. The server hands each one to the application as it arrives in order and returns an ACK naming the next number it expects: ACK 2, ACK 3, ACK 4.

    ACKs are cumulative: “ACK 4” means “I have everything before 4”. A segment the client sent but never sees acknowledged will be sent again.

    Scene: The client sends segments 1, 2 and 3 four milliseconds apart. Each reaches the server, is passed to the application, and an ACK for the next expected segment travels back.

    Key idea: Sequence numbers order the data; cumulative ACKs tell the sender what has arrived; a window keeps several segments in flight.

  3. 3. A segment is lost and resent

    Five segments leave; segment 2 is dropped at the router (congestion, a bad link). The server gets 1, then 3, 4 and 5. It cannot hand 3–5 to the application, because the stream must stay in order, so it buffers them and keeps answering ACK 2: three duplicate ACKs.

    Three duplicates tell the client that 2 is missing while later data still gets through, so it retransmits 2 at once (fast retransmit) instead of waiting for a timeout. When 2 arrives, the server releases 2, 3, 4 and 5 together and acknowledges with ACK 6. The application saw nothing for about 80 ms.

    Scene: Segment 2 is dropped at the router. The server receives 1, 3, 4 and 5, passes only 1 to the application and sends duplicate ACKs for 2. After the third duplicate the client resends 2; when it arrives the server passes 2, 3, 4 and 5 to the application at once.

    Key idea: TCP repairs loss by retransmitting, but the receiver holds everything after the gap until the gap is filled.

  4. 4. Head-of-line blocking across streams

    HTTP/2 sends many requests over one TCP connection, interleaving their data: here two images, A and B. Segment 3 carries part of image A, and it is lost.

    B’s next segments arrive fine, but TCP only knows one ordered byte stream. It cannot hand B2 and B3 to the browser while an earlier byte is missing, so image B stalls behind image A’s lost segment. That is head-of-line blocking: one loss delays everything behind it on the connection, even unrelated data.

    Scene: Two images share one TCP connection. Segment 3, part of image A, is lost. Image B’s later segments reach the server but are not delivered until A’s segment is retransmitted; then A2, B2, B3 and A3 are delivered together.

    Key idea: TCP orders everything on a connection, so one lost segment blocks all streams multiplexed on it.

  5. 5. UDP: fire and forget

    UDP is a thin layer over IP: it adds ports and a checksum, nothing else. No handshake, no sequence numbers, no ACKs, no retransmission. The client simply sends datagrams 1 to 5.

    Datagram 2 is lost and stays lost: nobody notices and nothing is resent. The others reach the application the moment they arrive. If ordering, reliability or congestion control matter, the application has to build them itself. For a voice call or a game update that is often exactly right: a resent packet would arrive too late to be useful.

    Scene: The client sends five UDP datagrams without a handshake. Datagram 2 is dropped at the router and never resent; the other four are passed to the application as soon as they arrive. No acknowledgements travel back.

    Key idea: UDP delivers datagrams immediately or not at all; anything more is the application’s job.

  6. 6. QUIC: reliable streams over UDP

    QUIC, the transport under HTTP/3, runs over UDP and does the reliability work itself, but per stream. Same two images, same lost packet carrying A2.

    B2 and B3 go to image B the moment they arrive: stream B has no gap. Only stream A waits, holding A3 until A2 is resent. QUIC acknowledges packets, notices that the packet carrying A2 is missing once three later packets have been acknowledged, and resends that data in a new packet. Loss on one stream no longer stalls the others.

    Scene: The same two images over QUIC. The packet carrying A2 is lost; B2 and B3 are delivered to image B as soon as they arrive, while image A waits for the resent A2 and then receives A2 and A3.

    Key idea: QUIC keeps ordering per stream, so a loss blocks only the stream it belongs to.

  7. 7. Choosing a transport

    TCP when you need every byte, in order, and a little latency on loss is acceptable: web APIs, databases, file transfer, most RPC. It is everywhere and every middlebox understands it.

    UDP when late data is worthless or you want full control: voice and video calls, games, DNS queries (one small question, one answer), telemetry. Add only the reliability you need.

    QUIC when you want TCP-like reliability without head-of-line blocking between streams, with TLS 1.3 built in and connection setup in one round trip: HTTP/3, and increasingly other protocols. Its costs: more CPU in user space and some networks that block or throttle UDP, so clients keep a TCP fallback.

    Scene: The client, router, server, application and two streams. Labels sum up when to use TCP, UDP and QUIC.

    Key idea: TCP for ordered reliability, UDP for timeliness and control, QUIC for reliable streams that do not block each other.