MQTT is a lightweight publish/subscribe messaging protocol designed for constrained devices and low-bandwidth, high-latency networks. It's the backbone of many IoT applications.
Unlike client-server (REST), MQTT uses an event-driven architecture:
Publisher → Broker → Subscriber
- Publisher sends messages to a topic
- Broker routes messages to subscribers
- Subscriber receives messages from topics they subscribed to
Topics are hierarchical strings separated by /:
home/livingroom/temperature
home/bedroom/light
sensors/+/motion # + is a single-level wildcard
sensors/# # # is multi-level wildcard
| Level | Guarantee | Use Case |
|---|---|---|
| QoS 0 | At most once | Weather sensors (occasional loss OK) |
| QoS 1 | At least once | Billing data (no loss allowed) |
| QoS 2 | Exactly once | Critical commands |
flowchart LR
subgraph "IoT Devices"
A[Sensor] --> B[MQTT Broker]
B --> C[Actuator]
D[Mobile App] --> B
E[Cloud Backend] --> B
end
B -.-> F[(Message<br/>Persistence)]
- Clean Session = true: Broker doesn't store subscriptions/messages for disconnected clients
- Clean Session = false: Broker stores messages until delivery
Last message on a topic is kept by the broker. New subscribers immediately receive it.
Client can set a message the broker sends if it disconnects unexpectedly.
| Industry | Application |
|---|---|
| Smart Home | Light, thermostat, door sensors |
| Industrial | Machine monitoring, predictive maintenance |
| Healthcare | Patient vital signs, equipment tracking |
| Agriculture | Soil moisture, greenhouse climate |
const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://broker.hivemq.com:1883');
// Subscribe to topic
client.subscribe('home/livingroom/temperature');
// Receive messages
client.on('message', (topic, message) => {
console.log(`Temperature: ${message.toString()}°C`);
});
// Publish message
client.publish('home/livingroom/temperature', '24.5');| Advantage | Why It Matters |
|---|---|
| Small overhead | Works on limited bandwidth |
| Three QoS levels | Flexible reliability |
| Pub/Sub decouples | Devices don't need to know each other |
| Last Will | Know when devices go offline |
| Retained messages | New subscribers get immediate state |
It competes with AMQP (enterprise, complex), CoAP (constrained HTTP-like), and WebSockets (web integration).