Overview
Protocol: MQTT v5.0 over TLS (MQTTS) Pattern: Publish/Subscribe Endpoint:mqtts://mqtt.petstoreapi.com:8883
When to Use MQTT:
- ✅ IoT devices and sensors
- ✅ Low-bandwidth networks
- ✅ Battery-powered devices
- ✅ Unreliable network connections
- ✅ Many devices publishing data
- ❌ Standard web applications (use REST/WebSocket instead)
- ❌ High-bandwidth data transfer
- ❌ Request/response pattern needed
How MQTT Works
- Extremely lightweight (2-byte header)
- Publish/Subscribe pattern
- Three Quality of Service (QoS) levels
- Works on unreliable networks
- Battery-efficient
Connection
Python (paho-mqtt)
JavaScript (MQTT.js)
ESP32 (Arduino)
Topics
Topic Structure
Wildcards
Publishing Messages
Python Example
JavaScript Example
Quality of Service (QoS)
QoS 0 - At Most Once
- Non-critical data
- High-frequency updates
- Where message loss is acceptable
QoS 1 - At Least Once
- Important data
- Must be delivered at least once
- Can handle duplicate messages
QoS 2 - Exactly Once
- Critical financial transactions
- Where duplicates cannot be tolerated
- Payment processing
Last Will and Testament
Retained Messages
Advanced Usage
Persistent Sessions
Batch Messages
Best Practices
1. Error Handling
2. Connection Management
3. Message Validation
Troubleshooting
Connection Failures
- Check TLS/SSL certificate
- Verify username/password
- Ensure port 8883 is accessible
- Check firewall rules
Missing Messages
- Verify QoS level
- Check topic subscriptions
- Ensure broker permissions
- Review message queue size
High Latency
- Reduce message size
- Optimize topic structure
- Check network connectivity
- Consider local broker
Comparison with Alternatives
| Feature | MQTT | WebSocket | HTTP |
|---|---|---|---|
| Pattern | Pub/Sub | Bidirectional | Request/Response |
| Overhead | Very Low | Low | High |
| Battery Efficient | ✅ | ⚠️ | ❌ |
| Unreliable Networks | ✅ | ❌ | ❌ |
| QoS Levels | ✅ | ❌ | ❌ |
| IoT Support | ✅ | ⚠️ | ❌ |
Security Best Practices
- Always use TLS (mqtts://)
- Use strong authentication (username/password or client certificates)
- Implement access control (topic-based permissions)
- Validate all messages (schema validation)
- Monitor for anomalies (unusual message patterns)
Interactive Documentation
- API Specification: AsyncAPI 3.0
- MQTT Quick Start: MQTT Guide
- Protocol Overview: All Protocols