CoAP GET/PUT/POST/DELETE: RESTful methods mirroring HTTP, carried over UDP with minimal overhead
MQTT Broker: A server that receives all published messages and routes them to subscribed clients; Mosquitto and HiveMQ are common choices
Retained Message: An MQTT message stored by the broker and delivered immediately to new subscribers, providing last-known-value semantics
Will Message: An MQTT message the broker sends on behalf of a client that disconnects unexpectedly, useful for device-offline alerts
CoAP Observe: An extension that allows a CoAP client to subscribe to resource updates, similar to MQTT subscriptions
Wireshark Dissector: A plugin that decodes CoAP or MQTT packets for inspection; essential for debugging protocol interactions
Loopback Testing: Running both client and broker/server on the same machine (localhost) to isolate protocol behaviour from network issues
32.1 In 60 Seconds
CoAP runs over UDP with a 4-byte base header, making it ideal for constrained devices with direct request-response communication. MQTT runs over TCP with a 2-byte minimum header, excelling at scalable publish-subscribe telemetry through a broker. This lab compares their architectures, overhead, QoS mechanisms, and transport layer trade-offs to help you choose the right protocol for your deployment.
32.2 Learning Objectives
By the end of this chapter, you will be able to:
Compare CoAP and MQTT architectures: Differentiate request-response and publish-subscribe patterns
Calculate protocol overhead: Compute header sizes and payload efficiency for each protocol
Select appropriate protocols: Justify CoAP or MQTT choice based on device constraints and use cases
Analyse transport layer trade-offs: Determine when UDP (CoAP) versus TCP (MQTT) is appropriate
Apply QoS levels: Match reliability requirements to MQTT QoS or CoAP confirmable messages
For Beginners: What You’ll Learn
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
The key takeaway is the 2.1x ratio: uncompressed MQTT/TCP/IPv6 transmits roughly twice the bytes per reading compared to 6LoWPAN-compressed CoAP/UDP, directly translating to proportionally higher radio energy consumption per packet.
Try It: Protocol Overhead Calculator
Adjust the payload size and protocol stack to compare CoAP vs MQTT overhead ratios interactively.
Objective: See MQTT publish-subscribe in action on an ESP32. The device publishes simulated sensor data to a topic and subscribes to a command topic, demonstrating the broker-mediated pattern described above.
The ESP32 publishes to iotclass/lab/sensors/env every 3 seconds – this is the pub/sub pattern MQTT uses
It also subscribes to iotclass/lab/commands – any message published to that topic by another client will appear
The broker (HiveMQ) routes messages between publishers and subscribers without them knowing each other
Compare this with CoAP’s direct request-response: MQTT uses a broker intermediary, adding latency but enabling many-to-many communication
32.5 Visual Reference Gallery
Visual: IoT Protocol Stack Layers
Figure 32.2: IoT Protocol Stack
The IoT protocol stack visualization shows how CoAP and MQTT sit at the application layer, each relying on different transport protocols (UDP and TCP respectively), with shared network and link layers beneath them.
32.6 Knowledge Check
Auto-Gradable Quick Check
Worked Example: Calculating MQTT QoS Power Impact
Scenario: A battery-powered temperature sensor sends 10-byte readings every 60 seconds via MQTT. The team debates MQTT QoS levels.
Since radio energy is roughly proportional to bytes transmitted, the QoS level directly scales energy cost per message.
Step 3: Quantify the daily impact
1,440 readings/day (every 60 sec)
QoS 0: 1,440 × 14 = 20,160 bytes/day (baseline)
QoS 1: 1,440 × 20 = 28,800 bytes/day (43% more radio traffic)
QoS 2: 1,440 × 28 = 40,320 bytes/day (100% more radio traffic)
QoS 2 doubles the radio traffic compared to QoS 0.
Step 4: Evaluate actual reliability need
Question: What happens if a single temperature reading is lost?
Data Pattern:
60-second intervals → 1,440 readings/day
QoS 0 with 1% loss → 14 readings lost/day
Result: Dashboard shows 23.5°C at 10:00, missing at 10:01, then 23.6°C at 10:02
Impact on monitoring dashboard: Negligible (next reading in 60 seconds)
Impact on trend analysis: Negligible (still 1,426 points/day for smoothing)
Impact on alerting: Potentially critical if loss occurs during temperature spike
Decision Matrix:
Use Case
QoS Choice
Rationale
General monitoring
QoS 0
60-second intervals + 1% loss = still 1,426 readings/day, trends clear
Critical alerting
QoS 1
43% radio traffic increase acceptable for ensured delivery of threshold alerts
Billing/compliance
QoS 2
100% radio traffic increase acceptable for exactly-once financial records
The Fix: Use QoS 0 for routine telemetry, QoS 1 for threshold alerts via topic separation:
# Sensor publishes to two topicsmqtt.publish("sensors/temp/raw", 23.5, qos=0) # Routine dataif temp > ALERT_THRESHOLD: mqtt.publish("alerts/temp/high", 23.5, qos=1) # Critical alert
Result:
99% of messages use QoS 0 (saves energy)
1% of messages use QoS 1 (when it matters)
Radio energy: essentially the same as pure QoS 0
Lesson: QoS 2 doubles the radio traffic of QoS 0 per message exchange. Only use it when exact duplicate prevention is financially or legally critical (billing, financial transactions). For monitoring, QoS 1 or even QoS 0 is usually sufficient.
Try It: MQTT QoS Traffic Comparison
Adjust the transmission interval and payload size to see how QoS level affects daily radio traffic volume.
Connecting an MQTT client before the broker is running produces a “connection refused” error that beginners mistake for a code bug. Fix: always start the broker first and verify it is listening on port 1883 before launching clients.
2. Forgetting to Subscribe Before Publishing in Lab Tests
Publishing a message and then subscribing means the subscriber misses messages sent before it connected (unless the message was retained). Fix: subscribe first, then publish; or use retained messages for state values.
3. Using CoAP Over TCP in Lab Work
CoAP is designed for UDP. Some libraries silently fall back to TCP, changing timing and reliability behaviour. Fix: explicitly specify UDP transport and verify with Wireshark.
4. Ignoring MQTT Keep-Alive Timeouts in Long Labs
If a lab exercise pauses for 60+ seconds without sending messages, the broker drops the client as disconnected. Fix: set keepalive=120 seconds or send periodic PINGREQ messages during idle periods.
Label the Diagram
Code Challenge
32.9 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