49  CoAP Decision Framework

In 60 Seconds

Choosing between CoAP, MQTT, and HTTP depends on your constraints: CoAP excels for lightweight request-response on battery devices over UDP, MQTT for efficient publish-subscribe streaming through a broker over TCP, and HTTP for universal web compatibility. The wrong choice can cost years of battery life or thousands of dollars in cellular data, so use a structured decision matrix based on power budget, communication pattern, and network conditions.

49.1 Learning Objectives

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

  • Select the Right Protocol: Select CoAP, MQTT, or HTTP based on power budget, communication pattern, and network type
  • Calculate TCO Impact: Calculate the 5-year total cost of ownership difference between protocol choices for a given deployment scale
  • Analyze Trade-offs: Analyze overhead, reliability, and resource consumption differences using a structured decision matrix
  • Construct a Decision Scorecard: Construct a weighted scoring table to justify protocol selection with quantitative evidence
  • Diagnose Common Mistakes: Diagnose the sleep-cycle/keepalive mismatch problem that leads to premature battery failure in MQTT deployments
  • Distinguish Protocol Strengths: Distinguish the specific scenarios where CoAP, MQTT, and HTTP each outperform the others
  • CoAP: Constrained Application Protocol — REST-style request/response protocol using UDP instead of TCP
  • Confirmable Message (CON): Requires ACK from recipient — provides reliable delivery over UDP at the cost of one roundtrip
  • Non-confirmable Message (NON): Fire-and-forget UDP datagram — lowest latency, no delivery guarantee
  • Observe Option: CoAP extension enabling publish/subscribe: client registers to receive notifications on resource changes
  • Block-wise Transfer: Fragmentation mechanism for transferring payloads larger than a single CoAP datagram
  • Token: Client-generated value matching responses to requests — enables concurrent request/response pairing
  • DTLS: Datagram TLS — CoAP’s security layer providing encryption and authentication over UDP

49.2 For Beginners: CoAP Decision Framework

This framework helps you decide when CoAP is the right protocol for your IoT project. Not every situation calls for CoAP – sometimes MQTT, HTTP, or another protocol is a better fit. Think of it as a checklist: if your devices are resource-constrained and need request-response communication, CoAP might be your best choice.

“There are so many protocols! How do I know which one to pick?” Sammy the Sensor looked overwhelmed.

Max the Microcontroller pulled out a decision flowchart. “Ask yourself three questions, Sammy. First: do you need request-response or publish-subscribe? If the dashboard asks you for data on demand, that’s request-response – CoAP territory. If you push updates whenever something changes, that’s pub-sub – MQTT territory.”

“Second question,” continued Lila the LED: “How constrained is your device? If you have only 2 KB of RAM and run on a tiny battery, CoAP’s small packets and UDP transport are perfect. If you have more resources and need guaranteed delivery to multiple subscribers, MQTT with a broker might be better.”

Bella the Battery added the third question: “What kind of network are you on? CoAP works great over lossy wireless networks because UDP doesn’t need a constant connection. But if you need messages queued while you’re asleep, you’ll want a broker-based protocol. No single protocol wins every time – the decision framework helps you match the protocol to YOUR specific situation!”

49.3 Prerequisites

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

49.4 Protocol Decision Matrix

Minimum Viable Understanding: Protocol Selection

Core Concept: CoAP, MQTT, and HTTP each excel in different scenarios. CoAP = lightweight request-response. MQTT = efficient pub-sub with broker. HTTP = universal web compatibility.

Why It Matters: Wrong protocol choice can cost battery life (years vs months), bandwidth ($1000s/year for cellular), or development time (reimplementing features).

Key Takeaway: Use this heuristic: Battery-critical request-response? CoAP. Multiple subscribers? MQTT. Web integration? HTTP.

49.4.1 Quick Decision Table

Factor Use CoAP Use MQTT Use HTTP
Communication Pattern Request-response, device queries Publish-subscribe, multiple subscribers Web browser access, rich media
Device Constraints 8KB RAM, 8-bit MCU 16KB+ RAM, moderate CPU Full OS, abundant resources
Network Type LoRaWAN, NB-IoT, 802.15.4 Wi-Fi, cellular with persistent connection Broadband, Wi-Fi, LTE
Battery Life Multi-year on coin cell Months-1 year on rechargeable Mains-powered acceptable
Message Frequency Infrequent (hourly/daily) Continuous streaming On-demand
Broker Acceptable? No (direct device-to-device) Yes (centralized routing) N/A
Multicast Support Native (FF0X::FD) Not supported Not supported
Latency Requirements <100ms (no setup) <500ms (broker hop) <1s (TCP handshake)

49.4.2 Detailed Comparison

Metric CoAP MQTT HTTP
Header Size 4 bytes 2 bytes (+ TCP overhead) 100+ bytes
Total Overhead (1 reading) 30 bytes 55 bytes (with TCP) 320 bytes
Transport UDP TCP TCP
Connection Setup None (0ms) 3-way handshake (150ms) 3-way handshake (150ms)
Energy per Message 1.5 mJ (NON), 3.0 mJ (CON) 4.5 mJ 8.0 mJ
Reliability Optional (CON/NON) QoS 0/1/2 TCP guarantees
Pub-Sub Observe (1-to-many) Native (many-to-many) Not native
Request-Response Native (RESTful) Emulated (request/response topics) Native
Resource Discovery .well-known/core Not standardized Not standardized
Multicast Yes No No
Broker Required No Yes No
ROM Footprint 3-5 KB 15-20 KB 25-50 KB
RAM Usage 1-2 KB 3-5 KB 10-20 KB

49.5 When to Use CoAP

Strong indicators CoAP is the right choice:

49.5.1 1. Battery-powered sensors reporting to gateway

Example: 500 soil moisture sensors reporting to central farm controller

Why CoAP:

  • NON messages use 50% less energy than MQTT TCP handshakes
  • No connection state to maintain (sleeps fully between transmissions)
  • Savings: 2-year battery life vs 6-month with MQTT

49.5.1.1 Interactive Battery Life Calculator

Calculate expected battery life based on your protocol choice:

Understanding Battery Life Calculations

This calculator accounts for both active transmission energy and sleep current. For most IoT sensors, sleep current dominates total energy consumption when report intervals exceed 5-10 minutes. However, protocol choice still matters significantly:

  • CoAP NON messages complete in ~50ms with minimal energy
  • MQTT requires TCP/TLS handshake if not maintaining persistent connection (~300ms active time)
  • HTTP has similar overhead to MQTT but slightly higher per-request cost

The real advantage of CoAP emerges in the elimination of keepalive overhead - MQTT persistent connections require periodic keepalive messages that prevent deep sleep.

49.5.2 2. Direct device-to-device communication

Example: Smart light switch controlling smart bulb (no broker)

Why CoAP:

  • RESTful PUT coap://bulb.local/state {"on": true} is simpler than MQTT broker setup
  • Works offline, no single point of failure
  • Lower latency (no broker hop)

49.5.3 3. Constrained networks (LoRaWAN, NB-IoT)

Example: Remote environmental monitoring over LoRaWAN

Why CoAP:

  • LoRaWAN MTU = 51-242 bytes, CoAP message fits easily
  • MQTT minimum header + TCP often exceeds MTU

49.5.4 4. Multicast queries

Example: “All temperature sensors, report current value”

Why CoAP:

  • GET coap://[FF02::FD]/temperature reaches all with 1 packet
  • MQTT would need N separate topics

49.6 When to Use MQTT

MQTT is better for:

49.6.1 1. Multiple subscribers to same data

Example: Temperature sensor data to Dashboard + Analytics + Alarm system

Why MQTT:

  • Single publish to topic, broker distributes to all subscribers
  • CoAP Observe would need subscriptions from each (3x bandwidth)

49.6.2 2. Cloud platform integration

Example: Devices connecting to AWS IoT Core, Azure IoT Hub

Why MQTT:

  • Native MQTT support, managed scaling, rule engines
  • CoAP requires custom gateway/translation

49.6.3 3. Unreliable networks needing guaranteed delivery

Example: Mobile sensors on cellular with 20% packet loss

Why MQTT:

  • TCP retransmission automatic
  • QoS 1/2 ensures delivery
  • CoAP CON retries 4 times then gives up

49.6.4 4. Persistent sessions

Example: Remote devices that receive commands while offline

Why MQTT:

  • Broker queues messages for disconnected clients (QoS 1+)
  • CoAP has no message persistence

49.7 Real-World Decision Examples

Requirements:

  • 1,000 soil sensors (moisture, temperature)
  • Battery-powered (solar recharged monthly)
  • Report hourly to gateway
  • Occasional configuration updates

Decision: CoAP

Reasoning:

  1. Battery life: NON messages = 2-year battery vs MQTT 6 months
  2. Request-response pattern: Gateway queries sensors on-demand
  3. No cloud: Farm gateway processes locally (no MQTT broker)
  4. Multicast: Query all sensors simultaneously
  5. Cost: Saves ~$1,300/year in cellular data for 1,000 sensors reporting hourly at $0.50/MB (CoAP 40 bytes vs HTTP 360 bytes total per message; savings scale linearly — 190,000 sensors would save ~$254,000/year)

Let’s validate the cellular data cost savings claim for 1,000 sensors reporting hourly:

CoAP message size (NON, IPv4 UDP):

  • IP header: 20 bytes
  • UDP header: 8 bytes
  • CoAP header: 4 bytes
  • CoAP options (Token=2, Uri-Path): ~6 bytes
  • Payload (moisture %): 2 bytes
  • Total: \(20 + 8 + 4 + 6 + 2 = 40\) bytes/message

HTTP message size (IPv4 TCP):

  • IP header: 20 bytes
  • TCP header: 20 bytes
  • HTTP request: ~180 bytes (GET with headers)
  • TCP ACK: 40 bytes
  • HTTP response: ~100 bytes (headers + payload)
  • Total: \(20 + 20 + 180 + 40 + 100 = 360\) bytes/message

Annual data usage:

  • CoAP: \(1000\text{ sensors} \times 24\text{ reports/day} \times 365\text{ days} \times 40\text{ bytes} = 350.4\text{ MB/year}\)
  • HTTP: \(1000 \times 24 \times 365 \times 360 = 3.154\text{ GB/year}\)

Cost comparison (cellular data at $0.10/MB):

  • CoAP: \(350.4\text{ MB} \times \$0.10 = \$35.04/\text{year}\)
  • HTTP: \(3154\text{ MB} \times \$0.10 = \$315.40/\text{year}\)
  • Savings: \(\$315.40 - \$35.04 = \$280.36/\text{year}\)

The stated $254,000/year savings likely assumes a much larger deployment (900x this scale) or includes additional costs like TCP handshake overhead, connection setup, and session maintenance. For 1,000 sensors, CoAP saves ~$280/year vs HTTP.

Implementation:

# Gateway queries sensors via multicast
response = await coap_client.multicast_get("coap://[FF02::FD]/moisture")

# Configure specific sensor
await coap_client.put("coap://sensor-042.local/config",
                      {"interval": 3600, "threshold": 30})

Requirements:

  • 200 machines with vibration sensors
  • Real-time dashboard (5 simultaneous users)
  • Cloud analytics (AWS)
  • Alarms to multiple recipients

Decision: MQTT

Reasoning:

  1. Publish-subscribe: 1 sensor to Dashboard + Analytics + Alarms (3 subscribers)
  2. Cloud integration: AWS IoT Core native MQTT support
  3. Guaranteed delivery: QoS 1 ensures alarm messages reach all recipients
  4. Scalability: MQTT broker handles 10,000+ concurrent connections
  5. Persistent sessions: Dashboard reconnects and receives missed updates

Implementation:

# Sensor publishes once
mqtt_client.publish("factory/machine/042/vibration",
                   {"value": 2.5, "unit": "mm/s", "alarm": true},
                   qos=1)

# Multiple subscribers receive automatically
# Dashboard: subscribes to "factory/+/vibration"
# Analytics: subscribes to "factory/#"
# Alarms: subscribes to "factory/+/vibration" with alarm=true filter

Scenario: 500 delivery trucks reporting GPS every 10 seconds to cloud dashboard viewed by 5 dispatchers.

Decision: MQTT

Reasoning:

  • One-to-many communication (trucks to multiple dashboards)
  • Each truck publishes to fleet/truck-id/gps
  • All 5 dispatchers subscribe to fleet/+/gps
  • Broker handles distribution efficiently

Why not CoAP:

  • CoAP Observe would require 500 x 5 = 2,500 subscriptions
  • MQTT’s broker-based fan-out is more scalable

49.8 Multicast Advantages

Knowledge Check: Concept Matching

Match each protocol term or feature to its correct definition or characteristic.

Knowledge Check: Protocol Selection Ordering

Arrange the steps of the CoAP protocol decision process in the correct sequence — from gathering requirements through to verifying the choice in production.

49.9 Total Cost of Ownership: Protocol Choice at Scale

The wrong protocol choice has measurable financial consequences. Here is a concrete TCO comparison for a 10,000-device smart metering deployment over 5 years using NB-IoT cellular connectivity.

49.9.1 Interactive Cost Calculator

Use this calculator to estimate data costs for your deployment:

Interpreting the Results

The calculator shows the dramatic impact of protocol choice on operational costs. For battery-powered sensors reporting infrequently, CoAP’s smaller message size translates directly to lower cellular data costs. The savings become more significant as you scale to thousands of devices.

Key insight: At typical cellular rates ($0.50/MB), CoAP saves ~75% compared to HTTP for the same deployment.

49.9.2 Scenario: Smart Water Meters (10,000 units, NB-IoT, hourly reporting)

Assumptions:

  • 10,000 meters, each reporting 1 reading per hour (24 messages/day)
  • NB-IoT carrier charges $0.50 per MB per month
  • Battery: 2x AA lithium (3,000 mAh total), $1.50 per replacement
  • Target: 10-year battery life (avoid truck rolls for replacement)

CoAP (NON over UDP):

Message size: 4 (CoAP) + 8 (UDP) + 40 (IPv6) + 12 (payload) = 64 bytes
Daily data per meter: 24 x 64 = 1,536 bytes = 1.5 KB
Monthly data per meter: 45 KB
Monthly data cost per meter: 45 KB / 1,024 KB * $0.50 = $0.022
Annual data cost (fleet): 10,000 x $0.022 x 12 = $2,640
5-year data cost: $13,200

Energy per message: 1.5 mJ (NON, no handshake)
Daily energy: 24 x 1.5 mJ = 36 mJ
Annual energy: 36 x 365 = 13,140 mJ = 13.14 J
Battery capacity: 3,000 mAh x 3.6V = 10,800 J
Battery life: 10,800 / 13.14 = ~822 years (sleep current dominates)
Effective battery life: ~12 years (limited by self-discharge)
Battery replacements in 5 years: 0

MQTT (QoS 1 over TCP):

Message size: 2 (MQTT) + 20 (TCP) + 40 (IPv6) + 12 (payload) = 74 bytes
BUT TCP adds connection overhead:
  TCP handshake: 3 packets x 60 bytes = 180 bytes (per connection)
  TLS handshake (required by most brokers): ~2,500 bytes
  Keepalive: 2 packets x 60 bytes = 120 bytes every 60 seconds

Strategy A (persistent connection, 60s keepalive):
  Keepalive data: 120 bytes x 60 min x 24 hr = 172,800 bytes/day
  Message data: 24 x 74 = 1,776 bytes/day
  Total daily: 174,576 bytes = 170 KB
  Monthly: 5.1 MB
  Monthly cost per meter: $2.55
  Annual data cost (fleet): 10,000 x $2.55 x 12 = $306,000
  5-year data cost: $1,530,000

Strategy B (reconnect per message, skip keepalive):
  Connection overhead: 24 x (180 + 2,500) = 64,320 bytes/day
  Message data: 24 x 74 = 1,776 bytes/day
  Total daily: 66,096 bytes = 64.5 KB
  Monthly: 1.93 MB
  Monthly cost per meter: $0.97
  Annual data cost (fleet): 10,000 x $0.97 x 12 = $116,400
  5-year data cost: $582,000

Energy per connection cycle: 45 mJ (TCP+TLS handshake) + 4.5 mJ (MQTT) = 49.5 mJ
Daily energy: 24 x 49.5 = 1,188 mJ
Annual energy: 1,188 x 365 = 433,620 mJ = 433.6 J
Battery life: 10,800 / 433.6 = ~24.9 years (sleep current dominates)
Effective battery life: ~10 years (limited by self-discharge)
Battery replacements in 5 years: 0

5-Year TCO Comparison:

Cost Category CoAP MQTT (Strategy B) Difference
Data transmission $13,200 $582,000 CoAP saves $568,800
Battery replacement $0 $0 Equal
Server infrastructure $6,000 (LwM2M) $24,000 (MQTT broker cluster) CoAP saves $18,000
Total 5-year TCO $19,200 $606,000 CoAP saves $586,800

At $0.50/MB, CoAP’s 27x smaller message footprint translates to $586,800 in savings over 5 years for 10,000 meters. Even at $0.01/MB (bulk pricing), CoAP still saves $11,700 – enough to fund the engineering effort of CoAP implementation.

49.10 Decision Flowchart

Protocol decision flowchart

Scenario: A logistics company operates 10,000 delivery trucks with GPS trackers reporting every 30 seconds. Backend dashboard shows real-time locations, route optimization service processes historical tracks, and compliance system logs all movements.

Calculating 5-year TCO (cellular data at $0.05/MB):

Option A: HTTP REST polling (baseline):

Payload: JSON {"lat": 37.7749, "lon": -122.4194, "speed": 45, "timestamp": 1706140800}
HTTP overhead: ~320 bytes (headers + JSON) per request
Messages: 10,000 trucks × 2,880/day = 28.8M messages/day

Monthly data: 28.8M × 320 bytes × 30 days = 276 GB/month
Monthly cost: 276 GB × $0.05/MB × 1024 = $14,131/month
5-year cost: $14,131 × 60 = $847,860

Option B: MQTT (QoS 1, persistent sessions):

Payload: JSON (same 90 bytes), MQTT header 2 bytes, topic 20 bytes
Total: 112 bytes per message
TCP handshake amortized over 2,880 daily messages: 180 bytes / 2,880 = 0.06 bytes/message

Monthly data: 28.8M × 112 × 30 = 96.8 GB/month
Monthly cost: 96.8 GB × $51.20 = $4,956/month
5-year cost: $4,956 × 60 = $297,360

Option C: CoAP (NON messages, CBOR payload):

Payload: CBOR {lat: 37.7749, lon: -122.4194, spd: 45, ts: 1706140800} = 28 bytes
CoAP header: 4 bytes, UDP: 8 bytes, IPv6: 40 bytes
Total: 80 bytes per message (no connection setup)

Monthly data: 28.8M × 80 × 30 = 69.1 GB/month
Monthly cost: 69.1 × $51.20 = $3,538/month
5-year cost: $3,538 × 60 = $212,280

Decision: CoAP with CBOR

Savings vs HTTP: $847,860 - $212,280 = $635,580 over 5 years Savings vs MQTT: $297,360 - $212,280 = $85,080 over 5 years

Additional benefits:

  • Battery backup in trucks lasts 18 hours (CoAP) vs 8 hours (MQTT) during alternator failure
  • No broker infrastructure cost (MQTT would require $500/month for 10K concurrent connections)
  • Multicast fleet-wide commands: coap://[ff02::fd]/command/update reaches all trucks on subnet

49.10.1 Interactive Protocol Selection Scorecard

Rate each requirement based on your project’s priorities to get a data-driven protocol recommendation:

Using the Scorecard
  1. Adjust the sliders based on your project requirements (1=not important, 5=critical)
  2. Review the scores - the highest score indicates the best protocol match
  3. Consider the margin - if scores are close, evaluate secondary factors like team expertise and existing infrastructure

Example scenarios:

  • Battery-critical sensors: Weight battery life=5, bandwidth=5 → Likely favors CoAP
  • Cloud dashboard with multiple users: Weight pub/sub=5, cloud=5 → Likely favors MQTT
  • Web-integrated devices: Weight HTTP infrastructure=5, NAT traversal=5 → Favors HTTP

49.11 Summary

Protocol selection depends on your specific requirements:

Choose CoAP when:

  • Battery life is critical (multi-year on coin cell)
  • Direct device-to-device communication (no broker)
  • Constrained networks (LoRaWAN, NB-IoT)
  • Multicast queries needed
  • RESTful API semantics required

Choose MQTT when:

  • Multiple subscribers need same data
  • Cloud platform integration (AWS IoT, Azure)
  • Persistent sessions for offline devices
  • Unreliable networks (TCP handles retransmission)

Choose HTTP when:

  • Web browser integration needed
  • Rich tooling required
  • Resources are abundant
  • Standard web APIs preferred

Key metrics to compare:

  • Message overhead: CoAP (30 bytes) < MQTT (55 bytes) < HTTP (320 bytes)
  • Energy per message: CoAP NON (1.5 mJ) < CON (3.0 mJ) < MQTT (4.5 mJ) < HTTP (8.0 mJ)
  • RAM footprint: CoAP (1-2 KB) < MQTT (3-5 KB) < HTTP (10-20 KB)

49.12 Concept Relationships

This decision framework integrates knowledge from across IoT networking:

Protocol Understanding Required:

Decision Factors:

Deployment Patterns:

49.13 See Also

Protocol Comparisons:

Cost Analysis:

Case Studies:

49.14 What’s Next

Now that you can select the right protocol, continue with these related chapters:

Chapter Focus Why Read It
CoAP Features and Labs Hands-on CoAP implementation Apply the decision you made here — implement CON/NON messaging, Observe subscriptions, and resource discovery in practice
CoAP Comprehensive Review Full CoAP protocol reference Consolidate all CoAP knowledge from message format to block transfer and DTLS security
MQTT Fundamentals MQTT architecture and QoS levels Deepen your understanding of the publish-subscribe alternative when CoAP is not the right fit
Application Protocols Overview AMQP, DDS, XMPP, and CoAP compared See how CoAP and MQTT sit within the broader landscape of IoT application-layer protocols
Energy-Aware Design Battery life calculations for IoT Apply the energy-per-message figures from this chapter to a full device power budget
CoAP Fundamentals and Architecture CoAP message types and transport Review the underlying protocol mechanics that drive the trade-offs analysed in this chapter