4  User Datagram Protocol (UDP)

In 60 Seconds

UDP is a connectionless transport protocol that deliberately omits reliability features (acknowledgments, ordering, flow control) to achieve minimal overhead with just an 8-byte header. This makes UDP ideal for battery-powered IoT sensors sending periodic telemetry, where a missed reading is simply replaced by the next one. UDP also serves as the foundation for IoT-optimized protocols like CoAP and MQTT-SN.

4.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Explain UDP fundamentals: Describe what makes UDP a connectionless, lightweight protocol and justify its design choices
  • Analyze header structure: Identify the four UDP header fields, their bit sizes, and their specific purposes
  • Compare UDP vs TCP: Evaluate the trade-offs and select the appropriate transport protocol for a given IoT scenario
  • Apply to IoT scenarios: Classify IoT protocols (CoAP, MQTT-SN, DNS, NTP) by how they leverage UDP’s properties
  • Construct reliable systems: Implement application-layer reliability on top of UDP using CoAP Confirmable messages
  • Calculate overhead impact: Assess the energy and bandwidth cost of UDP versus TCP for constrained IoT devices

4.2 Prerequisites

Before diving into this chapter, you should be familiar with:

MVU: UDP’s Design Philosophy

Core Concept: UDP deliberately omits reliability features (acknowledgments, ordering, flow control) to achieve minimal overhead and maximum speed.

Why It Matters: In IoT, every byte and millisecond counts. A temperature sensor sending readings every 5 seconds doesn’t need TCP’s reliability - if one reading is lost, the next one replaces it. UDP’s 8-byte header vs TCP’s 20+ bytes saves battery life across millions of transmissions.

Key Takeaway: UDP is not “broken TCP” - it’s a deliberate design choice that shifts reliability responsibility to the application layer, enabling protocols like CoAP to add exactly the reliability features needed without TCP’s overhead.

Sammy the Sensor says: “Hi friends! Let me tell you about UDP - the super-fast messenger!”

4.2.1 UDP is Like Throwing Paper Airplanes!

Imagine you want to send a message to your friend across the playground:

TCP Way (Like Sending a Letter):

  1. You call your friend: “Hey, are you ready to receive?”
  2. Friend calls back: “Yes, I’m ready!”
  3. You send the letter
  4. Friend calls: “Got it!”
  5. You wave goodbye
  6. Friend waves back
  • SO MANY STEPS!

UDP Way (Like Paper Airplanes):

  1. Write message on paper airplane
  2. THROW IT!
  3. Done!

Cartoon comparing UDP to throwing paper airplanes: fast one-step delivery with no confirmation versus TCP multi-step registered mail

UDP is like throwing paper airplanes - fast but no guarantee!
Figure 4.1: UDP is like throwing paper airplanes - fast but no guarantee!

4.2.2 Why Would Anyone Use UDP?

Light Lucy asks: “But what if the airplane gets lost?”

Sammy explains: “Good question! UDP is perfect when:

  • Speed matters most: Like when you’re playing an online game - you need to move NOW!
  • Messages keep coming: Like a temperature sensor sending “72F… 72F… 73F…” If one gets lost, the next one is already on its way!
  • One message to EVERYONE: UDP can throw the airplane to ALL your friends at once (that’s called multicast)!”

4.2.3 Real Examples for Kids

What You Use Why UDP is Perfect
Video calls A tiny glitch is OK, but lag is annoying!
Online games Your character must move RIGHT NOW
Weather updates New temperature coming in 5 seconds anyway
Voice assistants “Hey Alexa” needs instant response

4.2.4 The Sensor Squad Summary

Motion Marley says: “Remember kids - UDP is the FAST messenger. Not always reliable, but SUPER quick! Use it when speed beats perfection!”

Simple Definition: UDP (User Datagram Protocol) is like sending a postcard - quick and cheap, but you never know if it arrived.

4.2.5 What Makes UDP Different from TCP?

Feature UDP TCP
Connection No setup needed Must shake hands first
Reliability Hope for the best Guaranteed delivery
Speed Very fast Slower (waits for ACKs)
Order May arrive jumbled Always in order
Size 8-byte header 20+ byte header

4.2.6 When to Use UDP

Good for UDP:

  • Sensor readings that update frequently
  • Live video/audio streaming
  • Online gaming
  • DNS lookups
  • Time synchronization (NTP)

Bad for UDP:

  • File transfers (need complete file)
  • Web pages (need all HTML)
  • Email (can’t lose content)
  • Financial transactions (accuracy critical)

4.2.7 Key Terms

Term Simple Meaning
Datagram A single packet of data sent via UDP
Connectionless No need to establish connection first
Best-effort Will try to deliver, but no promises
Checksum Math trick to detect corrupted data
Port Address number for an application

4.3 User Datagram Protocol (UDP)

Time: ~15 min | Level: Intermediate | ID: P07.C31.U02

UDP is a connectionless protocol with very low overhead and fast transmission, but no guarantee for message delivery. It provides a thin layer above IP, adding only port numbers and an optional checksum.

4.3.1 UDP Characteristics

UDP connectionless workflow showing sender transmitting datagrams directly without establishing a connection or waiting for acknowledgment

UDP Connectionless Communication - No handshake, just send!
Figure 4.2: UDP Connectionless Communication - No handshake, just send!
UDP Properties Summary

Connectionless:

  • No connection establishment (no handshake)
  • No connection state maintained
  • Each datagram independent

Unreliable (Best-Effort):

  • No acknowledgments: Sender doesn’t know if received
  • No retransmission: Lost packets are not resent
  • No ordering: Packets may arrive out of order
  • No flow control: Can overwhelm receiver

Lightweight:

  • Small header: 8 bytes only
  • Minimal processing: No state, no retransmission logic
  • Low latency: Immediate transmission

Use Cases:

  • Sensor readings (temperature, humidity)
  • Real-time data (video streaming, voice)
  • DNS queries
  • IoT telemetry (CoAP, MQTT-SN)

4.3.2 UDP Header Structure

UDP 8-byte header structure with four 16-bit fields: source port, destination port, length, and checksum

UDP Header Structure - Only 8 bytes of overhead
Figure 4.3: UDP Header Structure - Only 8 bytes of overhead

UDP Header Fields:

Field Size Purpose
Source Port 16 bits Sending application’s port (optional, can be 0)
Destination Port 16 bits Receiving application’s port
Length 16 bits Total length (header + data) in bytes
Checksum 16 bits Error detection (optional in IPv4, mandatory in IPv6)

Total Header: 8 bytes (minimal overhead)

Maximum Payload: 65,507 bytes (65,535 - 20 IP header - 8 UDP header)

Side-by-side comparison of UDP 8-byte header versus TCP 20-byte minimum header showing TCP's additional sequence and control fields

UDP vs TCP Header - UDP is 60% smaller!
Figure 4.4: UDP vs TCP Header - UDP is 60% smaller!

TCP needs extra fields (sequence/ack numbers, flags, window) to provide reliability and flow control that UDP sacrifices for simplicity.

Overhead Comparison for 50-byte sensor payload:

Protocol Header Total Packet Overhead %
UDP 8 bytes 58 bytes 13.8%
TCP (min, no options) 20 bytes 70 bytes 28.6%
TCP (with 20B of options) 40 bytes 90 bytes 44.4%
Quick Check: UDP Header Fields

4.3.3 UDP in the Protocol Stack

Understanding where UDP fits in the network stack helps visualize how data flows from applications to the network:

Protocol stack showing UDP data encapsulated with UDP header, then IP header, then link-layer frame for network transmission

UDP Encapsulation in the Protocol Stack
Figure 4.5: UDP Encapsulation in the Protocol Stack

Encapsulation Example (50-byte sensor reading):

Layer Added Header Total Size
Application 0 bytes 50 bytes
UDP 8 bytes 58 bytes
IP 20 bytes 78 bytes
802.15.4 25 bytes 103 bytes

Overhead: 53 bytes (106%) for a 50-byte payload - this is why minimizing header size matters in IoT!

4.3.4 Interactive: UDP vs TCP Overhead Calculator

Use this calculator to compare protocol overhead for different payload sizes. Adjust the payload to see how UDP’s efficiency advantage changes.

4.3.5 Interactive: IoT Battery Life Estimator

Estimate how long a battery-powered sensor will last with different protocol choices.

4.3.6 Why UDP for IoT?

Diagram highlighting UDP advantages for IoT: low overhead, low power, multicast support, real-time performance, and simple implementation

Why UDP is the Protocol of Choice for IoT
Figure 4.6: Why UDP is the Protocol of Choice for IoT

Advantages:

  1. Low Overhead: 8-byte header vs 20-byte TCP header
  2. Low Power: No connection state = less memory, less processing
  3. Simplicity: Easy to implement on constrained devices
  4. Multicast/Broadcast: UDP supports one-to-many communication
  5. Real-Time: No retransmission delays

Disadvantages:

  1. Unreliable: Packets may be lost
  2. Unordered: Packets may arrive out of sequence
  3. No Congestion Control: Can overwhelm network

IoT Applications Using UDP:

Application Protocol Why UDP?
RESTful IoT CoAP Low overhead, supports multicast
Pub/Sub Sensors MQTT-SN Simple, broadcast discovery
Name Resolution DNS Single request-response
Time Sync NTP Low latency critical
Network Management SNMP Simple polling model
Streaming RTP/RTSP Latency over reliability

4.3.7 UDP Analogy: Traditional Mail vs Registered Mail

UDP is Like Traditional Mail

UDP is often compared to traditional mail delivery:

  • You write a letter (create datagram)
  • Drop it in mailbox (send datagram)
  • No acknowledgment that it was received
  • Don’t know if it was lost, delivered, or delayed
  • Can’t guarantee letters arrive in order you sent them

Example:

  • You mail 3 letters: Monday, Tuesday, Wednesday
  • They might arrive: Wednesday, Monday (Tuesday lost)
  • You won’t know Tuesday letter was lost unless recipient tells you

TCP would be like: Sending via registered mail with signature required, return receipt, and numbered tracking for every letter!

Mail analogy comparing UDP to dropping postcards in mailbox with no tracking versus TCP as registered mail with signature and receipt

UDP vs TCP: Mail Analogy
Figure 4.7: UDP vs TCP: Mail Analogy

4.3.8 Practical Example: UDP Packet Analysis

Let’s analyze a real UDP packet carrying a CoAP temperature reading:

Annotated UDP packet carrying CoAP temperature reading showing 8-byte UDP header fields and 20-byte CoAP payload breakdown

UDP Packet Analysis - CoAP Temperature Reading
Figure 4.8: UDP Packet Analysis - CoAP Temperature Reading
UDP Header (8 bytes):
16 33    - Source Port: 5683 (CoAP default)
16 33    - Destination Port: 5683
00 1C    - Length: 28 bytes
8A 4F    - Checksum

CoAP Payload (20 bytes):
44 01 00 01                  - CoAP Header (Ver=1, Type=CON, Code=GET)
01 02 03 04                  - Token
B4 74 65 6D 70               - Option: Uri-Path = "temp"
FF                           - Payload Marker
32 33 2E 35 43               - Payload: "23.5C"

Key Observations:

  • Port 5683 identifies this as CoAP traffic
  • Length (28) = 8 (header) + 20 (CoAP data)
  • No connection overhead - just data!

Energy Impact Analysis (802.15.4 radio at 250 kbps, 75 mW TX power):

Protocol Stack Bytes Transmitted TX Time Energy per Message
UDP + CoAP 28 bytes 0.90 ms 67.2 uJ
TCP + HTTP ~200 bytes 6.40 ms 480.0 uJ
Savings 172 bytes (86%) 5.50 ms (86%) 412.8 uJ (86%)

This 86% reduction in transmission size directly translates to longer battery life for IoT sensors.

4.4 Knowledge Checks

Test Your Understanding

Test your knowledge of UDP fundamentals with these questions.

4.5 Summary

In this chapter, we explored UDP (User Datagram Protocol), the lightweight transport protocol that powers most IoT communication.

Summary diagram of UDP key concepts: connectionless, 8-byte header, best-effort delivery, and IoT protocol foundation for CoAP and MQTT-SN

UDP Key Concepts Summary
Figure 4.9: UDP Key Concepts Summary

4.5.1 Key Takeaways

What You Should Remember
  1. UDP is deliberately simple: 8-byte header with only 4 fields (source port, destination port, length, checksum)

  2. Connectionless = No Handshake: Data is sent immediately without TCP’s 3-way handshake, saving time and energy

  3. Best-effort delivery: No acknowledgments, no retransmissions, no ordering - the application handles reliability if needed

  4. Perfect for IoT because:

    • 60% smaller header than TCP (8 vs 20+ bytes)
    • No connection state = less memory on constrained devices
    • Supports multicast/broadcast for device discovery
    • Real-time performance without retransmission delays
  5. Application-layer reliability: Protocols like CoAP add exactly the reliability features needed (confirmable messages) without TCP’s full overhead

  6. Know when to use it: UDP for periodic telemetry, real-time data, and discovery; TCP for file transfers and critical transactions

4.5.2 When-to-Use Decision Table

This decision table provides a systematic way to choose between UDP and TCP for any IoT data flow. Work through each row – if your application matches the UDP column for most rows, use UDP (or CoAP over UDP). If it matches TCP, use TCP (or MQTT over TCP).

Decision Factor Use UDP Use TCP Why It Matters
Data replaceability Next reading replaces lost one (temperature, humidity) Every value matters (firmware bytes, financial transactions) If data is replaceable, retransmission wastes energy for no benefit
Transmission frequency >1 message per minute <1 message per minute Frequent senders amortize connection cost poorly with TCP
Payload size <100 bytes >1,000 bytes UDP overhead is 8 bytes; for 50-byte payloads, that is 13.8% vs TCP’s 28.6% minimum
Power source Battery (2-10 year target) Mains-powered or recharged daily TCP handshake + keep-alive costs ~0.3 mAh/day minimum
Device RAM <64 KB SRAM >256 KB SRAM TCP connection state needs ~4 KB per connection
Latency tolerance Must respond <50 ms Can tolerate 100-500 ms TCP handshake adds 1.5 RTT before first data byte
Loss tolerance 1-5% loss acceptable 0% loss required UDP makes no delivery guarantees
Multicast needed Yes (device discovery, group control) No TCP cannot multicast; UDP supports it natively
Network type Any network with CoAP CON for reliability Lossy WAN where TCP’s congestion control helps (e.g., file transfer) UDP works on lossy links when paired with CoAP CON; raw UDP NON suits links where loss is tolerable
Existing infrastructure CoAP gateway available MQTT broker deployed Switching transport protocol affects the entire stack

Worked example applying the table:

A smart agriculture deployment has two data flows:

  1. Soil moisture readings (500 sensors, every 15 minutes, 32 bytes, battery-powered, 5% loss acceptable): Score 8/10 for UDP. Use CoAP over UDP with NON-confirmable messages.

  2. Irrigation valve commands (50 actuators, on-demand, 16 bytes, mains-powered, 0% loss required): Score 8/10 for TCP. Use MQTT QoS 1 over TCP with persistent connections.

4.5.3 Quick Reference Table

Aspect UDP TCP
Header Size 8 bytes 20-60 bytes
Connection None 3-way handshake
Reliability Best-effort Guaranteed
Ordering No Yes
Flow Control No Yes
Multicast Yes No
IoT Use Cases Sensors, streaming File transfer, commands
Energy Impact Low High
Concept Relationships

Depends on:

Enables:

  • CoAP Protocol - CoAP builds application-layer reliability on top of UDP’s lightweight transport
  • MQTT Fundamentals - MQTT messaging patterns, including MQTT-SN for UDP transport
  • DTLS Security - Datagram TLS secures UDP without TCP overhead

Related concepts:

  • UDP’s 8-byte header vs TCP’s 20-byte minimum creates 60% overhead reduction for small IoT payloads
  • UDP multicast enables one-to-many device discovery impossible with TCP’s point-to-point connections
  • UDP checksum is optional in IPv4 but mandatory in IPv6 to detect wireless link corruption
See Also

Fundamentals:

Applications:

External resources:

Common Pitfalls

UDP eliminates TCP handshake (saving 1 RTT) and header overhead (saving 12 bytes per packet). But these savings are often insignificant: for a sensor sending one 50-byte reading per minute, saving 12 bytes/reading = 17.3 KB/year — negligible. UDP’s real advantage is for: real-time streaming (voice, video) where TCP retransmissions cause unacceptable latency, or constrained devices where TCP stack doesn’t fit. For infrequent sensor reporting, TCP simplifies the application stack without meaningful performance cost.

UDP datagrams larger than the path MTU (typically 1280–1500 bytes) are fragmented at the IP layer. If any IP fragment is lost, the entire UDP datagram is discarded — there is no partial delivery. IP fragmentation also increases packet loss probability multiplicatively: a path with 1% packet loss probability has 3.9% datagram loss for a 4-fragment datagram. Size UDP payloads to stay below the path MTU minus headers (IP: 20–40 bytes, UDP: 8 bytes): target <1232 bytes for IPv6 (guaranteed 1280 MTU - 40 IP - 8 UDP).

UDP provides no delivery confirmation. Critical IoT commands (open emergency valve, trigger alarm, apply firmware update) sent over UDP may be silently lost. For critical commands, implement application-level acknowledgment: receiver sends explicit ACK packet with command ID; sender retransmits with exponential backoff until ACK received or MAX_RETRIES reached. CoAP Confirmable messages implement this pattern correctly — use CoAP rather than raw UDP for reliable command delivery.

UDP well-known ports are shared globally: CoAP uses 5683 (unencrypted) and 5684 (DTLS). Registering multiple services on the same port on the same device requires port multiplexing by the application. Using non-standard ports (e.g., UDP 8883 for MQTT-SN) without checking IANA registered ports may conflict with other applications. Register custom service ports with IANA or use the IANA dynamic port range (49152–65535) for non-standard services.

4.6 What’s Next

Now that you can explain UDP’s design, analyze its header, and evaluate its trade-offs, apply this knowledge to the following topics:

Topic Link Why It Matters
TCP Fundamentals transport-fund-tcp.html Compare reliable vs best-effort delivery; identify when TCP’s overhead is justified
Transport Protocols Overview transport-fund-overview.html Situate UDP and TCP within the broader transport layer design space
CoAP Protocol ../app-protocols/coap-fundamentals.html Build on UDP with optional confirmable messages for RESTful IoT communication
MQTT Fundamentals ../app-protocols/mqtt-fundamentals.html Distinguish TCP-based MQTT from UDP-based MQTT-SN for constrained sensor networks
DTLS Security transport-protocols-dtls.html Apply Datagram TLS to secure UDP communication without TCP overhead
Plain English Guide transport-prac-analogies.html Reinforce UDP vs TCP concepts through accessible analogies and worked scenarios