669  IoT Protocols Lab: CoAP vs MQTT

669.1 Learning Objectives

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

  • Compare CoAP and MQTT architectures: Understand request-response vs publish-subscribe patterns
  • Evaluate protocol overhead: Calculate header sizes and efficiency for each protocol
  • Select appropriate protocols: Choose CoAP or MQTT based on device constraints and use cases
  • Understand transport layer differences: Recognize when UDP (CoAP) vs TCP (MQTT) is appropriate
  • Apply QoS levels: Match reliability requirements to MQTT QoS or CoAP confirmable messages

What is this chapter? Deep comparison of the two most popular IoT application protocols: CoAP and MQTT.

Why it matters: - Wrong protocol choice wastes battery life or misses reliability requirements - CoAP excels for constrained devices with direct communication - MQTT excels for scalable telemetry with broker-based distribution

Prerequisites: - IoT Protocols Lab: IPv6 and 6LoWPAN - IoT Protocols Fundamentals

669.2 Application Layer Protocols

Traditional application protocols (HTTP, XMPP) are resource-demanding and not suitable for constrained IoT devices.

669.2.1 Why Not Use HTTP?

HTTP (Hypertext Transfer Protocol):

Overhead:

HTTP GET Request (minimum):
GET / HTTP/1.1\r\n
Host: example.com\r\n
\r\n

Size: ~40 bytes (just headers, no data)

HTTP Response:
HTTP/1.1 200 OK\r\n
Content-Type: application/json\r\n
Content-Length: 10\r\n
\r\n
{"temp":25}

Size: ~70 bytes headers + 10 bytes data = 80 bytes
Total exchange: ~120 bytes

Issues for IoT: - Verbose: Text-based, human-readable (wasteful for M2M) - TCP-based: Connection overhead - Stateful: Requires connection management - No pub/sub: Request-response only

When HTTP is OK: - Gateways: IoT gateway to cloud (mains-powered, reliable network) - RESTful APIs: Cloud services - Infrequent: Configuration, firmware updates

669.2.2 IoT-Specific Application Protocols

The two most popular IoT application protocols: 1. CoAP (Constrained Application Protocol) 2. MQTT (Message Queue Telemetry Transport)

669.3 CoAP vs MQTT Comparison

%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#E67E22', 'secondaryColor': '#16A085', 'tertiaryColor': '#E8F6F3', 'clusterBkg': '#E8F6F3', 'clusterBorder': '#16A085', 'fontSize': '12px'}}}%%
graph TB
    subgraph CoAP["CoAP Architecture"]
        Sensor1["IoT Sensor<br/>(Client)"]
        Gateway1["Gateway/Server"]

        Sensor1 -->|"GET /temp<br/>(4-byte header)"| Gateway1
        Gateway1 -->|"2.05 Content<br/>temp=23°C"| Sensor1
    end

    subgraph MQTT["MQTT Architecture"]
        Sensor2["IoT Sensor<br/>(Publisher)"]
        Broker["MQTT Broker"]
        App["Dashboard App<br/>(Subscriber)"]

        Sensor2 -->|"PUBLISH<br/>topic: sensors/temp"| Broker
        Broker -->|"PUBLISH<br/>temp=23°C"| App
    end

    CoAP -.->|vs| MQTT

    Note1["CoAP: Request-Response<br/>UDP, 4-byte header<br/>Constrained devices"]
    Note2["MQTT: Publish-Subscribe<br/>TCP, 2-byte header + topic<br/>Scalable, reliable"]

    Note1 -.-> CoAP
    Note2 -.-> MQTT

    style Sensor1 fill:#2C3E50,stroke:#16A085,color:#fff
    style Gateway1 fill:#16A085,stroke:#2C3E50,color:#fff
    style Sensor2 fill:#2C3E50,stroke:#16A085,color:#fff
    style Broker fill:#E67E22,stroke:#2C3E50,color:#fff
    style App fill:#16A085,stroke:#2C3E50,color:#fff

Figure 669.1: CoAP vs MQTT Communication Pattern Comparison

{fig-alt=“Comparison of CoAP and MQTT architectures showing CoAP’s request-response pattern between sensor and gateway using UDP with 4-byte headers versus MQTT’s publish-subscribe pattern with broker mediating between sensor publisher and dashboard subscriber using TCP”}

669.3.1 Detailed Comparison

Aspect CoAP MQTT
Model Request-Response (1-to-1) Publish-Subscribe (many-to-many)
Transport UDP (connectionless) TCP (connection-oriented)
Messaging RESTful (GET, POST, PUT, DELETE) Pub/Sub topics
Overhead Low (4-byte header) Medium (2-byte fixed + variable)
Reliability Optional (Confirmable messages) QoS levels (0, 1, 2)
Power Very low (UDP, no broker connection) Higher (TCP, always connected)
Real-Time Excellent (UDP, no broker hop) Good (broker adds latency)
Scalability Moderate (P2P connections) Excellent (broker decouples)
Discovery Built-in (Resource Discovery) None (app-level)
Security DTLS TLS (MQTTS)
Multicast Yes (UDP multicast) No (TCP point-to-point)
Message Size Small (UDP constraints) Flexible (TCP streaming)
Complexity Lower (simple devices) Higher (broker required)
Best For Constrained devices, real-time Data collection, dashboards

669.3.2 CoAP (Constrained Application Protocol)

NoteCoAP Characteristics

RESTful Design: - Mirrors HTTP (GET, POST, PUT, DELETE) - URI-based resources (coap://example.com/sensor/temp) - Content types (JSON, CBOR, XML)

Built for UDP: - Connectionless (low overhead) - Optional reliability (Confirmable vs Non-Confirmable) - Multicast support (discover devices)

Lightweight: - 4-byte header (vs 40+ HTTP) - Binary protocol (efficient parsing) - Small code footprint (~10 KB)

Features: - Resource discovery: /.well-known/core - Observe: Subscribe to resource changes - Block transfer: Large data in chunks

Use Cases: - Sensor readings (temperature, humidity) - Actuator control (lights, locks) - Device configuration - Resource-constrained networks

CoAP Message Example:

GET /sensor/temp
Host: fe80::1234

CoAP Header (4 bytes):
- Version, Type, Token Length, Code: 4 bytes
- Message ID: included

Total: ~20 bytes (including URI path)

vs HTTP: ~40 bytes minimum

669.3.3 MQTT (Message Queue Telemetry Transport)

NoteMQTT Characteristics

Publish-Subscribe: - Producers (sensors) publish to topics - Consumers (apps) subscribe to topics - Broker decouples publishers and subscribers

Designed for Telemetry: - Many sensors → Few subscribers - Persistent connections (TCP) - Quality of Service (QoS) levels

Lightweight (for TCP): - 2-byte fixed header + variable header - Binary protocol - Compact topic names

QoS Levels: - QoS 0: At most once (fire and forget) - QoS 1: At least once (acknowledged) - QoS 2: Exactly once (guaranteed)

Features: - Retained messages: Last value available to new subscribers - Last Will and Testament: Notify on disconnect - Clean session: Persistent vs ephemeral

Use Cases: - Telemetry collection (many sensors → cloud) - Dashboard updates (real-time monitoring) - Command distribution (cloud → devices) - Mobile apps (unreliable networks)

MQTT Topic Example:

Publishers:
- Sensor 1: Publish to "home/bedroom/temperature"
- Sensor 2: Publish to "home/kitchen/temperature"

Subscribers:
- Dashboard: Subscribe to "home/+/temperature" (all rooms)
- Logger: Subscribe to "home/#" (all topics under home)

Broker: Routes messages from publishers to subscribers

669.3.4 CoAP vs MQTT: When to Use

ImportantSelection Guide

Use CoAP when: - Constrained devices: Limited RAM/CPU (< 32 KB RAM) - Real-time: Low latency critical - Multicast: Need to address multiple devices simultaneously - Power-constrained: Battery-powered sensors - Direct M2M: Machine-to-machine without broker - RESTful: Web-style API desired - Example: Temperature sensor reporting to gateway

Use MQTT when: - Scalability: Many publishers, many subscribers - Reliable network: TCP acceptable (Wi-Fi, Ethernet, cellular) - Guaranteed delivery: QoS critical - Decoupling: Publishers/subscribers don’t know each other - Dashboard/monitoring: Real-time data visualization - Cloud integration: MQTT brokers widely supported - Example: Factory sensors → cloud → monitoring dashboard

Consider Hybrid: - CoAP for sensor → gateway (constrained network) - MQTT for gateway → cloud (reliable network)

669.5 Knowledge Check

  1. Which protocol choice best matches “many devices sending telemetry to the cloud with topic-based fan-out to multiple consumers”?

MQTT is designed around publish/subscribe with a broker, which fits telemetry fan-in and topic-based distribution to multiple subscribers.

  1. Which protocol is most aligned with a REST-like model (GET/PUT/POST/DELETE) for constrained devices over UDP?

CoAP is a constrained, RESTful application protocol typically transported over UDP, making it a good fit for lightweight request/response interactions.

669.6 Summary

This chapter compared the two dominant IoT application layer protocols:

  • HTTP is too verbose for IoT with 40+ byte headers and TCP connection overhead, making it unsuitable for constrained devices
  • CoAP provides RESTful semantics over UDP with a 4-byte header, multicast support, and optional reliability via confirmable messages
  • MQTT enables scalable pub/sub telemetry with broker decoupling, QoS levels (0/1/2), and features like retained messages and Last Will
  • Choose CoAP for constrained devices requiring low latency, multicast, or direct M2M communication with minimal power consumption
  • Choose MQTT for scalable data collection where many publishers feed dashboards and cloud services through a central broker
  • Hybrid architectures work well: CoAP from sensors to gateway, MQTT from gateway to cloud

669.7 What’s Next

With CoAP and MQTT characteristics understood, learn to systematically select protocols for your IoT projects: