40  CoAP Fundamentals

In 60 Seconds

CoAP (Constrained Application Protocol) is a lightweight RESTful protocol purpose-built for resource-constrained IoT devices, achieving 90-95% smaller headers than HTTP (4 bytes vs 200+) and 10-15x lower energy consumption over UDP. Its key differentiators are optional reliability via CON/NON message types and the Observe pattern for push-based updates without polling.

MVU: Most Valuable Understanding

CoAP is NOT “HTTP over UDP” - it’s a purpose-built protocol for constrained devices with unique features. The key insight is that CoAP achieves 90-95% smaller headers (4 bytes vs 200+ in HTTP), 10-15x lower energy consumption, and adds features HTTP lacks: optional reliability via CON/NON message types, and the Observe pattern for push-based updates without polling. Choose CoAP for request-response on battery devices; choose MQTT for pub-sub streaming.

40.1 CoAP Fundamentals

⏱️ ~8 min | ⭐⭐ Intermediate | 📋 P09.C28.U01a

This chapter introduces the Constrained Application Protocol (CoAP), a lightweight RESTful protocol designed specifically for resource-constrained IoT devices.

40.2 Learning Objectives

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

  • Explain CoAP’s Design: Describe how CoAP achieves 90-95% smaller headers than HTTP and justify why UDP transport is chosen over TCP for constrained devices
  • Compare Protocols: Distinguish between CoAP, HTTP, and MQTT across dimensions of overhead, reliability, and use-case fit, selecting the appropriate protocol for a given IoT scenario
  • Implement CoAP Communication: Apply CoAP GET, POST, PUT, and DELETE methods correctly for machine-to-machine resource operations
  • Analyze Message Type Trade-offs: Evaluate the energy and reliability consequences of choosing Confirmable (CON) versus Non-Confirmable (NON) messages for different sensor data scenarios
  • Calculate Protocol Overhead: Compute message sizes, fragmentation impact, and battery life estimates to justify CoAP adoption in resource-constrained deployments
  • Design CoAP-Based Systems: Construct a two-layer CoAP architecture that separates messaging reliability from RESTful request-response semantics

Think of CoAP as “HTTP’s little sibling” built specifically for tiny devices.

You know how websites use HTTP to communicate? When you visit a webpage, your browser sends a request (GET /page) and the server responds with content. CoAP works the same way, but it’s designed for devices with very limited resources—like a battery-powered temperature sensor with only 10KB of memory.

The Problem CoAP Solves:

HTTP is great for web browsers but terrible for tiny IoT sensors because: - HTTP headers can be hundreds of bytes—wasteful when your sensor data is just “22.5°C” - HTTP requires TCP connections with multiple handshakes—drains batteries - HTTP parsing is complex—needs more processing power

How CoAP is Different:

Feature HTTP CoAP
Header size 100s of bytes Just 4 bytes!
Runs over TCP (reliable but heavy) UDP (lightweight)
Best for Web browsers Tiny sensors

Real-world analogy: HTTP is like sending a formal letter (envelope, address, return address, stamp, tracking). CoAP is like sending a postcard—minimal overhead, gets the message across.

When to Use CoAP:

  • Direct device control: “Turn on the light” → device responds “OK”
  • Reading sensor values: “What’s the temperature?” → “22.5°C”
  • Very constrained devices: Devices with <100KB RAM, running on coin-cell batteries
  • Where UDP works: Local networks, not blocked by firewalls

Key Concepts You’ll Learn:

  • CON (Confirmable): “Did you get my message?” - reliable delivery
  • NON (Non-confirmable): Fire-and-forget - fastest but no guarantee
  • GET/POST/PUT/DELETE: Same concepts as HTTP REST APIs
  • Observe: Like subscribing to updates (similar to MQTT’s publish-subscribe)

By the end of this chapter, you’ll understand when to choose CoAP vs MQTT vs HTTP for your IoT projects!

Meet the Sensor Squad! Sammy the Temperature Sensor has a problem - sending messages is using up all his battery power!

The Problem: Sammy lives in a greenhouse and needs to tell the Gardener App what temperature it is. But sending letters (HTTP) takes SO much energy!

“Every time I send my temperature, I have to write this looooong letter,” sighs Sammy. “Dear Gardener App, Version 1.1, from Sammy, content type is text, my temperature is 22 degrees, sincerely yours truly…” That’s 200 tiny words just to say ONE number!

Lila the Light Sensor suggests: “Why not try POSTCARDS instead? That’s what CoAP is - the Postcard Protocol!”

With CoAP postcards, Sammy just writes: “22°C” - only 4 tiny words for the address plus the message!

Max the Motion Sensor explains the two types of postcards:

Red postcards (CON) are for IMPORTANT messages. When you send one, the Gardener App MUST send back a thumbs-up emoji to prove they got it!”

Blue postcards (NON) are for regular updates. You just toss them in the mailbox and hope they arrive. If one gets lost, no worries - the next one is coming in 5 minutes anyway!”

Bella the Button asks: “When should I use which color?”

Sammy’s Rule: “If the greenhouse will catch fire without this message, use RED (CON). If I’m just saying ‘still 22 degrees, still 22 degrees’, use BLUE (NON).”

The Happy Ending: Sammy switched from letters (HTTP) to postcards (CoAP) and now his battery lasts 2 YEARS instead of 2 months! The other sensors all learned the Postcard Protocol too.

The Lesson: CoAP is like sending postcards instead of formal letters - you get the message across with way less effort!

Key Takeaway

In one sentence: CoAP brings REST to constrained devices over UDP, providing HTTP-like semantics with minimal overhead for resource-limited IoT sensors.

Remember this rule: Use CoAP for request-response patterns on battery-powered devices that need direct addressing; use MQTT when you need event-driven pub-sub streaming or broker-based decoupling.

40.3 Prerequisites

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

  • MQTT Protocol: Understanding the alternative publish-subscribe messaging approach helps appreciate CoAP’s request-response model and when to choose each protocol
  • Networking Basics: Foundation for understanding RESTful principles, HTTP methods (GET/POST/PUT/DELETE), URIs, and how CoAP adapts these concepts for constrained devices
  • UDP/IP Networking: CoAP operates over UDP rather than TCP, requiring knowledge of connectionless communication, packet loss, and reliability trade-offs

Common Pitfalls

CON messages require an ACK roundtrip — on lossy networks with 20% packet loss, a 4-attempt retry with exponential backoff can delay responses by 45 seconds. Use NON for periodic telemetry where data freshness matters more than guaranteed delivery; reserve CON for actuation commands.

CoAP proxies cache GET responses based on Max-Age option — a sensor returning temperature with Max-Age=60 will serve cached values for 60 seconds even if the physical reading changes. Set Max-Age to match your data freshness requirement, not the default 60 seconds.

DTLS handshake (6-8 roundtrips) dominates latency for short-lived CoAP connections — repeatedly creating new DTLS sessions for each request adds 500-2000ms overhead. Use DTLS session resumption (RFC 5077) to reduce reconnection to 1 roundtrip after the initial handshake.

40.4 What is CoAP?

In Plain English

CoAP is like a lightweight version of the web (HTTP) designed for tiny devices. Instead of heavy web requests, CoAP uses small UDP packets - perfect for sensors with limited memory and battery.

Everyday Analogy: If HTTP is a formal letter with envelope, address, and tracking, CoAP is a postcard - gets the message across with much less overhead.

When you’d use it: A battery-powered temperature sensor that needs to last 2 years, a smart light bulb that responds to commands instantly, or a building with 1,000 sensors where bandwidth is limited.

Definition

CoAP (Constrained Application Protocol) is a specialized web transfer protocol designed for resource-constrained nodes and networks. It provides a lightweight RESTful interface similar to HTTP, but optimized for IoT devices with limited processing power, memory, and energy.

Designed by: IETF Constrained RESTful Environment (CoRE) Working Group

Key Characteristics:

  • Transport: UDP (not TCP like HTTP)
  • Architecture: RESTful (like HTTP)
  • Security: DTLS (Datagram TLS)
  • Overhead: Minimal (4-byte header vs HTTP’s larger headers)
  • Network: IPv4 and IPv6 (esp. for IEEE 802.15.4)
  • Use Cases: Smart energy, building automation, sensor networks

40.5 Why CoAP Instead of HTTP?

40.5.1 The Problem with HTTP for IoT

HTTP is excellent for the web, but problematic for constrained devices:

Issue HTTP CoAP
Protocol TCP (connection-oriented) UDP (lightweight)
Diagram showing CoAP's four message types: Confirmable (CON) requires acknowledgment for reliable delivery, Non-Confirmable (NON) provides fire-and-forget communication without acknowledgment, Acknowledgment (ACK) confirms receipt of CON messages, and Reset (RST) rejects invalid messages
Figure 40.1: CoAP message types: CON, NON, ACK, RST

Geometric diagram of CoAP message format showing compact 4-byte fixed header containing Version (2 bits), Type (2 bits for CON/NON/ACK/RST), Token Length (4 bits), Code (8 bits combining class and detail), and Message ID (16 bits). Variable-length Token, Options, and Payload follow the header. Shows how CoAP achieves minimal overhead compared to HTTP headers

CoAP Header Format
Figure 40.2: CoAP’s 4-byte base header achieves minimal overhead while providing reliable messaging options. The compact design is essential for resource-constrained devices with limited memory and bandwidth.

Artistic visualization of CoAP Observe mechanism showing client registering interest in a resource, then server pushing updates whenever the resource value changes. Demonstrates how CoAP enables publish-subscribe patterns similar to MQTT while maintaining RESTful semantics. Shows notification sequence with token matching for multiple observations

CoAP Observe Mechanism
Figure 40.3: CoAP Observe extends the RESTful model with server push notifications. Clients register interest in a resource, and the server pushes updates on value changes, combining the simplicity of REST with the efficiency of publish-subscribe.

Artistic visualization of CoAP protocol stack showing Application at top, CoAP layer providing RESTful interface, DTLS for security, UDP for transport, and IP/6LoWPAN at network layer, compared with HTTP stack showing HTTP over TLS over TCP.

CoAP Protocol Stack
Figure 40.4: CoAP protocol stack vs HTTP stack

CoAP runs over UDP rather than TCP, eliminating connection establishment overhead. For security, CoAP uses DTLS (Datagram TLS) which provides the same cryptographic protection as TLS but adapted for unreliable transport. The 6LoWPAN adaptation layer enables CoAP over IEEE 802.15.4 networks.

Geometric diagram of CoAP request-response transaction showing confirmable GET request from client to server, followed by piggybacked ACK response containing the requested resource representation, demonstrating reliable message exchange.

CoAP Request-Response
Figure 40.5: CoAP confirmable request with piggybacked response

Confirmable messages (CON) provide reliability over unreliable UDP. The server can piggyback the response directly on the ACK, reducing round trips. For slow operations, the server sends an empty ACK immediately and the response separately (separate response pattern).

Artistic representation of CoAP Block-wise transfer showing large resource split into multiple blocks with Block1 option for uploads and Block2 for downloads, enabling transfer of resources larger than typical CoAP message size limits.

CoAP Block Transfer
Figure 40.6: CoAP block-wise transfer for large resources

Block-wise transfer (RFC 7959) enables transferring resources larger than typical CoAP MTU limits. Block1 handles request payloads (e.g., firmware uploads), while Block2 handles response payloads. Each block is individually acknowledged, providing partial reliability.

Geometric diagram of CoAP resource discovery showing client sending GET request to /.well-known/core endpoint, server responding with CoRE Link Format listing available resources with attributes like rt (resource type), if (interface), and sz (size).

CoAP Resource Discovery
Figure 40.7: CoAP resource discovery using .well-known/core

CoAP devices expose their resources through the /.well-known/core URI, responding in CoRE Link Format. This enables automatic discovery of available sensors, actuators, and their capabilities, supporting zero-configuration deployments.

Header Size | 100s of bytes | 4 bytes minimum |
Power Consumption | High (TCP handshake) | Very low |
Overhead | Significant | Minimal |
Complexity | Complex parsing | Simple |
Best For | Web browsers | Sensors, actuators |
Real-World Example: Smart Light Bulb Control

Scenario: Your smartphone wants to turn on a Philips Hue-style smart light bulb.

HTTP Approach:

Total bytes: 547 bytes
- TCP handshake: 3 packets (SYN, SYN-ACK, ACK)
- HTTP request: ~200 bytes
  GET /light/on HTTP/1.1
  Host: 192.168.1.50
  User-Agent: SmartHome/1.0
  Accept: application/json
  Connection: keep-alive
  [blank line]
- HTTP response: ~150 bytes
  HTTP/1.1 200 OK
  Content-Type: application/json
  Content-Length: 15
  {"status":"on"}
- Time: 150-300ms
- Energy: ~45 mJ

CoAP Approach:

Total bytes: 28 bytes
- CoAP request: 14 bytes
  CON GET /light/on
  (4-byte header + 10 bytes token/options)
- CoAP response: 14 bytes
  ACK 2.04 Changed
  (4-byte header + 10 bytes payload)
- Time: 20-50ms
- Energy: ~3 mJ

Result: CoAP uses 95% fewer bytes, 10x faster response, and 15x less energy than HTTP. For a battery-powered light switch, this means 2 years of battery life vs 2 months with HTTP!

40.6 Putting Numbers to It

We can quantify the overhead ratio precisely. CoAP’s total message size is 28 bytes while HTTP requires 547 bytes:

\[\text{Overhead Ratio} = \frac{\text{HTTP bytes}}{\text{CoAP bytes}} = \frac{547}{28} \approx 19.5\]

For the smart building scenario with 500 switches and 20 presses/day:

\[\text{Daily Messages} = 500 \times 20 = 10{,}000 \text{ messages}\]

\[\text{Bandwidth Saved} = 10{,}000 \times (547 - 28) = 5{,}190{,}000 \text{ bytes/day} \approx 5.19 \text{ MB/day}\]

Over a year: \(5.19 \times 365 \approx 1{,}894 \text{ MB} \approx 1.85 \text{ GB saved}\). At typical cellular data rates ($0.50/MB), this saves approximately $947/year just in data costs.

Why this matters: In a smart building with 500 light switches each pressed 20 times/day, CoAP saves approximately 1.85 GB of bandwidth and $947/year in cellular data costs compared to HTTP.

UDP Means No Reliability Guarantees

CoAP uses UDP, which has critical implications for IoT deployments:

UDP characteristics:

  • No connection - packets can arrive out-of-order or be lost
  • No automatic retransmission - application must handle with CON messages
  • No congestion control - can overwhelm networks if not careful
  • Firewall/NAT challenges - many networks block UDP traffic

When this causes problems:

  • Lossy Wi-Fi/cellular networks: 10-30% packet loss means frequent retransmissions
  • Firewall traversal: Corporate networks often block UDP, preventing CoAP communication
  • NAT timeout: UDP “connections” expire faster than TCP (30-60 seconds typical)

Solutions:

  • Use CON messages for important data (adds reliability)
  • Implement exponential backoff for retransmissions
  • Consider MQTT (TCP-based) for unreliable networks
  • Use CoAP over DTLS for secure, more reliable communication
  • Test thoroughly in production network conditions
What Would Happen If: 15% Packet Loss Scenario

Scenario: You deploy 50 CoAP temperature sensors in a warehouse with spotty Wi-Fi. Network analysis shows 15% packet loss.

With NON (Non-Confirmable) Messages:

Impact analysis diagram showing NON messages result in 15% data loss (85% delivery) but 50% better battery life, with timeline showing some sensor readings lost but significantly reduced energy consumption over time
Figure 40.8: Impact of using NON messages showing 15 percent data loss but 50 percent better battery life

With CON (Confirmable) Messages:

Impact analysis diagram showing CON messages achieve 99.6% delivery rate through acknowledgments and retransmissions, but battery consumption doubles due to waiting for ACKs and retransmitting lost packets
Figure 40.9: Impact of using CON messages showing 99.6 percent delivery rate but doubled battery consumption

The Trade-Off Decision:

Approach Use When Don’t Use When
Stick with NON Data is statistical (average temps okay), battery life critical, dashboards show “last reading: 2 min ago” is acceptable Regulatory compliance required, missing data causes alarms, each reading is critical
Switch to CON Each reading matters (billing, safety), can afford battery replacement, data integrity > battery life Battery replacement impossible (remote sensors), network has >20% loss (retransmissions overwhelm it), latency-sensitive
Hybrid approach Send NON normally, CON for alerts/changes -
Switch to MQTT/TCP Persistent 15%+ loss, infrastructure supports broker, many sensors Low power critical, direct device-to-device needed

Real-World Fix: The warehouse deployed a mesh Wi-Fi extender ($80), reducing packet loss to 2%. Kept NON messages, achieved 98% delivery rate with 2-year battery life. Cost of solution < cost of 6-month battery replacements.

When to Choose CoAP Over MQTT

Both are lightweight IoT protocols, but serve different use cases:

Choose CoAP when:

  • You need request-response pattern (like HTTP GET/POST)
  • RESTful API design is important (resources with URIs)
  • Minimal overhead is critical (4-byte header vs MQTT’s 2-byte minimum + TCP overhead)
  • Devices sleep most of the time (CoAP stateless, reconnects fast)
  • Integration with web services (CoAP to HTTP proxies exist)

Choose MQTT when:

  • You need publish-subscribe (one-to-many communication)
  • Persistent connections are acceptable
  • Network is unreliable (TCP handles retransmissions automatically)
  • Multiple subscribers need same data
  • Broker-based architecture fits your deployment

Example: Smart thermostat that responds to user commands → CoAP. Temperature sensor publishing to dashboard and logging service → MQTT.

40.6.1 REST for Constrained Devices

REST (Representational State Transfer) is the standard interface between HTTP clients and servers. CoAP brings REST to IoT:

Sequence diagram showing CoAP RESTful operations with GET request retrieving temperature sensor value, POST creating new configuration, and PUT updating existing threshold setting, demonstrating REST semantics over UDP
Figure 40.10: CoAP RESTful Operations: GET, POST, and PUT Method Examples

Matrix diagram of CoAP message types showing four combinations: Confirmable (CON) for reliable delivery with acknowledgment, Non-Confirmable (NON) for fire-and-forget transmission, Acknowledgment (ACK) for confirming CON messages, and Reset (RST) for error signaling

This diagram shows CoAP’s four message types: CON for reliable transfer, NON for fire-and-forget, ACK for confirmations, and RST for error handling.

REST principles in CoAP:

  • Resources identified by URIs (like HTTP)
  • Standard methods: GET, POST, PUT, DELETE
  • Stateless client-server architecture
  • Content-type support (JSON, XML, etc.)

40.7 CoAP Architecture

CoAP is divided into two sublayers:

Layered architecture diagram showing CoAP two-layer model with Request/Response layer above handling REST semantics (GET, POST, PUT, DELETE) and Messaging layer below handling reliability (CON, NON, ACK, RST), demonstrating separation of concerns
Figure 40.11: CoAP Two-Layer Architecture: Request/Response and Messaging

40.7.1 Messaging Layer

Responsibilities:

  • Reliability (when needed)
  • Duplicate message detection
  • Message ID management
  • Acknowledgments

40.7.2 Request/Response Layer

Responsibilities:

  • Client-server communication
  • Resource operations (GET, POST, PUT, DELETE)
  • URI/URL resource retrieval
  • Content negotiation

Diagram showing how CoAP's Request/Response layer sits above the Messaging layer. The Request/Response layer handles GET, POST, PUT, DELETE operations and resource URIs, while the Messaging layer handles CON, NON, ACK, RST message types, retransmissions, and duplicate detection.

CoAP Two-Layer Architecture Interaction

This alternative view shows how application data flows through CoAP’s two layers before reaching the UDP transport. The separation of concerns allows the messaging layer to handle reliability independently from the RESTful semantics.

40.8 Knowledge Check

Term Definition
CoAP Constrained Application Protocol - lightweight RESTful protocol for IoT devices
CON Confirmable message - requires acknowledgment, provides reliability
NON Non-Confirmable message - fire-and-forget, no acknowledgment required
ACK Acknowledgment message - confirms receipt of CON messages
RST Reset message - indicates error or rejection of a message
DTLS Datagram TLS - security protocol for UDP (CoAP’s equivalent of TLS)
6LoWPAN IPv6 over Low-Power Wireless Personal Area Networks - adaptation layer for IEEE 802.15.4
Block-wise Transfer RFC 7959 extension for transferring large payloads in multiple blocks
Observe CoAP extension (RFC 7641) for server-push notifications on resource changes
Piggybacked Response Response sent directly within the ACK message to reduce round trips
Separate Response Response sent in a separate message after an empty ACK (for slow operations)

The Business Case for CoAP:

CoAP enables 10-15x longer battery life in IoT deployments compared to HTTP, directly reducing total cost of ownership through fewer battery replacements and lower maintenance visits.

Key Cost Savings:

Metric HTTP CoAP Savings
Battery life (AA cells) 2-4 months 2-3 years 6-15x
Bandwidth per message 500+ bytes 20-50 bytes 90-95%
Latency 150-300ms 20-50ms 3-10x faster
Annual data costs (1000 sensors) $15,000 $1,500 $13,500/year

When to Recommend CoAP:

  • Field deployments: Agricultural sensors, environmental monitoring, smart city infrastructure
  • Battery-powered devices: Anything that can’t be easily recharged or replaced
  • High-density deployments: Thousands of sensors where bandwidth costs matter
  • Low-latency control: Real-time actuator commands for industrial automation

Risk Considerations:

  • UDP may be blocked by corporate firewalls (test before deployment)
  • Fewer developers familiar with CoAP vs HTTP (training investment)
  • Smaller ecosystem of tools and libraries (improving rapidly)

Bottom Line: For battery-powered IoT with request-response communication patterns, CoAP delivers 10x+ operational cost savings with proven reliability. MQTT remains better for pub-sub streaming scenarios.

40.9 Worked Example: Choosing Between CoAP and HTTP for a Smart Building Retrofit

Scenario: A facility manager is retrofitting a 10-story office building with 800 battery-powered environmental sensors (temperature, humidity, CO2) and 200 mains-powered HVAC actuators. Sensors run on CR2477 coin cells (1,000 mAh) and must last 3 years. All devices communicate over 6LoWPAN/802.15.4 to floor gateways that bridge to the building management system (BMS). The BMS software team is experienced with REST APIs. Should the sensor-to-gateway communication use CoAP or HTTP?

Step 1: Message Size Comparison

A typical sensor reading: {"temp": 22.3, "rh": 45, "co2": 812} = 38 bytes payload.

Component HTTP (over TCP) CoAP (over UDP)
Transport header 20 bytes (TCP) 8 bytes (UDP)
Protocol header 200-400 bytes (HTTP headers, host, content-type, user-agent) 4 bytes (CoAP fixed header)
Options/URI ~50 bytes (URL path) ~12 bytes (CoAP URI options, compressed)
Payload 38 bytes 38 bytes
Total per message 308-508 bytes 62 bytes
TCP handshake (amortized) +120 bytes if connection reused; +240 bytes if new 0 bytes (UDP, connectionless)

Payload efficiency: CoAP achieves 61% payload efficiency (38/62) versus HTTP at 7-12% (38/308-508). For the same sensor reading, HTTP transmits 5-8x more bytes.

Step 2: Battery Life Calculation

Each sensor reports every 5 minutes (288 messages/day) over 802.15.4 at 250 kbps:

CoAP:
  TX per message: 62 bytes x 8 bits / 250,000 bps = 1.98 ms
  Daily TX: 288 x 1.98 ms = 570 ms at 17 mA = 2.69 uAh
  Daily sleep: 86,400 s at 2 uA = 48 uAh
  Total daily: 50.7 uAh
  Battery life: 1,000,000 uAh / 50.7 = 19,724 days = 54 years

HTTP (new TCP connection each time):
  TX per message: 508 bytes x 8 / 250,000 = 16.3 ms
  TCP handshake: 3 x 40 bytes x 8 / 250,000 = 3.84 ms
  Total TX: 288 x (16.3 + 3.84) ms = 5,800 ms at 17 mA = 27.4 uAh
  Daily sleep: 48 uAh
  Total daily: 75.4 uAh
  Battery life: 1,000,000 / 75.4 = 13,263 days = 36 years

Both protocols exceed the 3-year target in this calculation, but the real-world gap is larger because HTTP requires TCP state management (additional RAM and CPU wakeups for retransmissions and keepalives), which roughly doubles its actual energy consumption.

Step 3: 6LoWPAN Fragmentation Impact

802.15.4 maximum frame payload = 81 bytes (after MAC header). What happens when a message exceeds this?

Protocol Message Size Fragments Needed Fragmentation Overhead
CoAP 62 bytes 1 (fits in single frame) 0 bytes
HTTP (minimum) 308 bytes 4 fragments 16 bytes (4 x 4B fragment header)
HTTP (typical) 508 bytes 7 fragments 28 bytes

Critical insight: If any fragment is lost, the entire message must be retransmitted. At 5% link-level packet loss (typical for indoor 802.15.4), the probability of successfully delivering all fragments:

  • CoAP (1 fragment): 95% success rate
  • HTTP (7 fragments): 0.95^7 = 70% success rate

HTTP requires 43% more retransmissions than CoAP due to fragmentation losses alone.

Step 4: Decision Matrix

Criterion CoAP HTTP Winner
Message size 62 bytes 308-508 bytes CoAP
Battery life 54+ years 18-36 years CoAP
Fragmentation None (single frame) 4-7 fragments CoAP
Developer familiarity New protocol for team Existing expertise HTTP
Tool ecosystem aiocoap, libcoap Extensive HTTP
REST compatibility Full REST semantics Native REST Tie

Recommendation: Use CoAP for sensor-to-gateway communication. The BMS team’s HTTP expertise is preserved at the gateway, which translates CoAP to HTTP for the cloud-facing API. This is the standard architecture: constrained devices speak CoAP on the local network, while gateways bridge to HTTP/MQTT for backend systems.

For the 200 HVAC actuators (mains-powered): HTTP is acceptable since power is not a constraint. However, using CoAP uniformly simplifies the gateway’s translation logic and avoids maintaining two protocol stacks on the floor gateway.

40.10 Summary

This chapter introduced CoAP as a lightweight alternative to HTTP for constrained IoT devices:

  • CoAP vs HTTP: CoAP uses UDP with 4-byte headers (vs HTTP’s 200+ bytes over TCP), achieving 90-95% smaller overhead and 10-15x lower energy consumption
  • RESTful Design: CoAP uses familiar GET, POST, PUT, DELETE methods with URI-based resources, making it compatible with web service patterns
  • Message Types: Confirmable (CON) provides reliability with acknowledgments; Non-Confirmable (NON) offers fire-and-forget efficiency for frequent telemetry
  • Architecture: Two-layer design separates messaging (reliability, duplicate detection) from request/response (resource operations)
  • When to Use: Choose CoAP for request-response on battery-powered devices; choose MQTT for pub-sub streaming with brokers

Flowchart showing when to choose CoAP: use for request-response patterns, battery-powered devices, direct device communication. Choose MQTT for pub-sub patterns, unreliable networks, or broker-based architectures.

CoAP Decision Framework Summary

CoAP Decision Framework Summary

Figure 40.12: Decision framework for choosing CoAP, showing the protocol selection path based on communication pattern and device constraints.

40.11 How It Works: CoAP Request-Response Cycle

Understanding a complete CoAP transaction helps solidify the concepts:

Step-by-step CoAP GET request (CON message):

  1. Client builds request:
    • Creates 4-byte header: Version=1, Type=CON, TKL=2, Code=GET (0.01)
    • Generates random Message ID (e.g., 0x1234) for ACK matching
    • Creates random Token (e.g., 0xABCD) for request-response correlation
    • Adds Uri-Path option: /temperature
    • Total: 10 bytes (header + token + option)
  2. Client sends over UDP:
    • Adds UDP header (8 bytes), IPv6 header (40 bytes)
    • Starts retransmission timer (default: 2-3 seconds)
    • Radio transmits packet to server
  3. Server receives and processes:
    • Validates header (Version=1, Type=CON requires ACK)
    • Extracts Token (0xABCD) for response correlation
    • Routes to /temperature resource handler
    • Reads sensor: 22.5°C
  4. Server responds (piggybacked ACK):
    • Builds ACK header: Type=ACK, Code=2.05 Content
    • Copies Message ID from request (0x1234) - critical for ACK matching
    • Copies Token from request (0xABCD) - critical for request correlation
    • Adds Content-Format option: 0 (text/plain)
    • Adds payload: “22.5”
    • Sends response
  5. Client receives response:
    • Matches Message ID (0x1234) - stops retransmission timer
    • Matches Token (0xABCD) - correlates to original GET request
    • Extracts payload: “22.5”
    • Application displays temperature

Energy comparison (802.15.4 radio at 8mA TX, 5mA RX, 250 kbps):

  • Request TX: 10 bytes → 0.32 ms @ 8 mA = 0.71 μAh
  • Wait for ACK: 50 ms @ 5 mA (radio stays on in RX mode) = 69.4 μAh
  • Response RX: 15 bytes → 0.48 ms @ 5 mA = 0.67 μAh
  • Total CON transaction: ~70.8 μAh

If using NON instead: - Request TX: 0.71 μAh - No ACK wait: 0 μAh - Total NON transaction: ~0.71 μAh (~100x less energy than CON)

The dominant energy cost in a CON transaction is not the radio transmission itself but the 50 ms spent in receive mode waiting for the ACK. This is why NON is preferred for frequent sensor readings where occasional loss is tolerable.

40.12 Concept Relationships

This foundational chapter connects to multiple IoT domains:

Protocol Foundation:

CoAP Deep Dives:

Device Constraints:

Implementation:

40.13 See Also

Learning Resources:

Hands-On Practice:

Protocol Comparisons:

40.14 What’s Next

Now that you understand the fundamentals of CoAP and its architecture, the chapters below continue the CoAP deep-dive and place it in the broader IoT protocol context.

Chapter Focus Why Read It
CoAP Message Types CON, NON, ACK, RST exchange patterns and piggybacked vs separate responses Understand how CoAP achieves optional reliability over UDP and when to use each message type
CoAP Methods and Patterns GET, POST, PUT, DELETE semantics, Observe extension, and block-wise transfer Apply CoAP’s RESTful methods to design real sensor and actuator APIs
CoAP Message Format Binary header layout, options encoding, and token/Message ID fields Diagnose packet-level issues and implement CoAP parsers on constrained hardware
CoAP Security and Applications DTLS setup, certificate handling, and real-world deployment case studies Secure CoAP deployments and evaluate CoAP in production smart-building and agricultural systems
MQTT Protocol Publish-subscribe broker model, QoS levels, and persistent sessions Compare CoAP request-response with MQTT pub-sub to select the right protocol for each scenario
Application Protocol Integration CoAP-to-HTTP proxying, MQTT bridging, and gateway architectures Design gateway systems that translate CoAP from constrained networks to cloud HTTP/MQTT backends