Skip to content

TCP and UDP

Almost every byte your system sends rides on one of two transport protocols. TCP turns an unreliable network into a reliable, ordered byte stream and pays for it in round trips and per-connection state. UDP hands individual datagrams to the network and promises nothing more. Choosing between them — or picking QUIC, which builds TCP-like guarantees on top of UDP — shapes latency, scalability and how your system behaves when packets are lost.

TCP (RFC 9293) is connection-oriented. Before any data flows, both sides exchange initial sequence numbers in a three-way handshake; teardown uses FIN segments in each direction.

sequenceDiagram
  participant C as Client
  participant S as Server
  C->>S: SYN (seq = x)
  S-->>C: SYN-ACK (seq = y, ack = x+1)
  C->>S: ACK (ack = y+1), may carry the first request
  Note over C,S: 1 RTT before the client can send data
  C->>S: Data
  S-->>C: Data + ACK
  C->>S: FIN
  S-->>C: ACK, then FIN
  C->>S: ACK
  Note over C: TIME_WAIT (60 s on Linux)

The side that closes first keeps the socket in TIME_WAIT so that late segments from the old connection can’t be mistaken for a new one. TCP Fast Open (RFC 7413) can carry data in the SYN on repeat connections, but middlebox problems kept it niche; in practice, connection reuse and TLS 1.3 or QUIC do more to cut setup latency.

  • Every byte has a sequence number; the receiver acknowledges what it has received, and the sender retransmits anything not acknowledged within a timeout or signalled missing by duplicate ACKs.
  • A checksum catches corruption; corrupt segments are dropped and later resent.
  • The receiver reorders out-of-order segments and hands the application a contiguous byte stream. The application never sees gaps — but it also never sees anything past a gap until it is filled.

TCP carries bytes, not messages. Protocols on top (HTTP, gRPC, database wire protocols) add their own framing, such as length prefixes, to find message boundaries.

Two different windows cap how much unacknowledged data a sender may have in flight; the effective limit is the smaller of the two.

  • Flow control protects the receiver. It advertises a receive window (rwnd): how much buffer it has left. A slow consumer shrinks the window and the sender pauses — a built-in form of back pressure.
  • Congestion control protects the network. The sender keeps a congestion window (cwnd), growing it while ACKs arrive and cutting it when loss or rising delay signals congestion.

A new connection starts in slow start with a small window — 10 segments, about 14.6 KB (RFC 6928, the Linux default) — and roughly doubles it every round trip. At that rate a 1 MB response needs about 7 round trips to deliver; at 100 ms RTT that is 0.7 s before bandwidth even matters. This is why warm, reused connections are so much faster than new ones, and why Linux by default shrinks the window again after a connection has been idle.

To fill a long, fast path the window must reach the bandwidth-delay product: 1 Gbit/s × 100 ms = 12.5 MB in flight. Buffers smaller than that cap throughput regardless of link speed.

Algorithms differ in what they treat as congestion. CUBIC (RFC 9438), the default in Linux, Windows and Apple stacks, reacts to packet loss. BBR, developed at Google, models bottleneck bandwidth and round-trip time instead, which helps on lossy long-distance links; Google uses it for its own traffic, and its specification is still an IETF draft in 2026.

UDP (RFC 768) adds ports and a checksum to IP — an 8-byte header — and stops there. Each send is one datagram that arrives whole, arrives late, arrives twice, arrives out of order or never arrives. There is no connection state, no retransmission and no congestion control, so the application must decide how to handle loss and how fast it may send.

What that buys:

  • No setup cost. The first datagram carries data. A DNS lookup is one datagram out, one back.
  • No head-of-line blocking. A lost datagram delays nothing else; the application can skip it.
  • Broadcast and multicast. One send can reach every host on a subnet (broadcast) or a subscribed group (multicast); TCP can only talk to one peer.
  • Cheap fan-in. One socket can serve millions of clients without per-client kernel state.

Where it is used:

  • Bootstrapping protocols. A DHCP client has no IP address yet, so it broadcasts a discover message from UDP port 68 to port 67 and lets any server answer. DNS, NTP and SNMP are UDP for similar latency and simplicity reasons.
  • Real-time media. Voice and video (WebRTC sends SRTP, normally over UDP) prefer a glitch to a stall: a retransmitted audio frame that arrives 300 ms late is useless.
  • Games. Fast-paced multiplayer games send state snapshots many times a second; only the newest matters, so a lost one is simply superseded.
  • Lossy-tolerant hot paths. Facebook’s memcache clients sent reads over UDP and treated a dropped reply as a cache miss, cutting latency by about a fifth; writes and deletes stayed on TCP.

The flip side: UDP is a favourite tool for amplification DDoS — an attacker spoofs the victim’s address and a server sends a large reply to it. Never answer an unauthenticated small UDP request with a much larger response; memcached disabled UDP by default in 2018 after it was abused exactly this way, and QUIC servers may send at most three times the bytes they received until the client’s address is validated.

TCP connections are cheap individually and expensive in aggregate:

CostWhere it bitesTypical mitigation
Handshake RTTs (plus TLS)Every new connection, worst across regionsKeep-alive, connection pools, edge termination
Slow startFirst few hundred KB on each new connectionReuse warm connections
Kernel buffersMany idle or slow clientsAutotuning, limits, small idle timeouts
Process or thread per connectionPostgreSQL forks a process per client connectionPooler such as PgBouncer, fewer app instances
Ephemeral ports in TIME_WAITHigh rate of short connections to one backendReuse connections, spread across backend IPs
Load-balancer and NAT stateMillions of long-lived connectionsConnection limits, idle timeouts

Two quick numbers. Linux uses ephemeral ports 32768–60999, about 28,000 per source IP and destination; with a 60-second TIME_WAIT, one client opening a fresh connection per request to a single backend runs out at roughly 470 new connections per second. And a fleet of 500 application instances each holding 20 database connections already asks for 10,000 server-side connections — far beyond what a single relational database handles well. Hence connection pools at the client and poolers or proxies in front of databases and caches.

Head-of-line (HOL) blocking happens whenever independent pieces of data share one ordered channel: the item at the front stalls everything queued behind it.

sequenceDiagram
  participant S as Server
  participant N as Network
  participant C as Client TCP stack
  S->>N: Segment 1 (stream A)
  N->>C: Segment 1 delivered to app
  S->>N: Segment 2 (stream B)
  Note over N: Segment 2 is lost
  S->>N: Segment 3 (stream C)
  N->>C: Segment 3 buffered, not delivered
  S->>N: Segment 4 (stream A)
  N->>C: Segment 4 buffered, not delivered
  Note over C: Streams A and C wait for B
  S->>N: Segment 2 retransmitted
  N->>C: 2, 3 and 4 delivered together
  • At the application layer, HTTP/1.1 suffers it because responses on one connection must come back in request order.
  • At the transport layer, TCP suffers it because it promises one ordered byte stream. HTTP/2 multiplexes many streams over TCP, but when segment 2 (stream B) is lost, the kernel withholds segments 3 and 4 too, even though they belong to other streams. The stall lasts at least one RTT and, if the retransmission is also lost, much longer.

UDP-based protocols avoid it by delivering each datagram independently, and QUIC keeps per-stream ordering without imposing ordering across streams — so a loss in stream B delays only stream B.

QUIC (RFC 9000, 2021) is a full reliable transport that runs over UDP and lives in user space rather than the kernel. Running over UDP lets it pass through existing middleboxes and evolve without waiting for operating-system upgrades.

  • Streams: many independent, ordered, reliable streams per connection, with flow control per stream and per connection.
  • Built-in TLS 1.3: transport and crypto handshakes are combined (1 RTT, or 0-RTT on resumption), and almost all headers are encrypted, so middleboxes can’t ossify the protocol.
  • Connection IDs: a connection survives a client changing IP or port, for example Wi-Fi to cellular.
  • Modern loss recovery: packet numbers are never reused, which removes ambiguity about which copy of a retransmission was acknowledged.
  • Optional unreliable datagrams (RFC 9221) for media and games that want QUIC’s encryption and congestion control without retransmission.

QUIC is the transport for HTTP/3 and WebTransport. Costs: more CPU per byte than kernel TCP, UDP blocked or throttled on some corporate networks (so clients keep a TCP fallback), and fewer observability tools, because the payload and most headers are encrypted.

NeedTCPUDP (custom protocol)QUIC
Every byte, in orderYes, built inMust build it yourselfYes, per stream
Lowest latency, late data is uselessStalls on lossYesWith datagram extension
Many independent requests on one connectionHOL blockingYesYes
Broadcast or multicastNoYesNo
Setup cost1 RTT + TLSNone1 RTT including TLS, 0-RTT on resumption
Congestion controlBuilt inYour responsibilityBuilt in
Passes every firewallYesOften blockedOften blocked, needs TCP fallback
Typical usersHTTP/1.1–2, databases, SSH, SMTP, KafkaDNS, DHCP, NTP, VoIP, gamesHTTP/3, WebTransport, modern mobile apps

Default to TCP (or HTTP over it) for anything that must arrive intact. Pick UDP when timeliness beats completeness or you need broadcast, and accept that you now own congestion control and security. Pick QUIC — usually by enabling HTTP/3 at your CDN or load balancer — when clients are on lossy or changing networks.

  • HTTP — HTTP/1.1, HTTP/2 and HTTP/3 on top of these transports.
  • API styles — WebSockets, SSE and long polling all ride on long-lived TCP connections.
  • Load balancers — L4 balancing works at the TCP/UDP level.
  • Latency numbers — round-trip times that make handshakes expensive.
  • Queues and back pressure — flow control is back pressure at the transport layer.

Based on The System Design Primer by Donne Martin (CC BY 4.0). Restructured, rewritten and updated; site content is licensed under CC BY 4.0.