3  CoAP and MQTT Tradeoffs

app-protocols
coap
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.

3.1 Start Simple: Pick the Conversation Before the Header

Imagine two teams looking at the same soil sensor. One team wants the sensor to wake once a day, report moisture to a nearby gateway, receive an acknowledgment, and sleep again. The other team wants a building dashboard, rules engine, and maintenance app to see every update as it arrives. Those are different conversations, even if both carry a small temperature or moisture value.

For the first conversation, CoAP can feel natural because one endpoint asks or reports a resource and then goes quiet. For the second, MQTT can feel natural because a broker can fan out one publication to several subscribers and remember session state. Read the rest of the comparison as a set of proofs for that story: connection cost, reliability, broker ownership, battery impact, and the evidence a reviewer would keep.

Chapter Roadmap

This comparison is long because it answers several different design questions:

  1. First compare the interaction models: direct CoAP request/response versus MQTT broker publish/subscribe.
  2. Then inspect transport and reliability: UDP with CON/NON choices versus TCP plus MQTT QoS 0/1/2.
  3. Next count overhead with the chapter’s 68-byte CoAP and 154-byte MQTT example, then test the same assumptions in the calculator.
  4. After that use the selection framework and decision evidence table to turn the tradeoff into a reviewable record.
  5. Finally connect the quick reference, quizzes, and next chapters to the protocol you should study in more depth.

Checkpoint callouts summarize each major decision point. Interactive tools and quizzes are breathers: use them to test the current section before moving on.

3.2 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 behavior 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

3.3 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!”

3.4 Prerequisites

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


3.5 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:

3.5.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 3.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 3.2: Visual comparison of CoAP and MQTT protocol characteristics

3.5.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)

3.5.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
Check Your Understanding: QoS and Reliability

3.5.4 Security

You have now compared the main message pattern and the reliability knobs. The next layer is security, because DTLS or TLS can change the very overhead and wake-up costs that made one protocol look attractive.

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

3.5.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

3.5.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
Broker BexCheckpoint: Transport and Reliability

You now know:

  • CoAP is UDP-based and request/response oriented; MQTT is TCP-based and publish/subscribe oriented through a broker.
  • CoAP reliability is a per-message choice between CON and NON; MQTT reliability is selected with QoS 0, QoS 1, or QoS 2.
  • A daily report on a 2% loss network favors CoAP CON when battery life matters, while many consumers and durable fan-out favor MQTT.

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} \]

3.5.7 Calculation Audit

The estimate uses decimal megabytes and treats the MQTT TCP acknowledgment as radio-on airtime under the same 250 kbps link budget. The raw arithmetic is:

  • One year at a 60-second interval is 365 x 24 x 3600 / 60 = 525,600 messages.
  • CoAP traffic is 525,600 x 68 = 35,740,800 bytes, or 35.7 MB using 1 MB = 1,000,000 bytes.
  • MQTT traffic is 525,600 x 154 = 80,942,400 bytes, or 80.9 MB on the same decimal basis.
  • The byte reduction is 80,942,400 - 35,740,800 = 45,201,600 bytes, so the saving is 45,201,600 / 80,942,400 = 0.558, about 56%.
  • CoAP airtime is 68 x 8 / 250,000 = 0.002176 s; at 10 mW = 0.010 J/s, that is 0.010 x 0.002176 = 0.00002176 J, or 21.76 uJ.
  • MQTT airtime is 154 x 8 / 250,000 = 0.004928 s; at the same power, that is 49.28 uJ.

For a measured device budget, split transmit, receive, idle-listen, retries, and connection setup into separate states. This panel is a protocol-overhead comparison, not a battery-life proof for every radio.

Phoebe the physics guide

Phoebe’s Why

The 21.76 uJ and 49.28 uJ figures above are real per-message energies, but a coin cell does not dispense energy at a fixed voltage the way that arithmetic assumes. Internal resistance sags the cell’s terminal voltage under every current pulse the radio draws, and the nameplate mAh itself erodes quietly from self-discharge even between messages, so a design margin has to be subtracted before the nameplate number becomes a usable energy budget. Converting “49.28 uJ per message” into “years of service” needs that same sag-and-derating chain, not a second multiplication by nominal voltage.

The Derivation

Energy is the integral of voltage times current, not charge times a constant:

\[E = \int V(t)\,I(t)\,dt\]

Internal resistance \(R_{int}\) sags the terminal voltage under load:

\[V_{term} = V_{oc} - I\,R_{int}\]

Only after self-discharge and a design margin discount the nameplate charge does it become a usable energy budget:

\[E_{usable}(\mathrm{Wh}) \approx Q_{usable}(\mathrm{Ah}) \times V, \qquad Q_{usable} = f_{derate}\times Q_{nominal}\]

Worked Numbers: This Chapter’s 525,600 Messages

The chapter names no battery, so take a standard/typical sensor coin cell (CR2032, 3.0 V, 220 mAh, \(R_{int}\approx15\ \Omega\) typical):

  • Nameplate energy: \(E = 0.220\ \text{Ah}\times3.0\ \text{V} = 0.660\) Wh
  • Voltage sag during the radio-on pulse, using the chapter’s own 10 mW at 3.0 V (\(I=10/3.0=3.33\) mA): \(\Delta V = 0.00333\times15 = 0.0500\) V, terminal voltage falls to \(2.95\) V
  • Derated usable budget at 80%: \(E_{usable}=0.8\times0.660=0.528\) Wh \(=0.528\times3600=1900.8\) J
  • Annual radio-on energy from this chapter’s own per-message figures at 525,600 messages/year: CoAP \(=525{,}600\times21.76\ \mu\text{J}=11.4\) J; MQTT \(=525{,}600\times49.28\ \mu\text{J}=25.9\) J

Set against the 1900.8 J usable budget, the radio-on energy alone could run for \(1900.8/11.437=166\) years on CoAP or \(1900.8/25.902=73.4\) years on MQTT – both far beyond the cell’s real shelf and self-discharge life. That gap is the chapter’s own warning restated in numbers: transmit energy is not the binding constraint here, so idle-listen current, MCU active time, and self-discharge decide the real service life, not the protocol choice alone.

Broker BexCheckpoint: Overhead Arithmetic

You now know:

  • In the worked example, one year at a 60-second interval is 525,600 messages.
  • The chapter’s byte count gives 35.7 MB/year for CoAP and 80.9 MB/year for MQTT, a savings of about 56% under the stated assumptions.
  • The energy comparison is 21.76 uJ versus 49.28 uJ per message at 10 mW and 250 kbps, but real budgets must still separate transmit, receive, idle-listen, retries, and setup.

3.6 Interactive Protocol Overhead Calculator

3.7 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 ordered byte stream 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

3.7.0.1 Mobile decision snapshot

HTTP - Best when web compatibility and universal tooling matter most. - Tradeoff: highest bandwidth and battery overhead because of verbose headers and TCP setup.

MQTT - Best for many publishers, multiple subscribers, and event-driven cloud telemetry. - Tradeoff: requires broker infrastructure and a persistent TCP session.

CoAP - Best for constrained nodes that need direct request-response or Observe semantics. - Tradeoff: reliability is optional, so the application must choose CON/NON behavior intentionally.

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

3.8 Decision Evidence Checkpoint

A protocol decision is defensible only when the scorecard names its assumptions. Capture these fields before treating the choice as complete:

Evidence field CoAP-favoring signal MQTT-favoring signal HTTP-favoring signal
Communication pattern Direct request/response, resource state, or Observe near the edge Many publishers or subscribers through a broker Browser, administration, or integration API
Power and session cost Sleepy node cannot hold a TCP session and sends infrequent readings Device can maintain a session or gateway owns the session Mains-powered or gateway/cloud endpoint
Reliability need Per-message choice between CON and NON is enough Queued offline delivery or QoS levels are needed TCP request/response semantics are sufficient
Operations owner Gateway can own retry, translation, and discovery Broker team can monitor topics, queues, retained state, and dead letters API team can monitor status codes, auth, rate limits, and schemas
Retest trigger Packet loss, battery life, or firmware memory changes Subscriber count, queue depth, or reconnect behavior changes Client compatibility, API versioning, or auth boundary changes

Keep the selection record reviewable: include the weights, the measured packet or energy assumptions, the owner of the gateway or broker boundary, and a trigger that forces the team to rerun the comparison after deployment conditions change.

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

Broker-based - Loose coupling and topic-based discovery. - Built-in fan-out and offline buffering through the broker. - Tradeoff: the broker becomes critical infrastructure and adds one extra hop.

Direct - Minimal-latency path between known endpoints. - No central broker and fewer deployment dependencies. - Tradeoff: clients must handle retries, discovery, and repeated fan-out themselves.

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

Broker BexCheckpoint: Selection Evidence

You now know:

  • HTTP is strongest when web compatibility matters; MQTT is strongest when broker fan-out and subscriptions matter; CoAP is strongest for constrained direct request/response.
  • A decision record should name the communication pattern, power/session cost, reliability need, operations owner, and retest trigger.
  • Broker-based MQTT reduces coupling and adds fan-out, while direct CoAP or HTTP removes broker infrastructure but leaves retry, discovery, and repeated fan-out to the application.

3.9 Interactive Protocol Selection Tool

3.10 Knowledge Check

Test your understanding of protocol comparison concepts.

Quiz 1: CoAP vs MQTT Comparison
Quiz 2: Factory Real-Time Alerts
Quiz 3: Protocol Overhead Calculation
Protocol Concept Matching

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

The first half of the chapter gave you the protocol selection tools. The next compact layer explains why the same choice can change when devices sleep behind NAT, subscribers go offline, or a lossy link makes ordered TCP delivery stall behind one missing segment.

3.11 Overview: Two Interaction Models, Not Just Two Headers

CoAP and MQTT are often compared byte for byte, but their real difference is architectural. MQTT is broker-mediated publish and subscribe over a persistent TCP connection: clients connect to a broker, publish to topics, and subscribe to receive pushes. CoAP is a RESTful request and response over connectionless UDP, with an Observe option that adds a lightweight push. One keeps a standing connection to an intermediary; the other exchanges independent datagrams end to end.

That distinction drives everything else. TCP gives MQTT ordered, reliable byte delivery but requires a connection handshake and keepalive traffic to maintain. UDP lets CoAP send a single request as a single datagram with no connection to set up or hold open, at the cost of handling reliability per message when it needs it. Neither is universally better; they fit different traffic patterns.

For a smart-parking sensor that wakes once every ten minutes, measures occupancy, and reports through a nearby gateway, CoAP can send one confirmable message and let the radio sleep again. The gateway can expose a resource such as `/spaces/17/occupancy`, return a response code, and retry only that observation if no acknowledgment arrives. For a building platform that streams temperature, humidity, and alarm topics to a dashboard, rules engine, and maintenance app, MQTT's broker gives each consumer its own subscription without making the sensor know every destination.

The decision is therefore a boundary decision. CoAP keeps the endpoint relationship direct: the client asks a resource, the server answers, and any fan-out must be built elsewhere. MQTT centralizes fan-out: publishers do not know subscribers, but the broker becomes infrastructure that must be operated, secured, and monitored. A gateway may use both when constrained field devices speak CoAP locally and the site gateway republishes normalized events to MQTT for cloud consumers.

Intuition only: MQTT shines when a device wants a durable pipe to a broker that pushes to many subscribers. CoAP shines when a constrained device wants to send or fetch occasionally without maintaining a connection.

Where They Differ

Transport

MQTT over TCP (connection-oriented, ordered); CoAP over UDP (connectionless datagrams).

Pattern

MQTT broker pub/sub with push; CoAP RESTful request/response plus Observe.

Reliability

MQTT QoS levels backed by the broker; CoAP confirmable messages retransmitted end to end.

Security

MQTT commonly uses TLS; CoAP uses DTLS over UDP; both add a handshake cost.

Overview Knowledge Check

3.12 Practitioner: Count The Connection Overhead For Your Traffic

For a constrained, infrequent reporter, the deciding cost is often not the payload but the connection. MQTT pays a TCP handshake to open a connection and keepalive traffic to hold it; CoAP pays neither, sending each request as an independent datagram.

Worked Example: A Sensor Reporting Every 5 Minutes

The device sends one small reading every 300 s.

  • CoAP: each report is one confirmable request datagram plus one acknowledgment datagram - about one round trip, no connection to set up or keep. Between reports the radio can be fully off.
  • MQTT, reconnecting each time: every report first pays a TCP three-way handshake, then an MQTT CONNECT/CONNACK, and a TLS handshake if secured - several round trips of setup before the one-message payload.
  • MQTT, persistent connection: avoids re-handshaking but must send keepalive pings to hold the connection. With a 60 s keepalive, the device wakes roughly five times between reports just to say "still here," doing no useful work.

For this infrequent, battery-powered pattern CoAP avoids both the per-report handshake and the keepalive tax, so it is usually the lighter choice. If instead the device needed a broker to push commands down to it at any moment, MQTT's standing connection would be the feature, not the cost.

Make the estimate explicit before choosing. A CoAP confirmable exchange on IPv4 might carry a 4-byte CoAP header, 8-byte UDP header, 20-byte IPv4 header, and the link-layer frame. An MQTT report over a cold connection pays TCP SYN/SYN-ACK/ACK, TLS setup if enabled, MQTT CONNECT/CONNACK, PUBLISH, and DISCONNECT unless it holds the socket open. A persistent MQTT client avoids repeated setup but then the keepalive interval becomes part of the battery budget. For a five-minute report interval, a 60-second keepalive can create several radio wakes between useful payloads.

The practical worksheet should record report interval, payload size, expected packet loss, security handshake choice, broker requirement, NAT direction, and whether downlink commands are time-critical. If the device only reports and can tolerate direct request/response, CoAP usually wins. If the device needs asynchronous command delivery, retained state, or several subscribers, MQTT may justify the connection cost.

Overhead Comparison Ledger

Cost
CoAP (UDP)
MQTT (TCP)
Impact On Sleepy Node
Connection setup
None
TCP handshake + CONNECT (+ TLS)
Paid per report if reconnecting
Keepalive
None
Periodic ping to hold connection
Extra wakes with no data
Per-message header
4-byte CoAP over 8-byte UDP
2-byte MQTT over 20-byte TCP
Similar per packet; TCP adds state

Practitioner Knowledge Check

3.13 Under The Hood: Broker Persistence Versus End-To-End Datagrams

The reliability models differ in a way that decides which protocol fits. MQTT's delivery behavior runs through the broker: with a higher QoS and a persistent session, the broker stores messages and delivers them to a subscriber that was offline, and retained messages give a late joiner the last known value. That store-and-forward behavior is exactly what a device behind a network address translator needs, since it initiates the connection outward and the broker pushes down to it. CoAP has no broker in the middle. A confirmable message is retransmitted with backoff until the far endpoint acknowledges, but if that endpoint is offline there is no intermediary holding the data - reliability is end to end, with no built-in offline queue.

Transport choice adds a second effect on lossy links. TCP delivers bytes in order, so a single lost segment blocks everything behind it until it is retransmitted - head-of-line blocking that can stall an MQTT stream on a flaky radio. CoAP's independent UDP datagrams have no such coupling: losing one message does not delay the others, which suits high-loss networks. The honest conclusion is that there is no universal winner. Favor MQTT for push to many subscribers, offline delivery, and NAT traversal; favor CoAP for infrequent constrained request/response, lossy links, and designs with no broker to run. Match the protocol to the traffic pattern rather than to a benchmark of header bytes.

Under the hood, the broker changes failure ownership. With MQTT persistent sessions, the broker must track client id, session expiry, subscriptions, queued QoS 1 or QoS 2 messages, retained values, and Last Will state. That helps a sleeping or disconnected client resume, but it also means broker storage, access control, topic hygiene, and expiry policy are part of the protocol decision. A poorly chosen session expiry can either drop needed commands too early or retain stale commands that should no longer run.

CoAP moves that responsibility to the endpoints. Message IDs, tokens, ACK timeouts, retransmission counters, and Observe sequence numbers tell a client whether a specific exchange completed. There is no central place to queue work for an offline device, so the application must decide whether to retry later, store the command elsewhere, or mark the endpoint unavailable. That makes CoAP simpler for local constrained exchanges and less suitable for cloud-to-device command fan-out when devices sleep behind NAT.

Model Differences That Decide The Choice

Offline delivery

MQTT's broker can hold messages for an offline subscriber; CoAP has no broker queue.

NAT traversal

An MQTT device dials out and the broker pushes down; reaching a CoAP server behind NAT is harder.

Head-of-line blocking

TCP stalls the whole stream on one lost segment; CoAP's UDP datagrams are independent.

No universal winner

Choose by traffic pattern: push-to-many and offline favor MQTT; sparse, lossy, brokerless favor CoAP.

Under-the-Hood Knowledge Check

Broker BexCheckpoint: Reliability Ownership

You now know:

  • MQTT reliability is broker-mediated: persistent sessions, retained messages, queued QoS 1 or QoS 2 messages, and Last Will state all become broker operations concerns.
  • CoAP reliability is endpoint-mediated: message IDs, tokens, ACK timeouts, retransmission counters, and Observe sequence numbers describe a specific exchange.
  • For 200 pressure sensors with 5% packet loss and a <100 ms alert target, the chapter favors CoAP CON over CoAP NON, MQTT QoS 2, or HTTP polling.

3.14 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

CoAP quick reference - Best use case: direct device queries and local control. - Transport: UDP with very low overhead and low latency. - Setup: no broker required; reliability is optional. - Best suited to sensor data on constrained devices.

MQTT quick reference - Best use case: event distribution and telemetry fan-out. - Transport: TCP with built-in QoS and strong browser support via WebSockets. - Setup: requires a broker and slightly more complexity. - Best suited to events and dashboard telemetry.

🏷️ Label the Diagram

💻 Code Challenge

📝 Order the Steps

3.15 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

3.16 Concept Relationships

Protocol comparison connects to:

Individual Protocol Deep Dives:

Architecture Patterns:

Use Cases:

3.17 See Also

Implementation Guides:

Decision Frameworks:

Performance Analysis:

Tools:

3.18 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

3.18.0.1 HTTP and Modern Protocols for IoT

  • Focus: HTTP/2, HTTP/3, and WebSockets for IoT.
  • Why next: Learn when modern HTTP becomes viable on constrained devices.

3.18.0.2 CoAP Fundamentals and Architecture

  • Focus: request-response model, resource discovery, and Observe.
  • Why next: Put CON/NON messaging and /.well-known/core into practice.

3.18.0.3 MQTT Protocol Deep Dive

  • Focus: broker internals, QoS levels, and topic design.
  • Why next: Understand retained messages, last will, and session persistence.

3.18.0.4 AMQP vs MQTT and Use Cases

  • Focus: enterprise messaging tradeoffs across AMQP, MQTT, and STOMP.
  • Why next: Extend the comparison when MQTT’s feature set is not enough.

3.18.0.5 Edge and Fog Computing Architecture

  • Focus: protocol placement in multi-tier IoT systems.
  • Why next: See how CoAP at the edge and MQTT in the cloud work together.

3.18.0.6 IoT Protocol Selection Framework

  • Focus: a wider decision tree across all major IoT protocols.
  • Why next: Apply a systematic scoring approach beyond just CoAP and MQTT.