Skip to content
systemcoding.dev
Networking

TCP vs UDP Choosing a Transport for Systems Code

Choose between TCP and UDP for systems code by weighing reliability, ordering, latency and framing, with a decision table and the cost of each option.

5 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the C, Linux and C++ logos.

Every networked program starts with one decision: stream or datagram. TCP gives you a reliable, ordered byte stream and hides the network's mess. UDP gives you single messages and leaves the mess to you. Neither is better in general, and picking the wrong one costs either weeks of reimplemented reliability or a product that breaks the first time a packet is lost. This post compares them on the properties that matter in systems code, with Linux 6.12 as the reference platform, and ends with a decision table.

The definitions are in RFC 9293 for TCP and RFC 768 for UDP.

What TCP gives you

TCP provides a connection between two endpoints. The kernel runs a handshake, numbers every byte, acknowledges what arrives, retransmits what does not, reorders segments that arrive out of sequence and slows down when the network is congested. Your program sees a clean two-way byte stream: what one side writes, the other side reads, in the same order, without gaps or duplicates, or else the connection fails with an error.

That guarantee is valuable, and it has a price. The handshake costs a round trip before the first byte of data moves. A lost segment stalls everything behind it until the retransmission arrives, a problem called head-of-line blocking. The stream has no message boundaries, so you must frame messages yourself. And the kernel keeps state for every connection, which limits how many a machine can hold.

What UDP gives you

UDP provides independent datagrams. There is no connection, no handshake and no kernel memory per peer. Each message carries its own source and destination, goes out when you send it and arrives on its own or not at all. Boundaries are preserved, so one sendto becomes one recvfrom. There is no congestion control and no retransmission, so the sender can go as fast as the application chooses.

That freedom is also a burden. Loss, duplication and reordering are your problem. Nothing slows you down when the network is full, so an unthrottled sender harms everyone sharing the link, and a well-behaved protocol on UDP must add its own rate control. RFC 8085 gives the Internet Engineering Task Force's guidance for people designing such protocols, and its main message is that you inherit the duties TCP would have done for you.

Comparing them on what matters

PropertyTCPUDP
DeliveryReliable, or the connection failsBest effort, may be lost
OrderPreservedNot preserved
DuplicatesRemovedPossible
Message boundariesNone, a byte streamPreserved, one datagram per call
Setup costOne round trip for the handshakeNone
Congestion controlBuilt inNone, the application's duty
Per-peer kernel stateYes, per connectionNone
Broadcast and multicastNot possiblePossible
Typical failure modeStalls while retransmittingSilently loses data

Two rows decide most cases. If losing a message is a correctness bug, you need reliability, and rebuilding it on UDP means writing a transport protocol. If a late message is worse than a missing one, TCP's insistence on delivering everything in order works against you.

When TCP is the right default

Pick TCP when the data must arrive complete and in order and nobody cares about the last few milliseconds: file transfer, database traffic, remote procedure calls, HTTP, SSH, log shipping. Pick it also when you cannot afford to design a protocol. A TCP service can be written in an afternoon, debugged with ordinary tools and run through almost every firewall and proxy. For a first version, TCP is almost always the answer, and moving to something else later should be a measured decision.

When UDP is the right choice

UDP fits several situations well:

  • Small request and response exchanges, such as a DNS lookup, where a connection handshake would cost more than the work and a retry is cheap.

  • Real-time data, such as game state or audio, where an old update is useless once a newer one exists.

  • One-to-many delivery, where multicast or broadcast sends one packet to a group.

  • Custom transports, where you need independent streams without head-of-line blocking, as QUIC does on top of UDP.

Notice that the last case is not a beginner's shortcut. QUIC is a complete transport with reliability and congestion control, written in user space over UDP, specified in RFC 9000. UDP is the substrate, and the engineering effort of TCP is still done by someone.

The cost you pay in code

The difference shows up in the program. A TCP server needs listen, accept and a loop that handles partial reads and writes, plus framing. A UDP server needs one socket and one loop around recvfrom, but it must also decide what to do about loss, duplicates and large messages. Here is a short side-by-side:

c
/* TCP: read exactly len bytes, because the stream may deliver less per call. */
static int read_full(int fd, char *buf, size_t len)
{
    while (len > 0) {
        ssize_t n = recv(fd, buf, len, 0);
        if (n <= 0) return -1;
        buf += n;
        len -= (size_t)n;
    }
    return 0;
}

/* UDP: one call returns one whole message, or fails. */
ssize_t n = recvfrom(fd, buf, sizeof buf, 0, (struct sockaddr *)&peer, &plen);

The TCP version needs a loop because a message can arrive in pieces. The UDP version gets a whole message per call, but you have no idea whether the next one arrives.

Mistakes people make

Two opposite mistakes appear often. The first is choosing UDP because it is "faster", then adding acknowledgements, retries, ordering and flow control until the program is a slower and buggier TCP. TCP has had decades of tuning in the kernel, and a user-space copy of it rarely beats it. The second is choosing TCP for latency-sensitive streams and then fighting stalls, which happen because the stream must deliver old data before new data, even when the old data no longer matters.

Also watch the middle ground. If you need reliable messages and want boundaries, a length-prefixed protocol over TCP is usually simpler than a reliable layer over UDP. If you need only a few retries of small messages, UDP with a timeout and a request identifier is enough.

A quick way to decide

Ask three questions in order. Does losing one message break correctness? If yes, use TCP, or build reliability knowingly. Does a message lose its value when a newer one exists? If yes, UDP is a strong candidate. Do you need to reach many receivers with one send? Then UDP with multicast is the only option of the two. If none of these questions pulls you toward UDP, the default stays TCP, and you can revisit the choice once a measurement shows a real problem.

Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.
Systems Programming

How argc and argv Reach main in a C Program

The kernel copies argc and argv onto the new process's stack on execve, then startup code hands them to main. See the layout and measure it with a program.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.