732  User Datagram Protocol (UDP)

732.1 User Datagram Protocol (UDP)

⏱️ ~15 min | ⭐⭐ Intermediate | 📋 P07.C31.U02

UDP is a connectionless protocol with very low overhead and fast transmission, but no guarantee for message delivery.

732.1.1 UDP Characteristics

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor':'#2C3E50','primaryTextColor':'#fff','primaryBorderColor':'#16A085','lineColor':'#16A085','secondaryColor':'#E67E22','tertiaryColor':'#ecf0f1','background':'#ffffff','mainBkg':'#2C3E50','secondBkg':'#16A085','tertiaryBorderColor':'#95a5a6','clusterBkg':'#ecf0f1','clusterBorder':'#95a5a6','titleColor':'#2C3E50','edgeLabelBackground':'#ffffff','nodeTextColor':'#2C3E50'}}}%%
graph LR
    S[Sender] -->|Datagram 1| N[Network]
    S -->|Datagram 2| N
    S -->|Datagram 3| N

    N -->|Deliver| R1[Receiver]
    N -.->|May be lost| X[X]
    N -.->|May reorder| O[3,1,2]

    R1 -.->|No ACK| S

    subgraph "UDP Features"
        F1[8-byte header]
        F2[No connection]
        F3[No retransmission]
        F4[Low latency]
    end

    style S fill:#16A085,stroke:#2C3E50,color:#fff
    style N fill:#95a5a6,stroke:#2C3E50,color:#fff
    style R1 fill:#16A085,stroke:#2C3E50,color:#fff
    style X fill:#e74c3c,stroke:#c0392b,color:#fff
    style O fill:#f39c12,stroke:#e67e22,color:#fff
    style F1 fill:#27ae60,stroke:#16a085,color:#fff
    style F2 fill:#2C3E50,stroke:#16A085,color:#fff
    style F3 fill:#2C3E50,stroke:#16A085,color:#fff
    style F4 fill:#27ae60,stroke:#16a085,color:#fff

Figure 732.1: UDP Connectionless Communication Workflow
UDP is connectionless and unreliable but lightweight - ideal for IoT telemetry where data loss is acceptable
NoteKnowledge Check

Test your understanding of fundamental concepts with these questions.

Question 3: A battery-powered sensor uses CoAP (over UDP) to send alerts. Approximately 30% of alerts are lost due to poor signal. What should you do?

💡 Explanation: CoAP Confirmable messages add reliability to UDP without TCP overhead:

CoAP Confirmable (CON) messages: - Application-layer ACK: Receiver sends ACK within 2 seconds - Exponential backoff retransmit: 2s, 4s, 8s, 16s (configurable) - Message deduplication: Message ID prevents processing duplicates - Lightweight: Single ACK packet vs TCP’s continuous ACKs

Why NOT TCP: - Connection overhead: 3-way handshake for each alert wastes energy - Keep-alive: TCP requires periodic keep-alive packets (battery drain) - Head-of-line blocking: One lost packet delays all subsequent packets - Overkill: Alert is single message, not a stream

Why NOT blind 3× retransmit: - Wasteful: Sends 3× messages even when 1st succeeds (70% of the time) - Network congestion: Triples bandwidth usage - No confirmation: Still don’t know if alert delivered

Energy comparison (single alert):

CoAP NON (non-confirmable):
- Send: 1 packet (might be lost)
- Energy: 1 TX

CoAP CON (confirmable):
- Send: 1 packet + ACK receive
- If lost: Retransmit (2-4 attempts typical)
- Energy: 1.3-2× TX (70% success first try)

TCP:
- Handshake: SYN, SYN-ACK, ACK (3 packets)
- Data: Alert + ACK (2 packets)
- Close: FIN, FIN-ACK, ACK (3 packets)
- Total: 8 packets
- Energy: 8× TX

Best practice: Use CoAP CON for critical alerts, NON for routine telemetry. This balances reliability with efficiency.

Question 7: UDP checksum is optional in IPv4 but mandatory in IPv6. Why is the checksum important for IoT applications?

💡 Explanation: UDP checksum is critical error detection for unreliable wireless networks:

What checksum detects: 1. Radio interference: 2.4 GHz Wi-Fi/BLE/Zigbee congestion flips bits 2. Weak signal: Low RSSI increases bit error rate (BER) 3. Memory corruption: Sensor MCU RAM bit flips (cosmic rays, voltage fluctuations) 4. Hardware errors: Faulty radio transceiver or antenna

Checksum calculation (UDP):

1. Sum all 16-bit words in:
   - Pseudo IP header (src/dst IP, protocol)
   - UDP header (ports, length)
   - UDP payload data
2. Add carries back into sum
3. Take one's complement
4. Result: 16-bit checksum

Error detection rate: - Single bit error: 100% detection - Burst errors: ~99.9% detection - Random errors: (1 - 2^-16) = 99.998% detection

Why NOT other answers: - B (encryption): Checksum is integrity, not confidentiality. Use DTLS for encryption. - C (retransmission): UDP has no retransmission. Checksum only detects, doesn’t correct. Application must handle. - D (compression): Checksum adds 2 bytes, doesn’t compress.

IoT wireless links: - Wi-Fi: ~10^-5 BER (1 error per 100,000 bits) - Zigbee: ~10^-3 BER (1 error per 1,000 bits) in noisy environments - 100-byte packet: ~0.8% chance of error in Zigbee

IPv6 makes checksum mandatory because: - No IP-layer checksum in IPv6 (unlike IPv4) - Transport layer must ensure integrity - Critical for IoT’s unreliable wireless links

Real-world: Checksum failures trigger CoAP retransmission or MQTT republish at application layer.

732.2 UDP Properties

Connectionless: - No connection establishment (no handshake) - No connection state maintained - Each datagram independent

Unreliable: - 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)

732.2.1 UDP Header Structure

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor':'#2C3E50','primaryTextColor':'#fff','primaryBorderColor':'#16A085','lineColor':'#16A085','secondaryColor':'#E67E22','tertiaryColor':'#ecf0f1','background':'#ffffff','mainBkg':'#2C3E50','secondBkg':'#16A085','tertiaryBorderColor':'#95a5a6','clusterBkg':'#ecf0f1','clusterBorder':'#95a5a6','titleColor':'#2C3E50','edgeLabelBackground':'#ffffff','nodeTextColor':'#2C3E50'}}}%%
graph TB
    subgraph "UDP Datagram"
        subgraph "Header: 8 bytes"
            H1[Source Port<br/>16 bits<br/>Optional]
            H2[Dest Port<br/>16 bits<br/>Required]
            H3[Length<br/>16 bits<br/>Header+Data]
            H4[Checksum<br/>16 bits<br/>IPv6: Mandatory]
        end
        subgraph "Data"
            D[Payload<br/>Up to 65,507 bytes]
        end
    end

    H1 --> D
    H2 --> D
    H3 --> D
    H4 --> D

    style H1 fill:#2C3E50,stroke:#16A085,color:#fff
    style H2 fill:#E67E22,stroke:#16A085,color:#fff
    style H3 fill:#2C3E50,stroke:#16A085,color:#fff
    style H4 fill:#16A085,stroke:#2C3E50,color:#fff
    style D fill:#27ae60,stroke:#16a085,color:#fff

Figure 732.2: UDP Packet Header Structure (8 Bytes)

This variant directly compares UDP and TCP headers to show why UDP is preferred for constrained devices:

%%{init: {'theme': 'base', 'themeVariables': {'primaryColor':'#2C3E50','primaryTextColor':'#fff','primaryBorderColor':'#16A085','lineColor':'#16A085','secondaryColor':'#E67E22','tertiaryColor':'#7F8C8D'}}}%%
flowchart LR
    subgraph UDP["UDP Header (8 bytes)"]
        U1["Src Port<br/>2B"]
        U2["Dst Port<br/>2B"]
        U3["Length<br/>2B"]
        U4["Checksum<br/>2B"]
    end

    subgraph TCP["TCP Header (20+ bytes)"]
        T1["Src Port<br/>2B"]
        T2["Dst Port<br/>2B"]
        T3["Seq Num<br/>4B"]
        T4["Ack Num<br/>4B"]
        T5["Flags<br/>2B"]
        T6["Window<br/>2B"]
        T7["Checksum<br/>2B"]
        T8["Options<br/>0-40B"]
    end

    RESULT["For 50-byte payload:<br/>UDP: 8B overhead (14%)<br/>TCP: 20B overhead (29%)"]

    UDP --> RESULT
    TCP --> RESULT

    style U1 fill:#16A085,stroke:#2C3E50,color:#fff
    style U2 fill:#16A085,stroke:#2C3E50,color:#fff
    style U3 fill:#16A085,stroke:#2C3E50,color:#fff
    style U4 fill:#16A085,stroke:#2C3E50,color:#fff
    style T1 fill:#E67E22,stroke:#2C3E50,color:#fff
    style T2 fill:#E67E22,stroke:#2C3E50,color:#fff
    style T3 fill:#E67E22,stroke:#2C3E50,color:#fff
    style T4 fill:#E67E22,stroke:#2C3E50,color:#fff
    style T5 fill:#E67E22,stroke:#2C3E50,color:#fff
    style T6 fill:#E67E22,stroke:#2C3E50,color:#fff
    style T7 fill:#E67E22,stroke:#2C3E50,color:#fff
    style T8 fill:#7F8C8D,stroke:#2C3E50,color:#fff
    style RESULT fill:#2C3E50,stroke:#16A085,color:#fff

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

UDP header is minimal at 8 bytes with only essential fields - enabling low overhead for IoT

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)

732.2.2 Why UDP 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: - CoAP (Constrained Application Protocol): RESTful for IoT - MQTT-SN (MQTT for Sensor Networks): Pub/sub for sensors - DNS: Domain name resolution - NTP: Network time synchronization - SNMP: Network management - Streaming: Real-time audio/video (when latency > reliability)

732.2.3 UDP Analogy

TipUDP 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

WarningTradeoff: UDP Header Efficiency vs TCP Header Features

Option A: UDP (8-byte header) - Source port (2B), destination port (2B), length (2B), checksum (2B). For a 50-byte sensor payload: 8B overhead = 13.8% protocol tax. Typical IoT transmission: 58 bytes total, 172 packets/second at 80 kbps.

Option B: TCP (20-60 byte header) - Adds sequence number (4B), acknowledgment (4B), flags (2B), window (2B), options (0-40B). For same 50-byte payload: 20-40B overhead = 29-44% protocol tax. Same scenario: 70-90 bytes total, 111-143 packets/second at 80 kbps.

Decision Factors: Choose UDP when payload is small (<100 bytes), packet loss is acceptable (sensor telemetry replacing old values), and battery life matters (UDP saves 12-30 bytes per packet = 2-5% battery for frequent transmissions). Choose TCP when data integrity is critical (firmware updates, configuration), session state is needed (bidirectional commands), or payloads are large (>500 bytes where header overhead becomes negligible at <4%).

WarningTradeoff: Per-Message Connection vs Persistent TCP Connection

Option A: Per-message TCP connections - Connect, send, disconnect for each reading. 3-way handshake (3 packets, ~150ms RTT), data transfer (1-2 packets), 4-way termination (4 packets). Total: 8-9 packets minimum per message. Battery cost: ~8x energy per message vs persistent connection.

Option B: Persistent TCP connection - One handshake, keep-alive every 30-120 seconds (configurable), send multiple messages over connection lifetime. Memory cost: 4-8 KB RAM per connection for buffers/state. Gateway limit: typically 1,000-10,000 concurrent connections.

Decision Factors: Use per-message for infrequent data (hourly reports) where 8-packet overhead is amortized over long sleep periods, or when RAM is extremely constrained (<16 KB). Use persistent connections when sending >12 messages/hour (break-even point where keep-alive overhead < repeated handshakes), when bidirectional communication is needed (commands to devices), or when latency matters (<50ms response vs 150ms handshake).