2 CoAP Messages: Format Foundations
More
Depth: Practitioner
Progress saves as you read. Mark sections complete as you go; your progress appears in the sidebar.
2.1 Start With the Decision
This section: Start With the Decision — A constrained sensor has little memory, power, or network capacity, so it cannot waste bytes on each request.
A constrained sensor has little memory, power, or network capacity, so it cannot waste bytes on each request. CoAP is the compact request-and-response method used here. Its four-byte header records the version, type, token length, code, and message ID. A token follows that header; checking it helps match a reply to the right request.
2.2 Route Overview
This section: Route Overview — This is part 1 of 3.
This is part 1 of 3. Continue with CoAP Messages: Codes, Tokens, and Options.
2.3 Part Objectives
This section: Part Objectives
- Read version, type, token length, code, and message ID fields.
- Explain why CoAP keeps a fixed four-byte header.
2.4 Start With the First Four Bytes
This section: Start With the First Four Bytes — A gateway cannot debug CoAP by reading a friendly URL first.
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.
- 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
This section: 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
- 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
This section: 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
This section: 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.
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 36 bytes of text just for the request line and mandatory host header — 43.4% of the available payload before you even add content headers.
| Design Decision | HTTP Approach | CoAP Approach | Why CoAP Wins |
|---|---|---|---|
| Header size | Variable text, 200-800 bytes typical | Fixed 4 bytes binary | Fits in 6LoWPAN with room for payload |
| Session state | TCP connection + cookies | Stateless with Token | No RAM for connection tables on 32 kB MCUs |
| Metadata encoding | Text headers (Content-Type: application/json) | Binary option numbers (12 = Content-Format, value 50 = JSON) | 2 bytes vs 30+ bytes for same information |
| Reliability | TCP retransmits lost segments automatically (after a 3-way handshake) | Per-message choice: CON or NON | Routine telemetry can tolerate an occasional loss (NON); commands and firmware blocks use CON |
| Request matching | TCP connection scopes the response | Token field (0-8 bytes) | No connection setup overhead, works over UDP |
Why 4 bytes and not 2 or 8? The header must encode five 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 256 kB gateway, connection bookkeeping can consume a substantial share of RAM; measure the selected TCP stack and socket limits rather than assuming a fixed percentage. CoAP avoids per-peer TCP connection state, but clients retain outstanding-token state and servers may retain reliability or Observe state.
Why binary options instead of text headers? Consider telling the server the payload is JSON:
- HTTP:
Content-Type: application/json\r\n= 32 bytes. - CoAP: Content-Format 50 as the first option = 2 bytes (one header, one value).
This saves 30 bytes, a 16× metadata-size difference in this example. It does not by itself predict a fixed battery-life gain.
Checkpoint: 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 2 CoAP bytes instead of a 32-byte HTTP header line.
2.9 Continue: CoAP Wire Format and Option Encoding
This section: 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.
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
This section: Continue to the Next Part — Carry this evidence into CoAP Messages: Codes, Tokens, and Options, which begins with The CoAP Message Format.
Carry this evidence into CoAP Messages: Codes, Tokens, and Options, which begins with The CoAP Message Format.
Find help
3 reviewed answers.
Where should I start in a module?
Open the module page from the sidebar to see its chapters in order. Use the module map to return to a topic you need.
Modules and pathsReviewed
What can I try when a project does not work?
Check the symptom, then work through the diagnostic steps. Keep the error message and the smallest example that reproduces it.
When you are stuckReviewed
How do interactive examples work?
Use the interactive guide to check how examples and simulations work before changing your project.
Interactive examples guideReviewed
