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
For Beginners: What is CoAP and Why Do We Need It?
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!
Sensor Squad: Sammy Learns the Postcard Protocol
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
1. Using Confirmable Messages for Every CoAP Request
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.
2. Ignoring CoAP Proxy Caching Semantics
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.
3. Forgetting DTLS Session Management
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)
Figure 40.1: CoAP message types: CON, NON, ACK, RST
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.
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.
Alternative Views: CoAP Architecture Visualizations
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.
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).
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.
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 |
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!
Show code
viewof messagesPerDay = Inputs.range([1,1000], {label:"Messages per day",value:288,step:1})viewof messageSize = Inputs.range([20,500], {label:"Total message size (bytes)",value:62,step:1})viewof batteryCapacity = Inputs.select( [1000,2000,3000,5000], {label:"Battery capacity (mAh)",value:1000,format: x => x ===1000?"1000 mAh (CR2477 coin cell)": x ===2000?"2000 mAh (AA alkaline)": x ===3000?"3000 mAh (AA lithium)":"5000 mAh (2×AA)" })batteryLifeCalc = {const bitrate =250000;// 802.15.4 at 250 kbpsconst txCurrent =17;// mA during transmissionconst sleepCurrent =0.002;// 2 uA during sleepconst txTimeMs = (messageSize *8/ bitrate) *1000;const dailyTxMs = messagesPerDay * txTimeMs;const dailyTxmAh = (dailyTxMs /1000/3600) * txCurrent;const secondsPerDay =86400;const sleepTimeS = secondsPerDay - (dailyTxMs /1000);const dailySleepMAh = (sleepTimeS /3600) * sleepCurrent;const dailyTotal = dailyTxmAh + dailySleepMAh;const lifeDays = batteryCapacity / dailyTotal;const lifeYears = lifeDays /365;return {txTimeMs: txTimeMs.toFixed(2),dailyTxMs: dailyTxMs.toFixed(1),dailyTxmAh: dailyTxmAh.toFixed(3),dailySleepMAh: dailySleepMAh.toFixed(3),dailyTotal: dailyTotal.toFixed(3),lifeDays:Math.floor(lifeDays),lifeYears: lifeYears.toFixed(1),lifeMonths: (lifeYears *12).toFixed(0) };}
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
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:
Figure 40.8: Impact of using NON messages showing 15 percent data loss but 50 percent better battery life
With CON (Confirmable) Messages:
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:
Figure 40.10: CoAP RESTful Operations: GET, POST, and PUT Method Examples
Alternative View: Message Type Matrix
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:
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
Alternative View: CoAP Protocol Layer Interaction
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
Matching Quiz: CoAP Concepts and Definitions
Ordering Quiz: CoAP CON Request-Response Sequence
Quick Check: CoAP Fundamentals
Key Terms: CoAP Vocabulary
Term
Definition
CoAP
Constrained Application Protocol - lightweight RESTful protocol for IoT devices
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)
Executive Summary: CoAP for Business Decision-Makers
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?
+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.
html`<div style="background: #fff3cd; padding: 20px; border-radius: 8px; border-left: 4px solid #E67E22; margin: 20px 0;"> <h4 style="color: #2C3E50; margin-top: 0;">📦 6LoWPAN Fragmentation Impact Calculator</h4> <div style="background: white; padding: 15px; border-radius: 6px; margin-top: 15px;"> <div style="color: #7F8C8D; margin-bottom: 15px;"> 802.15.4 MTU = 81 bytes | Link loss rate = ${packetLoss}% </div> <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;"> <div style="background: #e8f5e9; padding: 15px; border-radius: 6px; border: 2px solid #16A085;"> <div style="font-weight: bold; color: #16A085; margin-bottom: 10px;">CoAP (62 bytes)</div> <div style="color: #2C3E50;"> <strong>${fragmentationCalc.coapFragments} fragment(s)</strong><br/> Success rate: <strong style="color: #16A085;">${fragmentationCalc.coapSuccess}%</strong><br/> Extra retransmissions: <strong>${fragmentationCalc.coapRetransmissions}%</strong><br/> Fragmentation overhead: ${fragmentationCalc.coapOverhead} bytes </div> </div> <div style="background: #ffebee; padding: 15px; border-radius: 6px; border: 2px solid #E67E22;"> <div style="font-weight: bold; color: #E67E22; margin-bottom: 10px;">HTTP (${fragmentPayload} bytes)</div> <div style="color: #2C3E50;"> <strong>${fragmentationCalc.httpFragments} fragments</strong><br/> Success rate: <strong style="color: #E67E22;">${fragmentationCalc.httpSuccess}%</strong><br/> Extra retransmissions: <strong>${fragmentationCalc.httpRetransmissions}%</strong><br/> Fragmentation overhead: ${fragmentationCalc.httpOverhead} bytes </div> </div> </div> <div style="margin-top: 15px; padding: 12px; background: #fff9c4; border-radius: 6px; font-size: 14px; color: #2C3E50;"> ⚠️ <strong>Impact:</strong> HTTP requires ${fragmentationCalc.httpRetransmissions}% more retransmissions than CoAP due to fragmentation. If ANY fragment is lost, the ENTIRE message must be retransmitted. </div> </div></div>`
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.
Label the Diagram
💻 Code Challenge
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
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
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:
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.