How MQTT Works over TCP, WebSockets, and TLS, and How CoAP Compares

This walkthrough uses captures from the late Nick Russo's free packet-capture library. They are in the IoT archive, iot_pcap.zip, under iot_pcap/: mqtt_unenc.pcapng, mqtt_unenc_ws.pcapng, mqtt_tls.pcapng, mqtt_tls_ws.pcapng, coap_get.pcapng, and coap_post_delete.pcapng. The archive is preserved by the Internet Archive, with the rest of the library listed on his job aid page. We decoded the captures with VisualEther, which turns a Wireshark PCAP into a sequence diagram with a plain-English caption on every message.

MQTT is the messaging protocol behind much of the Internet of Things. A sensor, a smart plug, or a Home Assistant server connects to a central server called a broker and publishes readings to named topics, such as home/kitchen/temperature. Anything subscribed to that topic gets each reading as it arrives. Zigbee2MQTT, Tasmota, and most cloud IoT services speak it.

The same MQTT session can travel four ways: over plain TCP, inside WebSocket so a web page can use it, inside TLS for encryption, or inside both. These captures record one client, the MQTT Explorer desktop app, doing the same thing all four ways against the public test broker test.mosquitto.org on November 29, 2020. Comparing them shows exactly what each layer adds and what an eavesdropper can still learn once TLS is on.

A fifth and sixth capture show CoAP, the other common IoT protocol. It does a similar job very differently: request and response over UDP, with no broker and no connection.

Four captures are drawn as annotated sequence diagrams:

  1. MQTT over TCP, port 1883: connect, subscribe, a burst of retained messages, and disconnect (74 frames).
  2. MQTT over WebSocket, port 8080: the same session behind an HTTP Upgrade (120 frames).
  3. MQTT over TLS 1.3, port 8883, without the session keys: only sizes and timing are visible (76 frames).
  4. CoAP GET requests over UDP, including separate responses, a block-wise transfer, and two errors (34 frames).

Each participant gets a lane, and each message is an arrow, numbered as in Wireshark and captioned with what it does. The three MQTT diagrams leave out some of the repeated statistics messages; the gaps in the frame numbers mark the cuts. Every diagram comes in three forms: an interactive viewer, an HTML page, and a printable PDF. In the viewer and the HTML page, clicking any message opens its full Wireshark field tree.

💡 Read the walkthrough and a diagram side by side: open the interactive diagram in a split-screen window, or open the HTML version in a new tab and snap the two windows side by side. Each capture section below links its own diagram.

MQTT in one minute

MQTT uses publish and subscribe. Clients never talk to each other directly; every message goes through the broker. A client publishes a message to a topic, a string with / separating its levels. The broker forwards it to every client whose subscription matches that topic. A subscription can use wildcards: + matches one level, and # matches all remaining levels, so home/# matches every topic under home/.

Every message has a quality of service (QoS) level:

A publisher can also ask the broker to retain a message. The broker keeps the last retained message on each topic and hands it to every new subscriber at once, so a dashboard that connects late still gets the latest value.

These captures use MQTT 3.1.1, an OASIS standard. Section numbers below refer to the 3.1.1 specification. The packets in these captures are:

PacketDirectionJobSection
CONNECTClient to brokerOpen a session: protocol level, client ID, Keep Alive, flags3.1
CONNACKBroker to clientAccept or refuse the session3.2
SUBSCRIBEClient to brokerAsk for topics matching a filter3.8
SUBACKBroker to clientGrant a QoS level for each filter, or refuse it3.9
PUBLISHEither wayCarry one message on one topic3.3
DISCONNECTClient to brokerEnd the session cleanly3.14

Two more appear in most long-lived sessions but not here: PINGREQ and PINGRESP (3.12 and 3.13), the keepalive heartbeat a client sends when it has had nothing else to send for its Keep Alive interval.

Every MQTT packet starts with a fixed header: one byte for the packet type and flags, then a "remaining length" of one to four bytes. A DISCONNECT is just those two bytes, 0xE0 0x00. That small size is why MQTT suits slow or metered links.

What does each transport add to MQTT?

Here are all four MQTT captures side by side. Each one connects to test.mosquitto.org from the same client, about 95 ms away:

TCPWebSocketTLSTLS + WebSocket
Capturemqtt_unencmqtt_unenc_wsmqtt_tlsmqtt_tls_ws
Broker port1883808088838081
Setup before CONNECTTCP handshakeTCP, then an HTTP UpgradeTCP, then a TLS 1.3 handshakeTCP, TLS 1.3, then an HTTP Upgrade
Round trips to CONNACK2334
CONNACK after the first SYN184 ms304 ms348 ms395 ms
Bytes added around each MQTT writeNone2 from the broker, 6 from the client22 per TLS recordBoth
What a passive observer readsEverythingEverythingServer name, sizes, timingServer name, sizes, timing

Ports 1883 and 8883 are registered with IANA for MQTT and MQTT over TLS (MQTT 3.1.1 section 4.2). WebSocket has no MQTT port of its own: brokers often sit behind the web ports 80 and 443, and test.mosquitto.org uses 8080 and 8081.

The WebSocket overhead counts frames with up to 125 bytes of payload, as every frame here has. The 22 TLS bytes are a 5-byte record header plus the 17 bytes AES-GCM adds; more on that in capture 3.

Capture 1: MQTT over TCP

This is MQTT with nothing around it: a TCP connection to port 1883 and every byte in the clear. The session lasts 20 seconds.

sequenceDiagram accTitle: MQTT over TCP session with test.mosquitto.org accDescr: After the TCP handshake, the client sends CONNECT with Clean Session set and Keep Alive 60. The broker accepts with CONNACK. The client subscribes to the number-sign wildcard and to dollar SYS slash number sign. The broker refuses the first and grants the second at QoS 0, then sends 53 retained statistics messages with RETAIN set. Live updates follow with RETAIN clear. The client publishes three test messages and then sends DISCONNECT and closes TCP. participant C as Client participant B as Broker C->>B: [4] CONNECT, clean session, Keep Alive 60 s B->>C: [6] CONNACK, accepted C->>B: [8] SUBSCRIBE # and SUBSCRIBE $SYS/# B->>C: [10] [12] SUBACK, # refused, $SYS/# granted B->>C: [13]-[31] PUBLISH x 53, RETAIN=1 B->>C: [33] onward, live PUBLISH, RETAIN=0 C->>B: [69] DISCONNECT, then TCP FIN
Capture 1 at a glance. Frame numbers are in brackets.

What does an MQTT CONNECT contain?

The client's name for itself, the rules for its session, and the protocol version. CONNECT must be the first packet on a new connection (3.1). Here it is 36 bytes:

🔗 [00003] Frame 4 MQTT CONNECT 2020-11-29T15:05:54.623218Z 💻 Client → 🖥 MQTT Broker
frame : Frame 4: Packet, 102 bytes on wire (816 bits), 102 bytes captured (816 bits) on interface en0, id 0
Section number : 1
Interface id : 0 (en0)
Interface name : en0
Interface description : Wi-Fi
Encapsulation type : Ethernet (1)
Arrival Time : Nov 29, 2020 20:35:54.623218000 India Standard Time
UTC Arrival Time : Nov 29, 2020 15:05:54.623218000 UTC
Epoch Arrival Time : 1606662354.623218000
Time shift for this packet : 0.000000000 seconds
Time delta from previous captured frame : 224.000 microseconds
Time delta from previous displayed frame : 224.000 microseconds
Time since reference or first frame : 90.001000 milliseconds
Frame Number : 4
Frame Length : 102 bytes (816 bits)
Capture Length : 102 bytes (816 bits)
Frame is marked : False
Frame is ignored : False
Protocols in frame : eth:ethertype:ip:tcp:mqtt
Character encoding : ASCII (0)
eth : Ethernet II, Src: c8:e0:eb:13:de:6d, Dst: 48:5d:36:c9:c9:6b
Destination : 48:5d:36:c9:c9:6b
Destination (resolved) : 48:5d:36:c9:c9:6b
Destination OUI : 48:5d:36 (Verizon)
Destination OUI (resolved) : Verizon
.... ..0. .... .... .... .... = LG bit : Globally unique address (factory default)
.... ...0 .... .... .... .... = IG bit : Individual address (unicast)
Address : 48:5d:36:c9:c9:6b
Address (resolved) : 48:5d:36:c9:c9:6b
Address OUI : 48:5d:36 (Verizon)
Address OUI (resolved) : Verizon
.... ..0. .... .... .... .... = LG bit : Globally unique address (factory default)
.... ...0 .... .... .... .... = IG bit : Individual address (unicast)
Source : c8:e0:eb:13:de:6d
Source (resolved) : c8:e0:eb:13:de:6d
Source OUI : c8:e0:eb (Apple, Inc.)
Source OUI (resolved) : Apple, Inc.
.... ..0. .... .... .... .... = LG bit : Globally unique address (factory default)
.... ...0 .... .... .... .... = IG bit : Individual address (unicast)
Address : c8:e0:eb:13:de:6d
Address (resolved) : c8:e0:eb:13:de:6d
Address OUI : c8:e0:eb (Apple, Inc.)
Address OUI (resolved) : Apple, Inc.
.... ..0. .... .... .... .... = LG bit : Globally unique address (factory default)
.... ...0 .... .... .... .... = IG bit : Individual address (unicast)
Type : IPv4 (0x0800)
Stream index : 0
ip : Internet Protocol Version 4, Src: 192.168.1.151, Dst: 5.196.95.208
0100 .... = Version : 4
.... 0101 = Header Length : 20 bytes (5)
Differentiated Services Field : 0x00 (DSCP: CS0, ECN: Not-ECT)
0000 00.. = Differentiated Services Codepoint : Default (0)
.... ..00 = Explicit Congestion Notification : Not ECN-Capable Transport (0)
Total Length : 88
Identification : 0x0000 (0)
010. .... = Flags : 0x2, Don't fragment
0... .... = Reserved bit : Not set
.1.. .... = Don't fragment : Set
..0. .... = More fragments : Not set
...0 0000 0000 0000 = Fragment Offset : 0
Time to Live : 64
Protocol : TCP (6)
Header Checksum : 0x12cd [validation disabled]
Header checksum status : Unverified
Source Address : 192.168.1.151
Source or Destination Address : 192.168.1.151
Source Host : 192.168.1.151
Source or Destination Host : 192.168.1.151
Destination Address : 5.196.95.208
Source or Destination Address : 5.196.95.208
Destination Host : 5.196.95.208
Source or Destination Host : 5.196.95.208
Stream index : 0
tcp : Transmission Control Protocol, Src Port: 50843, Dst Port: 1883, Seq: 1, Ack: 1, Len: 36
Source Port : 50843
Destination Port : 1883
Source or Destination Port : 50843
Source or Destination Port : 1883
Stream index : 0
Stream Packet Number : 4
Conversation completeness : Complete, WITH_DATA (31)
..0. .... = RST : Absent
...1 .... = FIN : Present
.... 1... = Data : Present
.... .1.. = ACK : Present
.... ..1. = SYN-ACK : Present
.... ...1 = SYN : Present
Completeness Flags : ·FDASS
TCP Segment Len : 36
Sequence Number : 1 (relative sequence number)
Sequence Number (raw) : 3281050995
Next Sequence Number : 37 (relative sequence number)
Acknowledgment Number : 1 (relative ack number)
Acknowledgment number (raw) : 235945248
1000 .... = Header Length : 32 bytes (8)
Flags : 0x018 (PSH, ACK)
000. .... .... = Reserved : Not set
...0 .... .... = Accurate ECN : Not set
.... 0... .... = Congestion Window Reduced : Not set
.... .0.. .... = ECN-Echo : Not set
.... ..0. .... = Urgent : Not set
.... ...1 .... = Acknowledgment : Set
.... .... 1... = Push : Set
.... .... .0.. = Reset : Not set
.... .... ..0. = Syn : Not set
.... .... ...0 = Fin : Not set
TCP Flags : ·······AP···
Window : 2058
Calculated window size : 131712
Window size scaling factor : 64
Checksum : 0x7a05 [unverified]
Checksum Status : Unverified
Urgent Pointer : 0
Options : (12 bytes), No-Operation (NOP), No-Operation (NOP), Timestamps
TCP Option - No-Operation (NOP)
Kind : No-Operation (1)
TCP Option - No-Operation (NOP)
Kind : No-Operation (1)
TCP Option - Timestamps : TSval 71086860, TSecr 260134833
Kind : Time Stamp Option (8)
Length : 10
Timestamp value : 71086860
Timestamp echo reply : 260134833
Timestamps
Time since first frame in this TCP stream : 90.001000 milliseconds
Time since previous frame in this TCP stream : 224.000 microseconds
SEQ/ACK analysis
iRTT : 89.777000 milliseconds
Bytes in flight : 36
Bytes sent since last PSH flag : 36
Client Contiguous Streams : 1
Server Contiguous Streams : 1
TCP payload (36 bytes)
PDU Size : 36
mqtt : MQ Telemetry Transport Protocol, Connect Command
Header Flags : 0x10, Message Type: Connect Command
0001 .... = Message Type : Connect Command (1)
.... 0000 = Reserved : 0
Msg Len : 34
Protocol Name Length : 4
Protocol Name : MQTT
Version : MQTT v3.1.1 (4)
Connect Flags : 0x02, QoS Level: At most once delivery (Fire and Forget), Clean Session Flag
0... .... = User Name Flag : Not set
.0.. .... = Password Flag : Not set
..0. .... = Will Retain : Not set
...0 0... = QoS Level : At most once delivery (Fire and Forget) (0)
.... .0.. = Will Flag : Not set
.... ..1. = Clean Session Flag : Set
.... ...0 = (Reserved) : Not set
Keep Alive : 60
Client ID Length : 22
Client ID : mqtt-explorer-5bd1fce3
Rendered from a Wireshark PCAP by VisualEther.

Frame 4, the CONNECT. Under MQ Telemetry Transport Protocol: Protocol Name MQTT, Version 4 (MQTT 3.1.1), Connect Flags 0x02 (Clean Session only), Keep Alive 60, and the Client ID.

The broker answers in frame 6 with CONNACK, return code 0, Connection Accepted. Its Session Present flag is 0, which section 3.2.2.2 requires after a clean-session CONNECT: there is no earlier session to resume. Two round trips (184 ms) after the first SYN, the client can subscribe.

Why does the client subscribe to both # and $SYS/#?

Because # does not match topics that start with $. A filter that begins with a wildcard never matches a topic name beginning with $ (4.7.2). Brokers publish their own statistics under $SYS/, so a client that wants everything must ask for $SYS/# separately.

Frame 8 carries both requests: two separate SUBSCRIBE packets in one TCP segment, each with its own Packet ID. Each SUBSCRIBE starts with the byte 0x82: packet type 8 plus flag bits 0010, which section 3.8.1 requires.

The broker answers each one in its own SUBACK, matched by Packet ID:

Packet IDFilterSUBACK return code
52247#0x80, Failure (frame 10)
52248$SYS/#0x00, granted QoS 0 (frame 12)

0x80 means the broker refused the subscription (3.9.3). MQTT 3.1.1 has no field to say why. The WebSocket capture, about six minutes later, gets the same refusal, so this broker's configuration did not allow a catch-all subscription. The $SYS/# subscription succeeds, and everything that follows comes from it.

What is a retained message?

A message the broker keeps for a topic, so a new subscriber gets the last value at once. Within a millisecond of the SUBACK, frames 13 to 31 deliver 53 retained $SYS statistics: the broker's version (mosquitto version 2.0-dev0), its uptime, its client counts, and its message rates. The broker had about 2,000 clients connected at that moment.

Every one of these PUBLISH packets has its RETAIN flag set. Section 3.3.1.3 sets the flag to 1 when the broker sends a message because of a new subscription, and to 0 when it forwards a message to an existing subscription. So the flag tells the subscriber whether it is seeing a stored value or a live one. Frame 33, 3.2 seconds later, shows the difference: a fresh uptime with RETAIN 0.

Frame 33 also shows what "last value" means. The retained uptime in frame 18 read 272,701 seconds; the live one reads 272,712, eleven seconds more, although only three seconds have passed. The retained copy was the last uptime the broker published, eight seconds before the client subscribed. A retained message is the last value stored, not a current reading.

Why do several PUBLISH packets share one TCP segment?

Because TCP carries a stream of bytes, not messages. The broker writes PUBLISH packets as fast as it can, and TCP packs them into segments as they fit. Frame 30 is one 1,448-byte segment holding 30 complete PUBLISH packets. Frame 17 holds two. A receiver finds the packet boundaries from each fixed header's remaining length, never from the segments.

This matters in Wireshark: the frame count understates the message count. The diagram draws one arrow per MQTT packet, so frame 30 appears as 30 arrows.

What happens to a message published to a $SYS topic?

Nothing visible: the broker does not deliver it. In frames 45, 49, and 67 the client publishes three test messages to $SYS/broker/messages, one JSON, one XML, and one plain text. The client is subscribed to $SYS/#, so it would receive its own messages if the broker forwarded them, and none come back. Section 4.7.2 reserves $ topics for the broker's own use.

The three payloads also show that MQTT does not care what a payload contains. MQTT 3.1.1 has no content-type field (MQTT 5 adds one); the publisher and subscribers must agree on the format themselves. All three are QoS 0, so they carry no Packet ID and get no acknowledgment.

How does an MQTT client disconnect?

It sends DISCONNECT and closes the TCP connection. Frame 69 is the two-byte packet 0xE0 0x00. A DISCONNECT tells the broker to discard the client's Will message, so a clean exit never triggers it (3.14.4). After sending DISCONNECT, the client must close the network connection, and its FIN follows 0.2 ms later.

The session never needed a keepalive: it lasted 20 seconds, well inside the 60-second Keep Alive, so no PINGREQ appears.

Capture 2: MQTT over WebSocket

A web page cannot open a raw TCP connection, but it can open a WebSocket: a two-way byte channel that starts life as an HTTP request. MQTT over WebSocket is how browser dashboards and web apps talk to a broker. The MQTT inside is unchanged; the broker listens on a web port, here 8080.

sequenceDiagram accTitle: MQTT over WebSocket session with test.mosquitto.org accDescr: After the TCP handshake, the client sends an HTTP GET for slash ws with Upgrade websocket and the mqtt subprotocol. The broker answers 101 Switching Protocols. The client sends the first byte of CONNECT in one masked WebSocket frame and the rest in the next. The broker accepts with CONNACK in an unmasked frame. Subscriptions and retained messages follow as in capture 1. To finish, the client sends DISCONNECT in two 1-byte frames, then a WebSocket Close frame, and the broker echoes the Close. participant C as Client participant B as Broker C->>B: [4] HTTP GET /ws, Upgrade websocket, subprotocol mqtt B->>C: [6] HTTP 101 Switching Protocols C->>B: [8] [9] CONNECT, split over two masked frames B->>C: [12] CONNACK, unmasked frame C->>B: [105] [106] DISCONNECT, split again C->>B: [107] WebSocket Close B->>C: [111] WebSocket Close
Capture 2 at a glance. The MQTT exchange matches capture 1. Frame numbers are in brackets.

How does the WebSocket upgrade work?

The client sends an ordinary HTTP/1.1 GET and asks the server to switch protocols (RFC 6455 section 4.1). Frame 4 carries the request headers:

The broker answers in frame 6 with 101 Switching Protocols (section 4.2.2). Its Sec-WebSocket-Accept is the base64 SHA-1 hash of the client's key joined to a fixed GUID; that value proves the server understood the WebSocket request. It selects mqtt and returns no extensions header, so compression is off and the MQTT bytes stay readable. From frame 7 on, the TCP stream carries WebSocket frames instead of HTTP.

The upgrade costs one extra round trip. CONNACK arrives 304 ms after the first SYN, against 184 ms over plain TCP.

Why does the client mask its WebSocket frames?

Because RFC 6455 says it must: a client masks every frame it sends, and a server never masks (section 5.1). The client picks a random 4-byte key for each frame and XORs the payload with it. The point is not secrecy, since the key travels in the frame. Masking stops a malicious page from making the browser send bytes that a proxy in the path would misread as an HTTP request and cache (section 10.3).

Masking makes the two directions different sizes. Each client frame here has a 6-byte header: 2 bytes of framing plus the 4-byte key. Each broker frame has 2. Wireshark removes the mask, so you read the real payload either way.

Why is the CONNECT split across two WebSocket frames?

Because the client wrote it in two pieces, and nothing requires MQTT packets to line up with WebSocket frames. Frame 8 is a WebSocket frame holding a single byte, 0x10, the CONNECT fixed header. Frame 9 holds the other 35 bytes. The client, the mqtt.js library inside MQTT Explorer, sends each packet's first byte as its own write, and each write becomes its own WebSocket frame. Its SUBSCRIBE, PUBLISH, and DISCONNECT packets split the same way.

MQTT 3.1.1 section 6 allows this explicitly: a single WebSocket frame can contain multiple or partial MQTT packets, and a receiver must not assume they are aligned. The broker goes the other way and sends each PUBLISH in a frame of its own. Frame 15 shows both cases at once: the end of one SUBSCRIBE and the whole next one, in one frame.

How do you decode MQTT over WebSocket in Wireshark?

Out of the box, you can't: Wireshark 4.6 shows these frames as WebSocket Binary with an opaque payload, and an mqtt display filter finds nothing. WebSocket hands its payload to another dissector only for subprotocols it has registered, and MQTT is not one of them. The WebSocket dissector tables don't support Decode As either, so no -d option helps.

A short Lua script fixes both problems. It registers the MQTT dissector for the mqtt subprotocol, and it joins MQTT packets that span WebSocket frames, like the split CONNECT above:

-- mqtt_over_ws.lua: decode MQTT carried in WebSocket frames (Wireshark 4.x).
local mqtt = Dissector.get("mqtt")
local tcp_stream = Field.new("tcp.stream")

local proto = Proto("mqttws", "MQTT over WebSocket")
local f_fragment = ProtoField.uint32("mqttws.fragment_len", "MQTT fragment length")
proto.fields = { f_fragment }

local pending = {}      -- unparsed bytes per TCP stream and direction
local per_payload = {}  -- complete MQTT packets found in each WebSocket payload

-- Length of the MQTT packet at the start of buf, or nil if not known yet.
local function packet_len(buf)
    local value, mult, i = 0, 1, 1
    while true do
        if i >= buf:len() then return nil end
        local b = buf:get_index(i)
        value = value + (b % 128) * mult
        mult = mult * 128
        i = i + 1
        if b < 128 then break end
        if i > 4 then return nil end
    end
    return i + value
end

function proto.dissector(tvb, pinfo, tree)
    local id = pinfo.number .. ":" .. tvb:offset() .. ":" .. tvb:bytes():tohex()
    if not pinfo.visited then
        local key = tostring(tcp_stream().value) .. ":" .. tostring(pinfo.src) .. ":" .. tostring(pinfo.src_port)
        local buf = pending[key] or ByteArray.new()
        buf:append(tvb:bytes())
        local out = {}
        while buf:len() >= 2 do
            local total = packet_len(buf)
            if total == nil or total > buf:len() then break end
            out[#out + 1] = buf:subset(0, total)
            if total == buf:len() then
                buf = ByteArray.new()
            else
                buf = buf:subset(total, buf:len() - total)
            end
        end
        pending[key] = buf
        per_payload[id] = out
    end

    local out = per_payload[id] or {}
    if #out == 0 then
        local sub = tree:add(proto, tvb(), "MQTT fragment, completed in a later WebSocket frame")
        sub:add(f_fragment, tvb:len())
        pinfo.cols.info:append(" [MQTT fragment]")
        return tvb:len()
    end
    for _, ba in ipairs(out) do
        mqtt:call(ba:tvb("Reassembled MQTT"), pinfo, tree)
    end
    return tvb:len()
end

DissectorTable.get("ws.protocol"):add("mqtt", proto)

Run it with tshark as tshark -2 -X lua_script:mqtt_over_ws.lua -r capture.pcapng -Y mqtt; the -2 gives the script a first pass to join the pieces. In Wireshark, copy the file into the Personal Lua Plugins folder shown under Help → About Wireshark → Folders and restart. The script only works when the capture includes the HTTP Upgrade, because that is where Wireshark learns the subprotocol.

How does a WebSocket connection close?

In two layers, after MQTT finishes. The client sends its DISCONNECT, split into two 1-byte frames (105 and 106). Then, in frame 107, it closes the WebSocket with a Close frame (opcode 8) whose body is empty, so it carries no status code. The broker echoes a Close of its own in frame 111, as RFC 6455 requires, and only then does TCP close. Over plain TCP, the WebSocket layer and its two Close frames don't exist.

Capture 3: MQTT over TLS, without the keys

Port 8883 is MQTT inside TLS, the same encryption HTTPS uses. The client and broker negotiate TLS 1.3 with the cipher suite TLS_AES_256_GCM_SHA384. No key log was recorded, so this capture shows exactly what anyone on the path would see: someone on the same wireless network, an ISP, or a corporate firewall. The diagram's labels are therefore TLS records, not MQTT packets, and every statement here about what is inside a record is an inference from its size and timing.

sequenceDiagram accTitle: MQTT over TLS 1.3 with test.mosquitto.org, as an observer sees it accDescr: The client sends a readable ClientHello naming test.mosquitto.org. The broker answers with a readable ServerHello choosing TLS 1.3, then encrypted records the size of a certificate, a CertificateVerify, and a Finished. The client sends its Finished and, in the same segment, nine tiny records that add up to the size of the CONNECT. A 4-byte record follows from the broker, the size of a CONNACK. Then come twelve tiny records the size of the two SUBSCRIBE packets and one record per retained PUBLISH. At the end come two 1-byte records the size of DISCONNECT, an alert-sized record, and a TCP reset from the broker. participant C as Client participant B as Broker C->>B: [4] ClientHello, SNI test.mosquitto.org B->>C: [6] ServerHello, TLS 1.3, AES-256-GCM B->>C: [7] encrypted "Certificate", "CertificateVerify", "Finished" C->>B: [9] "Finished" and 9 records, "CONNECT" B->>C: [14] 4-byte record, "CONNACK" B->>C: [23] [24] one record per "PUBLISH" C->>B: [70] [71] "DISCONNECT", "close_notify"
Capture 3 at a glance. Labels in quotes are inferred from record sizes. Frame numbers are in brackets.

What can you still see in an encrypted MQTT session?

More than you might expect. The ClientHello in frame 4 travels in the clear:

🤝 [00003] Frame 4 TLS Client Hello 2020-11-29T15:09:53.598187Z 💻 Client → 🖥 MQTT Broker
frame : Frame 4: Packet, 323 bytes on wire (2584 bits), 323 bytes captured (2584 bits) on interface en0, id 0
Section number : 1
Interface id : 0 (en0)
Interface name : en0
Interface description : Wi-Fi
Encapsulation type : Ethernet (1)
Arrival Time : Nov 29, 2020 20:39:53.598187000 India Standard Time
UTC Arrival Time : Nov 29, 2020 15:09:53.598187000 UTC
Epoch Arrival Time : 1606662593.598187000
Time shift for this packet : 0.000000000 seconds
Time delta from previous captured frame : 214.000 microseconds
Time delta from previous displayed frame : 214.000 microseconds
Time since reference or first frame : 93.962000 milliseconds
Frame Number : 4
Frame Length : 323 bytes (2584 bits)
Capture Length : 323 bytes (2584 bits)
Frame is marked : False
Frame is ignored : False
Protocols in frame : eth:ethertype:ip:tcp:tls
Character encoding : ASCII (0)
eth : Ethernet II, Src: c8:e0:eb:13:de:6d, Dst: 48:5d:36:c9:c9:6b
Destination : 48:5d:36:c9:c9:6b
Destination (resolved) : 48:5d:36:c9:c9:6b
Destination OUI : 48:5d:36 (Verizon)
Destination OUI (resolved) : Verizon
.... ..0. .... .... .... .... = LG bit : Globally unique address (factory default)
.... ...0 .... .... .... .... = IG bit : Individual address (unicast)
Address : 48:5d:36:c9:c9:6b
Address (resolved) : 48:5d:36:c9:c9:6b
Address OUI : 48:5d:36 (Verizon)
Address OUI (resolved) : Verizon
.... ..0. .... .... .... .... = LG bit : Globally unique address (factory default)
.... ...0 .... .... .... .... = IG bit : Individual address (unicast)
Source : c8:e0:eb:13:de:6d
Source (resolved) : c8:e0:eb:13:de:6d
Source OUI : c8:e0:eb (Apple, Inc.)
Source OUI (resolved) : Apple, Inc.
.... ..0. .... .... .... .... = LG bit : Globally unique address (factory default)
.... ...0 .... .... .... .... = IG bit : Individual address (unicast)
Address : c8:e0:eb:13:de:6d
Address (resolved) : c8:e0:eb:13:de:6d
Address OUI : c8:e0:eb (Apple, Inc.)
Address OUI (resolved) : Apple, Inc.
.... ..0. .... .... .... .... = LG bit : Globally unique address (factory default)
.... ...0 .... .... .... .... = IG bit : Individual address (unicast)
Type : IPv4 (0x0800)
Stream index : 0
ip : Internet Protocol Version 4, Src: 192.168.1.151, Dst: 5.196.95.208
0100 .... = Version : 4
.... 0101 = Header Length : 20 bytes (5)
Differentiated Services Field : 0x00 (DSCP: CS0, ECN: Not-ECT)
0000 00.. = Differentiated Services Codepoint : Default (0)
.... ..00 = Explicit Congestion Notification : Not ECN-Capable Transport (0)
Total Length : 309
Identification : 0x0000 (0)
010. .... = Flags : 0x2, Don't fragment
0... .... = Reserved bit : Not set
.1.. .... = Don't fragment : Set
..0. .... = More fragments : Not set
...0 0000 0000 0000 = Fragment Offset : 0
Time to Live : 64
Protocol : TCP (6)
Header Checksum : 0x11f0 [validation disabled]
Header checksum status : Unverified
Source Address : 192.168.1.151
Source or Destination Address : 192.168.1.151
Source Host : 192.168.1.151
Source or Destination Host : 192.168.1.151
Destination Address : 5.196.95.208
Source or Destination Address : 5.196.95.208
Destination Host : 5.196.95.208
Source or Destination Host : 5.196.95.208
Stream index : 0
tcp : Transmission Control Protocol, Src Port: 50858, Dst Port: 8883, Seq: 1, Ack: 1, Len: 257
Source Port : 50858
Destination Port : 8883
Source or Destination Port : 50858
Source or Destination Port : 8883
Stream index : 0
Stream Packet Number : 4
Conversation completeness : Complete, WITH_DATA (63)
..1. .... = RST : Present
...1 .... = FIN : Present
.... 1... = Data : Present
.... .1.. = ACK : Present
.... ..1. = SYN-ACK : Present
.... ...1 = SYN : Present
Completeness Flags : RFDASS
TCP Segment Len : 257
Sequence Number : 1 (relative sequence number)
Sequence Number (raw) : 2692372749
Next Sequence Number : 258 (relative sequence number)
Acknowledgment Number : 1 (relative ack number)
Acknowledgment number (raw) : 4079259506
1000 .... = Header Length : 32 bytes (8)
Flags : 0x018 (PSH, ACK)
000. .... .... = Reserved : Not set
...0 .... .... = Accurate ECN : Not set
.... 0... .... = Congestion Window Reduced : Not set
.... .0.. .... = ECN-Echo : Not set
.... ..0. .... = Urgent : Not set
.... ...1 .... = Acknowledgment : Set
.... .... 1... = Push : Set
.... .... .0.. = Reset : Not set
.... .... ..0. = Syn : Not set
.... .... ...0 = Fin : Not set
TCP Flags : ·······AP···
Window : 2058
Calculated window size : 131712
Window size scaling factor : 64
Checksum : 0x01b0 [unverified]
Checksum Status : Unverified
Urgent Pointer : 0
Options : (12 bytes), No-Operation (NOP), No-Operation (NOP), Timestamps
TCP Option - No-Operation (NOP)
Kind : No-Operation (1)
TCP Option - No-Operation (NOP)
Kind : No-Operation (1)
TCP Option - Timestamps : TSval 71324757, TSecr 260373808
Kind : Time Stamp Option (8)
Length : 10
Timestamp value : 71324757
Timestamp echo reply : 260373808
Timestamps
Time since first frame in this TCP stream : 93.962000 milliseconds
Time since previous frame in this TCP stream : 214.000 microseconds
SEQ/ACK analysis
iRTT : 93.748000 milliseconds
Bytes in flight : 257
Bytes sent since last PSH flag : 257
Client Contiguous Streams : 1
Server Contiguous Streams : 1
TCP payload (257 bytes)
tls : Transport Layer Security
Stream index : 0
TLSv1.3 Record Layer : Handshake Protocol: Client Hello
Content Type : Handshake (22)
Version : TLS 1.0 (0x0301)
Length : 252
Handshake Protocol : Client Hello
Handshake Type : Client Hello (1)
Length : 248
Version : TLS 1.2 (0x0303)
Expert Info (Chat/Deprecated) : This legacy_version field MUST be ignored. The supported_versions extension is present and MUST be used instead.
This legacy_version field MUST be ignored. The supported_versions extension is present and MUST be used instead.
Message : This legacy_version field MUST be ignored. The supported_versions extension is present and MUST be used instead.
Severity level : Chat
Group : Deprecated
Random : 56e2cb328edf4bcdad0dd8f201116675246d573be1a0225fdeefd490297f7163
Session ID Length : 32
Session ID : ac67f273ab8a2dcbe1994521132255da55daaa2ebb96fdbd4c22a33b807471bb
Cipher Suites Length : 36
Cipher Suites (18 suites)
Cipher Suite : TLS_AES_128_GCM_SHA256 (0x1301)
Cipher Suite : TLS_AES_256_GCM_SHA384 (0x1302)
Cipher Suite : TLS_CHACHA20_POLY1305_SHA256 (0x1303)
Cipher Suite : TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xc02f)
Cipher Suite : TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 (0xc02b)
Cipher Suite : TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (0xc030)
Cipher Suite : TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 (0xc02c)
Cipher Suite : TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 (0xcca9)
Cipher Suite : TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (0xcca8)
Cipher Suite : TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA (0xc009)
Cipher Suite : TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (0xc013)
Cipher Suite : TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (0xc00a)
Cipher Suite : TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (0xc014)
Cipher Suite : TLS_RSA_WITH_AES_128_GCM_SHA256 (0x009c)
Cipher Suite : TLS_RSA_WITH_AES_256_GCM_SHA384 (0x009d)
Cipher Suite : TLS_RSA_WITH_AES_128_CBC_SHA (0x002f)
Cipher Suite : TLS_RSA_WITH_AES_256_CBC_SHA (0x0035)
Cipher Suite : TLS_RSA_WITH_3DES_EDE_CBC_SHA (0x000a)
Compression Methods Length : 1
Compression Methods (1 method)
Compression Method : null (0)
Extensions Length : 139
Extension : server_name (len=23) name=test.mosquitto.org
Type : server_name (0)
Length : 23
Server Name Indication extension
Server Name list length : 21
Server Name Type : host_name (0)
Server Name length : 18
Server Name : test.mosquitto.org
Extension : extended_master_secret (len=0)
Type : extended_master_secret (23)
Length : 0
Extension : renegotiation_info (len=1)
Type : renegotiation_info (65281)
Length : 1
Renegotiation Info extension
Renegotiation info extension length : 0
Extension : supported_groups (len=8)
Type : supported_groups (10)
Length : 8
Supported Groups List Length : 6
Supported Groups (3 groups)
Supported Group : x25519 (0x001d)
Supported Group : secp256r1 (0x0017)
Supported Group : secp384r1 (0x0018)
Extension : ec_point_formats (len=2)
Type : ec_point_formats (11)
Length : 2
EC point formats Length : 1
Elliptic curves point formats (1)
EC point format : uncompressed (0)
Extension : session_ticket (len=0)
Type : session_ticket (35)
Length : 0
Session Ticket : <MISSING>
Extension : signature_algorithms (len=20)
Type : signature_algorithms (13)
Length : 20
Signature Hash Algorithms Length : 18
Signature Hash Algorithms (9 algorithms)
Signature Algorithm : ecdsa_secp256r1_sha256 (0x0403)
Signature Hash Algorithm Hash : SHA256 (4)
Signature Hash Algorithm Signature : ECDSA (3)
Signature Algorithm : rsa_pss_rsae_sha256 (0x0804)
Signature Hash Algorithm Hash : Unknown (8)
Signature Hash Algorithm Signature : Unknown (4)
Signature Algorithm : rsa_pkcs1_sha256 (0x0401)
Signature Hash Algorithm Hash : SHA256 (4)
Signature Hash Algorithm Signature : RSA (1)
Signature Algorithm : ecdsa_secp384r1_sha384 (0x0503)
Signature Hash Algorithm Hash : SHA384 (5)
Signature Hash Algorithm Signature : ECDSA (3)
Signature Algorithm : rsa_pss_rsae_sha384 (0x0805)
Signature Hash Algorithm Hash : Unknown (8)
Signature Hash Algorithm Signature : Unknown (5)
Signature Algorithm : rsa_pkcs1_sha384 (0x0501)
Signature Hash Algorithm Hash : SHA384 (5)
Signature Hash Algorithm Signature : RSA (1)
Signature Algorithm : rsa_pss_rsae_sha512 (0x0806)
Signature Hash Algorithm Hash : Unknown (8)
Signature Hash Algorithm Signature : Unknown (6)
Signature Algorithm : rsa_pkcs1_sha512 (0x0601)
Signature Hash Algorithm Hash : SHA512 (6)
Signature Hash Algorithm Signature : RSA (1)
Signature Algorithm : rsa_pkcs1_sha1 (0x0201)
Signature Hash Algorithm Hash : SHA1 (2)
Signature Hash Algorithm Signature : RSA (1)
Extension : key_share (len=38) x25519
Type : key_share (51)
Length : 38
Key Share extension
Client Key Share Length : 36
Key Share Entry : Group: x25519, Key Exchange length: 32
Group : x25519 (29)
Key Exchange Length : 32
Key Exchange : 645a4acb504d8d0cfc7b23380f1da9c6392a6fc1750b0aedc5035070d99fc853
Extension : psk_key_exchange_modes (len=2)
Type : psk_key_exchange_modes (45)
Length : 2
PSK Key Exchange Modes Length : 1
PSK Key Exchange Mode : PSK with (EC)DHE key establishment (psk_dhe_ke) (1)
Extension : supported_versions (len=5) TLS 1.3, TLS 1.2
Type : supported_versions (43)
Length : 5
Supported Versions length : 4
Supported Version : TLS 1.3 (0x0304)
Supported Version : TLS 1.2 (0x0303)
JA4 : t13d181000_e8a523a41297_78e6aca7449b
JA4_r : t13d181000_000a,002f,0035,009c,009d,1301,1302,1303,c009,c00a,c013,c014,c02b,c02c,c02f,c030,cca8,cca9_000a,000b,000d,0017,0023,002b,002d,0033,ff01_0403,0804,0401,0503,0805,0501,0806,0601,0201
JA3 Fullstring : 771,4865-4866-4867-49199-49195-49200-49196-52393-52392-49161-49171-49162-49172-156-157-47-53-10,0-23-65281-10-11-35-13-51-45-43,29-23-24,0
JA3 : dda262729e5413660ec0e6a8d4279860
Rendered from a Wireshark PCAP by VisualEther.

Frame 4, the TLS ClientHello. Under the Handshake Protocol: the 18 offered cipher suites and the extensions, including server_name test.mosquitto.org, supported_versions TLS 1.3 and 1.2, and a key_share for x25519. There is no ALPN extension.

From this one packet and the timing that follows, an observer learns:

What the observer cannot see: the broker's certificate, any topic, any payload, the client ID, or any MQTT return code. In TLS 1.3, every handshake message after the ServerHello is encrypted (RFC 8446 section 2), including the Certificate. In TLS 1.2 the certificate would travel in the clear. Wireshark labels every encrypted record Application Data, because the outer content type is always 23; the real type is hidden inside the encryption (section 5.2).

How do record sizes give away MQTT packets?

With AES-GCM, every TLS 1.3 record is exactly 17 bytes longer than its content: 1 byte for the hidden content type and a 16-byte authentication tag (section 5.2). Subtract 17, and you have the size of what is inside.

This client makes the arithmetic easy. It writes each field of each MQTT packet as a separate TLS record. Frame 9 carries the client's Finished and then nine tiny records. Compare their contents, by size, with the CONNECT from capture 1:

Record lengthContent (length - 17)CONNECT field of the same size
181 byteFixed header, 0x10
181 byteRemaining length, 34
192 bytesProtocol-name length
214 bytesMQTT
181 byteProtocol level, 4
181 byteConnect flags
192 bytesKeep Alive
192 bytesClient-ID length
3922 bytesClient ID: mqtt-explorer-5bd1fce3 is 22 characters

The nine records hold 36 bytes, exactly the size of the plain CONNECT. The rest of the session reads the same way:

So TLS hid every value, but leaked the shape: how many messages, how big, and when. For a smart-home device that publishes "door open" and "door closed" as different-size payloads, size alone could tell an observer which one it sent. TLS 1.3 lets a sender pad records to hide their size (section 5.4), and a client that writes each packet as a single record leaks less, but neither happened here.

The TLS handshake costs the same one extra round trip as the WebSocket upgrade, and the client saves another by sending its CONNECT in the same segment as its Finished, without waiting for the broker. CONNACK arrives 348 ms after the first SYN.

What about MQTT over TLS and WebSocket together?

The fourth capture, mqtt_tls_ws.pcapng, runs WebSocket inside TLS on port 8081, the setup a browser uses for a wss:// broker URL. It is not drawn as a separate diagram because it looks like capture 3 from outside. Its record sizes match capture 2 instead: the first client records hold 264 bytes (the HTTP GET in capture 2 is 264 bytes), 159 bytes back (the 101 response), then 7 and 41 bytes (the split CONNECT, with its 6-byte WebSocket headers). Here each WebSocket frame travels as one TLS record. It is the slowest of the four to connect, at four round trips and 395 ms to CONNACK.

How can you decrypt your own MQTT over TLS?

Give Wireshark the session keys. Most TLS libraries can write them to a key log file: browsers do when the SSLKEYLOGFILE environment variable is set, and Node.js does with its --tls-keylog option. Load the file under Wireshark's TLS protocol preferences, "(Pre)-Master-Secret log filename", and the records decode to MQTT, as in our decrypted QUIC and HTTP/3 walkthrough. Without the keys, capture 3 is what you get.

Capture 4: CoAP over UDP

CoAP, the Constrained Application Protocol, brings the web's request-and-response model to devices too small for HTTP. A client sends GET, POST, PUT, or DELETE to a URI, and the server answers with a response code, much like HTTP. But CoAP runs over UDP, with a 4-byte binary header and no connection, on port 5683 (RFC 7252 section 6.1). In this capture, a client walks through the resources of a public CoAP test server at 52.45.123.182.

How is CoAP different from MQTT?

MQTTCoAP
ModelPublish and subscribe through a brokerRequest and response, client to server
TransportTCP (also inside WebSocket or TLS)UDP (DTLS for security)
Default ports1883, and 8883 with TLS5683, and 5684 with DTLS
ConnectionA long-lived session, opened with CONNECTNone: the first packet is the request
ReliabilityTCP, plus QoS 0, 1, or 2Confirmable messages retransmitted until acknowledged
Smallest header2 bytes4 bytes
Updates pushed to clientsBuilt in, through subscriptionsWith the Observe option (RFC 7641)

MQTT suits many devices reporting to one hub or cloud service. CoAP suits devices that sleep most of the time, run on very constrained networks, or are easier to model as resources with URIs.

How does CoAP make UDP reliable?

With message types and Message IDs (section 4). A Confirmable (CON) message must be acknowledged; the sender retransmits it, waiting 2 to 3 seconds at first and doubling each time, up to 4 times (section 4.8). A Non-confirmable (NON) message is sent once. Every request in this capture is Confirmable.

Two numbers keep the exchanges straight:

Most of the time these two pairings coincide, because the response rides inside the ACK.

What is a CoAP piggybacked response?

A response carried in the ACK itself, the fast path (section 5.2.1). In frame 1 the client sends GET /advanced as a Confirmable message with Message ID 1697 and Token 7153. Frame 2, 18 ms later, is an ACK with the same Message ID and Token and code 2.05 Content, carrying the 17-byte body. One message acknowledges the request and answers it.

CoAP writes response codes as class.detail: 2.05 Content is the equivalent of HTTP's 200 OK, and 4.04 Not Found is HTTP's 404. Most requests in the capture get piggybacked responses, in 10 to 45 ms.

What is a CoAP separate response?

A response sent later, as a new message, when the server cannot answer at once (section 5.2.2). The server first sends an empty ACK, which stops the client's retransmissions, and sends the real response when it is ready. The resource /advancedSeparate is built to show it:

sequenceDiagram accTitle: CoAP separate response for GET advancedSeparate accDescr: The client sends a Confirmable GET with Message ID 4727 and Token 6562. The server answers 12.5 milliseconds later with an empty ACK for Message ID 4727. About 5 seconds later the server sends the response as a new Confirmable message with its own Message ID 103 and the same Token 6562. The client acknowledges Message ID 103. participant C as Client participant S as CoAP Server C->>S: [3] CON GET /advancedSeparate, MID 4727, Token 6562 S->>C: [4] ACK, empty, MID 4727 Note over S: about 5 s later S->>C: [5] CON 2.05 Content, MID 103, Token 6562 C->>S: [6] ACK, MID 103
A CoAP separate response, frames 3 to 6. The empty ACK matches the request by Message ID. The response matches it by Token.

The empty ACK in frame 4 echoes the request's Message ID, 4727, but has no Token: an empty message (code 0.00) must not carry one (section 4.1). The response in frame 5 is a new Confirmable exchange started by the server, with the server's own Message ID, 103, so only the Token, 6562, ties it to the request. Because it is Confirmable, the client acknowledges it in frame 6.

The capture has three separate responses. The server's Message IDs count up, 103, 104, and 105:

RequestEmpty ACK afterResponse afterServer Message ID
/advancedSeparate (frame 3)12.5 ms5.1 s103
/long (frame 19)2.1 s10.1 s104
/separate (frame 23)16 ms5.1 s105

For /long, the server took 2.1 seconds to send even the empty ACK. The client's first retransmission timer runs for 2 to 3 seconds, and no retransmission appears, so the ACK arrived in time.

The client's own ACKs (frames 6, 22, and 26) have a quirk: each one is an empty message that still echoes the Token. Section 4.1 says an empty message must have a Token length of 0 and treats anything more as a message format error. A server that rejected these ACKs would ignore them and retransmit its response (section 4.2). This server accepted them, and no retransmission followed.

How does CoAP send a large resource?

In blocks, using the Block2 option (RFC 7959). In frame 10, the response to GET /big carries Block2 with block number 0, the More flag set, and a block size of 1,024 bytes. The client asks for block 1 in frame 11, with a new Message ID but the same Token. Frame 12 delivers it with More clear, and Wireshark joins the two into 2,041 bytes. Each block is its own Confirmable exchange, so a lost block costs one retransmission, not the whole transfer.

What do CoAP POST and DELETE look like?

The sixth capture, coap_post_delete.pcapng, works on the server's /storage resource. It is short enough to read as a table:

FrameRequestResponse
1, 2GET /storage2.05 Content: Storage Resource for PUT, POST and DELETE
3, 4POST /storage, an 80-byte XML document2.01 Created, with a Location-Path option, storage
5, 6GET /storage2.05 Content: the 80-byte XML document
7, 8DELETE /storage2.02 Deleted
9, 10GET /storage4.04 Not Found
11, 12POST /storage again4.05 Method Not Allowed

Every response is piggybacked. The DELETE in frame 7 is the one request that carries no Token, which CoAP allows (section 5.3.1). After the DELETE, the resource is gone, and this server refuses a second POST to it.

Frequently asked questions

What port does MQTT use? 1883 for unencrypted MQTT and 8883 for MQTT over TLS, both registered with IANA. MQTT over WebSocket has no fixed port; it usually shares a web server's ports 80 and 443.

Is MQTT encrypted? Not by itself. Over port 1883, everything travels in the clear, as capture 1 shows, including any username and password in the CONNECT. Use TLS on port 8883, or WebSocket over TLS.

Why can't I see MQTT in Wireshark? Either the traffic is encrypted, so it shows as TLS Application Data, or it is inside WebSocket, which Wireshark doesn't decode as MQTT by default. For WebSocket, use the Lua script in capture 2; for TLS, you need the session keys.

What does a SUBACK return code of 0x80 mean? The broker refused that subscription. MQTT 3.1.1 gives no reason; MQTT 5 adds reason codes. In capture 1, test.mosquitto.org refuses # and accepts $SYS/#.

What is the RETAIN flag? When a client publishes with RETAIN set, the broker stores the message as the topic's last value. When the broker delivers a stored message to a new subscriber, it sets RETAIN to 1; when it forwards a live message, RETAIN is 0.

Does # match $SYS topics? No. A filter that starts with a wildcard never matches topic names that start with $. Subscribe to $SYS/# explicitly.

MQTT or CoAP? MQTT when many devices report to a central broker over TCP. CoAP when devices are very constrained or sleep most of the time, or when a resource-and-URI model fits better, over UDP.

Takeaways

  1. MQTT is small on the wire. A DISCONNECT is 2 bytes, a CONNECT 36, and one TCP segment can carry 30 PUBLISH packets.
  2. # doesn't cover $SYS. Clients that want broker statistics must subscribe to $SYS/# too, and a broker can refuse any subscription with 0x80.
  3. RETAIN tells stored from live. The broker sets it on messages sent because of a new subscription and clears it on normal forwarding, and a retained value can be stale.
  4. Each transport costs about one round trip. CONNACK came after 2 round trips over TCP, 3 over WebSocket or TLS, and 4 over both.
  5. MQTT packets need not line up with anything. Not with TCP segments, not with WebSocket frames, not with TLS records.
  6. TLS hides values, not shape. Without keys, the server name, record sizes, and timing still outline the whole session.
  7. CoAP gets reliability from Confirmable messages. The Message ID pairs a message with its ACK, and the Token pairs a response with its request, which is what makes separate responses work.