MQTT, the protocol for small messages over bad links

Networking

MQTT is a messaging protocol built for one situation: many small devices sending small messages over links that are slow, expensive or keep dropping. A temperature sensor, a car, a phone, a smart meter. It runs over TCP, usually with TLS on top, and its whole design follows from that situation: a 2-byte minimum packet, one long-lived connection per device, and a server that remembers what a device missed while it was offline.

The name once stood for MQ Telemetry Transport; today it is just a name. Version 3.1.1 (2014) is still everywhere; version 5 (2019) is the current standard and is what this article describes, with the differences called out. The standard ports are 1883 for plain TCP and 8883 for TLS.

One broker between everybody

MQTT does not connect a sender to a receiver. Every client opens one connection, to a broker, and the broker does the routing. A device that has something to say publishes a message to a topic, a string like greenhouse/temp. A client that wants messages subscribes with a topic filter. The broker copies each message to every client whose filter matches.

A greenhouse thermometer and a greenhouse door sensor each connect only to a broker; a phone app and a logger also connect only to the broker. The thermometer sends the reading 21.5 labelled greenhouse/temp, the door sensor sends open labelled greenhouse/door. The broker keeps a list of who asked for which labels: the phone asked for greenhouse/temp and gets a copy of 21.5; the logger asked for greenhouse/# and gets a copy of both. The thermometer never learns the phone exists. One middleman between every sender and receiver devices send labelled readings · apps ask for labels · the broker copies Greenhouse thermometer sender · publisher label: greenhouse/temp Greenhouse door sensor sender · publisher label: greenhouse/door Broker the post office keeps the list of who asked for what Phone app receiver · subscriber asked for: greenhouse/temp Logger receiver · subscriber asked for: greenhouse/# 21.5PUBLISH openPUBLISH a copy of 21.5 a copy of both 1 2 3 The thermometer never learns the phone exists: each of them only ever talks to the broker.
Publish/subscribe: a device labels each message with a topic, an app asks for topics, and the broker in the middle copies each message to everyone whose request matches. No device ever talks to an app directly.
A greenhouse thermometer and a greenhouse door sensor each connect only to a broker; a phone app and a logger also connect only to the broker. The thermometer sends the reading 21.5 labelled greenhouse/temp, the door sensor sends open labelled greenhouse/door. The broker keeps a list of who asked for which labels: the phone asked for greenhouse/temp and gets a copy of 21.5; the logger asked for greenhouse/# and gets a copy of both. The thermometer never learns the phone exists. One middleman in the middle devices send labels · apps ask for labels Thermometer sender · publisher greenhouse/temp Door sensor sender · publisher greenhouse/door 21.5PUBLISH openPUBLISH Broker the post office keeps the list of who asked for what a copy of 21.5 both Phone app receiver · subscriber asked: greenhouse/temp Logger receiver · subscriber asked: greenhouse/# 1 2 3 The thermometer never learns the phone exists: each only ever talks to the broker.
Publish/subscribe: a device labels each message with a topic, an app asks for topics, and the broker in the middle copies each message to everyone whose request matches. No device ever talks to an app directly.

Two things follow from this shape:

Topics and wildcards

A topic is a UTF-8 string split into levels by /. Topics are not declared anywhere: publishing to home/garage/temp creates it, as far as anyone can tell. Filters may use two wildcards: + matches exactly one level, and #, allowed only at the end, matches any number of levels, including none.

FilterMatches, and does not match
home/hall/temponly that topic; not home/hall
home/+/temphome/hall/temp; not home/a/b/temp
home/#home, home/a/b; not office/temp
#every topic except those starting with $
A grid of four published topics against three subscription filters. greenhouse/temp alone matches only greenhouse/temp. +/temp matches greenhouse/temp and garage/temp, because + stands in for exactly one word between slashes, but not greenhouse/bed1/soil. greenhouse/# matches greenhouse/temp, greenhouse/door and greenhouse/bed1/soil, everything under greenhouse however deep, but not garage/temp. Which readings does a filter catch? a topic is a path; a filter is a path with blanks in it 1 what the sensors publish to topics what an app asked for greenhouse/temp exactly this one +/temp + = any one word greenhouse/# # = all below it greenhouse/temp ✓ delivered ✓ delivered ✓ delivered greenhouse/door – – ✓ delivered greenhouse/bed1/soil – – ✓ delivered garage/temp – ✓ delivered – 2 3 + stands in for one word between slashes; # at the end stands for everything after it, however deep.
Topic filters: + fills exactly one slot between slashes, # at the end takes everything below that point. A tick means the broker would deliver that topic's messages to that subscription.
A grid of four published topics against three subscription filters. greenhouse/temp alone matches only greenhouse/temp. +/temp matches greenhouse/temp and garage/temp, because + stands in for exactly one word between slashes, but not greenhouse/bed1/soil. greenhouse/# matches greenhouse/temp, greenhouse/door and greenhouse/bed1/soil, everything under greenhouse however deep, but not garage/temp. Which readings does a filter catch? a filter is a path with blanks in it 1 asked for greenhouse/temp exactly this one greenhouse/temp ✓ delivered greenhouse/door – greenhouse/bed1/soil – garage/temp – 2 asked for +/temp + = any one word greenhouse/temp ✓ delivered greenhouse/door – greenhouse/bed1/soil – garage/temp ✓ delivered 3 asked for greenhouse/# # = all below it greenhouse/temp ✓ delivered greenhouse/door ✓ delivered greenhouse/bed1/soil ✓ delivered garage/temp – + = one word between slashes; # at the end = everything after it.
Topic filters: + fills exactly one slot between slashes, # at the end takes everything below that point. A tick means the broker would deliver that topic's messages to that subscription.

Topics beginning with $ are reserved for the broker’s own information ($SYS/… carries statistics on many brokers) and are left out of wildcard matches at the first level, so a subscriber to # does not get flooded with broker internals.

Three delivery guarantees

Every PUBLISH carries a quality of service level, QoS 0, 1 or 2. It is a promise about one hop: publisher to broker, or broker to one subscriber. The level a subscriber receives is the lower of what the publisher sent and what the subscriber asked for.

Three message ladders between the thermometer and the broker. QoS 0, send and forget: one PUBLISH, nothing back, the reading may be lost if the link breaks. QoS 1, until confirmed: PUBLISH with packet number 7, the PUBACK is lost when the link breaks, after reconnecting the thermometer sends 21.5 again with the DUP flag and gets the PUBACK, so the broker may receive it twice. QoS 2, exactly once: PUBLISH, PUBREC (received, remembering number 7), PUBREL (I will not resend), PUBCOMP (done), so the reading arrives exactly once at the cost of four packets. Three promises, three ladders what the thermometer and the broker say to each other for one reading send and forget 1 packetQoS 0 thermometer broker here is 21.5 PUBLISH 1 may be lost if the link breaks in flight until confirmed 2 packets, more after a resendQoS 1 thermometer broker here is 21.5, number 7 PUBLISH 1 ✕ got 7, but the link breaks reconnects 2 21.5 again, number 7 PUBLISH, DUP flag 3 got 7 PUBACK 4 may arrive twice, as it did here exactly once 4 packetsQoS 2 thermometer broker here is 21.5, number 7 PUBLISH 1 got 7, I will remember it PUBREC 2 I will not resend 7 PUBREL 3 done, 7 forgotten PUBCOMP 4 arrives exactly once Every extra reply buys more certainty and costs another packet: 1, 2 or 4 per reading.
The three delivery promises as the packets they cost. Each promise covers one hop; the broker repeats the exchange with every subscriber at the lower of the two sides' QoS levels.
Three message ladders between the thermometer and the broker. QoS 0, send and forget: one PUBLISH, nothing back, the reading may be lost if the link breaks. QoS 1, until confirmed: PUBLISH with packet number 7, the PUBACK is lost when the link breaks, after reconnecting the thermometer sends 21.5 again with the DUP flag and gets the PUBACK, so the broker may receive it twice. QoS 2, exactly once: PUBLISH, PUBREC (received, remembering number 7), PUBREL (I will not resend), PUBCOMP (done), so the reading arrives exactly once at the cost of four packets. Three promises, three ladders thermometer and broker, one reading send and forget 1 packetQoS 0 thermometer broker here is 21.5 PUBLISH 1 may be lost if the link breaks in flight until confirmed 2 packets, more after a resendQoS 1 thermometer broker here is 21.5, number 7 PUBLISH 1 ✕ got 7, but the link breaks reconnects 2 21.5 again, number 7 PUBLISH, DUP flag 3 got 7 PUBACK 4 may arrive twice, as it did here exactly once 4 packetsQoS 2 thermometer broker here is 21.5, number 7 PUBLISH 1 got 7, I will remember it PUBREC 2 I will not resend 7 PUBREL 3 done, 7 forgotten PUBCOMP 4 arrives exactly once More replies: more certainty, more packets. QoS 0, 1, 2 cost 1, 2, 4 packets per reading.
The three delivery promises as the packets they cost. Each promise covers one hop; the broker repeats the exchange with every subscriber at the lower of the two sides' QoS levels.

In practice QoS 1 with idempotent consumers is the common choice. QoS 2 is for messages where a duplicate would do harm and the consumer cannot deduplicate on its own, such as a command that toggles something.

A related guarantee is order: messages from one publisher on one topic at the same QoS arrive in the order they were sent.

Retained messages

A subscriber that joins late normally sees only messages published after it subscribed. For state, that is the wrong behaviour: an app that opens at 10:00 should not have to wait until the thermometer’s next reading to show a temperature.

A publisher can set the retain flag. The broker then keeps the last retained message for that topic and hands it to every new subscriber as soon as it subscribes. Publishing a retained message with an empty payload deletes it. Retained messages turn a topic into “the current value of X”, which is how most dashboards stay filled.

Two timelines of the same morning. The thermometer publishes 21.5 at 09:50 and 21.7 at 10:10; the phone app opens at 10:00. Without retain the phone sees nothing until 10:10, ten minutes of empty screen. With retain the broker has kept the last reading, 21.5, and hands it to the phone the moment it subscribes at 10:00; 21.7 then arrives live at 10:10. Why the phone shows a number straight away same thermometer, same phone; the only difference is one flag on the reading without retain the broker forgets each reading once delivered with retain the broker keeps the last reading 09:50 10:00 10:10 phone opens the app and subscribes 21.5 sentPUBLISH 21.5 sent, retainPUBLISH + retain flag 21.7 sent 21.7 sent phone shows nothing for 10 min phone shows 21.5 at once: the broker hands over the stored reading 1 2 3 Retain makes a topic mean 'the current value': latecomers get the last reading without waiting for the next.
A retained message is the broker remembering the last reading on a topic for whoever subscribes later. It turns a topic into 'the current value'.
Two timelines of the same morning. The thermometer publishes 21.5 at 09:50 and 21.7 at 10:10; the phone app opens at 10:00. Without retain the phone sees nothing until 10:10, ten minutes of empty screen. With retain the broker has kept the last reading, 21.5, and hands it to the phone the moment it subscribes at 10:00; 21.7 then arrives live at 10:10. Why the phone shows a number at once same morning, with and without one flag 1 without retain the broker forgets a reading once delivered 09:50 10:00 10:10 21.5 sentPUBLISH phone opens: shows nothing for 10 min 21.7 sent, phone shows 21.7 2 with retain the broker keeps the last reading 09:50 10:00 10:10 21.5 sentPUBLISH + retain phone opens: shows 21.5 at once, from the broker 21.7 sent, phone shows 21.7 Retain = the broker keeps the last reading for whoever subscribes later.
A retained message is the broker remembering the last reading on a topic for whoever subscribes later. It turns a topic into 'the current value'.

Keep-alive and the last will

On a mobile network or behind a NAT, a TCP connection can die without either end hearing about it: no FIN, no reset, just silence. MQTT deals with this with a clock.

At connect time the client states a keep-alive interval in seconds. It promises to send some packet at least that often; when it has nothing to say, it sends a PINGREQ (2 bytes) and the broker answers PINGRESP (2 bytes). If the broker hears nothing for 1.5 × keep-alive, it treats the client as gone and closes the connection. The client notices a dead broker the same way: a PINGRESP that does not come back.

The CONNECT can also carry a will: a topic, a payload, a QoS and a retain flag. The broker publishes it on the client’s behalf if the client disappears without a clean DISCONNECT: keep-alive expiry, a broken socket, a protocol error.

A timeline of the thermometer connected with a 60-second keep-alive and a will message greenhouse/status = offline. At 0 s it connects and leaves the will; at 60 s and 120 s it sends a 2-byte ping and gets a 2-byte answer. At 150 s its battery dies without a goodbye. The broker hears nothing for 90 seconds, 1.5 times the keep-alive, and at 210 s closes the connection and publishes the will on the thermometer's behalf, so the phone app shows offline. How a dead thermometer is noticed keep-alive 60 s · will: greenhouse/status = offline thermometer broker hello, my will is: offline CONNECT + will ok CONNACK still here PINGREQ 2 bytes noted PINGRESP 2 bytes still here PINGREQ noted PINGRESP 1 2 ✕ battery dies, no goodbye 3 90 s of silence = 1.5 × keep-alive 4 5 broker closes the connection and sends the will for it: greenhouse/status = offlinethe phone shows: offline 0 s 60 s 120 s 180 s Nobody reported the death; the clock did, and the will spoke for the thermometer.
A device that dies silently is noticed by the clock: after 1.5 × keep-alive without any packet the broker closes the connection and publishes the will the device left when it connected.
A timeline of the thermometer connected with a 60-second keep-alive and a will message greenhouse/status = offline. At 0 s it connects and leaves the will; at 60 s and 120 s it sends a 2-byte ping and gets a 2-byte answer. At 150 s its battery dies without a goodbye. The broker hears nothing for 90 seconds, 1.5 times the keep-alive, and at 210 s closes the connection and publishes the will on the thermometer's behalf, so the phone app shows offline. How a dead thermometer is noticed keep-alive 60 s · will = offline thermometer broker hello, if I vanish say: offline 0 s · CONNECT + will ok · CONNACK 1 still here 60 s · PINGREQ, 2 bytes noted · PINGRESP, 2 bytes 2 still here 120 s · PINGREQ noted · PINGRESP ✕ 150 s: battery dies, no goodbye 3 90 s silence = 1.5 × 60 s 4 5 at 210 s the broker closes the connection and sends the will: greenhouse/status = offline Nobody reported the death; the clock did.
A device that dies silently is noticed by the clock: after 1.5 × keep-alive without any packet the broker closes the connection and publishes the will the device left when it connected.

Will plus retain is the standard presence pattern: on connect the device publishes a retained online to its status topic and registers a retained offline as its will. Anyone, at any time, sees the right status, and nobody has to poll. MQTT 5 adds a will delay, so a device that reconnects within a few seconds does not flap its status.

Sessions: what the broker remembers

A session is the broker’s memory of a client: its subscriptions, plus the QoS 1 and 2 messages it has not yet acknowledged or not yet received. It is identified by the client identifier sent in CONNECT.

With a persistent session, a device can drop off the network, and when it reconnects with the same client identifier the broker still has its subscriptions and delivers the QoS 1 and 2 messages that arrived meanwhile. A device that sleeps for an hour to save battery misses nothing.

Persistent sessions are what make QoS 1 and 2 mean anything across a reconnect. Without one, the in-flight state is thrown away with the connection.

What MQTT 5 added

MQTT 3.1.1 was deliberately minimal. Version 5 kept the packet shapes and added properties: a length-prefixed list of typed fields at the end of the variable header of most packets. Through them:

FeatureWhat it does
Reason codesEvery acknowledgement can say why: not authorized, quota exceeded, no matching subscribers. In 3.1.1 a failed publish was mostly silent.
Session and message expirySessions expire after a set interval; a message can carry a lifetime, so a reading queued for a sleeping device is dropped once it is stale.
Topic aliasesAfter the first message, a long topic can be replaced by a 2-byte number for the rest of the connection. Saves bytes when topics are long and payloads small.
Shared subscriptions$share/g/jobs: the broker hands each message to one member of the group instead of all. Load balancing across consumers, without a separate queue.
User propertiesFree key–value pairs on a message, like HTTP headers: a content type, a trace id, a schema version.
Request / responseA response topic and correlation data on the request, so a reply can be routed back and matched.
Flow controlReceive maximum caps how many QoS 1/2 messages may be unacknowledged at once; maximum packet size caps packet size.
Server-sent DISCONNECTThe broker can say why it is closing the connection, instead of just closing it.

On the wire

Every MQTT packet starts with a fixed header of 2 to 5 bytes: one byte holding the packet type (4 bits) and flags (4 bits), then the remaining length, the number of bytes that follow. The remaining length is a variable-length integer: 7 bits per byte, the top bit set when another byte follows. Lengths below 128 take one byte; the maximum, 268,435,455, takes four. After that come a variable header that depends on the packet type (in MQTT 5 it ends with the properties), then the payload.

Here is a complete PUBLISH: the reading 21.5 on topic greenhouse/temp, at QoS 1.

The 26 bytes of one MQTT 5 PUBLISH carrying the reading 21.5 on topic greenhouse/temp at QoS 1: 0x32 (PUBLISH, QoS 1), 0x18 (24 bytes follow), 0x00 0x0F (name length 15), the 15 characters greenhouse/temp, 0x00 0x07 (packet id 7), 0x00 (no properties), then the 4 characters 21.5. 17 of the 26 bytes are the name. One reading, byte by byte 21.5 on greenhouse/temp at QoS 1 · 26 bytes · tinted = readable text, plain = protocol numbers 32 18 00 0F g r e e n h o u s e / t e m p 00 07 00 2 1 . 5 kind of packet fixed header name length the name: greenhouse/temp topic reply number packet id extras properties the reading payload 1 32 18 a PUBLISH at QoS 1; 24 more bytes follow 2 00 0F the name is 15 characters long 3 greenhouse/temp the name: the broker routes on this 4 00 07 number 7, so the 'got it' reply can be matched 5 00 no extras (MQTT 5 properties) 6 21.5 the reading: the broker never looks inside 17 of the 26 bytes are the name and 4 are the reading: in small messages the topic is the biggest part.
A whole PUBLISH is 26 bytes here: 2 of fixed header, 17 of topic, 3 of packet id and properties, 4 of payload. Tinted cells are text you could read; plain cells are numbers the protocol needs.
The 26 bytes of one MQTT 5 PUBLISH carrying the reading 21.5 on topic greenhouse/temp at QoS 1: 0x32 (PUBLISH, QoS 1), 0x18 (24 bytes follow), 0x00 0x0F (name length 15), the 15 characters greenhouse/temp, 0x00 0x07 (packet id 7), 0x00 (no properties), then the 4 characters 21.5. 17 of the 26 bytes are the name. One reading, byte by byte 21.5 on greenhouse/temp · 26 bytes 1 32 18 kind of packet a PUBLISH at QoS 1; 24 more bytes follow 2 00 0F name length 15 characters 3 g r e e n h o u s e / t e m p the name (topic): 15 characters, the biggest part 4 00 07 reply number (packet id) 7, matched by the 'got it' reply 5 00 extras (properties) none, MQTT 5 6 2 1 . 5 the reading (payload) the broker never looks inside 17 of 26 bytes are the name, 4 the reading: the topic is the biggest part.
A whole PUBLISH is 26 bytes here: 2 of fixed header, 17 of topic, 3 of packet id and properties, 4 of payload. Tinted cells are text you could read; plain cells are numbers the protocol needs.

Two things stand out. The topic is the largest part: 17 of the 26 bytes, sent in full with every message unless a topic alias replaces it. And the payload is opaque: the broker routes on the topic and never parses the body. JSON, a binary struct, a protobuf, compressed bytes: MQTT does not care, and does not tell the receiver which one it is unless a user property or a naming convention does.

The smallest packets are 2 bytes: PINGREQ is C0 00, PINGRESP is D0 00. An HTTP/1.1 request carries a request line and headers as text, typically a few hundred bytes before the body. That difference is most of MQTT’s reputation, and the MQTT vs HTTPS benchmark measures what it becomes on the wire once TCP, IP and TLS are added: the protocol’s bytes are only part of what a message costs.

Securing it

MQTT itself defines very little security; it relies on the layers around it.

The topic tree is the security boundary, so it is worth designing with ACLs in mind: put the device or tenant identity in the topic path, so that a rule like “client 42 may only touch sensors/42/…” can be written at all.

Where it fits, and where it does not

Good fitWhy
Telemetry from many devicesOne cheap connection each, small per-message overhead, fan-in at the broker
Commands to devices behind NATThe device dials out; commands come back down the same connection
Presence and current stateRetained messages plus wills give “last known value” and “is it online” for free
Unreliable or metered linksSessions survive reconnects; keep-alive costs a few bytes a minute
One event, many consumersPublish once; the broker fans out to every subscriber
Poor fitWhy
Request–response APIsPossible with MQTT 5, but HTTP has the tooling: status codes, caching, proxies, every client library
Large transfersA message is one MQTT packet (at most 256 MB) and brokers handle it whole; files and media belong on HTTP or object storage
Public, anonymous clientsHTTP infrastructure (CDNs, browsers, load balancers) assumes HTTP; MQTT in a browser needs WebSockets
Durable queues and replayA broker is not a log: no replay of old messages beyond retained values and queued session messages

The broker is also a single point everything depends on. At scale it becomes a cluster, and how sessions, retained messages and subscriptions are shared across nodes differs between brokers and is outside the standard.

The short version

Questions? Let's Chat :)

application