UDP: Fire and Forget

UDP: Fire and Forget in Python: TCP is a phone call: you dial, the other side answers, and you both know the connection exists. UDP is a postcard.

Concept Explanation

TCP is a phone call: you dial, the other side answers, and you both know the connection exists. UDP is a postcard. You write an address on a message and drop it in the box. It probably arrives. It might not. Two postcards might arrive out of order. Nobody tells you either way.

That sounds strictly worse — and for file transfers it is. But dropping the guarantees also drops the cost, and for some workloads that trade is exactly right.

TCP vs UDP

TCPUDP
ConnectionHandshake requiredNone
DeliveryGuaranteedBest effort
OrderGuaranteedNot guaranteed
DuplicatesPreventedPossible
SpeedSlower (acknowledgements, retries)Faster
Overhead per packet20+ bytes8 bytes
Data modelByte stream (needs framing)Discrete datagrams
Broadcast/multicastNoYes

The One Genuine Advantage Beyond Speed

UDP preserves message boundaries. One sendto becomes exactly one recvfrom. All that framing work TCP forced on you disappears — a datagram arrives whole or not at all.

When UDP Is the Right Answer

  • Live audio and video — a 40 ms-old audio frame is worthless; retransmitting it would make the stall worse than the gap.
  • Online game state — you want the latest position, not a replay of stale ones.
  • DNS — one small question, one small answer; a connection handshake would double the latency.
  • Metrics and logging (StatsD) — losing one of ten thousand counters does not matter.
  • Service discovery — broadcast "is anyone there?" to a whole subnet, which TCP simply cannot do.

When It Is the Wrong Answer

Anything where a missing byte corrupts the result: files, database queries, payments, API calls. If you find yourself adding acknowledgements and retransmissions on top of UDP, you are rebuilding TCP badly. Use TCP.

The API Is Simpler

No listen, no accept, no connect:

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)   # DGRAM, not STREAM
sock.sendto(b"payload", ("127.0.0.1", 9999))              # address per message
data, addr = sock.recvfrom(2048)                          # sender comes back too

Code Example #1 (Basic)

A UDP server and client. Note the total absence of connection setup.

# ---------- udp_server.py ----------
import socket

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
    sock.bind(("127.0.0.1", 9999))
    print("UDP server ready on 127.0.0.1:9999")

    while True:
        data, addr = sock.recvfrom(2048)     # one datagram, whole
        message = data.decode("utf-8", errors="replace")
        print(f"  {addr} -> {message!r}")

        if message.strip().lower() == "quit":
            break
        sock.sendto(f"heard: {message}".encode("utf-8"), addr)
# ---------- udp_client.py ----------
import socket

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
    sock.settimeout(2)                       # essential: nothing may ever reply
    server = ("127.0.0.1", 9999)

    for message in ("ping", "hello udp", "quit"):
        sock.sendto(message.encode("utf-8"), server)
        try:
            reply, _ = sock.recvfrom(2048)
            print(f"{message!r} -> {reply.decode()!r}")
        except socket.timeout:
            print(f"{message!r} -> no reply (this is normal for UDP)")

Start the client first, before any server exists. Nothing raises. The datagrams simply vanish, and the timeout is your only clue. That silence is UDP's defining characteristic.

Code Example #2 (Intermediate)

Adding sequence numbers so you can measure what UDP loses.

# ---------- sender.py ----------
import socket
import struct
import time

TOTAL = 500
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
dest = ("127.0.0.1", 9998)

for seq in range(TOTAL):
    # 4-byte sequence number + timestamp, so the receiver can spot gaps
    packet = struct.pack("!Id", seq, time.time())
    sock.sendto(packet, dest)
    time.sleep(0.001)

sock.sendto(b"END", dest)
print(f"Sent {TOTAL} datagrams.")
sock.close()
# ---------- receiver.py ----------
import socket
import struct

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# A bigger kernel buffer loses fewer packets during bursts
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 1 << 20)
sock.bind(("127.0.0.1", 9998))
print("Counting datagrams...")

seen = set()
out_of_order = 0
highest = -1

while True:
    data, _ = sock.recvfrom(2048)
    if data == b"END":
        break

    seq, sent_at = struct.unpack("!Id", data)
    if seq in seen:
        print(f"  duplicate: {seq}")
    seen.add(seq)

    if seq < highest:
        out_of_order += 1
    highest = max(highest, seq)

expected = highest + 1
missing = sorted(set(range(expected)) - seen)

print(f"Received {len(seen)} of {expected}")
print(f"Loss: {100 * len(missing) / expected:.1f}%")
print(f"Out of order: {out_of_order}")
print(f"First few missing: {missing[:10]}")

sock.close()

On localhost you will usually see 0% loss — the kernel never touches a real network. Run the two halves on different machines over Wi-Fi and the numbers become interesting. That gap between "works on my machine" and "works on a network" is the whole lesson.


Common Mistakes

  1. Expecting delivery: no exception is raised when a datagram is dropped. Silence is the failure mode. Always set a timeout on the client.
  2. Sending datagrams that are too large: above roughly 1472 bytes on Ethernet, IP must fragment the packet, and losing one fragment loses the whole datagram. Keep payloads under ~1400 bytes.
  3. Calling recv instead of recvfrom: you get the data but lose the sender's address, so you cannot reply.
  4. Assuming order: packet 7 can arrive before packet 5. If order matters, add sequence numbers — or use TCP.
  5. Reimplementing TCP: acknowledgements plus retries plus reordering on top of UDP is a well-known way to build something slower and buggier than TCP. Only do it when you genuinely need partial reliability (as QUIC does).
  6. Ignoring the receive buffer: a burst that overflows SO_RCVBUF is dropped by the kernel before your code ever sees it.
  7. Trusting the source address: UDP source addresses are trivially spoofed, which is why UDP services are favourite amplification vectors. Never make an authorisation decision from one.

Best Practices

  • Always set settimeout() on the client: without it, one lost datagram hangs your program forever.
  • Keep payloads under ~1400 bytes: stay inside a single Ethernet frame and avoid fragmentation entirely.
  • Add a sequence number to every packet if you care about loss or ordering — it costs 4 bytes and makes problems measurable.
  • Design the protocol to be idempotent: if processing the same datagram twice is harmless, duplicates stop mattering.
  • Send state, not deltas: "player is at (120, 45)" survives a dropped packet; "player moved +3" does not.
  • Raise SO_RCVBUF for high-rate receivers.
  • Validate every byte you decode: use errors="replace", check lengths before struct.unpack, and treat every datagram as attacker-controlled.
  • Default to TCP: choose UDP deliberately, for a reason you can state in one sentence.

Practice Exercises

  1. The Time Service: Write a UDP server that replies to any datagram with the current timestamp, and a client that queries it five times and reports the round-trip time for each.
  2. The Loss Meter: Run the sequence-number example above, then deliberately flood the receiver by removing the time.sleep(0.001). Record how the loss percentage changes and explain which buffer overflowed.
  3. The Discovery Broadcast: Enable SO_BROADCAST and send a "WHO_IS_THERE" datagram to 255.255.255.255 on a chosen port. Write a responder that answers with its hostname, and explain in a comment why this pattern is impossible with TCP.