Skip to content
Commitwise
Menu
Networking

TCP vs UDP

The two transport protocols under almost everything. Covers the TCP handshake, acknowledgements, retransmission, flow and congestion control, why latency beats bandwidth, connection refused vs timed out, TCP as a byte stream and message framing, Nagle, keepalives and idle timeouts, and when UDP is the better choice for calls, games, DNS and QUIC.

beginner

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

IP gets packets to the right machine, but it promises nothing: packets can be lost, duplicated, delayed or arrive out of order. The transport layer decides what to do about that, and there are two answers. TCP turns the unreliable network into a reliable, ordered stream of bytes, at the price of handshakes and waiting. UDP passes the packets through almost as they are, fast and with no guarantees.

“TCP or UDP?” is a standard interview question, and the reasoning behind it shows up everywhere: why a page over a slow mobile link takes so long, why a chat server sometimes receives half a message, why video calls stutter instead of freezing. This lesson follows Network layers, IP addresses and ports.

New to some of these? Open what you need, or skip ahead.

Basics:Packets, IP addresses and ports

Data crosses the network in packets of at most about 1,500 bytes. An IP address gets each packet to the right machine and a port to the right program on it. Routers on the way may drop packets when they’re busy. See Network layers, IP addresses and ports.

Basics:Latency and bandwidth

Latency is how long one trip takes, often measured as the round-trip time (RTT): a message there and the reply back, from about 1 ms in a data center to 100 ms or more across continents or on mobile. Bandwidth is how much data per second the link can carry. A wide road (bandwidth) doesn’t make a long road (latency) shorter.

Part Not started

TCP: reliable, ordered, connection-based

TCPTCPThe transport protocol that delivers a reliable, ordered stream of bytes over a connection.Open in glossary → (Transmission Control Protocol) gives programs a connection: a two-way pipe where every byte sent arrives, exactly once, in the order it was sent. HTTP/1.1 and HTTP/2, database connections, SSH and email all run over TCP.

It starts with the three-way handshakeTCP handshakeThe three messages (SYN, SYN-ACK, ACK) that open a TCP connection, costing one round trip.Open in glossary →:

client                                server
  | ---- SYN (I'd like to connect) ---->  |
  | <--- SYN-ACK (OK, me too) ----------  |
  | ---- ACK (great) ------------------>  |
  |        connection established         |

That costs one round trip before any data is sent. On a 100 ms mobile connection, 100 ms are gone before the request even starts.

Then TCP keeps its promise like this:

  • Numbering: every byte has a sequence number, so the receiver can put packets back in order and ignore duplicates.
  • Acknowledgements: the receiver tells the sender what it has received (“I have everything up to byte 48,000”).
  • Retransmission: if no acknowledgement comes in time, the sender sends the data again. A lost packet doesn’t lose data; it only causes a delay.
  • Flow control: the receiver says how much more it can take (the window), so a fast server doesn’t overwhelm a slow phone.
  • Congestion control: the sender starts slowly and speeds up while things go well, and slows down when packets get lost, so it doesn’t flood a busy network. This is called slow start.

When one side is done, it sends FIN (“I’m finished”), and the other side acknowledges and closes its half. A RST (reset) instead ends a connection abruptly: that’s what you get when you connect to a port where nothing is listening.

  • Handshake cost: 1 RTT for TCP, plus 1 RTT for TLS 1.3 (2 for TLS 1.2), before the first request byte. Connection reuse (keep-alive, pooling, HTTP/2 multiplexing) removes both. TCP Fast Open (data in the SYN) exists but is rarely usable through middleboxes; QUIC folds transport and TLS into 1 RTT, 0-RTT on resumption.
  • Reliability machinery: cumulative ACKs plus SACK (selective acknowledgements), fast retransmit after three duplicate ACKs, retransmission timeouts with exponential backoff (the initial timeout is 1 s; repeated SYN loss turns into seconds of delay).
  • Flow control: the receive window (scaled up to 1 GB with window scaling). Throughput is capped by window / RTT: a 64 KB window over 100 ms RTT is about 5 Mbit/s whatever the link speed. Buffer sizes should cover the bandwidth-delay product.
  • Congestion control: slow start from an initial window of 10 segments (about 14 KB), doubling per RTT until loss or a threshold; then CUBIC (Linux, macOS, Windows default) or BBR (model-based, Google’s choice for YouTube and Cloud) in steady state. Idle connections can fall back to slow start (tcp_slow_start_after_idle).
  • Head-of-line blocking: because delivery is in order, one lost packet holds back everything after it until the retransmission arrives, even data for unrelated HTTP/2 streams. That’s a main motivation for QUIC.
  • Connection states: SYN_SENT, ESTABLISHED, FIN_WAIT, CLOSE_WAIT (the app hasn’t closed its socket: a leak in your code if they pile up), TIME_WAIT (the side that closed first, 60 s on Linux).

Predict the output

Nothing listens on port 9 of this laptop. 10.255.255.1 is an address where nobody answers at all. How does each attempt fail?

# -z: only connect, -G 3: give up after 3 seconds (Linux nc: -w 3)
nc -vz -G 3 127.0.0.1 9
nc -vz -G 3 10.255.255.1 443
# where the time goes in one HTTPS request: DNS, TCP handshake, TLS, first byte
curl -s -o /dev/null -w 'dns %{time_namelookup}  tcp %{time_connect}  tls %{time_appconnect}  first byte %{time_starttransfer}  total %{time_total}\n' https://example.com/

# the handshake itself: SYN, SYN-ACK, ACK (flags S, S., .)
sudo tcpdump -n -i en0 'tcp port 443 and tcp[tcpflags] & (tcp-syn|tcp-fin|tcp-rst) != 0'

# connection states on this machine
netstat -an -p tcp | awk '{print $6}' | sort | uniq -c     # Linux: ss -tan | awk ...

Worked example: a small request over TCP

An app sends a 300-byte request and gets a 3,000-byte response, over a connection with a 50 ms round trip.

  1. Handshake. SYN, SYN-ACK, ACK: 50 ms. Nothing useful has been sent yet.
  2. Request. The client sends the 300 bytes, numbered 1 to 300, in one packet.
  3. Response. The server acknowledges the request and sends 3,000 bytes in three packets (each carries at most about 1,460 bytes). They are numbered so the client knows their order.
  4. A packet is lost. The second packet is dropped by a busy router. The client receives packets 1 and 3 and keeps telling the server “I have everything up to the end of packet 1”.
  5. Retransmission. The server notices the repeated acknowledgement (or its timer runs out) and sends packet 2 again.
  6. Delivery. Only now does the client’s TCP pass the response to the app, all 3,000 bytes in order. The app never knew a packet was lost; it just got the response later.
  7. Close. When the app is done, each side sends FIN and acknowledges the other’s. Usually, though, apps keep the connection open for the next request, so they don’t pay for the handshake again.
Deep diveWhy latency, not bandwidth, decides how fast a page loadsInterview favorite

“Users on a 100 Mbit/s mobile connection say the app is slow. How can that be?” Work out a cold fetch of a 100 KB response on a 100 ms RTT:

  1. DNS lookup, if not cached: up to 1 RTT.
  2. TCP handshake: 1 RTT.
  3. TLS 1.3 handshake: 1 RTT.
  4. Request and the first window of response: slow start allows about 10 segments, roughly 14 KB, in the first data round trip.
  5. The window doubles each round trip: 14 KB, then 29 KB, then 58 KB. After three data round trips about 100 KB has arrived.

That’s 5 to 6 round trips, 500 to 600 ms, and at 100 Mbit/s the bytes themselves would take 8 ms. Doubling the bandwidth changes almost nothing; halving the RTT halves the time.

What actually helps:

  • Reuse connections (keep-alive, HTTP/2, a single client instance), so steps 1 to 3 happen once.
  • Move servers closer: CDNs and edge termination cut the RTT for handshakes even when the origin is far away.
  • Send less in the critical path: the first 14 KB of a response matter most; compress, and don’t make the first screen wait for several sequential requests (each one costs a full round trip).
  • Newer protocols: TLS 1.3 (1 RTT instead of 2), session resumption and 0-RTT, HTTP/3 over QUIC (transport and TLS together), BBR congestion control on lossy links.

The same arithmetic explains why chatty APIs (ten sequential calls to render one screen) feel slow on mobile and fine in the office.

  • Handshake 1 RTT, TLS 1.3 another; reuse connections. Refused = RST (reachable, nothing listening); timeout = packets dropped (firewall, routing).
  • Sequence numbers, SACK, fast retransmit, RTO backoff; throughput ≤ window / RTT.
  • Slow start from about 14 KB, doubling per RTT; short transfers are RTT-bound. CUBIC vs BBR.
  • In-order delivery causes head-of-line blocking (HTTP/2 over TCP); QUIC avoids it.
  • CLOSE_WAIT piling up = your code isn’t closing sockets.
curl -s -o /dev/null -w 'tcp %{time_connect} tls %{time_appconnect} ttfb %{time_starttransfer}\n' https://host/
nc -vz -G 3 host 5432          # refused vs timed out
ss -tan state close-wait       # leaked sockets (Linux)

Check this part

  1. What are the three messages of the TCP handshake?

  2. A TCP packet is lost on the way. What does the app see?

  3. Connecting to a database fails with a timeout, not "connection refused". What does that suggest?

  4. A 100 KB response on a fresh connection with 100 ms RTT takes about 500 ms even on a fast link. Main reason?

TCP opens a connection with a three-way handshake (SYN, SYN-ACK, ACK), numbers every byte, acknowledges what arrived and resends what didn't, so the app gets every byte once and in order. Flow control stops a fast sender from overwhelming a slow receiver; congestion control (slow start) ramps up speed gradually, so short transfers are limited by round trips, not bandwidth.

Part Not started

A stream of bytes, not messages

The most common bug in code that uses sockets directly comes from one fact: TCP has no messages. It promises that the bytes arrive in order. It doesn’t promise that they arrive in the same pieces you sent.

If the sender writes "hello" and then "world", the receiver’s first read may return:

  • "hello", and the next read "world";
  • "helloworld" all at once;
  • "hel", then "loworld".

All three are correct TCP. And a single 200 KB write is never received in one read: it arrives in chunks of whatever size the network and the operating system’s buffers produce.

So programs that send messages over TCP need framing: a way for the receiver to find where one message ends and the next begins. There are two common ways:

  • Length prefix: before each message, send its length as a fixed-size number (4 bytes). The receiver reads 4 bytes, then reads exactly that many bytes. Binary protocols like PostgreSQL’s and Kafka’s do this.
  • Delimiter: end each message with a character that can’t appear inside it, usually a newline. The receiver collects bytes until it sees one. Newline-delimited JSON, Redis’ protocol and SMTP work like this.

HTTP does it for you (headers end with an empty line, and Content-Length or chunked encoding says where the body ends), which is why most app developers never meet the problem, until they write a socket server.

  • Framing is the application’s job: length prefixes (fixed or varint, plus a maximum size check so a corrupt or malicious length doesn’t allocate gigabytes), delimiters (with escaping or a guarantee the delimiter can’t appear), or self-describing formats. Also handle multi-byte UTF-8 characters split across reads: decode only complete frames.
  • Partial writes: write on a non-blocking socket can accept fewer bytes than given; loop or use APIs that write everything (OutputStream.write, Node’s buffered socket.write with backpressure via the drain event).
  • Nagle’s algorithm holds back small writes while earlier data is unacknowledged; combined with the receiver’s delayed ACK (up to 40 ms on Linux, longer elsewhere), a write-write-read pattern can stall by tens of milliseconds per request. Set TCP_NODELAY for request/response and interactive protocols (Go does by default), or better, assemble each message in one buffered write.
  • Dead connections: if the peer vanishes (crash, cable, NAT drops the mapping), nothing tells you until you send. TCP keepalive defaults to 2 hours idle on Linux, far too long; use application heartbeats or tune keepalive (seconds to minutes).
  • Idle timeouts: NAT gateways and load balancers drop idle connections (AWS ALB 60 s by default, NLB 350 s), often silently. A client pool that keeps idle connections longer gets a reset on the next request. Keep the pool’s idle timeout below the middlebox’s, and retry idempotent requests once on a reset.
  • Graceful close: shutdown(SHUT_WR) sends FIN but keeps reading; closing a socket with unread data sends RST and can destroy the last response the peer hasn’t read.

Predict the output

A client writes 'hello' and then 'world' to a TCP socket, flushing after each. The server waits a moment, then calls read with a 1,024-byte buffer once. What can that read return?

// client
out.write("hello".getBytes(UTF_8)); out.flush();
out.write("world".getBytes(UTF_8)); out.flush();

// server, a moment later
byte[] buffer = new byte[1024];
int n = in.read(buffer);
System.out.println(new String(buffer, 0, n, UTF_8));
// each message: 4-byte length, then the UTF-8 bytes
fun DataOutputStream.writeMessage(text: String) {
    val bytes = text.toByteArray(Charsets.UTF_8)
    writeInt(bytes.size)
    write(bytes)
    flush()
}

fun DataInputStream.readMessage(maxSize: Int = 1 shl 20): String {
    val length = readInt()                                // blocks until all 4 bytes are there
    require(length in 0..maxSize) { "Bad message length $length" }
    return String(readNBytes(length), Charsets.UTF_8)     // blocks until all bytes are there
}
// each message: 4-byte length, then the UTF-8 bytes
static void writeMessage(DataOutputStream out, String text) throws IOException {
    byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
    out.writeInt(bytes.length);
    out.write(bytes);
    out.flush();
}

static String readMessage(DataInputStream in, int maxSize) throws IOException {
    int length = in.readInt();                            // blocks until all 4 bytes are there
    if (length < 0 || length > maxSize) throw new IOException("Bad message length " + length);
    return new String(in.readNBytes(length), StandardCharsets.UTF_8);
}
import net from 'node:net';
import readline from 'node:readline';

// newline-delimited JSON: one message per line
const server = net.createServer((socket) => {
  const lines = readline.createInterface({ input: socket, crlfDelay: Infinity });
  lines.on('line', (line) => handleMessage(JSON.parse(line)));
});

function send(socket: net.Socket, message: unknown) {
  socket.write(JSON.stringify(message) + '\n');          // JSON.stringify never emits a raw newline
}

The chat server that loses messages under load

Spot the bugReading chat messages from a socket

Tap the line with the bug.

server.accept().use { socket ->
    val input = socket.getInputStream()
    val buffer = ByteArray(4096)
    while (true) {
        val n = input.read(buffer)
        if (n == -1) break
        val message = String(buffer, 0, n, Charsets.UTF_8)
        handleMessage(message)
    }
}
try (Socket socket = server.accept()) {
    InputStream in = socket.getInputStream();
    byte[] buffer = new byte[4096];
    while (true) {
        int n = in.read(buffer);
        if (n == -1) break;
        String message = new String(buffer, 0, n, StandardCharsets.UTF_8);
        handleMessage(message);
    }
}
const server = net.createServer((socket) => {
  socket.on('data', (chunk: Buffer) => {
    const message = JSON.parse(chunk.toString('utf8'));
    handleMessage(message);
  });
});

Deep diveThe first request after lunch always failsInterview favorite

Symptom: a service calls another through an AWS Application Load Balancer. After quiet periods, the first request sometimes fails with “connection reset” or “unexpected end of stream”; a retry works. Under steady load it never happens.

Cause: the client’s connection pool keeps idle connections for, say, 5 minutes. The load balancer closes connections idle for 60 seconds. When it does, the client’s side doesn’t notice (no one is reading, or the FIN arrives while the connection sits in the pool). The next request is written into a connection that’s already closed on the other end, and the reply is a RST.

Variants: NAT gateways that drop idle mappings silently (no FIN at all, so the request hangs until a timeout instead of failing fast), database connections dropped by a firewall overnight, mobile connections when the carrier NAT forgets the mapping.

Fixes:

  • Make the client give up first: pool idle timeout shorter than every middlebox’s (for the ALB, under 60 s, or raise the ALB’s idle timeout above the pool’s). For servers behind the balancer, the server’s keep-alive timeout should be longer than the balancer’s, so the balancer, not the server, closes idle connections.
  • Validate or refresh connections: database pools test connections (HikariCP’s keepaliveTime, maxLifetime below the firewall’s limit).
  • Retry once on a reset for idempotent requests; many HTTP clients (OkHttp) retry automatically on a stale pooled connection.
  • Heartbeats for long-lived connections (WebSockets, MQTT), shorter than the shortest idle timeout on the path.

It’s a good answer because it shows you know that “connection reset” usually isn’t the server crashing, and that every hop between client and server has its own idea of how long idle connections live.

  • TCP is a byte stream: frame messages (length prefix with a max size, or delimiter); decode UTF-8 per frame; handle partial writes and backpressure.
  • Nagle + delayed ACK stalls small writes: TCP_NODELAY or one buffered write per message.
  • Dead peers are invisible until you send; default keepalive is 2 h. Use heartbeats.
  • Idle timeouts: pool idle < middlebox idle (ALB 60 s); server keep-alive > balancer’s; retry idempotent requests once on reset.
val length = input.readInt()
require(length in 0..MAX) { "Bad length $length" }
val payload = input.readNBytes(length)
socket.tcpNoDelay = true

Check this part

  1. A client sends two messages over TCP. How many reads does the server need?

  2. Which is a way to frame messages over TCP?

  3. Each request does two small writes then waits for a reply, and gets an extra 40 ms. Likely cause?

  4. Requests fail with "connection reset" after idle periods, behind a load balancer with a 60 s idle timeout. Fix?

TCP delivers a stream of bytes, not messages: one write can arrive in several reads and several writes in one read. Apps must frame messages themselves, with a length prefix or a delimiter. Nagle's algorithm can add latency to small writes (TCP_NODELAY turns it off). Idle connections are cut silently by NATs and load balancers, so use keepalives and shorter pool idle times.

Part Not started

UDP: fast, simple, no promises

UDPUDPThe transport protocol that sends independent datagrams with no connection, ordering or delivery guarantee.Open in glossary → (User Datagram Protocol) is the opposite approach: each message, a datagram, is sent on its own, like a postcard. There’s no handshake, no acknowledgement, no resending and no ordering. A datagram either arrives whole or doesn’t arrive at all, and nobody tells the sender which.

That sounds worse, so why use it?

  • No waiting. No handshake before the first message, and a lost packet doesn’t hold up the ones behind it. With TCP, one lost packet stalls everything after it until it’s resent.
  • Late data is useless anyway. In a video call, a piece of audio that arrives 300 ms late can’t be played; it’s better to skip it and play the next one. A game needs the latest position of a player, not the position from half a second ago. TCP would carefully deliver the old data first.
  • Boundaries are kept. One datagram sent is one datagram received, so there’s no framing problem.
  • Small and cheap. A DNS question and answer fit in one datagram each: one round trip, nothing to set up or tear down.

So UDP is used for DNS, voice and video calls, online games, live streaming, and as the base of QUIC, the protocol under HTTP/3, which rebuilds reliability on top of UDP in a smarter way (covered in the HTTP/3 lesson later in this section).

The rule of thumb: use TCP (usually through HTTP) unless you have a real-time need where late data is worthless, and then use a library or protocol built on UDP (WebRTC, QUIC) rather than raw UDP.

  • Semantics: unreliable, unordered, possibly duplicated datagrams, boundaries preserved, at most 65,507 bytes of IPv4 payload but anything over the path MTU is fragmented, and losing one fragment loses the datagram. Keep datagrams under about 1,200 bytes (QUIC’s minimum path assumption) to avoid fragmentation.
  • What you must build yourself: sequence numbers to detect loss and reordering, selective retransmission only for data that’s still useful, congestion control (sending as fast as possible hurts everyone, including you), and pacing. This is why apps use RTP/SRTP (WebRTC), QUIC, or game networking libraries.
  • Connected UDP sockets (connect() on a UDP socket) filter to one peer and surface ICMP “port unreachable” as ECONNREFUSED on a later call.
  • Middleboxes: NAT mappings for UDP expire quickly (often 30 s to a few minutes), so real-time apps send keepalives; some corporate networks block UDP entirely, so QUIC and WebRTC need TCP or TLS fallbacks (HTTP/2, TURN over TCP 443).
  • QUIC: reliability and congestion control per stream in user space, TLS 1.3 built in (1-RTT, 0-RTT resumption), no head-of-line blocking across streams, connection IDs that survive changing IP (Wi‑Fi to mobile). Costs more CPU than kernel TCP.
  • Abuse: no handshake means source addresses can be spoofed, so UDP services that answer with more than they receive (open DNS resolvers, memcached, NTP) are used for amplification DDoS attacks. Rate-limit responses and don’t answer unauthenticated requests with large payloads.

Predict the output

On the same machine, a sender sends three UDP datagrams: 'a', 'b' and 'c'. The receiver waits a moment, then calls receive three times with a 1,024-byte buffer. What does it get?

# terminal 1: receive (python's socket API, three receives)
python3 -c "
import socket, time
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.bind(('127.0.0.1', 9999))
time.sleep(2)
for _ in range(3): print(s.recv(1024))"

# terminal 2: send three datagrams
python3 -c "
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for m in (b'a', b'b', b'c'): s.sendto(m, ('127.0.0.1', 9999))"
// receiver
DatagramSocket(9999).use { socket ->
    val buffer = ByteArray(1500)
    while (true) {
        val packet = DatagramPacket(buffer, buffer.size)
        socket.receive(packet)                              // one whole datagram, or blocks
        val text = String(packet.data, 0, packet.length, Charsets.UTF_8)
        println("${packet.socketAddress}: $text")
    }
}

// sender: no connection, no confirmation
DatagramSocket().use { socket ->
    val bytes = "position 12.5 40.1".toByteArray(Charsets.UTF_8)
    socket.send(DatagramPacket(bytes, bytes.size, InetAddress.getByName("127.0.0.1"), 9999))
}
// receiver
try (DatagramSocket socket = new DatagramSocket(9999)) {
    byte[] buffer = new byte[1500];
    while (true) {
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        socket.receive(packet);                             // one whole datagram, or blocks
        String text = new String(packet.getData(), 0, packet.getLength(), StandardCharsets.UTF_8);
        System.out.println(packet.getSocketAddress() + ": " + text);
    }
}

// sender: no connection, no confirmation
try (DatagramSocket socket = new DatagramSocket()) {
    byte[] bytes = "position 12.5 40.1".getBytes(StandardCharsets.UTF_8);
    socket.send(new DatagramPacket(bytes, bytes.length, InetAddress.getByName("127.0.0.1"), 9999));
}
import dgram from 'node:dgram';

// receiver
const receiver = dgram.createSocket('udp4');
receiver.on('message', (msg, rinfo) => console.log(`${rinfo.address}:${rinfo.port}: ${msg.toString('utf8')}`));
receiver.bind(9999);

// sender: no connection, no confirmation
const sender = dgram.createSocket('udp4');
sender.send('position 12.5 40.1', 9999, '127.0.0.1', () => sender.close());

Practice: TCP or UDP?

Exerciseeasy

Pick a transport

For each feature, choose TCP or UDP (or a protocol built on one of them) and give the reason:

  1. Uploading a profile photo.
  2. The voice in a video call.
  3. A multiplayer racing game sending every car’s position 30 times a second.
  4. Chat messages in a messaging app.
  5. Looking up api.shop.example in DNS.
›

Ask two questions: does every byte have to arrive, and is data that arrives half a second late still useful?

SolutionTry it yourself first
  1. TCP (HTTP). Every byte of the photo must arrive, and a short delay doesn’t matter.
  2. UDP (WebRTC’s RTP). A sound that arrives late can’t be played; skipping it is better than freezing the call while it’s resent.
  3. UDP. Only the newest position matters; an old one that arrives late is replaced by the next update 33 ms later anyway. Important events (a lap finished) are sent with the game’s own acknowledgements.
  4. TCP (HTTPS or a WebSocket). A chat message must never be lost or arrive out of order, and a few hundred milliseconds of delay is fine.
  5. UDP. One small question, one small answer, no connection to set up; the resolver just asks again if no answer comes. (Large answers fall back to TCP.)
Deep diveDesigning the network layer of a real-time game or callInterview favorite

“How would the clients of a multiplayer game talk to the server?” A strong answer separates the traffic by what it needs.

  • State updates (positions, aim, voice frames): UDP, sent at a fixed tick rate (20 to 60 Hz), each datagram complete on its own and small enough to avoid fragmentation. Every packet carries a sequence number; the receiver drops anything older than what it has. Instead of resending lost updates, send snapshots or deltas against the last acknowledged state, so a lost packet is repaired by the next one.
  • Important events (a purchase, a kill, a chat message): reliable delivery on top of UDP, using acknowledgements and resending inside the game protocol, or a separate TCP/WebSocket channel. Mixing them into one TCP stream would make every position update wait behind a lost chat packet.
  • Hiding latency: the client predicts its own movement immediately and reconciles with the server’s authoritative state; other players are shown slightly in the past and interpolated between snapshots, so jitter doesn’t look like teleporting.
  • Getting through networks: NAT keepalives, a fallback over TCP or WebSocket on 443 for networks that block UDP, and for peer-to-peer (calls), STUN for hole punching with TURN relays when it fails.
  • Congestion and fairness: adapt the send rate and quality (fewer updates, lower audio bitrate) when loss and delay rise, as WebRTC’s congestion control does; blasting at a fixed rate on a congested mobile link makes everything worse.
  • Security: authenticate and encrypt (DTLS, QUIC, or the game’s own crypto); never trust client-sent state; rate-limit to avoid becoming a DDoS amplifier.

Today you’d often use QUIC (reliable streams plus unreliable datagrams, RFC 9221), WebRTC data channels, or an engine’s networking library instead of raw sockets, but the trade-offs to explain are the same.

  • UDP: datagrams, no connection, loss, reordering, duplicates; boundaries kept. Stay under about 1,200 bytes to avoid fragmentation.
  • You build sequencing, selective reliability, congestion control and pacing, or use RTP/WebRTC/QUIC.
  • NAT UDP mappings expire fast; some networks block UDP (fallback to TCP 443).
  • QUIC: per-stream reliability in user space, built-in TLS 1.3, no cross-stream HOL blocking, connection migration.
  • Spoofable sources make UDP services DDoS amplifiers: rate-limit, no large unauthenticated replies.
DatagramSocket().use { s ->
    val b = "seq=812 x=12.5 y=40.1".toByteArray()
    s.send(DatagramPacket(b, b.size, InetAddress.getByName(host), 9999))   // fire and forget
}

Check this part

  1. Which is true about UDP?

  2. Why do video calls use UDP rather than TCP for audio?

  3. Why is HTTP/3 built on UDP?

  4. What makes some UDP services useful for DDoS amplification?

UDP sends independent datagrams with no connection, no acknowledgement, no ordering and no retransmission, but it keeps message boundaries and adds almost no delay. It suits DNS, voice and video calls, games and live streams, where late data is useless, and it is the base of QUIC and HTTP/3, which add reliability per stream in user space.

Key takeaways

  • TCP: handshake (SYN, SYN-ACK, ACK), then every byte arrives once and in order; lost packets are resent, which costs time.
  • “Connection refused” means the machine answered but nothing listens; a timeout means packets aren’t getting through.
  • TCP is a stream of bytes: frame your messages with a length prefix or a delimiter.
  • UDP: separate datagrams, no guarantees, no waiting; for DNS, calls, games and QUIC.
  • Default to TCP (through HTTP); choose UDP-based protocols when late data is worthless.
  • Short transfers are bound by round trips (handshakes, slow start), not bandwidth: reuse connections, move closer.
  • Head-of-line blocking in TCP motivates QUIC.
  • Nagle plus delayed ACK, 2-hour default keepalive, and middlebox idle timeouts cause real latency and reset bugs.
  • UDP apps must add sequencing, selective reliability and congestion control, survive NAT and blocked UDP, and avoid amplification.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.