
MQTT Protocol: How It Works, QoS Levels and When to Use It
MQTT protocol is the quiet workhorse of the Internet of Things. Every time a smart thermostat reports a temperature, a sensor sends a reading from a factory floor, or a connected car shares its location, there is a good chance MQTT is carrying that message. It is light, fast, and designed for devices that have little power, little memory, and unreliable networks.
In this guide, we explain what the MQTT protocol is, how it works, the three quality of service levels, and when to use MQTT instead of HTTP or other protocols. You will also learn how MQTT security works, and how to design a system that stays reliable when devices go offline.
What Is the MQTT Protocol?
MQTT stands for Message Queuing Telemetry Transport. It is a lightweight messaging protocol for small sensors and mobile devices, and it is now an ISO standard (ISO/IEC 20922) maintained by OASIS. It was invented in 1999 by Andy Stanford-Clark and Arlen Nipper, who needed a way for sensors on an oil pipeline to send data over a slow, unreliable satellite link.
MQTT uses a publish/subscribe model, rather than the request/response model used by HTTP. In HTTP, a client asks a server for data, and the server answers. In MQTT, a device publishes a message to a topic, and the broker sends that message to every device that has subscribed to that topic. The publisher and the subscriber never talk to each other directly. They only talk to the broker, which routes messages between them.
That separation is the key to MQTT’s success. A sensor does not need to know who will use its data, and a dashboard does not need to know which sensor sent a reading. Both only need to know the broker and the topic name. That makes it easy to add new devices, replace a device, or add a new application that listens to the same data.
How MQTT Works: Clients, Brokers and Topics
An MQTT system has three parts. A client is a device or application that connects to the broker. It can publish messages, subscribe to topics, or both. Most IoT devices, such as sensors and actuators, are MQTT clients. A broker is a server that receives messages from publishers and routes them to subscribers. Popular brokers include Mosquitto, HiveMQ, and EMQX, both open-source and hosted. A topic is a named channel that messages are published to, such as home/kitchen/temperature or factory/line1/machine2/vibration.
Topics are hierarchical, separated by slashes. A subscriber can subscribe to a single topic, or to a group of topics using wildcards. The plus sign matches one level, for example home/+/temperature will match home/kitchen/temperature and home/bedroom/temperature. The hash sign matches all levels below, for example home/# will match every topic under home.
A typical exchange is simple. A temperature sensor wakes up, connects to the broker, and publishes a message with the topic home/kitchen/temperature and the value 21.5. The broker looks at its list of subscribers for that topic, and sends the message to a thermostat app, a dashboard, and a data logger. The sensor then goes back to sleep. It does not wait for a reply, and it does not need to know who received the data.
MQTT is a small protocol, but it has a few features that make a big difference in real systems. The most important is quality of service, followed by retained messages and last will messages.
MQTT QoS Levels: 0, 1 and 2
| QoS level | Name | Delivery guarantee | Best for |
|---|---|---|---|
| QoS 0 | At most once | Message is sent once, may be lost | Frequent sensor data where losing one reading is fine |
| QoS 1 | At least once | Message is delivered, may be duplicated | Alerts and commands where delivery matters |
| QoS 2 | Exactly once | Message is delivered once, no duplicates | Payments and critical commands |
QoS 0 is the fastest and simplest. The publisher sends the message and does not wait for an acknowledgement. If the network drops the message, it is gone. That is fine for a temperature reading that is sent every ten seconds: losing one reading does not matter, because the next one will arrive soon.
QoS 1 adds an acknowledgement. The publisher stores the message until the broker confirms it received the message. If the acknowledgement does not arrive, the publisher sends the message again. That guarantees delivery, but it can also cause duplicates, so the subscriber must be able to handle the same message twice without harm.
QoS 2 is the slowest and most reliable. It uses a four-step handshake to make sure the message is delivered exactly once. Use it only when duplicates would cause a real problem, such as a command to open a valve or to charge a payment. For most IoT data, QoS 0 or QoS 1 is the right choice.
Choose the lowest QoS level that meets your needs. Higher QoS levels use more bandwidth, more battery, and more time. On a small device with a weak connection, the difference matters. A sensor that sends data every minute at QoS 0 will last far longer on battery than one that uses QoS 2 for every message.
Retained Messages, Last Will and Clean Sessions
A retained message is a message that the broker stores and sends to any new subscriber immediately. For example, a thermostat can publish its current setpoint as a retained message. When a new dashboard connects and subscribes, it will receive the setpoint at once, without waiting for the thermostat to publish again. Without a retained message, the dashboard would show a blank value until the next update.
A last will message is a message that a client asks the broker to publish if the client disconnects unexpectedly. A device can set a last will such as home/kitchen/sensor/status with the value offline. If the device loses power or its network connection drops, the broker will publish that message on its behalf, so other devices know it has gone offline. That is useful for monitoring: a dashboard can show a sensor as offline, rather than showing its last value forever.
A clean session, or clean start in MQTT 5, controls what happens when a client reconnects. With a clean session, the broker forgets the client’s subscriptions and queued messages. With a persistent session, the broker keeps them, and delivers queued messages when the client reconnects. Persistent sessions are useful for devices that sleep for long periods and need to catch up on messages they missed.
MQTT 5, the current version, adds more features, such as message expiry, shared subscriptions, topic aliases, and user properties that let applications add custom metadata to messages. Most new systems should use MQTT 5, but MQTT 3.1.1 is still widely used, especially on older devices. If you are buying new devices, check which version they support.
MQTT is not the only protocol for connected devices, and it is not always the right one. Knowing when to use it, and when to use something else, is part of good system design.
MQTT vs HTTP and CoAP
| Feature | MQTT | HTTP | CoAP |
|---|---|---|---|
| Model | Publish/subscribe | Request/response | Request/response |
| Overhead | Very low | High, headers are large | Low, over UDP |
| Best for | Many devices, frequent small messages | Web pages, APIs, one-off requests | Constrained devices, UDP networks |
| Real-time push | Yes, broker pushes messages | No, client must poll | Limited, observe mode |
| Offline devices | Broker queues messages | No queueing | Limited |
HTTP is the right choice when a device needs to fetch a web page, call an API, or send a single large request. It is well understood, and every system supports it. MQTT is the right choice when many devices need to send small messages often, when the network is unreliable, or when data needs to flow in real time to many subscribers. Use MQTT for telemetry, alerts, and control messages. Use HTTP for configuration, firmware downloads, and web interfaces.
CoAP is a lighter version of HTTP for very constrained devices, and it uses UDP instead of TCP. It is a good fit for a single device talking to a single server, but it does not have a broker, so it is less suited to systems where many applications need the same data. For most IoT projects, MQTT is the simpler and more flexible choice.
MQTT Security: What to Do and What to Avoid
MQTT by itself does not encrypt data, and it does not check who a client is unless you set that up. That is a security problem, because anyone who can connect to a broker can publish and subscribe to any topic. Do not run an open MQTT broker on the internet. It will be found, and it will be abused.
Start with the basics. Use TLS to encrypt traffic between clients and the broker, just as you would use HTTPS for a website. Require a username and password for every client, and give each client only the topics it needs. A temperature sensor should be able to publish to its own topic, not to the topic that controls a door lock. Use access control lists on the broker to enforce that.
Keep the broker patched, and monitor its logs for failed login attempts and unusual subscriptions. A client that subscribes to the # wildcard, which matches every topic, is a warning sign. So is a flood of messages from a single client. If a device is compromised, revoke its credentials promptly and check what it published.
Messages themselves may also need protection. MQTT data travels over IP networks, and the same principles that protect other traffic apply here. For example, IPsec protects network traffic at the IP layer, and it is a useful layer of defence for devices that send sensitive data over an untrusted network. In a wired network, the physical connection matters too: a network switch that supports VLANs can separate IoT devices from office computers, so a compromised sensor cannot reach a workstation.
When to Use MQTT: Common Use Cases
MQTT is used in far more places than most people realise. In a smart home, it connects thermostats, lights, door sensors, and voice assistants. In a factory, it connects machines, sensors, and production dashboards. In agriculture, it connects soil sensors and irrigation controllers. In transport, it connects vehicles, fleet trackers, and traffic sensors. In energy, it connects solar inverters, smart meters, and grid controllers.
The common thread is many devices, small messages, and a need for real-time data. If you have ten devices, HTTP may be simpler. If you have ten thousand devices, MQTT will be far more efficient. If your devices need to send data every second, MQTT’s low overhead will save battery and bandwidth. If your devices are often offline, MQTT’s queuing and last will features will keep the system reliable.
MQTT is less suited to large files, video, or voice. Those need a different protocol, such as HTTP for files or WebRTC for media. It is also less suited to a single request that needs a direct answer, such as asking a server for the current time. Use the right protocol for each job, and use MQTT for what it does best: small, frequent, real-time messages between many devices.
If a device cannot connect to the broker, check the network first. Check that the device has an IP address, that it can reach the broker, and that the broker is running. A device that cannot get an address from DHCP may end up with an APIPA address, which means it cannot reach the network at all. That is a network problem, not an MQTT problem, and it needs to be fixed before MQTT can work. Check the firewall next: MQTT normally uses port 1883, and MQTT over TLS uses port 8883. If those ports are blocked, the client will not connect.
Frequently Asked Questions
Is MQTT free to use?
Yes. MQTT is an open standard, and there are many free and open-source brokers, such as Mosquitto, as well as free client libraries for almost every programming language. Hosted brokers charge for managed service, support, and scale, but the protocol itself is free.
What port does MQTT use?
MQTT normally uses TCP port 1883 for unencrypted traffic, and port 8883 for MQTT over TLS. MQTT over WebSockets usually uses port 80 or 443, so that it can pass through firewalls that only allow web traffic.
What is the difference between MQTT and HTTP?
HTTP is a request/response protocol, where a client asks for data and a server answers. MQTT is a publish/subscribe protocol, where a publisher sends a message to a topic and a broker delivers it to subscribers. MQTT has far less overhead, works better for real-time data, and handles offline devices better. HTTP is better for web pages, APIs, and one-off requests.
Is MQTT secure?
MQTT can be secure, but only if you configure it correctly. By default, MQTT does not encrypt data or check who a client is. Use TLS for encryption, require a username and password, limit each client to the topics it needs, keep the broker patched, and never expose an open broker to the internet.
Can MQTT work without the internet?
Yes. MQTT works on any TCP/IP network, including a local network with no internet connection. You can run a broker on a local server, a Raspberry Pi, or even on a device itself. That makes MQTT a good choice for factories, farms, and buildings where devices need to work even when the internet is down.
Conclusion
The MQTT protocol is simple, light, and well suited to the Internet of Things. Its publish/subscribe model lets devices share small messages in real time, without knowing who will use the data. Its quality of service levels let you choose the right balance between speed and reliability. Its retained messages and last will features keep systems working when devices go offline.
If you are building an IoT system, start with a broker that is well supported, use TLS and authentication from the start, and choose QoS 0 or QoS 1 for most data. Add security, monitoring, and access control before you go to production, not after. Done right, MQTT will quietly carry your data for years, with little fuss and little cost.


