---
title: TCP vs UDP: Differences, Handshake and When to Use UDP
url: https://www.masaischool.com/resources/tcp-vs-udp-difference
description: TCP vs UDP explained with a table, a three-way handshake walk-through, localhost socket demos showing byte streams vs datagrams, and a use-case table.
updated: 2026-12-01
publisher: Masai (https://www.masaischool.com)
---

# TCP vs UDP: Differences, the Three-Way Handshake and When to Use Each

> **Short answer**
>
> **TCP** is connection-oriented: it sets up a connection with a three-way handshake, then delivers bytes reliably and in order, with flow and congestion control. UDP is connectionless: it sends independent datagrams with no handshake, no retransmission and no ordering, which makes it lighter and lower-latency for real-time traffic.

Every comparison page lists the same rows: reliable versus unreliable, slow versus fast. This one backs the claims with two Python programs that ran on 1 December 2026 (Python 3.9.6, localhost). They show the difference you can honestly demonstrate on one machine: byte streams versus datagrams, and what happens to a burst of data a slow receiver cannot keep up with.

It is the transport-layer deep dive for the [OSI model walk-through](https://www.masaischool.com/resources/osi-model-explained). For interview practice, continue with [computer networks interview questions](https://www.masaischool.com/resources/computer-networks-interview-questions); for the secure layer above TCP, see [how HTTPS works](https://www.masaischool.com/resources/how-https-works-explained).

## TCP vs UDP: the difference table

Both are transport-layer protocols that deliver data between ports on two hosts. TCP is specified in RFC 9293 and UDP in RFC 768. The UDP header has four fields (source port, destination port, length, checksum) and is 8 bytes. A TCP header is at least 20 bytes because it carries sequence numbers, acknowledgements, flags and a window.

| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented: handshake before data | Connectionless: just send |
| Reliability | Acknowledgements and retransmission of lost data | None built in; lost datagrams stay lost |
| Ordering | Bytes delivered in order | No ordering guarantee across datagrams |
| Data model | Byte stream, no message boundaries | Datagrams, boundaries preserved |
| Flow and congestion control | Yes (window, congestion algorithms) | No; the application must be considerate |
| Header size | 20 bytes minimum | 8 bytes |
| Speed and latency | Handshake and recovery add delay | Lower overhead, no waiting for retransmits |
| Broadcast and multicast | No, one connection is point to point | Supported |
| Typical users | Web pages, email, file transfer, SSH, databases | DNS lookups, live voice and video, games, QUIC |

'UDP is faster' is true only in a narrow sense: it has less overhead and does not wait. If your application needs every byte, you will rebuild acknowledgements and retries yourself, and the result may be slower than TCP.

## The three-way handshake

Before any application data, TCP agrees a connection with three segments. Each side picks an initial sequence number (ISN) so later bytes can be numbered and acknowledged.

1. **SYN:** the client sends a segment with the SYN flag and its ISN, say x.
2. **SYN-ACK:** the server replies with SYN and ACK set, its own ISN y, and an acknowledgement of x+1.
3. **ACK:** the client acknowledges y+1. Both sides are now in the established state and data can flow, in both directions.

Closing uses FIN segments, normally one in each direction, which is why it is described as a four-step close. Connecting to a port nobody is listening on makes the server's operating system reply with a reset, and the client's program gets an error. That error is a feature of TCP, and it is demonstrated below. UDP has no such feedback.

The cost is one round trip before the first byte of data, and more if TLS follows. That delay is one reason QUIC was built: it combines the transport and TLS handshakes.

## Executed localhost demos: byte stream vs datagrams

The program has three parts. First, a TCP sender makes three separate sendall calls and the receiver reads once: it gets one joined chunk, because TCP is a stream with no message boundaries. Second, a TCP burst of 2,000 records is sent to a receiver that starts reading late: TCP slows the sender down until the receiver catches up, and everything arrives in order. Third, the same burst over UDP is sent to a receiver with a deliberately small receive buffer (4096 bytes requested, and the operating system may round it up), and most datagrams are dropped with no error at the sender.import socket, threading, time def tcp_demo(): srv = socket.socket(); srv.bind(("127.0.0.1", 0)); srv.listen() port = srv.getsockname()[1] def sender(): c = socket.create_connection(("127.0.0.1", port)) for word in (b"one", b"two", b"three"): c.sendall(word) # three separate send calls c.close() t = threading.Thread(target=sender); t.start() conn, _ = srv.accept(); time.sleep(0.3) # let all three arrive before reading data = conn.recv(100) print("TCP received:", data, "in one recv: a byte stream has no message boundaries") t.join(); conn.close(); srv.close() try: socket.create_connection(("127.0.0.1", port), timeout=2) except ConnectionRefusedError: print("TCP connect to a closed port: ConnectionRefusedError (handshake failed, sender knows)") def udp_demo(): rx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) rx.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096) # a deliberately tiny receive buffer rx.bind(("127.0.0.1", 0)); port = rx.getsockname()[1] tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) for word in (b"one", b"two", b"three"): tx.sendto(word, ("127.0.0.1", port)) time.sleep(0.2) print("UDP received:", [rx.recvfrom(100)[0] for _ in range(3)], "(one datagram per recv: boundaries kept)") N = 2000 for i in range(N): tx.sendto(i.to_bytes(4, "big") + b"x" * 200, ("127.0.0.1", port)) # burst while nobody is reading time.sleep(0.2); rx.settimeout(0.3); got = [] try: while True: got.append(int.from_bytes(rx.recvfrom(2048)[0][:4], "big")) except socket.timeout: pass print(f"UDP burst: sent {N}, received {len(got)}, lost {N - len(got)} (no error reached the sender)") print("UDP order of what arrived is increasing:", got == sorted(got)) tx.sendto(b"anyone there?", ("127.0.0.1", 9)); print("UDP send to a port with no listener: no exception, no handshake") def tcp_burst(): srv = socket.socket(); srv.bind(("127.0.0.1", 0)); srv.listen() port = srv.getsockname()[1]; N, SIZE = 2000, 204 def sender(): c = socket.create_connection(("127.0.0.1", port)) for i in range(N): c.sendall(i.to_bytes(4, "big") + b"x" * 200) # blocks when the receiver falls behind c.close() t = threading.Thread(target=sender); t.start() conn, _ = srv.accept(); time.sleep(0.3); buf = b"" # start reading late, like the UDP receiver while True: chunk = conn.recv(65536) if not chunk: break buf += chunk ids = [int.from_bytes(buf[k:k + 4], "big") for k in range(0, len(buf), SIZE)] print(f"TCP burst: sent {N}, received {len(ids)}, in order: {ids == list(range(N))}") t.join(); conn.close(); srv.close() if __name__ == "__main__": tcp_demo(); tcp_burst(); udp_demo()

Output from one run:TCP received: b'onetwothree' in one recv: a byte stream has no message boundaries TCP connect to a closed port: ConnectionRefusedError (handshake failed, sender knows) TCP burst: sent 2000, received 2000, in order: True UDP received: [b'one', b'two', b'three'] (one datagram per recv: boundaries kept) UDP burst: sent 2000, received 17, lost 1983 (no error reached the sender) UDP order of what arrived is increasing: True UDP send to a port with no listener: no exception, no handshake

- The first TCP line usually shows the three words joined. It is timing-dependent in principle, because TCP may deliver them in separate reads; the point is that your code cannot rely on one send equalling one recv. Real protocols add their own framing, such as a length prefix or HTTP's Content-Length.
- The UDP burst loss (17 of 2,000 here) is real and caused by the tiny buffer and the sender being faster than the reader. The exact number changes on every machine and run. The receiver also saw no reordering, which is typical on localhost: reordering and loss on the real internet come from routers and links, which one machine cannot reproduce honestly, so the demo does not claim to.
- TCP's refusal on a closed port reaches the program as ConnectionRefusedError. UDP's sendto to a port with no listener returns normally.

To see why servers prefer TCP for most things, compare with the thread-per-connection or async models in [process vs thread](https://www.masaischool.com/resources/process-vs-thread-explained): each accepted TCP connection is a long-lived object the server has to keep, which UDP does not require.

## When to use UDP: a use-case table

| Use case | Usual transport | Why |
|---|---|---|
| Web pages, REST APIs (HTTP/1.1, HTTP/2) | TCP | Need every byte, in order. Usually wrapped in TLS |
| Email, file transfer, SSH, databases | TCP | Correctness matters more than a few milliseconds |
| DNS lookups | UDP port 53 by default, TCP when needed | A question and a small answer fit one datagram each; TCP is used when the answer is too large or for zone transfers, and servers must support it (RFC 7766) |
| HTTP/3 | QUIC, which runs over UDP | Gets reliability, ordering per stream and encryption from QUIC itself (RFC 9000, RFC 9114) |
| Live voice and video calls | Typically UDP (RTP, as in WebRTC) | A late packet is worthless; skipping it beats waiting |
| Recorded video streaming (YouTube, OTT) | Commonly HTTP over TCP, or HTTP/3 over QUIC | Buffering hides delay, and reuse of web infrastructure and CDNs |
| Online games | Often UDP with custom reliability for the few messages that need it | Latest position matters more than a resent old one |
| DHCP, NTP, SNMP, service discovery | UDP | Short request and response; broadcast or multicast in some cases |

The pattern: choose UDP when stale data is useless and your application can tolerate or repair loss, and choose TCP when you cannot. QUIC shows the middle path. It does not make UDP reliable; it builds reliable, congestion-controlled streams on top of UDP in user space, so changes do not wait for operating system updates. If you want to build something with both, the [backend project ideas](https://www.masaischool.com/resources/projects/backend-project-ideas) list includes small server projects that fit.

## Checklist: which one should I use?

- Does every byte have to arrive, in order? TCP, or QUIC.
- Is a late packet worse than a lost one (voice, game state)? UDP, with your own handling.
- One small request and one small reply? UDP can be enough, if you add retries (DNS does).
- Need to send to many receivers at once? UDP multicast or broadcast.
- Not sure? Use TCP and an existing protocol such as HTTP. Writing your own reliability layer is rarely worth it.

## Frequently asked questions

### What is the main difference between TCP and UDP?

TCP sets up a connection and guarantees reliable, in-order delivery of a byte stream with flow and congestion control. UDP sends independent datagrams with no connection, no retransmission and no ordering, so it has less overhead and lower latency but leaves loss handling to the application.

### What is the three-way handshake in TCP?

The client sends SYN with its initial sequence number, the server replies SYN-ACK with its own number and an acknowledgement, and the client sends ACK. Then the connection is established and data flows. It costs one round trip before the first byte of application data.

### When should you use UDP instead of TCP?

Use UDP when data is time-sensitive and a late packet is useless, as in live voice, video calls and games, or for tiny request-response exchanges such as DNS. Also use it when you need multicast, or when you are building your own transport like QUIC.

### Does DNS use TCP or UDP?

Both. Queries normally go over UDP port 53 because they are small. DNS falls back to TCP when a response is too large, and zone transfers use TCP. RFC 7766 requires DNS implementations to support TCP as well.

### Is UDP faster than TCP?

UDP has less overhead and does not wait for acknowledgements, so each datagram has lower latency. It is not faster for reliable transfer: if you need every byte, your application has to detect loss and resend, which TCP already does very well.

### Which transport does QUIC use?

QUIC runs on top of UDP. It adds reliable, ordered streams, congestion control and built-in TLS 1.3 itself, and HTTP/3 runs over it. Using UDP lets QUIC be updated in applications and pass through existing networks.
