Chapters

2 CoAP Messages: Format Foundations

coap
message
format

2.1 Start With the Decision

A constrained sensor cannot waste bytes on every request. The first four CoAP bytes must carry enough state to route and match the message.

2.2 Route Overview

This is part 1 of 3. Continue with CoAP Messages: Codes, Tokens, and Options.

2.3 Part Objectives

  • Read version, type, token length, code, and message ID fields.
  • Explain why CoAP keeps a fixed four-byte header.
In 60 Seconds

Match One Reply to the Right Request

Picture a controller asking a leak sensor for its state while another request is still in flight. Four valid header bytes do not prove that the reply belongs to the current question or carries the expected content.

CoAP means the compact request-and-response method used here. A gateway is the device or service that joins two system paths. A payload is the useful content carried inside a message.

Send two numbered requests, delay one reply, repeat a request, change the content type, and restart the receiver. Record token, message identity, code, source, time, unit, and accepted application state. Reject a mismatched reply instead of guessing.

This runway does not prove identity, delivery, or physical action. The deeper sections explain header fields, message types, tokens, methods, options, content formats, and bounded decode checks.

A CoAP message consists of a compact 4-byte fixed header (version, type, token length, code, message ID), an optional token for request-response matching, delta-compressed options, and an optional payload. Understanding this binary format is essential for debugging network captures and optimizing message sizes on constrained networks where every byte impacts battery life and airtime cost.

2.4 Start With the First Four Bytes

A gateway cannot debug CoAP by reading a friendly URL first. It sees four bytes, then has to decide whether the datagram is Confirmable or Non-confirmable, which request or response code it carries, which Message ID is being acknowledged, and how much token data comes next.

This page turns that packet into a story: fixed header first, token second, compressed options third, payload marker only when a body follows. Once that order is clear, parser failures become visible instead of mysterious.

Chapter Roadmap
  • In 60 Seconds
  • Start With the First Four Bytes
  • Quick Check: Token Versus Message ID
  • Key Concepts
  • For Beginners: CoAP Message Format
  • Prerequisites
  • Why CoAP’s Format Exists: Design Rationale
  • Checkpoint: Format Constraints
  • Continue: CoAP Wire Format and Option Encoding

2.5 Learning Objectives

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

  • Decode CoAP Headers: Analyze and decode the 4-byte fixed header field-by-field, identifying version, type, token length, code, and message ID
  • Distinguish Options Encoding: Explain how delta compression works and calculate the byte savings compared to naive full-number encoding
  • Apply Response Codes: Select correct 2.xx/4.xx/5.xx codes for specific scenarios and justify the choice
  • Implement Token Matching: Construct proper request-response correlation logic using tokens rather than message IDs
  • Compare CoAP and HTTP: Calculate message size differences and evaluate the energy impact on battery-powered constrained devices
  • Diagnose Message Format Errors: Identify common parsing mistakes such as confusing Message ID with Token and incorrect Content-Format selection
Quick Check: Token Versus Message ID

Read these points as one connected sequence: start with CoAP: Constrained Application Protocol — REST-style request/response protocol using UDP instead of TCP; then Confirmable Message (CON): Requires ACK from recipient — provides reliable delivery over UDP at the cost of one roundtrip; then Non-confirmable Message (NON): Fire-and-forget UDP datagram — lowest latency, no delivery guarantee; then Observe Option: CoAP extension enabling publish/subscribe: client registers to receive notifications on resource changes; then Block-wise Transfer: Fragmentation mechanism for transferring payloads larger than a single CoAP datagram; then Token: Client-generated value matching responses to requests — enables concurrent request/response pairing; and finish with DTLS: Datagram TLS — CoAP’s security layer providing encryption and authentication over UDP.

  • CoAP: Constrained Application Protocol — REST-style request/response protocol using UDP instead of TCP
  • Confirmable Message (CON): Requires ACK from recipient — provides reliable delivery over UDP at the cost of one roundtrip
  • 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: Fragmentation mechanism for transferring payloads larger than a single CoAP datagram
  • 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

2.6 For Beginners: CoAP Message Format

Every CoAP message has a specific structure — a compact header followed by optional fields and the actual data. Think of it like a postcard: the header is the address and stamp (small, fixed size), and the rest is your message. CoAP keeps the header tiny (just 4 bytes) so that even the smallest devices can handle it.

2.7 Prerequisites

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

  • CoAP Introduction - Understanding why CoAP exists and its design goals
  • Binary number representation (bits, bytes, hexadecimal notation)

2.8 Why CoAP’s Format Exists: Design Rationale

Before dissecting the format byte by byte, it is worth understanding why CoAP’s designers made each choice. Every field exists to solve a specific problem that HTTP headers solve poorly in constrained environments.

The core constraint: IEEE 802.15.4 (6LoWPAN) frames have a maximum transfer unit of 127 bytes. After MAC headers (23 bytes), 6LoWPAN compression (13 bytes), and UDP headers (8 bytes), only 83 bytes remain for the application. An HTTP GET request with minimal headers (GET /temp HTTP/1.1\r\nHost: sensor\r\n\r\n) consumes 39 bytes of text just for the request line and mandatory host header — nearly half the available payload before you even add content headers.

Design DecisionHTTP ApproachCoAP ApproachWhy CoAP Wins
Header sizeVariable text, 200-800 bytes typicalFixed 4 bytes binaryFits in 6LoWPAN with room for payload
Session stateTCP connection + cookiesStateless with TokenNo RAM for connection tables on 32 kB MCUs
Metadata encodingText headers (Content-Type: application/json)Binary option numbers (12 = Content-Format, value 50 = JSON)2 bytes vs 30+ bytes for same information
ReliabilityTCP guarantees delivery (3-way handshake overhead)Per-message choice: CON or NONSensor telemetry doesn’t need guaranteed delivery; firmware updates do
Request matchingTCP connection scopes the responseToken field (0-8 bytes)No connection setup overhead, works over UDP

Why 4 bytes and not 2 or 8? The header must encode four things: version (future-proofing), message type (reliability selection), token length (variable for flexibility), response code (method or status), and message ID (deduplication). Two bytes cannot encode all five fields with sufficient range. Eight bytes would waste precious 6LoWPAN space. Four bytes — 32 bits — is the minimum that encodes everything needed while leaving 79 of 83 available bytes for tokens, options, and payload.

Why Token instead of TCP sessions? A typical IoT gateway manages 50-200 sensors simultaneously. If each sensor maintained a TCP connection, the gateway would need 50-200 open sockets, each consuming ~1-4 kB of RAM for TCP state. On a gateway with 256 kB RAM, that is 10-80% of memory just for connection bookkeeping. CoAP’s token-based matching needs zero persistent state — the 0-8 byte token travels with the message, and the server can be truly stateless.

Why binary options instead of text headers? Consider telling the server the payload is JSON:

  • HTTP: Content-Type: application/json\r\n = 32 bytes of ASCII text
  • CoAP: Option delta=12, length=1, value=50 = 3 bytes of binary

That is a 10x reduction. Over a network where each transmitted byte costs battery (LoRa: ~0.5 mJ per byte at SF12), this savings directly translates to months of additional battery life.

Broker BexCheckpoint: Format Constraints

You now know:

  • A 127-byte IEEE 802.15.4 frame leaves only 83 bytes for application data.
  • CoAP’s 4-byte header carries version, type, token length, code, and Message ID.
  • Content-Format JSON can take 3 CoAP bytes instead of a 32-byte HTTP header line.

2.9 Continue: CoAP Wire Format and Option Encoding

The main chapter below stays focused on CoAP message structure, methods, response codes, tokens, options, worked comparisons, and parser exercises. For the deeper wire-level contract behind fixed-header bits, TKL offsets, Code class/detail decoding, option delta encoding, critical/elective option handling, payload-marker boundaries, and byte-by-byte trace review, continue to CoAP Wire Format and Option Encoding.

2.10 Continue to the Next Part

Carry this evidence into CoAP Messages: Codes, Tokens, and Options, which begins with The CoAP Message Format.