CoAP Advanced Features: Reference
More
Depth: Practitioner
Progress saves as you read. Mark sections complete as you go; your progress appears in the sidebar.
Start With the Almost-Too-Large Update
Prove the Update Through a Broken Link
Picture a street sensor that needs a software fix over a weak radio link. The update is too large for one message, and the device may sleep before every part arrives. A safe release needs a clear final result, not a pile of successful sends.
Follow the opening case from its first sign to a careful next step.
Firmware is the software installed on a device. An over-the-air (OTA) update delivers replacement firmware through the network. CoAP, the Constrained Application Protocol, exchanges requests and responses for named resources.
Work through the street sensor’s update before choosing an extension. The existing tour uses a 2,048-byte image and 256-byte pieces: 2,048 / 256 = eight blocks, numbered 0 through 7. If a client sends those bytes in PUT requests to the sensor, use Block1, the option for request bodies. If the sensor requests them with GET and receives the bytes in responses, use Block2, the option for response bodies. The direction of the body decides the option; the word “firmware” does not.
Suppose the acknowledgment for block 2 is lost. Retry that exchange and check that the receiver stores its bytes once. Block 7 has the more flag cleared, but that alone does not prove the image is authentic or installed. Check the complete image, its trusted source, and the device’s reported running version before approving the update.
Start an update, lose one block, repeat another, delay the last block, and restart the device. It must keep the old safe version or accept one complete new version. The service must show which outcome occurred.
A restart adds a different question: did the implementation persist enough state to continue with the same image? Block-wise transfer does not promise persistent recovery after power loss. Carry that question through discovery, transport selection, and the fleet example below.
First, use Block1 and Block2 for payloads that do not fit one datagram. Then use /.well-known/core instead of hard-coded resources. Next, decide when UDP, TCP, WebSockets, or DTLS changes the design. Finally, pressure-test NAT, timeout, proxy, and OTA evidence. Checkpoints summarize each layer; Deep-dive sections are optional.
Learning Objectives
By the end of this chapter, you will be able to:
- Implement Block-wise Transfer: Apply RFC 7959 to handle large payloads (firmware updates) over CoAP’s UDP transport.
- Configure Resource Discovery: Construct
.well-known/coreendpoints with CoRE Link Format attributes. - Evaluate CoAP Transport Options: Select between UDP, TCP, and WebSockets based on network constraints and device requirements.
- Analyze DTLS Security Overhead: Calculate handshake RTT costs and justify security mode selection for constrained deployments.
- Diagnose Block Transfer Failures: Distinguish between timeout cascade, packet loss, and NAT expiry failure modes.
- CoAP: A resource request/response protocol; the base specification uses UDP, and RFC 8323 defines reliable transports.
- Confirmable Message (CON): Requests an acknowledgment and supports bounded retransmission; an ACK alone does not establish successful application processing.
- 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: Application-layer transfer of a representation in numbered pieces, distinct from IP fragmentation.
- 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.
For Beginners: CoAP Advanced Features
Beyond basic request-response messaging, CoAP offers features like resource observation (automatic notifications when data changes), block transfers (sending large data in chunks), and resource discovery (finding what services a device offers). These features make CoAP a powerful, lightweight communication tool for constrained IoT devices.
The dashboard needs repeated readings; the updater needs a large body. These are different problems. Observe maintains a notification relationship for a resource, while block-wise transfer carries pieces of a representation.
For the eight-block street-sensor update, retrying block 2 repeats its 256-byte payload. The receiver must handle the repeat without adding those bytes twice. Discovery can help the updater find an advertised resource, but it neither provisions credentials nor proves that every device is reachable.
Prerequisites
Before diving into this chapter, you should be familiar with:
- CoAP Introduction - CoAP basics and design goals.
- CoAP Message Format - Header structure and options.
- CoAP Observe Extension - Server push notifications.
Before choosing an extension, use the figure in the parent chapter to separate the three problems that advanced CoAP features solve: repeated updates, payloads too large for one datagram, and one-to-many operations.
In the figure in the parent chapter, Observe replaces repeated polling with notifications when data changes. Block-wise transfer splits a large representation into bounded pieces. Multicast sends one request towards a group. Each is a separate extension. Choose the one that fits the traffic problem instead of treating “advanced CoAP” as one bundle. The next section covers the size problem. Use the linked Observe material for rules about the notification lifecycle.
Continue: CoAP Block Transfer and Discovery Contracts
The main chapter below stays focused on the advanced-feature tour. For the deeper contract behind Block1 and Block2 sizing, NUM/M/SZX encoding, retry and resume evidence, CoRE Link Format discovery, Max-Age, ETag revalidation, and proxy caching, continue to CoAP Block Transfer and Discovery Contracts.
Block-wise Transfer (RFC 7959)
The first problem is size. CoAP exchanges are intentionally small, so firmware images and log uploads need reviewable pieces.
Core Concept: The path maximum transmission unit (MTU) limits packet size without fragmentation. Headers and security consume part of that budget. Block-wise transfer divides a representation into pieces; the implementation must reconstruct and validate the result.
Why It Matters: The sensor can retry a piece rather than restarting the whole image. It still needs a policy for duplicate blocks, interrupted transfers, and final acceptance.
Key Takeaway: Use Block2 for large response payloads (downloads), Block1 for large request payloads (uploads). Each block includes block number, more-flag, and size.
Block2: Large Response Payloads
A large server response, such as a firmware image, cannot safely be treated as one oversized datagram. Use the figure in the parent chapter to see which state must survive while the client assembles that representation piece by piece.
Read the figure in the parent chapter with these corrections: a token correlates a request with its response; subsequent block requests may use different tokens. Representation consistency is a separate check: compare ETags when supplied and reject blocks from a changed representation rather than mixing versions. Validate each response’s block number, decoded size, payload length, and representation metadata, then place its payload at offset NUM × decoded block size. Track covered byte ranges so duplicates do not add bytes and reordered responses do not change placement; appending each distinct arrival once is insufficient.
Before accepting the image, require complete byte coverage through the final block and a consistent total length. For this updater, verification of the complete image against a trusted expected hash is an application acceptance policy, not a guarantee supplied by RFC 7959.
Block2 option format:
- NUM: Block number (0-based sequence).
- M: More flag (1 = more blocks follow, 0 = last block).
- SIZE: Decoded block size in bytes (16, 32, 64, 128, 256, 512, 1024). The encoded SZX field is a size exponent, not a byte count.
Block1: Large Request Payloads
Used when client sends large data to server (e.g., uploading logs):
Client -> Server: PUT /logs/daily
Block1: NUM=0, M=1, SIZE=512
Payload: [first 512 bytes]
Server -> Client: 2.31 Continue
Block1: NUM=0, M=1, SIZE=512
Client -> Server: PUT /logs/daily
Block1: NUM=1, M=1, SIZE=512
Payload: [next 512 bytes]
... until final block with M=0 ...
Server -> Client: 2.04 Changed
Implementation with Reliability
async def download_firmware(uri, output_file):
block_num = 0
block_size = 1024
consecutive_failures = 0
with open(output_file, 'wb') as f:
while True:
# Adaptive timeout with exponential backoff
timeout = min(2.0 * (1.5 ** consecutive_failures), 30.0)
try:
request = Message(
code=GET,
uri=uri,
msg_type=CON, # Reliable for each block
block2=(block_num, False, block_size)
)
response = await protocol.request(request, timeout=timeout).response
# Write block to file
f.write(response.payload)
consecutive_failures = 0
# Check if more blocks available
if response.opt.block2.more:
block_num += 1
else:
break # Last block received
except TimeoutError:
consecutive_failures += 1
if consecutive_failures > 10:
raise TransferFailed(f"Failed at block {block_num}")
print(f"Downloaded {block_num + 1} blocks")
The code above is a sketch, not a verified library procedure. It assumes a fixed block size and appends each response without validating its block number or representation identity. Before using this pattern, check the installed library API, returned offsets, changed block sizes, duplicate handling, and final integrity. Its file is opened afresh; it does not implement recovery after reboot.
Performance Analysis
Scenario: An illustrative 256 KiB firmware image over LoRaWAN, with an assumed 10% loss rate. KiB means 1,024 bytes; the table identifies the radio constraints missing from a CoAP-only estimate.
| Approach | Blocks | Retransmissions | Time | Success Rate |
|---|---|---|---|---|
| Single 256 KiB payload | Not a valid LoRaWAN application payload; split into regional-size fragments | — | Depends on regional data rate and duty restrictions | — |
| 1 KiB blocks (NON) | Each 1 KiB block must be further fragmented to fit the regional LoRaWAN application-payload limit | No CoAP retransmission | Calculate from fragmentation and radio schedule | Incomplete if fragments are lost |
| 1 KiB blocks + CON | Each block requires further LoRaWAN fragmentation | Depends on fragment retries | Calculate from regional payload and radio schedule | Depends on retry and integrity policy |
| 512 byte blocks + CON | Each block still requires LoRaWAN fragmentation | Depends on fragment retries | Calculate from regional payload and radio schedule | Depends on retry and integrity policy |
Assume each whole block attempt independently succeeds with probability , and ignore acknowledgment loss. Without retries, all blocks arrive with probability:
For 1KB blocks (256 blocks total) without confirmations (NON):
Under an idealized unlimited-retry model, the expected attempts per block are:
Total time for 256 blocks at 200 ms per confirmed block:
For 512-byte blocks, there are 512 blocks. At the same independent loss probability, each attempt still succeeds with probability 0.9. Smaller blocks reduce payload bytes repeated per retry, but more blocks reduce the probability of completing without any loss. The time product above includes idealized retry attempts but excludes acknowledgment loss, backoff, radio fragmentation, airtime restrictions, and receive windows. It is not a LoRaWAN completion-time estimate.
Key insight: Without retries, more fragments mean more chances for loss. With capped retries, compute completion probability from all radio fragments and the retry policy; smaller blocks can reduce bytes retransmitted after a loss.
Checkpoint: Block-wise Transfer
You now know:
- Block2 handles large responses; Block1 handles large requests.
- The block option carries NUM, M, and a block size such as 512 or 1024 bytes. In the 256 KiB, 10% packet-loss example, both 1 KiB and 512-byte CoAP blocks require smaller LoRaWAN fragments; transfer time must be recalculated for the chosen region, data rate, duty limit, acknowledgments, and retry policy.
You need to send a 10 KiB firmware update over a lossy CoAP/UDP path (15% datagram loss). After allowing for CoAP headers, token, options, payload marker, and network/security overhead, the path permits up to 1024 payload bytes per block without fragmentation, but the priority is to limit bytes resent after loss while detecting failed delivery. Which listed block-wise configuration best fits?
256-byte blocks with CON messages for reliability
Correct. Among these options, 256-byte CON blocks detect failed delivery and limit each block retry to 256 payload bytes instead of 1024. The smaller blocks add exchanges, so a full transfer budget still needs measurement.
A 1,800-byte update crosses a path limited to 300-byte CoAP payloads. Which legal block size fits without exceeding the limit, and how many data blocks are needed?
Use 256-byte blocks and send eight data blocks.
Correct. 256 is the largest power-of-two CoAP block size below 300; ceil(1800/256) is eight.
Interactive: Block-wise Transfer Time Calculator
Try It:
- Keep image size and loss fixed; reduce block size. Expect more blocks and a lower displayed NON first-pass success rate. A higher rate would contradict this model’s independent fixed-loss assumption.
- Compare the displayed time with a trace. This estimate assumes unlimited independent attempts; real CON exchanges have bounded retries and backoff.
- Treat the recommendation label as a heuristic. It cannot establish an optimal size or radio feasibility.
Key Principle: The optimizer uses assumed loss thresholds and a 12-byte CoAP allowance. It does not measure a path or include all network and security headers. Its MTU clamp can return a value outside the legal block sizes. Choose a legal size that fits the full packet budget, then measure completion and retry cost; the displayed “optimal” label is not evidence.
See why the tempting answer fails.
Resource Discovery (RFC 6690)
Once payloads can move safely, the next question is how a client knows which resources exist. Discovery replaces guessed URIs with an inventory.
Core Concept: A CoAP server that implements RFC 6690 discovery exposes /.well-known/core, which returns selected resource links in CoRE Link Format. The server chooses which links and attributes to include.
Why It Matters: A client can inspect advertised links instead of guessing paths. It still needs a reachable server, permission, and an application agreement about what each resource means.
Key Takeaway: Implement /.well-known/core (RFC 7252 §7.2 says servers SHOULD) and tag links with rt= (resource type), if= (interface) and obs (observable, RFC 7641 §6).
Discovery Request-Response
Client Request:
GET coap://sensor.local/.well-known/core
Server Response (Link Format, Content-Format: 40):
</sensors/temp>;rt="temperature";if="sensor";obs,
</sensors/humidity>;rt="humidity";if="sensor";obs,
</sensors/pressure>;rt="pressure";if="sensor",
</actuators/led>;rt="light";if="actuator",
</config/interval>;rt="config";if="parameter"
Link Format Attributes
| Attribute | Meaning | Example |
|---|---|---|
| rt | Resource Type | rt="temperature" |
| if | Interface | if="sensor" |
| ct | Content Format | ct=50 (JSON) |
| sz | Estimated maximum representation size, in bytes | sz=256 |
| obs | Observable | obs (flag) |
| title | Human Name | title="Room Temp" |
Filtered Discovery
Request only specific resource types:
# Find all temperature sensors
GET coap://sensor.local/.well-known/core?rt=temperature
Response:
</sensors/temp>;rt="temperature";if="sensor";obs,
</sensors/temp_outdoor>;rt="temperature";if="sensor";obs
# Find all observable resources
GET coap://sensor.local/.well-known/core?obs
Multicast Discovery
Multicast discovery asks every eligible node the same resource question without sending one request per address. Send a NON GET to the link-local CoAP multicast group and /.well-known/core; each server then returns its own unicast response after a randomized Leisure delay. NON avoids an acknowledgment storm, while the delayed unicast replies reduce collisions and let the client associate each discovery record with one endpoint. The result is efficient inventory evidence, not reliable group command delivery.
GET coap://[FF02::FD]/.well-known/core
# All CoAP devices respond with their resource list
Device 1: </temp>;rt="temperature"
Device 2: </humidity>;rt="humidity"
Device 3: </pressure>;rt="pressure"
Checkpoint: Discovery Contracts
You now know:
/.well-known/corereturns CoRE Link Format instead of guessed paths.rt,if,ct,sz,obs, andtitledescribe resources and behavior.- Multicast discovery can query
coap://[FF02::FD]/.well-known/core, but the client still initiates the request.
CoAP over TCP (RFC 8323)
Why CoAP-over-TCP?
Problem: Suppose the street-sensor updater cannot use its UDP route. Check whether policy blocks UDP, whether a NAT mapping has expired, and whether a supported TCP service is reachable. UDP carries separate datagrams; TCP provides an ordered byte stream. Stream order does not prove application execution order or successful installation.
Solution: RFC 8323 defines CoAP over reliable transports (TCP, TLS, WebSockets).
Protocol Differences
| Feature | CoAP/UDP | CoAP/TCP |
|---|---|---|
| Transport | Unreliable UDP | Reliable TCP |
| Message Types | CON, NON, ACK, RST | No message type field; requests, responses, and signaling messages |
| Reliability | Application (CON/ACK) | Transport (TCP) |
| Message ID | Required | Absent |
| Connection | None | TCP 3-way handshake |
| Default Port | 5683 (coap://) | 5683 (coap+tcp://) |
| Secure Port | 5684 (coaps://) | 5684 (coaps+tcp://) by default |
Header Format Changes
CoAP/UDP header (4 bytes):
|Ver| T | TKL | Code | Message ID |
CoAP/TCP framing (at least 2 bytes before any token/options):
| Len | TKL | Extended Length (if any) | Code | Token (if any) |
Key changes:
- No Message ID (TCP sequence numbers handle ordering).
- No Type field (TCP reliability eliminates CON/NON/ACK).
- Length field (for framing over stream).
Decision Framework: Test the selector with both “Firewall blocks UDP” and “Battery-powered device” checked. Its heuristic can still recommend UDP. That result conflicts with the blocked route: reject it and verify a supported permitted path. NAT presence alone does not require TCP, and battery cost needs measurement.
When to Use
Use a reliable transport when the endpoints support it and the permitted path requires it. WebSockets need matching service support too; an open web port alone is insufficient. For the street sensor, compare reconnect cost and idle energy on the actual path before choosing TCP or UDP. TCP does not provide multicast, and connection setup matters when devices sleep between transfers.
You’re deploying CoAP sensors in a factory. IT blocks UDP port 5683, will not approve a UDP exception, and confirms that a suitable TCP 443 route is available. Which listed solution keeps CoAP methods while fitting that policy?
Use CoAP over TCP per RFC 8323 via the approved TCP 443 route.
Correct. RFC 8323 defines CoAP over TCP. On the permitted TCP route, it retains CoAP methods while replacing UDP message-layer CON/NON/ACK handling with reliable transport. TCP 443 still needs the intended CoAP service and firewall configuration.
Factory IT approves UDP 5683 for these sensors and has no usable TCP route. Which transport keeps standard CoAP methods within this policy?
CoAP over the approved UDP 5683 path
Correct. UDP 5683 is now permitted and reachable, so ordinary CoAP datagrams fit the stated route.
DTLS Security
Transport and security answer separate questions: can the peers exchange traffic, and can they protect it? A permitted TCP path still needs a suitable service and security configuration. DTLS protects datagrams between its endpoints.
CoAP uses DTLS (Datagram TLS) for security over UDP:
Security Modes
| Mode | Description | Use Case |
|---|---|---|
| NoSec | No security | Development only |
| PreSharedKey | Symmetric keys pre-installed | Factory provisioning |
| RawPublicKey | Asymmetric without certificates | Lightweight devices |
| Certificate | Full X.509 certificates | Enterprise deployments |
DTLS Handshake
Securing a datagram transport requires a handshake that can tolerate loss without letting an unauthenticated sender consume unlimited server state. the figure in the parent chapter shows where the DTLS cookie challenge fits before keys protect application traffic.
This figure depicts a DTLS 1.2-style certificate exchange, not a universal sequence for every version or credential mode. Follow the figure in the parent chapter downward. The first ClientHello prompts a stateless cookie challenge; the client proves return reachability by repeating ClientHello with that cookie. Only then do the server parameters, certificate and key exchange, and Finished messages establish the protected session. Encrypted application data starts after this exchange, which explains the setup cost explored by the calculator next.
Key Insight: DTLS setup cost varies with cookie exchange, profile, and loss. The calculator uses deployment-measured full-handshake and resumed-handshake setup RTTs; message-flight counts are not RTT counts. Measure both paths on the target link before estimating reconnection cost.
Checkpoint: Transport and Security
You now know:
- CoAP/UDP uses CON, NON, ACK, RST, and Message IDs; CoAP/TCP removes those message types.
- A supported CoAP/TCP service may fit a permitted TCP route. Verify policy and measure device cost; TCP does not provide multicast.
- NoSec provides no DTLS protection. PSK, raw public keys, and certificates require different credential arrangements. Measure full and resumed setup on the target link.
A measured DTLS full handshake took 600 ms and session resumption took 200 ms on this link. How much measured setup time was saved?
400 ms
Correct. These are deployment measurements, not DTLS-required RTT counts; 600 ms minus 200 ms equals 400 ms saved.
On this link, a full DTLS setup measured 750 ms and a resumed setup measured 180 ms. How much setup time does resumption save?
570 ms
Correct. Subtracting resumed setup from full setup gives 570 ms.
Common Pitfalls
The mistake: Using fixed CoAP timeout settings for a long block-wise transfer can cause repeated retries or an abandoned transfer on a lossy link.
Why It Happens: A timeout may reflect loss, a slow response, or lost path state. The default initial ACK timeout is not a deadline for an entire multi-block transfer. Restarting the whole image after one failed exchange is an implementation policy, not a block-wise requirement.
The Fix: Implement adaptive timeouts and resumable transfers:
def download_with_resume(uri, resume_from=0):
block_num = resume_from
consecutive_failures = 0
base_timeout = 2.0
while True:
timeout = min(base_timeout * (1.5 ** consecutive_failures), 30.0)
try:
response = coap_get(uri, block2=(block_num, 0, 1024), timeout=timeout)
save_progress(block_num, response.payload)
consecutive_failures = 0
if response.block2.more:
block_num += 1
else:
return assemble_firmware()
except TimeoutError:
consecutive_failures += 1
if consecutive_failures > 10:
save_resume_point(block_num)
raise TransferSuspended(block_num)
The Mistake: Assuming a network address translation (NAT) gateway preserves a UDP return path throughout a long idle period. Mapping lifetimes depend on the gateway and policy; the page has no measurements supporting a universal interval.
The Fix:
- Test UDP connectivity before design.
- Measure mapping expiry and test a keepalive interval against both that lifetime and the device energy budget.
- Consider CoAP over TCP for NAT-hostile networks.
- Compare measured DTLS full and resumed setup costs after connectivity is restored; resumption does not repair an expired NAT mapping.
Worked Example: OTA Firmware Update for 500 Street Lights
The pieces now meet one operational question: can block transfer, frame limits, packet loss, and gateway parallelism finish inside a fixed maintenance window?
Transfer example: A council proposes a 128 KiB image for 500 lights in a two-hour window. Apply the street-sensor rule: identify which peer requests the image, choose the body option, and count the blocks. At 128 bytes per block, 131,072 / 128 = 1,024 blocks.
The calculations retained below are a hypothetical planning worksheet. The assumed 242-byte radio allowance, 12-byte CoAP allowance, 1.5-second exchanges, eight concurrent streams, gateway prices, and labor costs are unverified premises. A radio chip model does not establish a LoRaWAN application-payload limit or downlink concurrency. Region, data rate, receive class, security overhead, airtime restrictions, and gateway transmit scheduling must be checked before using this worksheet for a rollout.
Step 1: Calculate block count and transfer time per device
Firmware size: 128 KB = 131,072 bytes
Block size: 128 bytes (leaving room for CoAP headers within 242-byte limit)
CoAP header + Block2 option: ~12 bytes
Total per-message payload: 128 + 12 = 140 bytes (fits in 242-byte LoRaWAN frame)
Block count: 131,072 / 128 = 1,024 blocks per device
Here the device requests image blocks with GET, so the firmware is in Block2 responses. Assume a 1.5-second exchange only to inspect the worksheet arithmetic; it is not a measured Class C timing. The extra 8% below is a one-pass retry allowance, not the expected attempts under repeated independent loss:
Optimistic transfer time: 1,024 blocks x 1.5 seconds = 1,536 seconds = 25.6 minutes
With 8% packet loss and 1 retry per loss:
Expected retransmissions: 1,024 x 0.08 = ~82 extra blocks
Adjusted time: (1,024 + 82) x 1.5 = 1,659 seconds = 27.7 minutes per device
Step 2: Assess parallelism constraints
For arithmetic only, suppose a scheduler could maintain eight independent streams at the assumed 28-minute completion time. Receive-channel count does not establish simultaneous downlink capacity:
Devices per gateway: 8 parallel streams
Time per batch: 28 minutes
Batches needed: 500 / 8 = 62.5 -> 63 batches
Total time with 1 gateway: 63 x 28 = 1,764 minutes = 29.4 hours
Under those assumptions the worksheet exceeds two hours. Its gateway-count calculation is conditional; adding gateways does not by itself remove shared airtime or scheduling constraints:
Available time: 120 minutes
Batches possible per gateway: 120 / 28 = 4.3 -> 4 batches
Devices per gateway: 4 batches x 8 channels = 32 devices
Gateways needed: 500 / 32 = 15.6 -> 16 gateways
Step 3: Design the update strategy with CoAP Block-wise features
| Design Decision | Choice | Rationale |
|---|---|---|
| Block size | 128 bytes | Fits LoRaWAN frame with CoAP headers |
| Message type | CON | ACK and bounded retry improve delivery; final hash and install checks still decide integrity |
| Resume support | Persist validated transfer state | Recovery also needs image identity, offsets, and stored bytes; saving a number alone is insufficient |
| Integrity check | Verify complete image against trusted metadata | A hash detects mismatch; trusted provenance and installation checks remain separate |
| Rollback plan | Keep previous firmware in secondary flash partition | The bootloader/update policy must detect failure and select that fallback; demonstrate recovery after a failed update |
Step 4: Cost analysis
Option A: Sequential update (1 gateway, no parallelism)
Time: 500 devices x 28 min = 14,000 minutes = 9.7 days
Gateway cost: 1 x $1,500 = $1,500
Labor: 0 (unattended)
Risk: Very slow, devices run outdated firmware for days
Option B: Parallel update (16 gateways, 2-hour window)
Time: 2 hours (single maintenance window)
Gateway cost: 16 x $1,500 = $24,000 (but gateways serve normal traffic too)
Labor: 1 technician x 2 hours = $100
Risk: Low, all devices updated simultaneously
Option C: Incremental rollout (4 gateways, 4 nights)
Time: 4 maintenance windows x 2 hours = 8 hours total
Gateway cost: 4 x $1,500 = $6,000
Devices per night: 128
Risk: Medium -- staged rollout catches firmware bugs before full deployment
Decision: Do not approve a gateway purchase from these figures. First demonstrate one complete update, interruption recovery, and an observed installed version. Then measure a pilot under the actual radio schedule and estimate fleet capacity from that evidence. Staged deployment limits exposure, but neither the proposed nightly count nor completion window is established here. Resume after power loss requires persisted implementation state and validation that the image has not changed.
- Record body direction, negotiated size, block offsets, and image identity. Expect 1,024 payload blocks for this fixed-size image; a different count needs an explanation such as renegotiated size.
- Interrupt and repeat an exchange, then reboot the receiver. Expect no duplicated stored bytes and either verified recovery or a clean restart; an unexplained offset indicates lost or inconsistent state.
- Verify the complete image against trusted update metadata, install it under the device’s update policy, and read its running version. A final block or matching hash alone does not establish trusted origin or successful installation.
Checkpoint: OTA Rollout Evidence
You now know:
- The 128 kB firmware image becomes 1,024 blocks at 128 bytes each.
- The worksheet gives 29.4 hours only under its assumed eight-stream scheduler and 28-minute batches. Actual gateway capacity remains unverified.
- The accepted design is not just faster transfer; it needs resume state, SHA-256 verification, rollback, staged rollout, and gateway capacity evidence.
Choose which feature addresses each update-path problem. Match by body direction, discovery need, credential arrangement, or permitted transport; one feature does not establish the others.

Maths · guided foundations
Block Airtime and the Retransmission Penalty
Check the quantities and assumptions.
Bridge a constrained observation into enterprise work without merging protocol guarantees in the diagram the chapter figure.
Read the chapter figure from the cold-room sensor to the edge. CoAP discovery finds the resource, and Max-Age gives the gateway a bounded cache rather than a timeless truth. The gateway then publishes into an AMQP exchange whose binding selects a durable queue for enterprise work. At the consumer, acknowledgement policy defines the remaining failure trade: at-most-once may lose work, while at-least-once may repeat it. The bridge preserves both contracts explicitly, so a CoAP response or AMQP broker acceptance is not mistaken for proof that the final application acted.
Summary
For an update, locate the body first: Block1 carries request bodies; Block2 carries response bodies. Choose a legal block size within the complete packet budget, calculate the block count, and inspect duplicates, retries, and restart state.
Discovery gives advertised links, a reachable transport carries exchanges, and security protects the relevant endpoints. Each addresses a different failure. Approve the update only with complete-image checks, trusted provenance, and installation evidence. Use measured radio and gateway capacity before transferring a one-device result to a fleet.
Concept Relationships
Advanced CoAP features connect to:
Foundation Concepts:
Review the message format first to locate the block options and payload marker, then compare Observe as a different way to move resource data.
- CoAP Message Format - Options and payload marker used in block transfer.
- CoAP Observe Extension - Related push notification pattern.
- CoAP Fundamentals - Basic architecture that advanced features extend.
Practical Applications:
Start with firmware updates to see where block transfer is used, then examine 6LoWPAN to place CoAP on a constrained network.
- OTA Firmware Updates - Block-wise transfer for production updates.
- 6LoWPAN Integration - CoAP over constrained networks.
- Thread Networking - CoAP as application layer.
Security:
Read the DTLS guide for transport protection, then compare the security modes available to a CoAP deployment.
- DTLS for IoT - Securing CoAP communications.
- CoAP Security Modes - NoSec, PSK, certificates.
See Also
Standards:
Read the block transfer rules first. Then use the link format rules to find resources.
Implementation:
Use the block and discovery contracts for the detailed rules, then try the lab to trace those rules on a device.
Comparison:
Compare CoAP with HTTP for the transport choice, then read the chunking rationale for the large payload case.
What’s Next
| Chapter | Focus | Why Read It |
|---|---|---|
| CoAP Block Transfer and Discovery Contracts | Block option encoding, per-block retries, discovery metadata, and proxy cache evidence | Turn the feature overview into a reviewable implementation contract |
| CoAP API Design | RESTful resource modeling and URI design | Apply the resource discovery patterns from this chapter to design well-structured CoAP APIs |
| CoAP Decision Framework | When to use CoAP vs MQTT vs HTTP | Evaluate trade-offs using the transport and security knowledge built here |
| CoAP Fundamentals and Architecture | Core CoAP message model and architecture | Reinforce the foundation that all advanced features extend |
| OTA Firmware Updates | Production firmware update workflows | See Block-wise Transfer applied end-to-end in a real OTA update pipeline |
| DTLS and Security | DTLS handshake mechanics and cipher suites | Deepen understanding of the security modes introduced in this chapter |
| 6LoWPAN Overview | IPv6 adaptation for constrained networks | Understand the network layer that CoAP block transfer and discovery operate over |



