5  CoAP vs MQTT Comparison

In 60 Seconds

CoAP uses UDP-based request-response for one-to-one communication with built-in resource discovery, while MQTT uses TCP-based publish-subscribe for many-to-many messaging through a broker. CoAP’s 4-byte header is smaller than MQTT’s 2-byte minimum but MQTT’s persistent connections amortize TCP overhead across many messages. Choose CoAP for RESTful device APIs with infrequent interactions; choose MQTT for continuous telemetry streaming to multiple subscribers.

5.1 Learning Objectives

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

  • Compare Architecture Models: Distinguish between CoAP’s request-response and MQTT’s publish-subscribe patterns, explaining the coupling implications of each
  • Evaluate Transport Trade-offs: Analyze UDP vs TCP implications for IoT deployments, justifying which is appropriate given device constraints and reliability needs
  • Assess QoS Options: Compare reliability mechanisms in both protocols and select the appropriate QoS level for a given use case
  • Calculate Protocol Overhead: Compute header sizes, per-message bandwidth, and annual energy expenditure to demonstrate efficiency trade-offs between CoAP and MQTT
  • Select Protocols: Apply a decision framework to design protocol selection for real-world IoT deployments based on specific technical requirements
  • Diagnose Configuration Errors: Identify and fix common protocol misconfiguration patterns such as persistent MQTT connections for infrequent sensors
  • MQTT: Message Queuing Telemetry Transport — pub/sub protocol optimized for constrained IoT devices over unreliable networks
  • Broker: Central server routing messages from publishers to all matching subscribers by topic pattern
  • Topic: Hierarchical string (e.g., home/bedroom/temperature) used to route messages to interested subscribers
  • QoS Level: Quality of Service 0/1/2 trading delivery guarantee for message overhead
  • Retained Message: Last message on a topic stored by broker for immediate delivery to new subscribers
  • Last Will and Testament: Pre-configured message published by broker when a client disconnects ungracefully
  • Persistent Session: Broker stores subscriptions and pending messages allowing clients to resume after disconnection

5.2 For Beginners: CoAP vs MQTT

CoAP and MQTT are two popular IoT communication protocols with different strengths. MQTT is like a radio broadcast – a central broker distributes messages to subscribers. CoAP is like a web request – devices directly ask each other for information. Choosing between them depends on your network setup, device resources, and communication patterns.

“I use MQTT to report my temperature readings,” said Sammy the Sensor. “Why would anyone use CoAP instead?”

Lila the LED jumped in: “Because I don’t need a middleman! With CoAP, I talk directly to the device that wants my data – like sending a text message straight to a friend. With MQTT, I have to go through a broker – like posting on a bulletin board and hoping someone reads it.”

“But the broker is useful!” argued Sammy. “If the dashboard app is offline, the broker holds my messages until it comes back. With CoAP, if nobody answers my message, it’s just… gone.” Max the Microcontroller nodded. “You’re both right. MQTT is better when you have unreliable connections and need the broker to buffer messages. CoAP is better when you want fast, direct request-response – like asking a sensor ‘what’s your temperature right now?’”

Bella the Battery settled the debate: “For my power budget, CoAP wins when I only need occasional readings – one request, one response, done. But MQTT wins when I need continuous updates pushed to me without asking every time. Pick the tool that fits the job!”

5.3 Prerequisites

Before diving into this chapter, you should be familiar with:


5.4 CoAP vs MQTT: Detailed Comparison

Choosing between CoAP and MQTT is not always straightforward. Both protocols excel in different scenarios. Here’s a comprehensive comparison:

5.4.1 Architecture and Communication Model

Aspect CoAP MQTT
Pattern Request-Response (client-server) Publish-Subscribe (broker-based)
Communication One-to-One Many-to-Many
Coupling Tight (direct connection) Loose (decoupled via broker)
Discovery Built-in resource discovery Topic-based addressing

Table: Detailed CoAP vs MQTT Comparison

FACTOR CoAP MQTT
Main transport protocol UDP TCP
Typical messaging Request/response Publish/subscribe
Effectiveness in LLNs Excellent Low/fair (Implementations pairing UDP with MQTT are better for LLNs.)
Security DTLS SSL/TLS
Communication model One-to-one Many-to-many
Strengths Lightweight and fast, with low overhead, and suitable for constrained networks; uses a RESTful model that is easy to code to; easy to parse and process for constrained devices; support for multicasting; asynchronous and synchronous messages. TCP and multiple QoS options provide robust communications; simple management and scalability using a broker architecture.
Weaknesses Not as reliable as TCP-based MQTT, so the application must ensure reliability. Higher overhead for constrained devices and networks; TCP connections can drain low-power devices; no multicasting support.
Figure 5.1

Comparison table showing CoAP versus MQTT across dimensions including transport protocol (UDP vs TCP), messaging pattern (request-response vs publish-subscribe), effectiveness in Low-power Lossy Networks, security mechanisms (DTLS vs SSL/TLS), communication models (one-to-one vs many-to-many), and relative strengths and weaknesses for constrained IoT applications

CoAP vs MQTT Protocol Comparison
Figure 5.2: Visual comparison of CoAP and MQTT protocol characteristics

5.4.2 Network and Transport

Aspect CoAP MQTT
Transport UDP (User Datagram Protocol) TCP (Transmission Control Protocol)
Reliability Optional confirmable messages TCP ensures delivery
Overhead Very low (4-byte header) Low (2-byte header + TCP)
Connection Connectionless Persistent connection
Latency Lower (no handshake) Slightly higher (TCP handshake)

5.4.3 Quality of Service and Reliability

Aspect CoAP MQTT
Message Types CON (confirmable), NON (non-confirmable) QoS 0, 1, 2
Acknowledgment Optional ACK messages Depends on QoS level
Retransmission Application handles it QoS 1&2 handle automatically
Duplicate Detection Message IDs Packet identifiers

5.4.4 Security

Aspect CoAP MQTT
Security Layer DTLS (Datagram TLS) TLS/SSL
Authentication Pre-shared keys, certificates Username/password, certificates
Encryption Yes (with DTLS) Yes (with TLS)
Overhead DTLS adds overhead to UDP TLS integrated with TCP

5.4.5 Resource Usage

Aspect CoAP MQTT
Memory Footprint Minimal Small
Power Consumption Very low (UDP, sleep modes) Low (keep-alive messages)
Battery Life Excellent Very good
Bandwidth Very efficient Efficient

5.4.6 Design Philosophy

Aspect CoAP MQTT
Inspired By HTTP (RESTful) MQTT for SCADA
Paradigm Resource-oriented Message-oriented
Standards Body IETF (RFC 7252) OASIS (ISO/IEC 20922)
Target Constrained nodes Telemetry and messaging

Scenario: A sensor sends a 10-byte temperature reading every 60 seconds for 1 year.

CoAP NON message (UDP): \[ \begin{align} \text{CoAP header} &= 4 \text{ bytes} \\ \text{Token + options} &= 6 \text{ bytes} \\ \text{Payload} &= 10 \text{ bytes} \\ \text{UDP header} &= 8 \text{ bytes} \\ \text{IPv6 header} &= 40 \text{ bytes} \\ \text{Total} &= 68 \text{ bytes per message} \end{align} \]

MQTT QoS 0 message (TCP): \[ \begin{align} \text{MQTT fixed header} &= 2 \text{ bytes} \\ \text{Topic length + topic} &= 2 + 20 = 22 \text{ bytes} \\ \text{Payload} &= 10 \text{ bytes} \\ \text{TCP header} &= 20 \text{ bytes} \\ \text{IPv6 header} &= 40 \text{ bytes} \\ \text{TCP ACK (return)} &= 60 \text{ bytes} \\ \text{Total} &= 154 \text{ bytes per message} \end{align} \]

Annual bandwidth: \[ \begin{align} \text{Messages/year} &= \frac{365 \times 24 \times 3600}{60} = 525{,}600 \\ \text{CoAP annual} &= 525{,}600 \times 68 = 35.7 \text{ MB} \\ \text{MQTT annual} &= 525{,}600 \times 154 = 80.9 \text{ MB} \\ \text{Savings} &= \frac{80.9 - 35.7}{80.9} \times 100\% = 56\% \end{align} \]

Battery impact (10 mW TX power, 250 kbps data rate): \[ \begin{align} \text{TX time (CoAP)} &= \frac{68 \times 8}{250{,}000} = 2.2 \text{ ms} \\ \text{TX time (MQTT)} &= \frac{154 \times 8}{250{,}000} = 4.9 \text{ ms} \\ \text{Energy per message} &: \text{CoAP } 22 \mu\text{J vs MQTT } 49 \mu\text{J (2.2×)} \end{align} \]

5.5 Interactive Protocol Overhead Calculator

5.6 Protocol Selection Framework

Tradeoff: HTTP vs MQTT vs CoAP

Decision context: When selecting an application protocol for IoT communication

Factor HTTP MQTT CoAP
Battery impact High (connection overhead) Medium (persistent TCP) Low (connectionless UDP)
Bandwidth High (verbose headers) Low (2-byte header) Very low (4-byte header)
Latency Medium-High (TCP + headers) Low (persistent connection) Lowest (UDP, no handshake)
Reliability TCP guaranteed QoS 0/1/2 options Optional CON/NON
Complexity Simple (universal) Moderate (broker required) Low (direct communication)
Pattern Request-Response Publish-Subscribe Request-Response + Observe
Ecosystem Universal Strong IoT Growing

Choose HTTP when:

  • Integrating with existing web infrastructure and REST APIs
  • Building mobile/web apps that communicate with gateways or cloud
  • Debugging and development simplicity is priority
  • Bandwidth and battery constraints are not critical (Wi-Fi/Ethernet devices)

Choose MQTT when:

  • Many devices need to publish to or subscribe from a central system
  • Event-driven architecture with multiple consumers per message
  • Devices have intermittent connectivity (store-and-forward via broker)
  • Smart home, telemetry dashboards, industrial monitoring

Choose CoAP when:

  • Constrained devices with limited RAM/flash (8-bit MCUs)
  • Battery-powered sensors on LPWAN (6LoWPAN, Thread)
  • Direct device-to-device or device-to-gateway communication
  • RESTful semantics needed on constrained networks

Default recommendation: MQTT for cloud/broker-based IoT systems, CoAP for constrained edge networks, HTTP only when interfacing with web systems or during prototyping

Tradeoff: Broker-Based (MQTT) vs Direct Communication (CoAP/HTTP)

Option A: Use a broker-based architecture where all messages flow through a central MQTT broker Option B: Use direct device-to-device or device-to-server communication with CoAP or HTTP

Decision Factors:

Factor Broker-Based (MQTT) Direct (CoAP/HTTP)
Coupling Loose (devices don’t know each other) Tight (must know endpoint addresses)
Discovery Topic-based (subscribe to patterns) Requires discovery protocol
Fan-out Built-in (1 publish to N subscribers) Must implement multi-cast or repeat
Single point of failure Broker is critical Distributed, no central point
Latency +1 hop through broker Direct path, minimal latency
Offline handling Broker stores messages Client must retry
Scalability Scales horizontally with broker cluster Scales naturally (peer-to-peer)
Infrastructure Requires broker deployment/management Simpler deployment

Choose Broker-Based (MQTT) when:

  • Multiple consumers need the same data (dashboards, logging, analytics)
  • Devices should not know about each other (decoupled architecture)
  • Message persistence is needed for offline devices
  • Topic-based routing simplifies message organization
  • Enterprise-scale deployments with centralized management

Choose Direct Communication (CoAP/HTTP) when:

  • Latency-critical control loops require minimal hops
  • Simple point-to-point communication between known endpoints
  • Broker infrastructure is impractical (resource-constrained networks, isolated sites)
  • RESTful semantics and HTTP-style resources are natural fit
  • Avoiding single points of failure is priority

Default recommendation: Broker-based (MQTT) for telemetry collection and event distribution; direct communication (CoAP) for device control and local sensor networks

5.7 Interactive Protocol Selection Tool

5.8 Knowledge Check

Test your understanding of protocol comparison concepts.

Match each CoAP or MQTT concept to its correct definition or use case.

5.9 Summary Table: Quick Reference

Criterion CoAP MQTT
Best Use Case Direct device queries Event distribution
Communication Request-Response Publish-Subscribe
Transport UDP (lightweight) TCP (reliable)
Power Ultra-low Low
Reliability Optional Built-in (QoS)
Scalability Good Excellent
Complexity Low Medium
Browser Support Limited Good (WebSockets)
Setup No broker needed Requires broker
Latency Low Medium
Data Type Sensor data Events/telemetry

5.10 Key Takeaways

Summary

Core Concepts:

  • CoAP uses UDP with request-response pattern; MQTT uses TCP with publish-subscribe
  • CoAP has 4-byte minimum header; MQTT has 2-byte minimum header (plus TCP overhead)
  • CoAP offers optional reliability (CON/NON); MQTT provides QoS 0/1/2 levels
  • Both protocols target constrained environments but with different design philosophies

Practical Applications:

  • Use CoAP for battery sensors, direct device control, and constrained networks
  • Use MQTT for telemetry dashboards, event-driven systems, and cloud integration
  • Hybrid architectures combine both protocols for optimal efficiency

Design Considerations:

  • Evaluate latency requirements, power constraints, and communication patterns
  • Consider broker infrastructure costs for MQTT vs direct communication for CoAP
  • Factor in existing ecosystem and tooling support for your platform

5.11 Concept Relationships

Protocol comparison connects to:

Individual Protocol Deep Dives:

Architecture Patterns:

Use Cases:

5.12 See Also

Implementation Guides:

Decision Frameworks:

Performance Analysis:

Tools:

5.13 What’s Next?

Chapter Focus Why Read It
HTTP and Modern Protocols for IoT HTTP/2, HTTP/3, WebSockets for IoT Understand when HTTP is viable on constrained devices and how modern HTTP versions reduce overhead
CoAP Fundamentals and Architecture CoAP request-response model, resource discovery, Observe extension Deep-dive the protocol you just compared — implement CON/NON messages and /.well-known/core discovery
MQTT Protocol Deep Dive MQTT broker architecture, QoS levels, topic design Master publish-subscribe internals: retained messages, last will, clean vs. persistent sessions
AMQP vs MQTT and Use Cases Enterprise messaging comparison: AMQP, MQTT, and STOMP Extend the comparison to enterprise-grade brokers when MQTT’s feature set is insufficient
Edge and Fog Computing Architecture Protocol placement in multi-tier IoT architectures See how CoAP at the edge and MQTT in the cloud fit together in real deployments
IoT Protocol Selection Framework Comprehensive decision tree across all IoT protocols Apply a systematic scoring approach to select protocols beyond just CoAP and MQTT