TCP vs UDP — how do they differ and when would you choose each?
Short answer
TCP is connection-oriented: it handshakes, numbers bytes, retransmits losses, and controls congestion, giving reliable ordered delivery at the cost of latency and overhead. UDP is connectionless and fire-and-forget — no handshake, no retransmission, no ordering. Use TCP when correctness matters (web, email, file transfer) and UDP when speed matters more than perfection (DNS, VoIP, gaming, video).
TCP and UDP are the two main transport-layer protocols, and the choice between them is a trade-off between reliability and latency. Understanding when each wins is core networking knowledge.
What TCP gives you
TCP is connection-oriented. Before any data flows, it runs a three-way handshake. It numbers every byte so the receiver can reassemble the stream in order, acknowledges what it receives, retransmits anything lost, and uses flow control and congestion control to avoid overwhelming the receiver or the network. The cost of all this is overhead and added latency — round trips for setup, waits for acknowledgements, head-of-line blocking when a segment is lost.
What UDP gives you
UDP is connectionless: it just wraps your payload in a small header with source/destination ports and a checksum, then sends it. No handshake, no retransmission, no ordering, no congestion control. If a packet is lost, it's gone unless the application handles it. This makes UDP fast and stateless, with tiny overhead.
Choosing between them
Use TCP when every byte must arrive correctly and in order: HTTP(S), SSH, email, file transfer. Use UDP when timeliness beats completeness: real-time voice and video, online games, and DNS, where a dropped query is just retried. Modern protocols blur the line — QUIC runs reliable, multiplexed, encrypted streams on top of UDP to avoid TCP's head-of-line blocking.
Security note
UDP's lack of state makes it the favorite vector for reflection and amplification DDoS (DNS, NTP, memcached), because a spoofed source address gets a large reply sent to the victim.
Interviewers want the reliability-vs-speed framing plus a couple of correct example protocols on each side.
Likely follow-ups
- Why does DNS use UDP for most queries but switch to TCP for large responses?
- How does QUIC give TCP-like reliability on top of UDP?
- What does UDP's lack of state mean for spoofing and amplification attacks?