Chapters

Delivery and Security Decisions: CoAP API Design Reference

Return to the parent chapter.

Start With the Decision

A farm gateway asks a valve to close. The valve receives the request, but its acknowledgement is lost. Should the gateway repeat the request, assume the valve stayed open, or check its state?

An API is the set of requests a service accepts. This API needs separate rules for message delivery, permission to act, and evidence that the valve closed. Work through that decision, then apply it to readings that can tolerate loss.

Route Overview

This is part 2 of 2. Review CoAP API Design: Resource and Response Contracts for the preceding evidence.

Learning Objectives

  • Choose a delivery policy from the cost of losing or repeating an operation.
  • Decide who may use a resource and what evidence proves the requested outcome.

Chapter Roadmap

  • Message Type Selection
  • Security Best Practices
  • Worked Example: Smart Agriculture API
  • Case Study: Smart Agriculture Sensor Network
  • Working Code: Python CoAP Client and Server
  • Putting Numbers to It: CoAP Message Types and Battery Life
  • Common Pitfalls
  • Common Pitfall: CoAP Observe Notification Flood
  • Pitfall: HTTP-CoAP Proxy Caching Stale Data
  • Label the Diagram
  • Code Challenge
  • Order the Steps
  • Concept Relationships
  • See Also
  • Match the Concepts
  • What’s Next
  • Summary

Message Type Selection

For the valve, choose a Confirmable (CON) request: the sender expects acknowledgement and can retransmit if none arrives. An ACK is that acknowledgement. It confirms message receipt; an empty ACK does not report the request’s result. Even a successful application response needs a defined relationship to the physical valve state.

Suppose the request says “set closed” rather than “toggle.” Setting the same desired state again is idempotent: repetition preserves the intended state. If the ACK is lost, a retry should not turn the valve back on. CoAP duplicate handling and application state checks both matter; a new application request is not automatically the same message-layer retransmission.

A timeout means the sender did not receive the expected acknowledgement. The valve might still have acted. Read back its state or consult an application result before deciding what to do next.

A Non-confirmable (NON) message has no message-layer acknowledgement or retransmission. Use it for a routine moisture reading only when missing that reading is acceptable and a later one replaces it. NON does not stop a server from returning a response to a request.

Apply this decision rule:

  1. State what happens if the operation is lost or repeated.
  2. Choose CON when acknowledgement and bounded retries are needed; define what happens if they time out.
  3. Choose NON when loss is acceptable without message-layer retries.
  4. Separately define the application response, duplicate policy and evidence of the physical outcome.

Security Best Practices

The farm’s monitoring client may read valve state, but only its controller may change it. Encryption does not express that distinction. Authentication establishes a peer’s identity; authorization decides whether that identity may use a particular method on a resource.

For the valve, protect the exchange, check the controller’s write permission, and validate the requested state before acting. Keep those checks separate from the evidence that the valve actually closed.

Protect Production CoAP Exchanges

coaps://sensor.local/v1/temperature    # Secure CoAP

Datagram Transport Layer Security (DTLS) protects messages between its connection endpoints. The coaps:// URI above names a DTLS-protected CoAP service. Choose credentials that the deployment can provision, replace and revoke:

  1. A pre-shared key (PSK) is a secret provisioned to the peers. Protect its distribution and replacement.
  2. A raw public key (RPK) is a public key used without a certificate. The peer still needs a trusted association between that key and an identity.
  3. An X.509 certificate binds a public key to an identity through a certificate trust system. Plan certificate validation and renewal.

Object Security for Constrained RESTful Environments (OSCORE) protects CoAP message content between configured security endpoints. It can preserve that protection through a forwarding proxy. Decide where protection terminates before choosing DTLS, OSCORE, or a deployment that uses both. Neither choice replaces resource authorization.

Security Checklist

Review the valve’s controls as separate questions:

  • Protect the exchange between the intended security endpoints.
  • Permit the controller to write; restrict the monitoring client to reads.
  • Validate payload structure and allowed valve states before applying a change.
  • Limit accepted work per authenticated device; measure rejection and overload behavior.
  • Preserve the security context’s replay checks, which reject reuse of old protected messages.
  • Choose session idle limits from reconnect cost and exposure; plan credential replacement and revocation.

A valid credential does not make every request authorized. Replay checks do not decide whether a newly issued command is safe. Keep application state and outcome checks too.

Rate Limiting

Suppose a faulty farm sensor sends repeated requests. A per-device limit bounds how much work the gateway accepts from that identity. It reduces one source of overload; it does not guarantee that the service cannot be overwhelmed.

The existing example policy allows 10 requests/minute. A rejected request can receive 4.29 Too Many Requests with a Max-Age backoff interval. The example’s RATE_LIMIT_EXCEEDED error key and retry_after = 45 are application payload fields, not standard CoAP option names. If used together, make their retry advice consistent.

A token bucket holds permission tokens: each accepted request consumes one, the bucket has a maximum capacity, and tokens refill over time. Capacity permits a burst; refill controls the long-run admitted rate. Log rejections so a failed valve request can be distinguished from a network timeout.

Interactive Rate Limit Analysis

Read the two rates separately. “Max Requests per Window” divided by “Time Window” sets the displayed sustained-rate calculation. “Refill Rate” controls token supply in the simulation. The model does not enforce both as one policy: changing the window alone changes the display but not the token timeline. The default 0.17 tokens/second only approximates 10 requests/minute.

Predict which change admits more requests: increasing bucket capacity permits a larger initial burst; increasing refill supplies more tokens over time. The simulation refills before each request attempt and uses a fixed attempt schedule. “Burst duration” is capacity divided by the displayed window rate, not a guaranteed time limit. Use the model to compare assumptions, then implement and test one consistent limiter.

Worked Example: Smart Agriculture API

Complete the running valve decision: send an idempotent “set closed” request using CON, authorize only the controller to write, validate the state value, and check the returned application result and valve-state evidence. If acknowledgement times out, record the outcome as unknown until it is checked. Now transfer those rules to a farm’s sensor traffic.

Case Study: Smart Agriculture Sensor Network

Transfer scenario: Assume 200 battery-powered soil moisture sensors report to a central gateway. This is a design exercise, not a measured deployment.

OperationExample contractReason and evidence needed
Routine moisture reportNON POST to .../v1/sensors/field3-42/moistureA later reading replaces loss in this scenario; retain its timestamp so silence is visible.
Important alertCON POST to .../v1/sensors/field3-42/alertAcknowledgement and retry feedback matter; the application still needs evidence that the alert was handled. Repeated POST processing needs a duplicate policy.
Battery stateGET with Observe on .../v1/sensors/{sensor_id}/batteryObserve registers interest in later state notifications instead of repeated polling. Define notification thresholds and stale-state behavior.
Reporting configuration.../v1/sensors/{sensor_id}/configRestrict changes to the configuration controller; sensor identity alone does not grant write permission.

The moisture payload carries value, unit and timestamp. CBOR is a binary representation candidate; compare its encoded size with the alternative payload before claiming a bandwidth saving. Alerts carry type, threshold and current reading. These fields describe the example contract, not a universal schema.

Keep sensor permissions scoped to their own resources. A v1 path can keep today’s moisture contract while v2 adds temperature and pH, but both versions still need defined permissions and migration behavior.

Before reading on, decide: if the gateway receives a CON alert and its ACK is lost, is the alert known to be unhandled? No. The sender lacks receipt evidence; it cannot infer the gateway’s application outcome from that absence.

Working Code: Python CoAP Client and Server

The following aiocoap outline uses a temperature resource to check response behavior. It is an implementation sketch, not a complete secured server. Apply the valve rule: a response code, an authorized write and a physical measurement are separate evidence.

Python CoAP Server (Gateway)

  1. Define TemperatureResource with a stored value and source timestamp.
  2. Implement render_get() to encode value, unit and timestamp as bytes and return 2.05 Content. Set content_format=50 for JSON.
  3. Implement render_put() with identity, write-permission and input checks before changing stored state. Return 2.04 Changed only for an accepted update.
  4. If supporting Observe, use an observable resource implementation with registration and notification support. A base resource and an updated_state() call alone do not establish that lifecycle.
  5. Register v1/temperature and v1/config, then create the server context. UDP port 5683 in this outline describes plain CoAP; it does not configure DTLS or OSCORE.

Expected result: an allowed GET returns the stored value with its source timestamp and declared representation. A successful write changes that stored value. Neither result proves a new physical sensor sample was taken. A response lacking the expected format or timestamp leaves part of the contract unverified.

Python CoAP Client (Sensor)

  1. Create a client context with create_client_context() and request .../v1/temperature using GET.
  2. Expect 2.05 Content, check the declared format, and decode the JSON value and timestamp. A successful code with an old timestamp is still unsuitable for a fresh-state decision.
  3. As the authorized writer, send a PUT containing the new value. Expect 2.04 Changed, then read back the stored state. A timeout leaves the outcome unknown; check before issuing a new action.
  4. Request an unregistered path and expect 4.04 Not Found; try an unsupported method and expect 4.05 Method Not Allowed. A success response means the resource or method policy differs from the test contract.
  5. Repeat the write as a read-only identity. Expect rejection with no state change. Acceptance exposes a missing permission check even if transport protection works.

CLI Testing with coap-client

Use a locally available coap-client; package and executable names depend on the installed libcoap build. Replace ... below with your configured endpoint. These are command templates, not a security configuration.

  1. Read: coap-client -m get .../v1/temperature. Expect 2.05 Content and a value with a timestamp. An unreachable endpoint gives no evidence of current state.
  2. Update as an allowed writer: coap-client -m put -e '{"value":23.1}' .../v1/temperature. Expect 2.04 Changed, then repeat the GET. An unchanged value requires checking the handler and resource contract.
  3. Test Observe only if implemented: coap-client -m get -s 60 .../v1/temperature. Expect an initial response and later notifications when the resource changes under its notification policy. Silence alone cannot distinguish an unchanged resource from a broken observation.
  4. Discover: coap-client -m get .../.well-known/core. Expect the discoverable resource links. Discovery does not grant write permission; verify permissions separately.

Illustrative charge model: A battery sensor reports every 60 seconds for 1 year using a nominal 220 mAh CR2032 at 3 V. These assumed current and time values are not a measured device profile.

CON message charge (seconds multiplied by milliamperes):

TX message (50 ms @ 10 mA)=50×10−3×10=0.5 mAsRX ACK (100 ms @ 5 mA)=100×10−3×5=0.5 mAsTotal per message=1.0 mAs=0.278 μAh\begin{align} \text{TX message (50 ms @ 10 mA)} &= 50 \times 10^{-3} \times 10 = 0.5 \text{ mAs} \\ \text{RX ACK (100 ms @ 5 mA)} &= 100 \times 10^{-3} \times 5 = 0.5 \text{ mAs} \\ \text{Total per message} &= 1.0 \text{ mAs} = 0.278 \text{ } \mu\text{Ah} \end{align}

NON message charge:

TX message (50 ms @ 10 mA)=0.5 mAsNo ACK wait=0 mAsTotal per message=0.5 mAs=0.139 μAh\begin{align} \text{TX message (50 ms @ 10 mA)} &= 0.5 \text{ mAs} \\ \text{No ACK wait} &= 0 \text{ mAs} \\ \text{Total per message} &= 0.5 \text{ mAs} = 0.139 \text{ } \mu\text{Ah} \end{align}

Annual comparison (525,600 messages):

CON charge=525,600×0.278/1000≈146 mAhSleep charge=0.005×24×365=44 mAhTotal CON=146+44=190 mAh (battery life=220/190=1.16 years)NON charge=525,600×0.139/1000≈73 mAhTotal NON=73+44=117 mAhBattery life=220117=1.88 years\begin{align} \text{CON charge} &= 525{,}600 \times 0.278 / 1000 \approx 146 \text{ mAh} \\ \text{Sleep charge} &= 0.005 \times 24 \times 365 = 44 \text{ mAh} \\ \text{Total CON} &= 146 + 44 = 190 \text{ mAh (battery life} = 220/190 = 1.16 \text{ years)} \\ \\ \text{NON charge} &= 525{,}600 \times 0.139 / 1000 \approx 73 \text{ mAh} \\ \text{Total NON} &= 73 + 44 = 117 \text{ mAh} \\ \text{Battery life} &= \frac{220}{117} = 1.88 \text{ years} \end{align}

Model result: the rounded charge budgets extrapolate to about 14 months with CON and 23 months with NON, roughly 62% longer in this model. They are not measured lifetimes or a guaranteed target. The estimate omits retransmissions, security setup, sensor/processor work and battery behavior. The annual comparison uses mAh, a charge unit; the calculator below labels these charge quantities as “energy.”

Interactive Battery Life Optimizer

Predict the effect before moving a control: a longer reporting interval reduces modeled radio charge while sleep charge stays fixed. Switching to NON removes only this model’s assumed ACK receive window. The widget’s “doubling radio time” statement is incorrect: CON models 50 ms of TX plus 100 ms of RX, or 150 ms of active radio time, versus 50 ms for NON—three times as long. At the default currents, TX uses 0.050 s × 10 mA = 0.5 mAs and RX uses 0.100 s × 5 mA = 0.5 mAs, so CON doubles radio charge from 0.5 to 1.0 mAs. The widget’s “50% radio energy” saving for NON therefore describes the default radio charge comparison, not active time or total device charge; it is not a protocol guarantee. Its controls labelled “Power (mA)” actually take current. Compare charge budgets here, then measure the real device before selecting a battery.

Maths · guided foundations

What the ACK Costs Over a Year

Check the quantities and assumptions.

Common Pitfalls

Common Pitfall: CoAP Observe Notification Flood

Sampling a sensor and notifying its observers are different jobs. Sending a notification for every small change can increase wakeups and traffic. That does not make every slow or silent client proof of a notification flood.

Check notification counts and client behavior before changing the policy. A Reset (RST) tells the sender that the receiver did not recognize the message context; it can reflect lost observation state. It is not an overload diagnosis by itself.

The preserved sketch below shows a common trap. Its or condition sends when either the change threshold is crossed or the elapsed time reaches the interval. A rapid large change therefore bypasses MIN_NOTIFY_INTERVAL; the code does not enforce a minimum gap between notifications. It also omits state initialization and the surrounding server implementation.

# BAD: Notify on every sensor reading
@coap_resource('/temperature')
def on_read():
    current_temp = read_sensor()
    notify_observers(current_temp)  # Called 10x/second!

# GOOD: Throttle with change threshold
MIN_NOTIFY_INTERVAL = 5.0  # seconds
CHANGE_THRESHOLD = 0.5     # degrees

@coap_resource('/temperature')
def on_read():
    current_temp = read_sensor()

    should_notify = (
        abs(current_temp - last_notified_temp) >= CHANGE_THRESHOLD or
        (time.time() - last_notify_time) >= MIN_NOTIFY_INTERVAL
    )

    if should_notify:
        notify_observers(current_temp)
        last_notified_temp = current_temp
        last_notify_time = time.time()

For a hard minimum gap, first require the elapsed time to reach the minimum, then evaluate the change condition. If unchanged values also need periodic refresh, define that refresh interval separately. The example’s 5 seconds and 0.5 degrees are illustrative choices, not deployment recommendations.

Initialize and update notification state consistently, test rapid changes, and keep the timestamp of the last accepted reading. Set Max-Age, the response’s freshness lifetime, to match the contract. A client must recognize expired evidence even when no notification arrives.

Pitfall: HTTP-CoAP Proxy Caching Stale Data

Now transfer the valve rule to a temperature decision made through an HTTP-to-CoAP proxy. A cached response may satisfy a display but be too old for control. A cache stores a response for reuse; freshness asks whether its age still meets the contract.

The sketch below reuses a cached response only while its age is less than both the client’s allowed age and the CoAP response’s Max-Age. Read that condition before assuming a cache hit provides a new measurement. The allowlist also restricts which CoAP targets the proxy can contact.

ALLOWED_COAP_TARGETS = {'temperature': 'coap://sensor.local/temperature'}

@app.route('/coap/<path:resource>')
async def proxy_coap(resource):
    # Resolve only configured targets; never construct a target from raw input.
    coap_uri = ALLOWED_COAP_TARGETS.get(resource)
    if coap_uri is None:
        abort(404)

    # HTTP Cache-Control controls this client's use of the proxy cache.
    directives = {}
    for part in request.headers.get('Cache-Control', 'max-age=60').split(','):
        name, separator, value = part.strip().partition('=')
        name = name.strip().lower()
        if name == 'max-age' and (name in directives or not separator or
                                  not value.strip().isdecimal()):
            abort(400)
        directives[name] = value.strip()
    client_max_age = int(directives.get('max-age', 60))
    if 'no-cache' in directives or 'no-store' in directives:
        client_max_age = 0

    # Check cache with client's freshness requirement
    if coap_uri in cache:
        response, cached_time, server_max_age = cache[coap_uri]
        age = time.time() - cached_time
        effective_max_age = min(client_max_age, server_max_age)

        if age < effective_max_age:
            return response.payload  # Cache hit
    # ... fetch from device if stale

Key principle: in this sketch, HTTP Cache-Control: max-age=0 prevents the shown local cache-hit branch. It does not guarantee a new sensor sample. Fetch and storage behavior are omitted; the sketch does not implement a complete HTTP cache, including no-store handling. Check the source timestamp, upstream cache policy and behavior when fresh evidence cannot be obtained. CoAP Max-Age is a response option, not a request for a new measurement.

Label the Diagram

Knowledge check · self-test

Knowledge check

Test your understanding.

Code Challenge

Knowledge check · self-test

Knowledge check

Test your understanding.

Order the Steps

Knowledge check · self-test

Knowledge check

Test your understanding.

Concept Relationships

This chapter on CoAP API design connects to several key concepts:

Builds on:

Review response codes and options in the message format, then revisit the REST principles that shape this API.

Relates to:

Compare MQTT publish and subscribe APIs with HTTP resource APIs before choosing how clients interact with the service.

Enables:

Build the API in the labs. Then use the decision guide to check whether CoAP fits.

See Also

Related Chapters:

Review advanced CoAP features before refining the resource contract, since block transfer and Observe affect API behavior.

External Resources:

Read the CoAP rules first. Then use the CoRE link format to describe resources.

Match the Concepts

What’s Next

Use the decision framework to choose CoAP for the service, then study advanced features before building the API.

Summary

Start with the operation’s consequence: can a lost reading be replaced, and what would a repeated command do? Choose CON for acknowledgement and retries when needed, or NON when that message-layer evidence is unnecessary. Neither choice proves a physical outcome.

Protect the exchange, authorize the identity’s method on the resource, and validate input before acting. After a timeout or cached read, check application results and source timestamps. Record unknown or stale state explicitly instead of treating message receipt as completion.

Continue Your Route

This is the last part of this chapter. Return to CoAP API Design: Resource and Response Contracts or continue from the coap module index.

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.