Networking Interview Prep
TCP and UDP

UDP

Fast Communication

LinkedIn Hook

There is a protocol that sends your data with zero setup, zero guarantees, and zero apologies — and it powers half the internet.

DNS lookups. Video calls. Online gaming. Live sports streams. All running on a protocol that does not even check if the other side received the data.

That is UDP — and it is not broken. It is deliberately fast.

Here is what most developers do not understand:

  • UDP has no handshake — the first packet IS the request
  • UDP has no acknowledgement — you fire and forget
  • UDP header is only 8 bytes vs TCP's 20+ bytes (2.5× smaller)
  • When a video frame is lost, you do not want it retransmitted — you want the next frame

The insight: reliability is not always what you want. Sometimes freshness matters more than completeness. Sometimes latency matters more than accuracy. UDP is the right tool when the application can tolerate (or handle) loss better than delay.

Full lesson → [link]

#Networking #UDP #BackendEngineering #SystemDesign #InterviewPrep


UDP thumbnail


What You'll Learn

  • What UDP is and why "connectionless" means it is fundamentally different from TCP
  • The UDP header — why it is only 8 bytes and what each field does
  • Why packet loss is acceptable (even preferred) for certain applications
  • The real use cases for UDP: DNS, video streaming, gaming, VoIP, QUIC
  • How applications built on UDP implement their own reliability when they need it

The Analogy That Makes This Click

UDP is a postcard. TCP is a registered letter.

With a postcard, you write your message, drop it in the mailbox, and walk away. You do not know if it arrived. You do not wait for a signature. If the postcard gets lost in the mail, the recipient never knows you sent it. There is no going back to ask "did you get it?"

But postcards have advantages: they are cheap (no envelope, no signature process), they are fast (no waiting at the post office), and for certain messages — a "Happy Birthday!" — you do not really need confirmation. The next time you see the person is fine.

UDP is the postcard protocol. For DNS: you ask a question, you get an answer — if the answer does not arrive in 2 seconds, ask again. For video streaming: you want the next frame now, not a retransmitted frame from 500ms ago. For gaming: the player's position 200ms ago is useless — you want the current position, even if some intermediate updates were lost.


What Is UDP?

UDP (User Datagram Protocol) is a Layer 4 (Transport Layer) protocol — the same layer as TCP. It provides:

  • Connectionless communication — no handshake, no setup, no teardown. Send and done.
  • No guaranteed delivery — packets may be lost; the sender is not informed
  • No ordering — packets may arrive out of order; UDP does not reorder them
  • No retransmission — lost packets are gone; UDP will not re-send them
  • No flow control — the sender can send as fast as it wants regardless of receiver state
  • No congestion control — UDP does not back off when the network is congested (this is a responsibility left to the application or upper protocol)
  • Checksums — UDP does include an optional checksum for error detection (but corrupted datagrams are simply dropped, not retransmitted)

The result: UDP is significantly faster and simpler than TCP for many use cases.


The UDP Header — 8 Bytes

UDP's minimal header is one of its biggest advantages:

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|          Source Port          |       Destination Port        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|             Length            |            Checksum           |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                        Data (variable)                        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
FieldSizePurpose
Source Port2 bytesSender's port (used for the response)
Destination Port2 bytesWhich service the datagram is for
Length2 bytesTotal length of header + data
Checksum2 bytesError detection (optional in IPv4, mandatory in IPv6)

Total: 8 bytes. Compare to TCP's minimum of 20 bytes.

There are no sequence numbers, no ACK numbers, no window size, no flags. The simplicity is the feature.


Why Losing Packets Is Sometimes Fine

The key insight is that reliability is not always what an application needs. What some applications need is low latency and freshness.

Video / Audio Streaming

A video call sends 30 frames per second. Each frame contains the full image (or a delta from the previous). If frame #15 is lost:

  • If TCP: the receiver halts, waits for retransmission, then plays frames 15, 16, 17 in a burst — causing a freeze followed by a stutter.
  • If UDP: the receiver skips frame 15 and renders frame 16. You might see a tiny glitch. The call continues smoothly.

Frame 15 retransmitted 200ms later is worthless — the user has moved on. Freshness beats completeness.

Online Gaming

The game server sends player position updates 64 times per second (every 15ms). If one update is lost:

  • TCP: game freezes waiting for the lost update to be retransmitted.
  • UDP: the client interpolates between the last known position and the next received update. The experience is smooth even with some loss.

DNS

A DNS query is a single small packet. A DNS response is also typically a single small packet. If the response does not arrive within ~2 seconds, the resolver simply re-sends the query. No complex handshake needed for a one-shot question-answer exchange.


Real-World UDP Use Cases

ApplicationWhy UDP?
DNSSingle-packet query/response; simple retry if no reply
Video streaming (UDP-based)Freshness over completeness; tolerable visual artifacts
VoIP (Zoom, Teams, WhatsApp calls)Latency is more disruptive than occasional crackle
Online gamingPosition updates go stale immediately; loss is better than lag
DHCPClient has no IP yet, cannot establish a TCP connection
SNMPSimple management queries; retry logic at application level
QUIC (HTTP/3)UDP base layer with custom reliability built on top
NTP (time sync)Single packet time request/response

QUIC — UDP With Custom Reliability

An important modern example: QUIC (the protocol under HTTP/3) is built on top of UDP. But QUIC adds its own:

  • Stream multiplexing (multiple requests on one connection, no head-of-line blocking)
  • Encryption (always-on TLS 1.3)
  • Connection migration (change IP mid-connection, e.g., phone switches from WiFi to LTE)
  • Selective retransmission (only the lost stream stalls, not the whole connection)

QUIC proves that UDP + custom reliability can outperform TCP in the right conditions — especially on lossy mobile networks. By controlling the reliability layer, QUIC avoids TCP's head-of-line blocking problem.


Code Example 1 — UDP Socket (Node.js)

// UDP client and server using Node.js dgram module
// Server listens for messages; client sends a message and exits

const dgram = require("dgram");

// === UDP Server ===
const server = dgram.createSocket("udp4");

server.on("message", (msg, remoteInfo) => {
  const received = msg.toString();
  console.log(`[Server] Received "${received}" from ${remoteInfo.address}:${remoteInfo.port}`);

  // Server sends a reply datagram back to the sender
  const reply = Buffer.from(`Echo: ${received}`);
  server.send(reply, remoteInfo.port, remoteInfo.address, (err) => {
    if (err) console.error("[Server] Send error:", err);
    // No connection state — each message is independent
  });
});

server.on("listening", () => {
  const { address, port } = server.address();
  console.log(`[Server] Listening on ${address}:${port}`);
});

server.on("error", (err) => {
  console.error("[Server] Error:", err);
  server.close();
});

server.bind(41234);  // No handshake needed — just bind and listen

// === UDP Client ===
const client = dgram.createSocket("udp4");

client.on("message", (msg, remoteInfo) => {
  console.log(`[Client] Got reply: "${msg.toString()}" from ${remoteInfo.address}:${remoteInfo.port}`);
  client.close();  // UDP client can close anytime — no teardown handshake
  server.close();
});

// No connect() needed — send directly to server address + port
const message = Buffer.from("Hello UDP");
client.send(message, 41234, "127.0.0.1", (err) => {
  if (err) {
    console.error("[Client] Send error:", err);
    client.close();
  } else {
    console.log(`[Client] Sent "${message.toString()}" to 127.0.0.1:41234`);
    // Fire and forget — we wait for a reply, but UDP doesn't guarantee one
  }
});

// Output:
// [Server] Listening on 0.0.0.0:41234
// [Client] Sent "Hello UDP" to 127.0.0.1:41234
// [Server] Received "Hello UDP" from 127.0.0.1:<ephemeral-port>
// [Client] Got reply: "Echo: Hello UDP" from 127.0.0.1:41234

Code Example 2 — Application-Layer Reliability on UDP

// Shows how to implement basic reliability on top of UDP
// (simplified version of what QUIC / custom game protocols do)

class ReliableUDPSender {
  constructor(sendFn, timeoutMs = 500, maxRetries = 3) {
    this.send      = sendFn;
    this.timeout   = timeoutMs;
    this.maxRetries = maxRetries;
    this.pending   = new Map();   // seqNum -> { resolve, reject, timer, retries }
    this.seq       = 0;
  }

  sendReliable(data) {
    return new Promise((resolve, reject) => {
      const seqNum = ++this.seq;
      const packet = { seqNum, data };

      const attempt = (retryCount) => {
        if (retryCount > this.maxRetries) {
          this.pending.delete(seqNum);
          return reject(new Error(`Packet ${seqNum} dropped after ${this.maxRetries} retries`));
        }

        console.log(`[Sender] Send seq=${seqNum} "${data}" (attempt ${retryCount + 1})`);
        this.send(packet);  // Fire the UDP datagram

        const timer = setTimeout(() => {
          console.log(`[Sender] Timeout for seq=${seqNum} — retrying`);
          attempt(retryCount + 1);  // No ACK received — retransmit
        }, this.timeout);

        this.pending.set(seqNum, { resolve, reject, timer });
      };

      attempt(0);
    });
  }

  receiveACK(seqNum) {
    const pending = this.pending.get(seqNum);
    if (!pending) return;
    clearTimeout(pending.timer);
    this.pending.delete(seqNum);
    console.log(`[Sender] ACK received for seq=${seqNum} — confirmed`);
    pending.resolve(seqNum);
  }
}

// === Simulation ===

let dropNext = true;  // Simulate one lost packet

const sendFn = (packet) => {
  if (dropNext) {
    console.log(`[Network] Dropped packet seq=${packet.seqNum} (simulated loss)`);
    dropNext = false;
    return;  // Pretend the packet never arrived
  }
  // Simulate receiver sending ACK after 100ms
  setTimeout(() => {
    console.log(`[Receiver] Received seq=${packet.seqNum} "${packet.data}" — sending ACK`);
    sender.receiveACK(packet.seqNum);
  }, 100);
};

const sender = new ReliableUDPSender(sendFn, 300, 3);

sender.sendReliable("Hello via reliable UDP")
  .then(seq => console.log(`[App] Packet ${seq} delivered successfully`))
  .catch(err => console.error(`[App] Failed:`, err.message));

// Output:
// [Sender] Send seq=1 "Hello via reliable UDP" (attempt 1)
// [Network] Dropped packet seq=1 (simulated loss)
// [Sender] Timeout for seq=1 — retrying
// [Sender] Send seq=1 "Hello via reliable UDP" (attempt 2)
// [Receiver] Received seq=1 "Hello via reliable UDP" — sending ACK
// [Sender] ACK received for seq=1 — confirmed
// [App] Packet 1 delivered successfully

UDP visual 1


Common Mistakes

Mistake 1 — Assuming UDP is inherently unreliable for all use cases

UDP is unreliable at the transport layer, but the application can implement exactly the reliability it needs on top. QUIC does this. Most game engines do this. The advantage over TCP is that application-level reliability can be selective — you retransmit only the data that matters, not everything. TCP retransmits all subsequent data when one segment is lost (head-of-line blocking), which is worse than selective application-layer recovery in some scenarios.

Mistake 2 — Thinking UDP has no error detection

UDP has an optional checksum (mandatory in IPv6). If a datagram arrives corrupted, the receiver's UDP stack discards it — no notification to either side. But corruption detection exists. What UDP does not do is retransmit the discarded datagram. Error detection ≠ error correction or retransmission.

Mistake 3 — Using UDP where you actually need ordering

Video game position updates are fine to lose individually because each update is independent — a new position can be understood without the previous one. But if you are streaming audio at the packet level and packets 1 through 5 arrive in order 1, 3, 2, 4, 5 — that out-of-order delivery causes audible glitches unless your application reassembles them. If order matters and you choose UDP, you must implement your own sequence numbers at the application layer (which is exactly what RTP — Real-time Transport Protocol — does for audio/video over UDP).


Interview Questions

Q: What makes UDP faster than TCP?

UDP has no handshake (no RTT overhead before sending), no ACK wait (no send-and-wait cycles), no retransmission (lost data is gone), no flow or congestion control (sender runs at full speed), and a smaller header (8 bytes vs TCP's 20+). The result: the first datagram reaches the server the moment it is sent, with no setup cost.

Q: What are the main use cases for UDP?

Q: Can you build reliability on top of UDP?

Yes — and many protocols do. QUIC (HTTP/3) runs on UDP and adds encryption, stream multiplexing, and selective retransmission. RTP (Real-time Transport Protocol) adds sequence numbers and timestamps to UDP for audio/video. Game engines implement custom ACK and delta-compression schemes on UDP. The advantage of building reliability on top of UDP is that you can make it domain-specific: retransmit only what matters, tolerate loss for stale data, and avoid TCP's head-of-line blocking.

Q: Why does DNS use UDP instead of TCP?

DNS queries and responses typically fit within a single 512-byte datagram (or up to 4096 bytes with EDNS). A TCP handshake would cost one full RTT before the query could even be sent — doubling the latency of every DNS lookup. Since DNS can simply retry the query if no response arrives within a timeout, the cost of occasional packet loss is lower than the cost of a mandatory 3-way handshake for every lookup. DNS does fall back to TCP for responses larger than the UDP limit or for zone transfers.

Q: What is head-of-line blocking and how does UDP help?

In TCP, if one segment is lost, all subsequent segments are buffered and cannot be delivered to the application until the lost segment is retransmitted and received. This is head-of-line blocking — one lost packet stalls everything behind it. In UDP, each datagram is independent — a lost datagram does not block any other datagrams. QUIC exploits this: it uses UDP and implements per-stream retransmission, so a lost packet in stream A does not delay stream B.


Quick Reference — Cheat Sheet

UDP KEY PROPERTIES
─────────────────────────────────────────────
Connection   : None — no handshake, no teardown
Reliability  : None — fire and forget
Ordering     : None — packets may arrive out of order
Speed        : Fast — no overhead, minimal header
Header size  : 8 bytes (vs TCP's 20+ bytes)
Error detect : Optional checksum (corrupted packets dropped, not retransmitted)

UDP HEADER
─────────────────────────────────────────────
[ Source Port 2B ][ Dest Port 2B ][ Length 2B ][ Checksum 2B ]
Total: 8 bytes

WHEN TO USE UDP
─────────────────────────────────────────────
✅ Latency matters more than completeness
   → DNS, VoIP, online gaming, video calls
✅ Data goes stale immediately
   → Game position updates, sensor streams
✅ Small single-packet exchanges
   → DNS, DHCP, NTP, SNMP
✅ You will build custom reliability on top
   → QUIC (HTTP/3), RTP, custom game protocols
✅ Broadcast / multicast needed
   → LAN discovery, IPTV

COMMON UDP PORTS
─────────────────────────────────────────────
53   DNS
67   DHCP server
68   DHCP client
69   TFTP
123  NTP
161  SNMP
443  QUIC (HTTP/3)

Previous: Lesson 4.1 — TCP — Reliable Communication → Next: Lesson 4.3 — TCP vs UDP — The Complete Comparison →


This is Lesson 4.2 of the Networking Interview Prep Course — 8 chapters, 32 lessons.

On this page