MQTT

Also known as: Message Queuing Telemetry Transport

On this page 7

MQTT (Message Queuing Telemetry Transport) is a lightweight publish/subscribe messaging protocol in which clients exchange messages through a central broker instead of addressing each other directly. Among the Internet protocols, it occupies the application layer and usually runs over TCP on port 1883, or over TLS on port 8883, which makes it a common choice for telemetry, the Internet of Things and any system where many small devices report data over unreliable or low-bandwidth links.

The protocol was designed in 1999 for monitoring oil pipelines over satellite connections, and its priorities still show that origin: a two-byte minimum header, tolerance of intermittent connectivity and very modest demands on device memory. It is standardized by OASIS as versions 3.1.1 and 5.0, and version 3.1.1 is also published as ISO/IEC 20922.

How the MQTT publish/subscribe model works

MQTT works by decoupling senders from receivers: a publisher sends a message to a named topic on the broker, and the broker forwards it to every client that has subscribed to a matching topic. Publishers do not know who receives their data, and subscribers do not need to know where it came from, which simplifies adding or removing devices.

Each client opens a long-lived TCP connection to the broker with a CONNECT packet and keeps it alive with periodic PINGREQ packets according to the negotiated keep-alive interval. Because the device initiates the connection, MQTT passes through NAT and firewalls far more easily than protocols that require inbound connections to the device.

The protocol defines a small set of control packets. The table below lists the ones that appear in almost every session.

PacketDirectionPurpose
CONNECT / CONNACKClient to broker, then replyOpen a session and report the result
PUBLISHBoth directionsCarry a message to a topic
SUBSCRIBE / SUBACKClient to broker, then replyRegister interest in topic filters
PUBACK, PUBREC, PUBREL, PUBCOMPBoth directionsAcknowledge delivery at QoS 1 and 2
PINGREQ / PINGRESPClient to broker, then replyProve the connection is still alive
DISCONNECTEither side in MQTT 5.0Close the session cleanly
Core MQTT control packets

Topics, wildcards and retained messages

An MQTT topic is a UTF-8 string with hierarchical levels separated by slashes, such as plant1/line3/temperature. Topics are not created in advance; the broker treats any valid string as a topic the moment a client publishes or subscribes to it, so topic design is a naming convention rather than a server configuration.

Subscribers can use two wildcards. The plus sign matches exactly one level, and the hash sign matches all remaining levels and must appear last. The examples below show how filters select topics.

Topic filterMatchesDoes not match
plant1/+/temperatureplant1/line3/temperatureplant1/line3/motor/temperature
plant1/#Every topic under plant1plant2/line1/temperature
+/+/statusplant1/line3/statusplant1/status
$SYS/#Broker statistics on many brokersOrdinary application topics
Topic filter matching examples

A retained message is the last message on a topic that the broker stores and delivers immediately to every new subscriber. Retention lets a dashboard that connects later see the current state of a device without waiting for the next update. The Last Will and Testament is a message the client registers at connect time; the broker publishes it if the client disconnects unexpectedly, which is the standard way to signal that a device has gone offline.

Quality of service levels in MQTT

MQTT offers three quality of service (QoS) levels that trade delivery guarantees against traffic and latency. QoS applies to each hop separately: the publisher negotiates it with the broker, and each subscriber receives the message at the lower of the published and the subscribed QoS.

LevelGuaranteePackets per messageTypical use
QoS 0At most once, no acknowledgment1Frequent sensor readings where a lost value does not matter
QoS 1At least once, duplicates possible2Most telemetry and alerts with idempotent handling
QoS 2Exactly once via four-step handshake4Billing events, commands that must not repeat
MQTT quality of service levels

Guarantees also depend on session persistence. With a persistent session, the broker queues QoS 1 and QoS 2 messages for a disconnected subscriber and delivers them on reconnection. Without it, messages published while the client was offline are lost regardless of QoS. A frequent mistake is assuming that QoS 2 means end-to-end exactly-once processing; it covers only the protocol hop, not the application logic behind it.

MQTT 3.1.1 compared with MQTT 5.0

MQTT 5.0, published in 2019, keeps the same packet structure but adds features that large deployments previously had to build themselves. Most current brokers support both versions, and clients of different versions can share one broker.

FeatureMQTT 3.1.1MQTT 5.0
Error reportingFew return codesReason codes on most acknowledgments
MetadataNot availableUser properties as key-value pairs
Load balancingBroker-specific extensionsShared subscriptions in the standard
Message lifetimeUnlimitedMessage expiry interval
Request/responseAd hoc topic conventionsResponse topic and correlation data
Bandwidth savingFull topic name every timeTopic aliases
Main differences between MQTT versions

Compared with HTTP, MQTT keeps one connection open and pushes data as it arrives, while HTTP follows a request/response pattern in which the client must poll or hold requests open. Compared with WebTransport or plain WebSocket messaging, MQTT adds standardized topics, QoS and broker semantics; it can itself run over WebSocket so that browsers act as MQTT clients.

Security and deployment considerations

MQTT itself provides only a username and password field in the CONNECT packet, so real security comes from the transport and the broker. Production systems should use TLS for every connection, preferably with client certificates or token-based authentication, and the broker should enforce topic-level access control lists so that a compromised device cannot read or write other devices’ topics.

Public scans regularly find brokers exposed without authentication on port 1883, leaking sensor data and accepting commands from anyone. The table below summarizes common problems and their fixes.

MistakeConsequenceFix
Anonymous access on port 1883Anyone can read and publishRequire TLS and authentication
Overly broad # subscriptionsExcess traffic and data exposureGrant narrow topic filters per client
Duplicate client identifiersClients repeatedly disconnect each otherGenerate a unique ID per device
Large payloads such as imagesBroker memory pressure and latencySend a reference and store files elsewhere
QoS 2 everywhereUnneeded round trips and loadUse QoS 1 with idempotent consumers
Common MQTT deployment mistakes

Scaling a single broker is straightforward up to hundreds of thousands of connections, depending on hardware and message rate; beyond that, operators use clustered brokers or bridge several brokers together. The MQTT-SN variant serves sensor networks that run over UDP or non-IP links.

In plain words

MQTT works like a notice board in a shared hallway. Devices pin short notes under labeled headings, and anyone interested in a heading gets a copy of each new note automatically. Nobody has to walk from door to door delivering messages.

The board keeper, called the broker, makes sure each note reaches the right people, keeps the latest note on display for newcomers and announces when a device suddenly goes silent. The key idea is that senders and receivers never talk directly, which keeps small, battery-powered devices simple and lets new readers join at any time.

A real-world example

A food-processing company monitors 240 refrigerated storage units across six warehouses. Each unit has a small controller that publishes its temperature every 30 seconds at QoS 0 to topics such as warehouse4/unit17/temp, and publishes door-open alarms at QoS 1 so that no alarm is lost. Each controller registers a Last Will message that marks the unit as offline if its cellular link drops.

A central broker, reachable only over TLS on port 8883, enforces rules so that each controller may write only to its own topics. The operations dashboard subscribes to +/+/temp and receives retained values the moment an operator opens it, while an alerting service subscribes to alarm topics through a persistent session. The result is near-real-time visibility over low-cost cellular data plans, and maintenance teams learn about a failing compressor or an open door within seconds instead of discovering spoiled stock at the next manual inspection.