The Internet of Things connects billions of devices worldwide. These devices share a common challenge: communicating efficiently over unreliable networks with limited bandwidth. MQTT solves this challenge perfectly.
Understanding MQTT
MQTT stands for Message Queuing Telemetry Transport. It was invented in 1999 by Andy Stanford-Clark and Arlen Nipper. Their goal was to create a protocol for monitoring oil pipelines over satellite links.
The protocol's design reflects these origins. It works over limited bandwidth. It handles unstable connections gracefully. It requires minimal resources on devices.
MQTT uses a publish-subscribe model. Devices publish messages to topics. Other devices subscribe to topics they care about. The broker routes messages between publishers and subscribers.
This decoupling is powerful. Publishers don't need to know who's listening. Subscribers don't need to know where messages come from. The broker handles everything.
MQTT Architecture
The publish-subscribe architecture involves three components.
Publishers send messages to the broker. A temperature sensor publishes readings to the "sensors/temperature" topic. An application publishes order updates to "orders/status".
The broker receives messages and forwards them to subscribers. Popular brokers include Mosquitto, EMQX, and cloud services like AWS IoT and Azure IoT Hub.
Subscribers receive messages on topics they follow. Applications subscribe to specific topics like "sensors/+/temperature" where the + is a wildcard.
This architecture scales well. Adding new devices doesn't require changes to existing publishers or subscribers. Topics route messages efficiently.
MQTT Quality of Service
MQTT offers three levels of delivery guarantee. Choose the appropriate level for your use case.
QoS 0 (At most once): The message sends once, without acknowledgment. Network loss may result in lost messages. Use for non-critical sensor data where missing readings don't matter.
QoS 1 (At least once): The message delivers at least once. The sender retries until acknowledgment arrives. Duplicates may occur. Use for data where missing messages are worse than duplicates.
QoS 2 (Exactly once): The message delivers exactly once. A four-part handshake ensures no loss and no duplicates. Use for critical commands where duplicates cause problems.
MQTT vs HTTP
HTTP dominates the web, but MQTT suits IoT better for many scenarios.
Connection overhead: HTTP requires a new connection for each request. MQTT maintains persistent connections. For frequent small messages, MQTT uses far less bandwidth.
Message size: HTTP headers alone exceed 200 bytes. MQTT messages need just 2 bytes of overhead. Over limited cellular or satellite links, this matters significantly.
Battery usage: Opening and closing TCP connections drains batteries quickly. MQTT's persistent connections use minimal power.
Quality of service: HTTP doesn't guarantee delivery. MQTT offers explicit delivery guarantees at three levels.
HTTP remains better for request-response interactions and browser-based applications. MQTT excels for sensor networks and device communication.
Practical MQTT Example
Connect a temperature sensor to the Pet Store API using MQTT:
First, install an MQTT client:
npm install mqtt
Publish temperature readings:
const mqtt = require('mqtt');
const client = mqtt.connect('mqtt://broker.petstoreapi.com', {
clientId: 'petstore-iot-device-001',
username: 'your-api-key'
username: 'your-api-key',
clientId: 'temperature-sensor-001'
});
client.on('connect', () => {
console.log('Connected to MQTT broker');
// Publish temperature every 30 seconds
setInterval(() => {
const reading = {
sensor: 'temperature',
value: readTempSensor(),
unit: 'celsius',
timestamp: Date.now()
};
client.publish(
'petstore/sensors/temperature',
JSON.stringify(reading),
{ qos: 1 }
);
}, 30000);
});
Subscribe to alerts:
client.subscribe('petstore/alerts/#', { qos: 1 });
client.on('message', (topic, message) => {
const alert = JSON.parse(message.toString());
handleAlert(alert);
});
The topic hierarchy organizes messages logically. Sensors publish to sensor topics. Subscriptions use wildcards to match multiple topics.
Topic Design
Good topic design makes MQTT implementations manageable.
Hierarchical structure organizes topics logically:
petstore/
sensors/
temperature
humidity
orders/
created
updated
shipped
alerts/
low-stock
system-error
Wildcards simplify subscriptions:
+matches one level:petstore/+/alertsmatches "petstore/sensors/alerts" and "petstore/orders/alerts"#matches all remaining levels:petstore/sensors/#matches everything under sensors
Naming conventions prevent conflicts. Use lowercase, hyphens for separation. Avoid special characters.
MQTT over TLS
Production deployments require encryption. MQTT over TLS uses port 8883. The connection encrypts all traffic.
const client = mqtt.connect('mqtts://broker.petstoreapi.com:8883', {
clientId: 'petstore-iot-device-001',
username: 'your-api-key'
cert: readFileSync('client.crt'),
key: readFileSync('client.key'),
ca: readFileSync('ca.crt')
});
Never transmit credentials or data without encryption. IoT devices often operate in untrusted environments.
When MQTT Makes Sense
MQTT is purpose-built for specific scenarios:
Sensor networks benefit most. Sensors send small amounts of data frequently. MQTT minimizes bandwidth and battery usage.
Unstable networks work well with MQTT. The protocol handles connection drops gracefully. Messages queue until connection restores.
Device-to-device communication suits the pub-sub model. Devices can communicate without a central server managing every interaction.
Large-scale deployments scale efficiently. The broker architecture handles millions of connections. Topic-based routing minimizes processing overhead.
Consider alternatives for browser-based applications or request-response patterns.
Pet Store API and MQTT
The Pet Store API supports MQTT for IoT integrations. Connect sensors to track inventory conditions, monitor storage environments, and receive real-time alerts.
Use the MQTT endpoint to publish sensor data. Subscribe to topics for order updates and system alerts.
Find the MQTT configuration at docs.petstoreapi.com. Authentication uses API keys. Topics follow a consistent naming convention.
MQTT provides the efficiency IoT applications need. Small message sizes, persistent connections, and reliable delivery make it ideal for connected devices.