Application Layer Protocol: The topmost protocol layer responsible for encoding, transporting, and interpreting application data between devices and services
MQTT: A publish-subscribe messaging protocol designed for constrained devices; uses a broker to decouple publishers and subscribers
CoAP: Constrained Application Protocol; a RESTful protocol designed for UDP that mirrors HTTP semantics with minimal overhead
AMQP: Advanced Message Queuing Protocol; a broker-based protocol with rich routing, reliability, and security features for enterprise IoT
Publish-Subscribe Pattern: A messaging pattern where senders (publishers) emit messages to named topics, and receivers (subscribers) consume only the topics they register for
QoS Level: A guaranteed delivery tier; MQTT offers QoS 0 (fire-and-forget), 1 (at-least-once), and 2 (exactly-once)
Topic Hierarchy: A slash-separated namespace (e.g., building/floor2/room3/temp) used in MQTT to organise and filter messages
24.1 In 60 Seconds
The IoT application layer is dominated by two protocols: CoAP (request-response over UDP, like a lightweight HTTP for constrained devices) and MQTT (publish-subscribe over TCP, ideal for scalable telemetry with a broker). Choose CoAP for direct device-to-device communication with minimal overhead; choose MQTT when you need one-to-many distribution, persistent sessions, and QoS guarantees through a central broker.
Learning Objectives
By the end of this chapter, you will be able to:
Compare CoAP and MQTT architectures, overhead, and QoS mechanisms
Differentiate request-response and publish-subscribe communication patterns
Apply interactive tools to benchmark protocol characteristics
Select CoAP or MQTT based on device constraints and deployment requirements
Evaluate the role of HTTP, AMQP, and WebSocket in IoT systems
Sensor Squad: CoAP or MQTT? The Big Decision!
“I need to send my temperature data to the cloud,” said Sammy the Sensor. “Should I use CoAP or MQTT?” Max the Microcontroller asked two questions. “First, are you talking to one server or broadcasting to many listeners? Second, do you run on batteries or mains power?”
“I am battery-powered and I send directly to one gateway,” said Sammy. “Then CoAP is perfect for you,” Max replied. “It runs on UDP, has only a 4-byte header, and works like a web request – you ask, the server answers. Super lightweight for constrained devices.”
Lila the LED had different needs. “I am a smart light that needs to listen for commands from MULTIPLE sources – a phone app, a voice assistant, and a schedule timer.” Max nodded. “MQTT is your choice. You subscribe to a topic like ‘living-room/lights’ and the broker delivers any message published to that topic. One-to-many communication through a central hub.”
“Think of CoAP as a phone call – direct, one-to-one,” summarized Bella the Battery. “And MQTT as a radio station – one broadcast, many listeners. CoAP uses less energy because UDP has no connection overhead. MQTT is more reliable because TCP guarantees delivery. Match the protocol to your communication pattern!”
24.2 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).
24.2.1 Communication Patterns
Figure 24.1: Request-response (CoAP) vs Publish-subscribe (MQTT) communication patterns
24.2.2 CoAP (Constrained Application Protocol)
Overview: CoAP is “HTTP for IoT” - a RESTful protocol designed for constrained devices and networks.
useCaseRecommendations = {const recommendations = [];if (selectedProtocols.includes("MQTT") && selectedProtocols.includes("CoAP")) { recommendations.push({title:"MQTT vs CoAP: Classic IoT Comparison",content:`**Choose CoAP** for battery-powered sensors (<32KB RAM), direct device control, or multicast needs. Example: Temperature sensors in a building.**Choose MQTT** for cloud-connected telemetry, many publishers/subscribers, or dashboard integration. Example: Smart home data to cloud platform.**Hybrid Strategy**: CoAP for sensor-to-gateway (constrained network), MQTT for gateway-to-cloud (reliable network).` }); }if (selectedProtocols.includes("CoAP") && selectedProtocols.includes("HTTP")) { recommendations.push({title:"CoAP vs HTTP: Constrained vs Web",content:`**Choose CoAP** when devices are resource-constrained. CoAP is "HTTP for IoT" with RESTful semantics but dramatically lower overhead (4-byte application header + 8-byte UDP vs 200+ byte HTTP headers + 20-byte TCP).**Choose HTTP** for well-resourced devices needing maximum web compatibility. HTTP/2 improves efficiency but still requires more resources than CoAP.**Key Difference**: UDP (CoAP) vs TCP (HTTP) - CoAP saves power by avoiding connection setup.` }); }if (selectedProtocols.includes("MQTT") && selectedProtocols.includes("AMQP")) { recommendations.push({title:"MQTT vs AMQP: IoT vs Enterprise",content:`**Choose AMQP** for enterprise messaging with complex routing, transactional guarantees, or financial systems. Richer features but higher complexity.**Choose MQTT** for lightweight IoT telemetry, simpler implementation, or resource-constrained devices. More widely adopted in IoT.**Use Case Split**: AMQP for business-critical messaging, MQTT for sensor data collection.` }); }if (selectedProtocols.includes("WebSocket")) { recommendations.push({title:"WebSocket for Real-Time IoT",content:`**Choose WebSocket** when you need bidirectional real-time communication with web browsers. Perfect for live dashboards, chat-like interactions, or streaming data.**Advantage**: Full-duplex communication over a single TCP connection after initial HTTP handshake.**Trade-off**: Persistent connection requires more power than CoAP but less overhead than repeated HTTP requests.` }); }// General low-power recommendationif (selectedProtocols.includes("CoAP")) { recommendations.push({title:"Low-Power Applications",content:`For battery-powered sensors requiring years of operation, **CoAP over UDP** is optimal:- 4-byte header (vs 40+ for HTTP)- No TCP connection overhead- Connectionless = no keep-alive packets- Optional confirmable messages only when needed` }); }// General cloud recommendationif (selectedProtocols.includes("MQTT")) { recommendations.push({title:"Cloud Integration",content:`For cloud-connected IoT with many devices, **MQTT** excels:- Pub/Sub decouples publishers from subscribers- Broker handles fan-in from thousands of devices- Cloud platforms (AWS IoT, Azure IoT Hub) natively support MQTT- Last Will Testament (LWT) for device offline detection` }); }// Security-focused recommendationif (selectedData.some(p => p.security>=8)) { recommendations.push({title:"Security Considerations",content:`**High-security protocols** in your selection:- **MQTT/HTTP/WebSocket**: Use TLS/SSL for encryption- **CoAP**: Use DTLS (Datagram TLS) for UDP- **AMQP**: TLS + SASL authentication**Trade-off**: Security overhead increases power consumption. For extremely constrained devices, consider application-level encryption.` }); }return recommendations;}html`<div style="margin-top: 20px;"> <h3 style="color: #2C3E50; border-bottom: 2px solid #16A085; padding-bottom: 10px;"> Use Case Recommendations </h3>${useCaseRecommendations.map(rec =>` <div style="background: #f8f9fa; border-left: 4px solid #16A085; padding: 15px; margin: 15px 0; border-radius: 4px;"> <h4 style="margin-top: 0; color: #2C3E50;">${rec.title}</h4> <div style="line-height: 1.6; white-space: pre-line;">${rec.content}</div> </div> `).join('')}</div>`
How to Use This Protocol Analyzer
Select Protocols: Check 2-3 protocols from the list above to compare them
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
Review Bar Charts: Compare protocols side-by-side across individual metrics
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
24.4 Worked Example: Choosing a Protocol Stack for a Cold-Chain Logistics Fleet
A pharmaceutical company ships temperature-sensitive vaccines across 200 refrigerated trucks. Each truck has a sensor that measures temperature every 60 seconds and must alert the cloud within 5 seconds if temperature leaves the 2–8 °C safe range. The gateway in each truck has an LTE-M modem (cellular backhaul). Design the protocol stack from sensor to cloud.
Step 1: Characterise the traffic.
Parameter
Value
Normal readings
50 bytes every 60 s (timestamp + temp + humidity + GPS)
Alert messages
Same 50 bytes, but delivery must be confirmed
Fleet size
200 trucks
Uplink bandwidth per truck
50 B / 60 s = 0.83 B/s = 6.7 bps
Fleet aggregate
200 x 6.7 bps = 1,340 bps (~1.3 kbps)
The cloud also needs to push firmware updates (~100 KB) to each truck once per quarter and send configuration changes (100 bytes) ad hoc.
Sensor to gateway (CoAP): The MCU has only 32 KB RAM. CoAP’s 4 KB stack fits comfortably, and UDP’s connectionless design means no keep-alive drain on the MCU’s power budget. Normal readings use NON (non-confirmable) messages; temperature alerts use CON (confirmable) with a 2-second ACK timeout, well within the 5-second alert window.
Gateway to cloud (MQTT QoS 1): The gateway is a Linux SBC with 512 MB RAM, so MQTT’s TCP overhead is irrelevant. MQTT’s publish-subscribe architecture means the same temperature data reaches both the alert engine and the analytics pipeline without duplication. The gateway publishes to fleet/{truckId}/telemetry and fleet/{truckId}/alerts.
Firmware downloads: The cloud publishes firmware chunks to fleet/{truckId}/ota using MQTT QoS 1. The gateway assembles chunks and flashes the sensor MCU over SPI.
Step 4: Quantify the overhead savings.
Over 24 hours, one truck sends 1,440 normal readings + ~2 alerts:
Metric
CoAP (sensor-to-GW)
If we used MQTT instead
Packet overhead per reading
4 B (CoAP) + 8 B (UDP) = 12 B
2 B (MQTT) + 20 B (TCP) = 22 B
Daily overhead
1,440 x 12 = 17.3 KB
1,440 x 22 = 31.7 KB
Keep-alive
0 B (stateless)
60 x 4 B PINGREQ/PINGRESP = 240 B/hr = 5.8 KB/day
Total daily overhead
17.3 KB
37.5 KB
TCP connection setup
0 (UDP)
3-way handshake at startup + reconnects
CoAP saves 54% of protocol overhead on the constrained sensor-to-gateway link, and eliminates keep-alive traffic entirely.
Putting Numbers to It
Comparing CoAP versus MQTT overhead requires calculating total bytes transmitted per day, including application headers, transport headers, and keep-alive traffic.
MQTT uses 3.56× more bandwidth than CoAP for the same sensor-to-gateway link, primarily due to TCP connection overhead and mandatory keep-alive packets. For battery-powered sensors, this translates to proportionally higher radio energy consumption.
Try It: Protocol Overhead Calculator
Adjust your deployment parameters to compare CoAP vs MQTT daily overhead on a sensor-to-gateway link.
Connection: Application Protocol Choice meets Transport Protocol Selection
This hybrid CoAP/MQTT architecture mirrors the transport-layer split discussed in TCP vs UDP Fundamentals. At the constrained edge, UDP (and hence CoAP) wins because connectionless operation eliminates keep-alive overhead and reduces MCU RAM requirements. At the gateway-to-cloud boundary, TCP (and hence MQTT) wins because reliable ordered delivery, TLS, and broker fan-out justify the higher overhead on a resource-rich gateway. The protocol boundary at the gateway is where the system transitions from “constrained network” to “reliable network” – a pattern repeated in almost every production IoT deployment.
Quick Check: CoAP vs MQTT Selection
24.5 Other Application Protocols
24.5.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
Best for: Industrial automation, financial systems, enterprise IoT
24.5.3 WebSocket
Full-duplex communication for: - Real-time dashboards - Live data streaming - Browser-based IoT interfaces
Knowledge Check: Application Protocols
Matching Exercise: Protocol Characteristics
Ordering Exercise: Hybrid Protocol Stack Design
Common Pitfalls
1. Using MQTT QoS 2 for All Messages “to be Safe”
QoS 2 requires four-message handshakes per publish, tripling network traffic. For high-frequency sensor readings, this exhausts bandwidth and broker resources. Fix: use QoS 0 for telemetry and QoS 1 only for commands or alarms.
2. Designing Flat MQTT Topic Namespaces
Publishing everything to a single topic like sensors makes filtering impossible and causes all subscribers to receive all messages. Fix: design a hierarchical topic namespace (e.g., site/building/floor/device/metric) from the start.
3. Choosing CoAP Over MQTT Without Considering Broker Availability
CoAP is peer-to-peer and works without a broker, but loses publish-subscribe fan-out capabilities. Fix: use CoAP when direct device-to-device or device-to-server REST semantics are needed; use MQTT when fan-out to multiple consumers is required.
4. Ignoring Payload Encoding Efficiency
JSON payloads are human-readable but expensive: a reading of {"temperature": 23.5} is 22 bytes; the same in CBOR is 5 bytes. Fix: use binary encoding (CBOR, MessagePack) for high-frequency sensor data on constrained links.
Label the Diagram
Code Challenge
24.6 Summary
Key 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)