TCP, UDP, ports, and sockets
Choose TCP or UDP
Compare TCP streams with UDP datagrams and choose transport behavior based on application needs.
8 minute lesson
TCP gives applications a reliable, ordered byte stream between two endpoints. It detects loss, retransmits data, puts bytes back in order, and controls how quickly data is sent. You write bytes in, the other side reads the same bytes out, and TCP handles everything that can go wrong in between.
UDP sends independent datagrams. It preserves message boundaries — one send is one message — but does not itself guarantee delivery, ordering, duplicate removal, or congestion response. What you get is an address, a port, and a fire-and-forget message.
Feel the difference with nc
You can experience both with netcat. Open two terminals. In the first, listen on TCP:
nc -l 8080
In the second, connect and type:
nc localhost 8080
hello over tcp
The connection exists before any data flows — kill the listener and the client notices immediately. Now repeat with UDP, adding -u to both sides:
nc -u -l 8080 # terminal 1
nc -u localhost 8080 # terminal 2
Messages still arrive, but stop the listener and the sender keeps typing happily into the void. Nothing tells it the other side is gone. That’s the UDP contract: no connection, no delivery confirmation, no feedback.
What each one is used for
You use TCP every day: HTTP, SSH, databases — anywhere every byte must arrive, in order. DNS queries typically ride UDP because a query is one small message, and if the answer doesn’t come back, asking again is cheaper than maintaining a connection. DHCP also uses UDP while a machine is still discovering its network configuration.
Video calls and games use UDP because a late packet is worthless; better to drop it and move on than stall the stream waiting for a retransmission. HTTP/3 runs over QUIC, which uses UDP as its base and implements reliability, encryption, and congestion control above it.
The choice is about behavior, not speed
Neither transport makes an application correct. An application using UDP may add acknowledgments and retries — at which point it has rebuilt part of TCP, hopefully for a good reason. An application using TCP must still define its own message boundaries inside the byte stream, because TCP deliberately doesn’t preserve them.
Choose from the behavior the application needs. TCP is common when every byte must arrive in order. UDP is useful when independent messages, low overhead, multicast, or application-controlled recovery matter.
Be suspicious of “UDP is faster” as a blanket claim. UDP has less overhead per packet, but TCP’s perceived slowness usually comes from doing work your application would otherwise have to do itself. Skipping the work is only faster when you genuinely didn’t need it.
Lesson completed