Chapters

Implementation and Operations: CoAP Security Reference

Return to the parent chapter.

Related reference: CoAP message types.

Start With the Decision

CoAP is a request-and-response protocol for constrained devices. A resource is a named target, such as /config/interval; PUT requests a change to its state. A client sends a confirmable (CON) PUT /config/interval to change a sensor’s reporting interval. The server sends an empty acknowledgment (ACK), then a separate 4.05 Method Not Allowed response carrying the request’s Token, the value used to correlate a response with its request. Should the operator increase the retry timeout?

No. The response shows that the request reached CoAP resource handling, but this resource does not support PUT. Check the resource’s method contract. The empty ACK alone showed receipt of the CON message; it did not prove the configuration changed.

Observed evidenceNext lookupDecision
No CoAP response; security handshake failedTroubleshootingCheck security setup before resource handling
Empty ACK, no final response yetImplementation patternsTrack the separate response using the Token
4.04 or 4.05 responseResponse codesCheck resource path or supported method
Large transfer failsMTU pitfallInspect packet size and block-transfer evidence

This reference covers base CoAP over the User Datagram Protocol (UDP) in RFC 7252, Observe notifications in RFC 7641, and block transfer, which splits a representation into smaller exchanges, in RFC 7959. Library behavior and deployment policy require separate verification.

Route Overview

Continue with CoAP Security: CON and NON Trade-Offs.

Part Objectives

  • Use response and trace evidence to select the next diagnostic test.
  • State the observation that would confirm or reject the diagnosis.

Start With the Situation

Keep the configuration request as the running example. A resource is a named target such as /config/interval. Its contract defines supported methods, accepted payload formats, permissions, and response meanings. Diagnose against that contract before changing transport settings.

Overview

An endpoint is the addressed protocol peer. Use the linked tables to distinguish a missing response from a returned error. Record the endpoint, method, path, Token, message identifiers, timestamps, and response or timeout. Record the security mode and non-secret identity reference; never log keys.

Review CoAP Security: Protection and Application Fit for the security design that precedes these operational checks.

Learning Objectives

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

  • distinguish message receipt from a completed resource operation
  • choose a diagnostic test from a response code or missing-response trace
  • verify a proposed fix against the resource contract

Chapter Roadmap

  • Start With the Situation
  • Overview
  • CoAP Implementation Patterns
  • Practical CoAP Implementation Resources
  • Checkpoint: Operational Debugging
  • Try It: CoAP Response Code Reference
  • Troubleshooting Common Issues
  • Common Problems and Solutions
  • Common Pitfalls
  • Common Pitfall: CoAP Message Size Exceeds MTU
  • Common Pitfall: Misusing CON vs NON Message Types

CoAP Implementation Patterns

For the configuration request, PUT specifies the requested resource operation. CON enables acknowledgment and bounded retransmission. A Message ID identifies the message for acknowledgment and duplicate handling; the Token correlates the response with the request. An empty ACK uses the request’s Message ID, while a separate response carries the request’s Token and its own Message ID.

ContractInspect in the running exampleWhat it establishes
Resource operationPUT, /config/interval, payload formatWhether the requested change is supported
Message exchangeCON, ACK, Message ID, retriesReceipt or exchange failure; no actuation guarantee
Request/responseToken, endpoint and security context, final codeWhich request the result belongs to
Observe, if usedGET with Observe option, Token and notification sequenceUpdates to a resource representation; not a configuration write

See RFC 7252 §§4.2, 4.5, 5.2–5.3 and 5.8 and RFC 7641 §§3.2–3.4. A CoAP stack implements message exchange; application code must still define permissions and verify the intended state.

Use Figure 1 as a role map. Observe notification order uses serial-number comparison, including wraparound; it is not an indefinitely increasing counter.

CoAP vs HTTP vs MQTT: Performance Comparison

A short fixed header is not a complete packet-size or energy comparison. For the configuration request, count the encoded path, Token, options, payload marker and payload, then UDP/IP and security overhead. Include acknowledgments, retries and any security handshake in an exchange measurement.

Protocol scopeHeader fact or old worksheet assumptionLimit of comparison
CoAP over UDP, RFC 7252 §34-byte fixed headerToken, options and payload framing add bytes
HTTP/1.1 over TCPOld worksheet assumed 200 header bytesAssumption, not a protocol minimum or measured request
MQTT over TCPOld worksheet used the 2-byte minimum fixed headerA PUBLISH also needs variable-header fields, including a topic representation

Do not select a protocol from these header rows. Measure complete exchanges on the target path, report bytes per completed operation and latency in milliseconds, and state connection/security reuse. The old per-message energy costs have no measurement source and cannot support a battery-life estimate.

Practical CoAP Implementation Resources

Library and Tool Starting Points:

These links identify implementation projects, not guaranteed feature support. Check the installed version, security backend, Observe and block-transfer support before adopting an example.

Testing and Debugging Tools:

Use a controlled local endpoint with a documented resource contract. Command options depend on the installed libcoap version; check its help before running these preserved examples.

  • coap-client (libcoap): Command-line CoAP client for testing

    # GET request
    coap-client -m get coap://localhost/temperature
    
    # POST with payload
    coap-client -m post coap://localhost/sensor -e "22.5"
    
    # Observe resource
    coap-client -m get -s 60 coap://localhost/temperature
  • Wireshark: CoAP dissector included (filter: coap)

  • Record client and server versions alongside traces so a library-specific failure can be reproduced.

Example Implementation Patterns:

Pattern 1: Sensor Reading (CON exchange shown)

The preserved sketch below uses CON despite its former NON label. Its byte total and latency are unverified, and “Guaranteed” is incorrect: retries can end without a response. Use the message flow only; measure size and timing on the actual path.

Sensor → Gateway:  CON GET /temperature
Gateway → Sensor:  ACK 2.05 Content
                   Payload: 22.5°C

Overhead: 2 messages, ~50 bytes total
Latency: 1 RTT (~20-50ms on local network)
Reliability: Guaranteed (CON requires ACK)

Pattern 2: Frequent Updates (Observe)

This abbreviated flow omits the client ACKs required for the CON notifications shown. Observe extends GET; traffic and energy savings depend on update rate, polling policy and retries.

Client → Server:   CON GET /temperature, Observe: 0
Server → Client:   ACK 2.05 Content, Observe: 12
                   Initial value: 22.5°C

[30 seconds later]
Server → Client:   CON 2.05 Content, Observe: 13
                   Updated value: 23.1°C

[30 seconds later]
Server → Client:   CON 2.05 Content, Observe: 14
                   Updated value: 22.9°C

Overhead: 1 subscribe + N notifications
Battery savings: Avoid polling every 30s

Pattern 3: Multicast Discovery

FF02::FD is the link-local IPv6 All CoAP Nodes multicast address. Scope, interface membership and loss limit the replies; the sketch cannot establish that every device was found. Restrict discovery reachability and response volume to reduce reflection risk (RFC 7252 §§8,11.3,12.8).

Client → FF02::FD: NON GET /.well-known/core
Device1 → Client:  NON 2.05 Content
                   </temperature>,</humidity>
Device2 → Client:  NON 2.05 Content
                   </pressure>,</light>

Use case: Discover all CoAP devices on local network
Result: List of available resources from all devices

Bex guides the message review.Checkpoint: Operational Debugging

Check the running example before changing a setting:

  • The base RFC 7252 Token is 0–8 bytes. Match it within the endpoint and security context; do not use a Message ID alone to identify a separate response.
  • Default ACK_TIMEOUT is 2 s, ACK_RANDOM_FACTOR is 1.5 and MAX_RETRANSMIT is 4. The first timeout is randomized between 2 and 3 s, then doubled. Maximum transmit span is 45 s and maximum transmit wait is 93 s (RFC 7252 §4.8); these are message-exchange bounds, not application deadlines.
  • A returned 4.05 points to the method/resource contract. Increasing a retransmission timeout cannot make PUT supported.

CoAP Response Code Categories

Class, base CoAPMeaningDiagnostic use
2.xxSuccessRead the specific code; an empty ACK has no success code
4.xxClient errorCheck request, resource contract and authorization
5.xxServer errorCheck server or upstream evidence before retrying

The tool lists selected base codes and block-transfer codes; it is not an exhaustive registry. See RFC 7252 §5.9 and RFC 7959 §4.

Try It: CoAP Response Code Reference

An entity tag (ETag) identifies a representation version for cache validation.

Timed lookup: start a timer, find 4.05, and choose the next test for the configuration request. Stop when you can justify the test. Answer: inspect the resource’s supported methods, because the request reached a resource that rejects this method. Do not infer a network timeout from this response.

Select a category or search for a code. HTTP labels are conceptual parallels, not automatic proxy mappings.

The troubleshooting material below reuses the same pattern: identify the failed layer first, then choose the smallest fix that matches that layer.

Hands-On Learning Resources

Use a local fixture rather than assuming a public server is available. These steps describe a practice test; no requests have been run for this page.

  1. Configure an isolated test server with /temperature supporting GET and /config/interval supporting GET but rejecting PUT. Record the server version and this contract. Expected: both resources are registered. A missing resource would confound a method-rejection test.
  2. Run the preserved local GET command above after confirming the fixture address. Expected: 2.05 Content with a response Token matching the request. A timeout calls for endpoint/transport checks; 4.04 calls for path/registration checks.
  3. Send a CON PUT to /config/interval using the installed client’s documented syntax and capture the exchange. Expected: 4.05. If the server first sends an empty ACK, continue to the separate response. 2.04 means the fixture permits PUT; inspect the fixture before claiming the intended rejection test passed.
  4. Record method, path, endpoint, Token, Message IDs, timestamps, final code and next test. Expected: “check supported methods,” with 4.05 as evidence. “Raise retry timeout” does not explain the returned rejection.

Transfer: a secure firmware upload produces a failed Datagram Transport Layer Security (DTLS) handshake and no CoAP response. First compare the configured security modes, identity references and non-secret error logs. Changing Block1 size is premature because no CoAP resource exchange has been established.

Implementation reading: Californium client example, aiocoap guided tour, and ESP32 CoAP example. Verify examples against the selected release; availability was not checked here.

Troubleshooting Common Issues

Common Problems and Solutions

Locate the last successful boundary before changing settings. A timeout alone does not identify the cause.

ObservationNext testEvidence that narrows the diagnosis
No reply to CONCheck endpoint, listener and allowed UDP path; inspect both endsRequest absent at server suggests a path/endpoint issue; arrival without reply requires server evidence
Empty ACK, no final responseTrack separate response by Token and application deadlineACK proves message receipt; handler completion remains unknown
DTLS handshake failsCompare configured security modes and identity setupNon-secret handshake error precedes CoAP processing
4.04Check exact path and registrationCorrect endpoint responds but cannot find the target
4.05Check supported methods on that pathRunning example rejects PUT; transport tuning will not fix it
Block transfer stopsInspect Block1/Block2 options, byte offsets and packet sizesSmaller negotiated blocks help only if size/fragmentation is the cause
Observe updates stopCheck freshness, registration and reachabilityRe-register if needed; silence alone does not prove a server crash
Multicast has no repliesCheck interface, membership and multicast scope/routingFF02::FD is link-local; FF05::FD is site-local, not evidence of device presence

Debug Checklist:

  • Endpoint and security: verify the configured UDP listener (defaults: 5683 for CoAP, 5684 for CoAP over DTLS), firewall and interface. Ping success does not prove UDP reachability. Record compatible DTLS configuration and peer verification results; do not disable production security to test connectivity.
  • Request/response: record URI, method, message type, Token, Message ID and code. CON can be acknowledged with an empty ACK before a separate response; NON has no message-layer ACK but can still receive a response. Use the configured randomized retry schedule, not fixed 2/4/8/16 s expectations.
  • Observe: registration uses GET with Observe=0. Freshness is whether a representation is still usable under its age limit. Match notifications to the registration and compare sequence values with wrap-aware rules (RFC 7641 §3.4); apply a freshness policy before declaring data current.
  • Block transfer: Block1 carries request blocks; Block2 carries response blocks. Check byte offsets and consistent representation assembly, including block-size changes and retransmissions (RFC 7959 §2).
  • Load and duplicates: measure retry rate, response latency and handler load. A duplicate CON normally receives the same acknowledgment while the request is processed once (RFC 7252 §4.5); simply dropping every duplicate can provoke more retries.

Common Error Codes:

CodeMeaning and next check
2.01 CreatedCreation succeeded; check location where applicable; POST or PUT may create
2.02 DeletedDeletion succeeded
2.03 ValidCached representation validated; use the ETag request option
2.04 ChangedChange succeeded at the resource interface; verify physical action separately
2.05 ContentRepresentation returned
4.00 / 4.02Bad request / bad option; inspect request syntax or critical options
4.01 / 4.03Missing appropriate authorization / refusal that authorization will not resolve
4.04 / 4.05Missing resource / method unsupported on that resource
5.00 / 5.03Unexpected server condition / temporary unavailability; inspect server evidence and any Max-Age retry hint

Tools for Debugging:

Use libcoap client/server tools for controlled probes and Wireshark (coap) for decoded exchanges. The preserved tcpdump -i any port 5683 -vv command is scoped to that port and omits the default secure port. Encrypted application details require authorized endpoint logs. Californium and aiocoap logging depend on their installed versions.

Common Pitfalls

Common Pitfall: CoAP Message Size Exceeds MTU

A large configuration may work over Wi-Fi but fail on a constrained path. The maximum transmission unit (MTU) is the largest IP packet the path can carry without IP fragmentation; it is not a CoAP payload allowance. Account for IP, UDP, security and CoAP fields before choosing a block size.

The mistake: treating a payload limit from one network as universally safe.

Symptoms: small requests succeed while larger requests or responses fail; a trace may show fragmentation without successful reassembly.

Why it happens: losing a required fragment prevents reassembly. CoAP retransmission repeats a message rather than selectively retransmitting IP fragments. Link-layer recovery is a separate mechanism. IPv6’s minimum MTU is 1280 bytes; a 127-byte IEEE 802.15.4 frame is a link-layer limit, not the IPv6 MTU. Header compression and security change the available payload budget (RFC 7252 §4.6).

The protected Python example below delegates block handling to the library but does not explicitly set the block size described in its comments. The C example uses placeholder helpers and illustrative 64/1024-byte thresholds; its “Safe” comments are unverified and do not establish a path budget.

The fix:

# Use CoAP Block-wise Transfer (RFC 7959) for large payloads
from aiocoap import Message, Context
from aiocoap.numbers.codes import GET

async def get_large_resource(uri):
    context = await Context.create_client_context()

    # Request with Block2 option - library handles chunking
    request = Message(code=GET, uri=uri)
    # Block size: 64 bytes (szx=2), 128 bytes (szx=3), 256 bytes (szx=4)
    # Smaller blocks = more round trips but works on constrained networks

    response = await context.request(request).response
    return response.payload  # Library reassembles blocks automatically
// Embedded C: Check payload size before sending
#define COAP_MAX_PAYLOAD_6LOWPAN  64   // Safe for 802.15.4
#define COAP_MAX_PAYLOAD_UDP      1024 // Safe for most networks

size_t max_payload = is_constrained_network() ?
    COAP_MAX_PAYLOAD_6LOWPAN : COAP_MAX_PAYLOAD_UDP;

if (payload_len > max_payload) {
    // Use Block1 (request) or Block2 (response) transfer
    return coap_send_blockwise(payload, payload_len, max_payload);
}

Prevention: negotiate a supported block size and test the complete secured packet on the constrained path. Expected: all byte ranges arrive and the assembled representation is consistent. If smaller blocks still fail, inspect loss, authorization, total-size limits and server state before attributing the failure to MTU.

Common Pitfall: Misusing CON vs NON Message Types

For the configuration request, CON provides bounded retries and receipt evidence. It cannot make an unsupported PUT succeed or prove an actuator changed state. NON omits message-layer acknowledgment; a NON request can still have a response.

The mistake: choosing one message type for every workload or treating a missing response as proof that no action happened.

Symptoms: unnecessary ACK/retry traffic for replaceable readings, or an unknown command outcome after a timeout.

Why it happens: the exchange policy is mistaken for the application result. A server may act and then lose its response. Before repeating an action, read back state or use application duplicate controls.

The protected Python below is a sketch: context must already exist and security is not configured. Its “~5x” battery comment is unverified; an ACK provides no security guarantee. is_successful() checks the response class, not the physical door state, and the exception branch means outcome unknown rather than proof the command failed.

The fix:

from aiocoap import Message, Context
from aiocoap.numbers.codes import GET, PUT
from aiocoap.numbers.types import CON, NON

# NON for periodic telemetry (loss acceptable, battery critical)
async def send_temperature_reading(temp):
    request = Message(
        code=PUT,
        mtype=NON,  # Fire-and-forget, ~5x better battery life
        uri='coap://server/sensors/temp',
        payload=f'{temp}'.encode()
    )
    await context.request(request).response

# CON for critical commands (must know if it worked)
async def unlock_door():
    request = Message(
        code=PUT,
        mtype=CON,  # Need acknowledgment for security
        uri='coap://door/lock',
        payload=b'unlock'
    )
    try:
        response = await context.request(request).response
        return response.code.is_successful()
    except Exception:
        return False  # Command failed, alert user

# CON for configuration changes (must be applied)
async def update_reporting_interval(seconds):
    request = Message(
        code=PUT,
        mtype=CON,  # Config must be confirmed
        uri='coap://sensor/config/interval',
        payload=str(seconds).encode()
    )
    return await context.request(request).response

Decision matrix:

WorkloadCandidate policyRequired evidence
Replaceable periodic readingNON if occasional loss is acceptableFreshness and measured loss meet application needs
Alarm or commandCON if receipt/failure detection is neededApplication result, deadline and safe retry behavior
Configuration updateCON plus supported method and readbackReturned result and observed setting agree
Status queryCON or NON according to response needsResult arrives before it becomes stale
Firmware downloadBlock2 with a suitable exchange policyComplete, consistent representation; CON supplies ACK behavior, not Block2

Prevention: choose per workload and test a lost response. For the running example, fix the method contract first; for the secure-upload transfer example, resolve the handshake first.

Continue to the Next Part

Carry this evidence into CoAP Security: CON and NON Trade-Offs, which begins with Try It: CON vs NON Message Type Advisor.

Detail notes moved from the chapter

Historical protected source blocks retained for the chapter preservation check.

Overview of message types, resource methods and Observe notifications; distinguish exchange receipt from resource results.
Read message types as exchange controls, methods as resource operations, and Observe as continuing GET updates. These roles explain why an ACK cannot prove a configuration change.

Hi, I’m Broker Bex. What do you need?

Find help

Let’s find what you need

Find a lesson or return to your module guide.

Give feedback

Help improve this chapter

Tell us what helped or what needs fixing.

Tips

Try a small next step

A few ways to get more from this chapter.

Ask AI

Continue the conversation

Take the conversation further with your preferred assistant.

AI help is available in supported modules when enabled in Settings.

No live person answers on independent study. Feedback does not promise a personal reply.

For welfare or safety concerns, follow your school’s procedures outside IoTClass.