HomeBlogMQTT 5 Packet Decoder: A Wire-by-Wire Guide

MQTT 5 Packet Decoder: A Wire-by-Wire Guide

Decode MQTT 5 packets byte by byte: Remaining Length, properties, shared subscriptions, reason codes, AUTH, and tested diagnostics across 64 checks.

DevKit is maintained by hcatree. I wrote the tools on this site and ran the compression benchmarks myself — the script and the raw data download from the benchmarks page.

2026-11-2711 min read

An MQTT packet looks simple until a property block, shared subscription, or truncated capture arrives. The useful question is “which bytes justify each field, and where must the decoder stop guessing?”

I exercised the decoder behind DevKit’s MQTT 5.0 Decoder with generated reference packets, malformed inputs, and a concatenated stream. The harness printed MQTT vectors passed: 64 checks. It uses mqtt-packet 9.0.2 to generate reference bytes, then asserts this project’s decoded fields and diagnostics. This is not an independent decoder comparison and not proof of complete MQTT 5 conformance.

The scope is raw MQTT wire data only: no TLS, WebSocket framing, PCAP, broker connection, session reconstruction, QoS retransmission state, or Pub/Sub history.

The fixed header is a routing instruction

Every packet begins with a byte whose high nibble identifies the type and low nibble contains flags. Except for PUBLISH, flags are fixed: PUBREL, SUBSCRIBE, and UNSUBSCRIBE require 0x2.

The implementation recognizes all 15 MQTT 5 packet types:

Type Packet Fixed flags Body highlights
1 CONNECT 0x0 Protocol level, Connect Flags, Keep Alive, properties, Client Identifier, optional Will and credentials
2 CONNACK 0x0 Session Present, Reason Code, properties
3 PUBLISH Variable Topic Name, optional Packet Identifier, properties, payload
4 PUBACK 0x0 Packet Identifier, optional Reason Code and properties
5 PUBREC 0x0 Packet Identifier, optional Reason Code and properties
6 PUBREL 0x2 Packet Identifier, optional Reason Code and properties
7 PUBCOMP 0x0 Packet Identifier, optional Reason Code and properties
8 SUBSCRIBE 0x2 Packet Identifier, properties, filter/options pairs
9 SUBACK 0x0 Packet Identifier, properties, one return code per subscription
10 UNSUBSCRIBE 0x2 Packet Identifier, properties, Topic Filters
11 UNSUBACK 0x0 Packet Identifier, properties, one Reason Code per filter
12 PINGREQ 0x0 Empty
13 PINGRESP 0x0 Empty
14 DISCONNECT 0x0 Optional Reason Code and properties
15 AUTH 0x0 Optional Reason Code, authentication properties

Four control packets make a compact sanity check:

c000    PINGREQ:    type 12, Remaining Length 0
d000    PINGRESP:   type 13, Remaining Length 0
e00104  DISCONNECT: type 14, Remaining Length 1, Reason Code 0x04
f000    AUTH:       type 15, Remaining Length 0

DISCONNECT 0x04 means Disconnect with Will Message. AUTH f000 decodes as implicit Success. Neither compact form grants permission to append arbitrary bytes: the harness separately checks that extra PINGREQ body data is rejected.

Remaining Length sets the boundary

Remaining Length counts the Variable Header plus Payload, excluding the fixed-header byte and the length encoding itself. It uses a Variable Byte Integer: each byte contributes seven data bits, little-endian groups, with bit 7 indicating continuation. The encoding uses one to four bytes and represents 0 through 268,435,455.

A useful mental model is:

value = (b0 & 0x7f)
      + (b1 & 0x7f) × 128
      + (b2 & 0x7f) × 128²
      + (b3 & 0x7f) × 128³

The harness generates a QoS 0 PUBLISH with topic large, an empty property block, and 20,000 ASCII A payload bytes. The decoded packet is 20,012 bytes long:

30 a8 9c 01 00 05 6c 61 72 67 65 00 41 41 41 ...
│  └───────┘ └───────────┘ │  └───────────────┘
│  RL = 20,008  Topic      │  Payload: 20,000 × 41
PUBLISH QoS 0   "large"    Property Length = 0

a8 9c 01 contributes 8 + 28×128 + 1×16,384 = 20,008. The eight body bytes before the payload are the two-byte topic length, five topic bytes, and one zero Property Length byte. The fixed header is four bytes, so 4 + 20,008 = 20,012.

MQTT 5 packet anatomy and Remaining Length

This boundary tells both parsers where the packet ends and the next fixed header begins. If it overruns the input, the tool records a truncated packet and stops; later bytes cannot safely become another packet.

Two generated dumps, decoded by the project

These dumps were produced with mqtt-packet 9.0.2 and then passed through decodeMqtt(). The explanations below follow the decoder’s actual byte ranges, not just the generator’s input object.

CONNECT: 34 bytes

10 20 00 04 4d 51 54 54 05 02 00 1e 0d 11 00 00
00 3c 21 00 14 22 00 08 19 01 00 06 64 65 76 6b
69 74
  • 10: CONNECT with zero flags. 20: Remaining Length 32.
  • 00 04 4d 51 54 54: UTF-8 string MQTT; 05: protocol level 5.
  • 02: Clean Start. 00 1e: Keep Alive 30 seconds.
  • 0d: 13 property bytes: Session Expiry Interval 60 (11 0000003c), Receive Maximum 20 (21 0014), Topic Alias Maximum 8 (22 0008), and Request Response Information 1 (19 01).
  • 00 06 64 65 76 6b 69 74: Client Identifier devkit.

Result: one CONNECT, protocol level 5, four properties, no errors, all 34 bytes consumed.

PUBLISH: 115 bytes

33 71 00 19 64 65 76 6b 69 74 2f 73 65 6e 73 6f
72 2f 74 65 6d 70 65 72 61 74 75 72 65 00 2a 3f
01 01 02 00 00 00 1e 23 00 02 08 00 0c 64 65 76
6b 69 74 2f 72 65 70 6c 79 09 00 02 09 08 0b 07
0b 09 03 00 10 61 70 70 6c 69 63 61 74 69 6f 6e
2f 6a 73 6f 6e 26 00 04 75 6e 69 74 00 01 43 7b
22 74 65 6d 70 65 72 61 74 75 72 65 22 3a 32 31
2e 35 7d
  • 33: PUBLISH, QoS 1, RETAIN set, DUP clear. 71: Remaining Length 113.
  • 00 19 and 25 bytes: Topic Name devkit/sensor/temperature. 00 2a: Packet Identifier 42.
  • 3f: 63 property bytes: Payload Format Indicator 1 (01), Message Expiry Interval 30 (02), Topic Alias 2 (23), Response Topic (08), Correlation Data 0908 (09), Subscription Identifiers 7 and 9 (0b twice), Content Type application/json (03), and User Property unit=C (26).
  • Final 20 bytes: UTF-8 {"temperature":21.5}.

The decoder reports 115 bytes consumed, nine properties, QoS 1, Packet Identifier 42, Topic Alias 2, Payload Format 1, and no errors. Repeated Subscription Identifiers are legal on PUBLISH; repeatability depends on property and context.

PUBLISH: flags, aliases, and opaque payloads

PUBLISH packs RETAIN into bit 0, QoS into bits 2–1, and DUP into bit 3. QoS 0 has no Packet Identifier; QoS 1 and 2 do. The harness covers all three QoS values and checks that QoS 3 and DUP-at-QoS-0 are errors.

A zero-length Topic Name requires a non-zero Topic Alias; the harness includes that case. The decoder does not maintain alias bindings across packets: two appearances of alias 2 do not prove an identical topic.

Properties describe the message; they do not transform its payload. Content Type application/json is metadata, not a JSON parser. Payload Format Indicator 1 adds a validation obligation: the harness rejects both an ill-formed UTF-8 PUBLISH payload and an ill-formed UTF-8 Will payload when that indicator is set. Without it, the payload remains opaque bytes.

SUBSCRIBE: filters and options travel together

SUBSCRIBE carries a Packet Identifier, properties, and Topic Filter/Subscription Options pairs. The harness generates devkit/+/status, $share/workers/jobs/#, and /finance.

The options byte carries maximum QoS, No Local, Retain As Published, and Retain Handling. Tested values include 0x2d (QoS 1, No Local, Retain As Published, Retain Handling 2), 0x02 (shared QoS 2), and 0x00 (QoS 0).

For $share/{ShareName}/{filter}, only the final filter participates in published-topic matching. ShareName is a server-side sharing group. The harness checks an empty ShareName, a missing filter, and No Local enabled on a shared subscription. It also rejects a/b+c, because + must occupy an entire topic level; the same rule requires # to be final and occupy a complete level. Wildcards are valid in filters, including UNSUBSCRIBE filters, but invalid in a PUBLISH Topic Name.

Reason codes and AUTH are context-sensitive

Reason codes are packet-specific: 0x10 means No matching subscribers for PUBACK but is rejected for CONNACK. SUBACK and UNSUBACK carry one code per requested item, each validated against its own table.

Publication acknowledgements have omission rules: length 2 carries only the Packet Identifier; length 3 adds Reason Code; length 4 or more makes properties explicit. Success and empty properties are implicit in the shorter forms. The harness exercises all three.

DISCONNECT with Remaining Length 0 means Normal disconnection by implication. AUTH may also use f000 for implicit Success, but once a Reason Code is present its Property Length must follow. The generated AUTH example decodes 0x18 as Continue authentication, method SCRAM, authentication data 01 02 03, Reason String challenge, and User Property step=1. The harness rejects authentication data without an authentication method and AUTH properties that omit the method. These are wire checks, not verification of SCRAM or credentials.

The strict errors actually tested

The vector suite deliberately exercises these diagnostics:

Input defect Checked behavior
CONNECT fixed flags 0x1 Reports the required flag mismatch
PUBLISH QoS 3, or DUP set at QoS 0 Rejects the illegal flag combination
PUBLISH declaring five body bytes with only one available Reports a Remaining Length overrun
PUBACK Packet Identifier 0000 Reports that a Packet Identifier must not be zero
Unknown property ID Reports it and leaves remaining property bytes untyped rather than guessing their length
Authentication Method on PUBACK Reports a property-context violation
Repeated Reason String on PUBACK Reports forbidden repetition here
Empty/malformed shared filters, or shared No Local Reports the specific shared-subscription violation
Invalid UTF-8 topic bytes ff fe Reports an invalid UTF-8 sequence
Payload Format 1 with ff payload Reports a payload UTF-8 violation

Unknown property handling is conservative: an ID carries no standalone wire type, so its value length may be unknowable. The decoder emits an error instead of inventing a parse.

The implementation caps streams at 20,000 packets and trees at 50,000 nodes; uploads are limited to 2 MB. These are practical guards, not protocol limits. A clean packet is not a valid session: ordering, authorization, alias history, retransmission state, and broker behavior remain outside the decode.

Concatenated packets: recover the boundary, not the session

The harness concatenates generated PINGREQ, PUBLISH, and PINGRESP packets. Remaining Length separates them into three packets with no errors and 11 bytes consumed.

It also concatenates a malformed PUBACK (40 02 00 00) with a valid PINGRESP (d0 00). The first packet has a reliable boundary but an illegal zero Packet Identifier. The decoder reports that error and still produces packet #2 as PINGRESP. This is recovery within a supplied byte stream, not session reconstruction. A broken Remaining Length cannot offer the same guarantee because the next packet’s start is unknown.

The linked tree and hex view tie every label and diagnostic to an exact byte range; the payload panel separates text from binary. Start with a short control packet, verify its boundary, then inspect properties. If your capture contains TLS or WebSocket frames, extract the MQTT bytes first; the decoder does not guess at another protocol.

References

Environment: measured 2026-11-27 on Windows x64 with Node.js v24.22.0 and tsx v4.23.15. Reference bytes were generated by mqtt-packet 9.0.2 from tmp/mqtt-ref; npx tsx tmp/mqtt-vectors.ts reported MQTT vectors passed: 64 checks. No benchmark or throughput result is claimed.

Discuss this articleEchoForum · no sign-up, replies in any language

Related Tools

MQTT 5.0 DecoderInspect MQTT packets, properties & payloads