Imagine you have a smart home with 50 devices: lights, sensors, thermostats, cameras, and door locks. Each device needs to communicate, but here's the catch:
Every device asks the server repeatedly:
Problems:
Devices subscribe once, receive updates when they happen:
Benefits:
✅ Minimal bandwidth (only send when there's news)
✅ Battery efficient (no constant polling)
✅ Low server load (push only when needed)
✅ Real-time (instant delivery)
✅ Scales easily (1M devices, same efficiency)
Pause and think: What if devices could "subscribe" to topics and only receive messages when something actually happens?
MQTT (Message Queuing Telemetry Transport) is a lightweight publish/subscribe messaging protocol designed for constrained devices and unreliable networks.
Key insight: Instead of constantly asking "Any news for me?", devices say "Tell me when there's news about X" and go to sleep until notified.
The MQTT broker is like a post office that routes messages between publishers and subscribers.
Broker's Job:

Features:
Popular MQTT Brokers:
Publishers send messages to topics without knowing who will receive them.
Publisher Example:
Key Point: Publishers don't care who's listening. They just send to a topic.
Subscribers register interest in topics and receive messages when they're published.
Subscriber Example:
Key Point: Subscribers don't know who's publishing. They just listen to topics.
Topics are hierarchical strings that organize messages, like a file system path.
Topic Structure:
Topic Hierarchy Example:
Subscribe to multiple topics at once using wildcards.
Single-level wildcard (+):
Multi-level wildcard (#):
Practical Examples:
You have 100 soil moisture sensors that need to report data every 5 minutes.
Every 5 minutes, each sensor:
Characteristics:
Costs:
❌ High bandwidth (HTTP headers overhead)
❌ Battery drain (maintain HTTP connection)
❌ Server processes 28,800 requests/day
❌ Firewall/NAT traversal issues
Each sensor publishes when it has data:
Characteristics:
Benefits:
✅ 93% less bandwidth (1.44 MB vs 20.16 MB)
✅ Battery efficient (persistent connection)
✅ Broker handles routing (server just subscribes)
✅ Works through NAT/firewalls
Real-world parallel: HTTP is like mailing individual letters. MQTT is like having a subscription to a newspaper — you only get what's relevant, when it's published.
MQTT provides three levels of message delivery guarantee:
How it works:

Characteristics:
✅ Fastest delivery
✅ Lowest overhead
❌ No delivery guarantee
❌ Message may be lost
Use when: Loss is acceptable (e.g., frequent sensor readings where next reading compensates)
Example:
How it works:

Characteristics:
Use when: Messages are important but duplicates are acceptable
Example:
How it works:

Characteristics:
Use when: Duplicates would cause problems (e.g., financial transactions, critical commands)
Example:
| Use Case | Recommended QoS | Reason |
|---|---|---|
| Temperature sensor | 0 | High frequency, loss acceptable |
| Motion detection | 1 | Important but duplicates OK |
| Door lock/unlock | 1 | Must arrive, duplicate is safe |
| Alarm trigger | 2 | Critical, no duplicates |
| Stock price feed | 0 | High frequency, latest matters |
| Payment confirmation | 2 | Must be exactly once |
| Chat message | 1 | Should arrive, duplicates filtered |
When you publish with the "retained" flag, the broker stores the last message and delivers it immediately to new subscribers.
Without Retained Message:
With Retained Message:
Code Example:
Use Cases:
A message the broker sends automatically if a client disconnects unexpectedly.
How It Works:
Code Example:
Monitoring Example:
Use Cases:
The broker remembers subscriptions and queues messages for disconnected clients.
Without Persistent Session:
With Persistent Session:
Code Example:
Requirements:
clean_session=FalseUse Cases:
Clients and brokers send periodic "ping" messages to detect broken connections.
How It Works:
Configuration:
Guidelines:
Match the scenario to the best protocol:
A. Real-time stock trading dashboard B. Firmware update download (100 MB) C. Smart home temperature sensors (100 devices) D. RESTful API for user authentication E. Chat application (1000 concurrent users) F. Serving web pages G. IoT sensors on oil rig (unreliable network) H. Video streaming
A. Stock trading dashboard → WebSocket (3) Real-time bidirectional data, but HTTP-based. WebSocket better than MQTT for browser integration.
B. Firmware update (100 MB) → HTTP/Other (1/4) Large file transfer - use HTTP or FTP, not optimized for MQTT.
C. Smart home sensors → MQTT (2) Perfect use case: many devices, low bandwidth, pub/sub pattern.
D. User authentication → HTTP (1) Standard request/response pattern, works well with REST.
E. Chat application → MQTT or WebSocket (2/3) Both work! MQTT for lightweight mobile apps, WebSocket for web browsers.
F. Serving web pages → HTTP (1) Standard protocol for web content delivery.
G. IoT on oil rig → MQTT (2) Unreliable network, need persistent sessions, low bandwidth - MQTT excels here.
H. Video streaming → Other (4) Use RTSP, HLS, or WebRTC - not designed for MQTT.
"MQTT is only for tiny embedded devices and sensors."
MQTT is excellent for ANY scenario requiring efficient, real-time, pub/sub messaging!
Mobile Applications:
Gaming:
Financial Services:
Social Media:
Enterprise Applications:
Facebook Messenger:
AWS IoT Core:
| Feature | MQTT | HTTP | WebSocket |
|---|---|---|---|
| Connection | Persistent | Request/Response | Persistent |
| Pattern | Pub/Sub | Client/Server | Bidirectional |
| Overhead | 2 bytes | 100s of bytes | ~2 bytes |
| Real-time | ✅ Excellent | ❌ Polling needed | ✅ Excellent |
| Bandwidth | ✅ Minimal | ❌ High | ✅ Low |
| Battery | ✅ Efficient | ❌ Draining | ✅ Efficient |
| QoS | ✅ Built-in (0,1,2) | ❌ None | ❌ None |
| Offline | ✅ Persistent sessions | ❌ No | ❌ No |
| Broker | ✅ Required | ❌ Not needed | ❌ Not needed |
| Browser | ⚠️ Via WebSocket | ✅ Native | ✅ Native |
| NAT/Firewall | ✅ Works well | ✅ Works well | ✅ Works well |

MQTT is lightweight and efficient - Designed for constrained devices and low-bandwidth networks
Publish/Subscribe pattern - Decouples publishers from subscribers for scalable architecture
QoS levels provide guarantees - Choose between fire-and-forget, acknowledged, and exactly-once delivery
Topic-based routing - Hierarchical topics with wildcards enable flexible message routing
Built for unreliable networks - Persistent sessions, retained messages, and LWT handle connection issues
Not just for IoT - Excellent for any real-time, event-driven application (messaging, gaming, notifications)
Security matters - Always use TLS, authentication, and topic-based authorization in production
Broker is critical - Choose and configure your broker carefully for your scalability needs
paho-mqtt libraryReal-world parallel: MQTT is like having a smart assistant who knows exactly who cares about what information and only tells people what they need to know, when they need to know it — instead of everyone constantly asking "Any news for me?"