Use TCP when you need every byte in the right order. Use UDP when fresh data matters more than complete data.
TCP is connection-oriented. It sets up a connection with a handshake first. Then it delivers a reliable byte stream in order:
- Lost segments are sent again (retransmitted).
- Duplicate segments are dropped.
- Data arrives in the order it was sent.
- It also does flow control (not sending faster than the receiver can read) and congestion control (not overloading the network).
The costs of TCP are handshake latency, state kept for every connection, and stalls while lost data is resent.
UDP is connectionless. It sends independent datagrams (single self-contained packets). Each one has an 8-byte header and a checksum, and nothing more. There is no handshake, no retransmission, no ordering and no congestion control. Each datagram arrives whole or not at all.
Use TCP when correctness matters more than latency:
- HTTP/1.1 and HTTP/2
- database protocols
- SSH
Use UDP when fresh data beats complete data, or when the application wants its own control:
- DNS queries
- voice and video calls
- games
- metrics, like StatsD
- QUIC, which builds reliability and encryption on top of UDP for HTTP/3
- TCP uses a connection and gives a reliable, ordered byte stream with flow and congestion control.
- UDP sends connectionless datagrams with no delivery or ordering guarantees.
- TCP costs handshake latency and stalls while lost data is resent.
- Use TCP for HTTP, databases and SSH. Use UDP for DNS, real-time media, games and QUIC.
- TCP (MDN) (https://developer.mozilla.org/en-US/docs/Glossary/TCP)developer.mozilla.org
- UDP (MDN) (https://developer.mozilla.org/en-US/docs/Glossary/UDP)developer.mozilla.org