658  IoT Application Layer Protocols

CoAP vs MQTT and Protocol Comparison

NoteLearning Objectives

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

  • Compare CoAP and MQTT application protocols for IoT
  • Understand request-response vs publish-subscribe communication patterns
  • Use interactive tools to compare protocol characteristics
  • Identify when to use CoAP vs MQTT based on requirements
  • Understand the role of HTTP and AMQP in IoT systems

658.1 Application Layer: CoAP vs MQTT

The application layer defines how IoT devices exchange meaningful data. Two protocols dominate: CoAP (Constrained Application Protocol) and MQTT (Message Queue Telemetry Transport).

658.1.1 Communication Patterns

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#E8F6F3'}}}%%
graph TB
    subgraph "Request-Response (CoAP)"
        Client1["Client<br/>(Sensor)"]
        Server1["Server<br/>(Gateway)"]
        Client1 -->|"GET /temperature"| Server1
        Server1 -->|"2.05 Content: 25.5°C"| Client1
    end

    subgraph "Publish-Subscribe (MQTT)"
        Pub["Publisher<br/>(Sensor)"]
        Broker["MQTT Broker"]
        Sub1["Subscriber<br/>(Dashboard)"]
        Sub2["Subscriber<br/>(Logger)"]
        Pub -->|"PUBLISH home/temp: 25.5"| Broker
        Broker -->|"25.5°C"| Sub1
        Broker -->|"25.5°C"| Sub2
    end

    style Client1 fill:#16A085,stroke:#2C3E50,color:#fff
    style Server1 fill:#2C3E50,stroke:#16A085,color:#fff
    style Pub fill:#E67E22,stroke:#2C3E50
    style Broker fill:#2C3E50,stroke:#16A085,color:#fff
    style Sub1 fill:#7F8C8D,stroke:#2C3E50,color:#fff
    style Sub2 fill:#7F8C8D,stroke:#2C3E50,color:#fff

Figure 658.1: Request-response (CoAP) vs Publish-subscribe (MQTT) communication patterns

{fig-alt=“Two communication patterns: CoAP showing client-server request-response with GET and Content messages, MQTT showing publisher sending to broker which fans out to multiple subscribers”}

658.1.2 CoAP (Constrained Application Protocol)

Overview: CoAP is “HTTP for IoT” - a RESTful protocol designed for constrained devices and networks.

Characteristic CoAP Comparison
Transport UDP (port 5683) No connection overhead
Header size 4 bytes fixed vs HTTP ~200+ bytes
Message types CON, NON, ACK, RST Confirmable or fire-and-forget
Methods GET, PUT, POST, DELETE Same as HTTP REST
Security DTLS Datagram TLS for UDP
Observation Observe option Server push notifications

CoAP Message Format:

 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Ver| T |  TKL  |      Code     |          Message ID           |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|   Token (0-8 bytes)           |                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+                               +
|                                                               |
|                       Options (if any)                        |
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|1 1 1 1 1 1 1 1|    Payload (if any)                           |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

CoAP Message Types: - CON (Confirmable): Requires ACK, provides reliability - NON (Non-confirmable): Fire-and-forget, no ACK - ACK (Acknowledgment): Response to CON - RST (Reset): Reject message or indicate error

658.1.3 MQTT (Message Queue Telemetry Transport)

Overview: MQTT is a lightweight publish-subscribe protocol optimized for unreliable networks.

Characteristic MQTT Comparison
Transport TCP (port 1883, 8883 for TLS) Reliable delivery
Header size 2 bytes minimum Very compact
Message types CONNECT, PUBLISH, SUBSCRIBE… Full message lifecycle
QoS levels 0, 1, 2 At-most-once to exactly-once
Security TLS Standard TCP encryption
Broker Required Central message routing

MQTT QoS Levels: - QoS 0 (At most once): Fire-and-forget, no acknowledgment - QoS 1 (At least once): Acknowledged delivery, may duplicate - QoS 2 (Exactly once): Four-way handshake, guaranteed single delivery

MQTT Fixed Header:

 7 6 5 4 3 2 1 0
+-+-+-+-+-+-+-+-+
| Type  |D|Q|R|  <- Control packet type + flags
+-+-+-+-+-+-+-+-+
| Remaining Length (1-4 bytes, variable)
+-+-+-+-+-+-+-+-+-+-+...

658.1.4 Side-by-Side Comparison

Feature CoAP MQTT
Architecture Client-Server Publish-Subscribe
Transport UDP TCP
Overhead 4 bytes + options 2 bytes + topic
Reliability Application layer (CON/NON) Transport layer (TCP) + QoS
Power Lower (connectionless) Higher (keep-alive)
Scalability Direct 1-to-1 Broker handles fan-out
Latency Lower (no handshake) Higher (TCP setup)
Multicast Native support Requires broker topics
Discovery CoRE Link Format Topic conventions
Caching Built-in (ETag, Max-Age) Application-level
Best for Constrained devices, local control Cloud telemetry, many subscribers

Use CoAP when: - Device is battery-powered (no TCP keep-alive drain) - Device has < 32KB RAM (smaller stack) - You need direct device-to-device communication - Low latency is critical (no TCP handshake) - You want RESTful API style (GET/PUT/POST)

Use MQTT when: - Many devices send to one cloud (fan-in) - One message goes to many subscribers (fan-out) - You need guaranteed delivery (QoS 1/2) - Device is mains-powered (can afford TCP overhead) - Cloud platform already uses MQTT (AWS IoT, Azure IoT Hub)

Hybrid Approach: Many IoT systems use both:

[Sensor] --CoAP/UDP--> [Gateway] --MQTT/TCP--> [Cloud]
  • CoAP for battery-efficient sensor-to-gateway
  • MQTT for reliable gateway-to-cloud

658.2 Interactive Protocol Comparison Tool

Use this advanced tool to compare IoT application protocols across multiple dimensions:

TipHow to Use This Protocol Analyzer
  1. Select Protocols: Check 2-3 protocols from the list above to compare them
  2. Analyze the Radar Chart: The radar chart shows 8 key metrics on a 0-10 scale (higher = better). Each protocol appears as a colored polygon - larger areas indicate better overall performance
  3. Review Bar Charts: Compare protocols side-by-side across individual metrics
  4. Read Recommendations: Use case-specific guidance appears at the bottom based on your selection

Understanding the Metrics:

  • Bandwidth Efficiency: How well the protocol uses available bandwidth (low overhead = high score)
  • Latency: Response time (lower latency = higher score)
  • Power Efficiency: Battery life impact (lower power consumption = higher score)
  • Security: Built-in security features and robustness
  • Simplicity: Ease of implementation and understanding
  • Scalability: Ability to handle many devices/connections
  • Reliability: Message delivery guarantees
  • Low Overhead: Header size and protocol overhead (smaller = higher score)

658.3 Other Application Protocols

658.3.1 HTTP for IoT

While not optimized for constrained devices, HTTP remains important for: - Gateway-to-cloud communication: RESTful APIs - Configuration interfaces: Web-based device management - Integration: Connecting to existing web services

HTTP/2 improvements for IoT: - Header compression (HPACK) - Multiplexing (multiple requests per connection) - Server push

658.3.2 AMQP (Advanced Message Queuing Protocol)

Enterprise-grade messaging with: - Complex routing rules - Transactional guarantees - Message acknowledgments - Queue persistence

Best for: Industrial automation, financial systems, enterprise IoT

658.3.3 WebSocket

Full-duplex communication for: - Real-time dashboards - Live data streaming - Browser-based IoT interfaces

Question: An industrial monitoring system compares CoAP (UDP-based, 4-byte header) vs MQTT (TCP-based, 2-byte header + TCP overhead) for 500 sensors sending 10-byte readings every 30 seconds. Network analysis shows 15% packet loss. CoAP uses confirmable messages with exponential backoff averaging 1.2s including retries. MQTT uses TCP retransmission (200ms RTT) but requires 600ms TCP connection setup. Which protocol minimizes latency for real-time alerts while handling packet loss?

Explanation: For real-time industrial monitoring, CoAP’s connectionless UDP provides: (1) No TCP setup delay (600ms savings), (2) Lower total overhead (32 bytes: 6+4+4+10 for 6LoWPAN+UDP+CoAP+data vs 42 bytes: 6+20+2+10 for 6LoWPAN+TCP+MQTT+data), (3) Predictable 1.2s average latency including retries, (4) No connection state management required. Despite MQTT’s smaller application header (2 bytes vs 4), the TCP overhead (20 bytes) makes total packet size larger. CoAP excels for direct sensor-to-gateway communication in lossy industrial environments where sensors sleep/wake intermittently.

Question: A healthcare IoT system transmits ECG data (250 Hz sampling, 2 bytes/sample = 500 bytes/sec) from wearables to monitoring stations. IEEE 802.15.4 provides 250 kbps with 102-byte usable payload. The application requires < 100ms latency for arrhythmia detection. Comparing protocol stacks: HTTP/TCP/IPv4 (162 bytes overhead), MQTT/TCP/6LoWPAN (94 bytes overhead), and CoAP/UDP/6LoWPAN (39 bytes overhead), which minimizes transmission time and meets latency requirements?

Explanation: For real-time medical IoT, CoAP/UDP/6LoWPAN provides: (1) Minimal overhead (39 bytes) allows 63-byte payload in single 102-byte frame, (2) No fragmentation for typical sensor readings, (3) Lowest latency: 1.89ms (CoAP) vs 8.65ms (MQTT with TCP overhead) vs 10.82ms (HTTP), (4) Connectionless operation ideal for intermittent wearable sensors, (5) Best payload efficiency: 33.9% vs 17.5% (MQTT) vs 11.0% (HTTP). HTTP requires 162 bytes overhead needing 2+ frames just for headers. While all technically meet 100ms requirement, CoAP provides 4.6x lower latency than MQTT.

658.4 Summary

TipKey Takeaways

CoAP (Constrained Application Protocol): - RESTful semantics (GET/PUT/POST/DELETE) like HTTP - UDP transport with 4-byte header - Confirmable (CON) or Non-confirmable (NON) messages - Best for: constrained devices, low power, direct communication

MQTT (Message Queue Telemetry Transport): - Publish-subscribe pattern with broker - TCP transport with 2-byte minimum header - QoS 0/1/2 for delivery guarantees - Best for: cloud telemetry, many subscribers, reliable delivery

Protocol Selection: - Battery-powered sensors: CoAP (no keep-alive overhead) - Cloud dashboards: MQTT (broker scales subscribers) - Web integration: HTTP (universal compatibility) - Enterprise messaging: AMQP (transactional guarantees) - Real-time browser: WebSocket (full-duplex)

Hybrid Architecture: Most IoT systems use multiple protocols:

[Sensor] --CoAP--> [Gateway] --MQTT--> [Cloud] --HTTP--> [App]

658.5 What’s Next?

Continue to Protocol Selection Guide for comprehensive decision frameworks and interactive tools to choose the right protocol combination for your IoT deployment.