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.
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.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:
Senders and receivers are decoupled. The thermometer does not know the phone app exists, how many loggers are listening, or whether anybody is. Adding a subscriber changes nothing on the device.
Devices never accept connections. A sensor behind a home router or on a mobile network cannot be reached from outside, but it can always dial out. Once its connection to the broker is up, messages flow both ways over it: the device can be sent a command by subscribing to its own command topic.
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.
Filter
Matches, and does not match
home/hall/temp
only that topic; not home/hall
home/+/temp
home/hall/temp; not home/a/b/temp
home/#
home, home/a/b; not office/temp
#
every topic except those starting with $
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.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.
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.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.
QoS 0, at most once. The sender writes the PUBLISH and forgets it. TCP still retransmits lost segments, so on a healthy connection nothing is lost; what QoS 0 gives up is the case where the connection itself breaks while the message is in flight, and a broker is free to drop QoS 0 messages when a slow subscriber’s queue fills up. The message is then gone.
QoS 1, at least once. The PUBLISH carries a 2-byte packet identifier and the sender keeps a copy until a PUBACK with that identifier comes back. If the connection breaks first, the sender sends it again after reconnecting, with the DUP flag set. The receiver may therefore see it twice, so a QoS 1 consumer must cope with duplicates, for example by making the handling idempotent.
QoS 2, exactly once. Four packets. The receiver answers PUBREC (“received, and I have stored the identifier”); the sender answers PUBREL (“release it, I will not resend”); the receiver answers PUBCOMP. Because the receiver remembers the identifier between PUBREC and PUBREL, a resent PUBLISH is recognised and not delivered twice. The price is two round trips and state on both sides.
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.
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'.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 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 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.
MQTT 3.1.1 has one flag, clean session: either the session ends with the connection, or it lives until the client connects with the flag set.
MQTT 5 separates the two questions. Clean start says whether to discard an old session at connect; session expiry interval says how long the broker keeps the session after the connection drops (0 = not at all, 4,294,967,295 = forever). A session that nobody resumes is eventually cleaned up instead of filling the broker.
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:
Feature
What it does
Reason codes
Every acknowledgement can say why: not authorized, quota exceeded, no matching subscribers. In 3.1.1 a failed publish was mostly silent.
Session and message expiry
Sessions 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 aliases
After 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 properties
Free key–value pairs on a message, like HTTP headers: a content type, a trace id, a schema version.
Request / response
A response topic and correlation data on the request, so a reply can be routed back and matched.
Flow control
Receive maximum caps how many QoS 1/2 messages may be unacknowledged at once; maximum packet size caps packet size.
Server-sent DISCONNECT
The 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.
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.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.
TLS for the connection, on port 8883. Without it, the username, password and every payload cross the network in clear text. The TLS handshake is the most expensive part of a new connection, which is one reason devices keep one connection open for hours.
Authentication in CONNECT: a username and password field, or a client certificate presented during the TLS handshake (common for devices, since a certificate can be provisioned at the factory and revoked individually). MQTT 5 adds an AUTH packet for challenge–response methods.
Authorization is the broker’s job: access control lists that say which client may publish or subscribe to which topics. A sensor should be able to publish to sensors/42/# and nothing else; a compromised sensor should not be able to subscribe to # and read the whole fleet.
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 fit
Why
Telemetry from many devices
One cheap connection each, small per-message overhead, fan-in at the broker
Commands to devices behind NAT
The device dials out; commands come back down the same connection
Presence and current state
Retained messages plus wills give “last known value” and “is it online” for free
Unreliable or metered links
Sessions survive reconnects; keep-alive costs a few bytes a minute
One event, many consumers
Publish once; the broker fans out to every subscriber
Poor fit
Why
Request–response APIs
Possible with MQTT 5, but HTTP has the tooling: status codes, caching, proxies, every client library
Large transfers
A 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 clients
HTTP infrastructure (CDNs, browsers, load balancers) assumes HTTP; MQTT in a browser needs WebSockets
Durable queues and replay
A 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
One TCP connection per client, to a broker; publishers and subscribers never meet.
Topics are paths; + matches one level, # the rest.
QoS 0, 1 and 2 are per-hop promises costing 1, 2 and 4 packets.
Retained messages hold the current value; wills announce an unannounced death; keep-alive notices silence after 1.5 × the interval.
Sessions let a device sleep or drop off without missing QoS 1 and 2 messages.