How MQTT Works
MQTT uses a publish/subscribe model. A broker routes messages. Publishers send to topics. Subscribers receive from topics. Topics are hierarchical: home/bedroom/temperature. Wildcards: + for one level, # for all remaining.
QoS Levels
- ▸QoS 0 — Fire and forget. Use for frequent sensor readings.
- ▸QoS 1 — Delivered at least once. Use for important events.
- ▸QoS 2 — Exactly once. Slowest. Use for critical commands.
Topic Design Best Practices
- ▸home/living_room/temperature — by location
- ▸devices/esp32_001/sensors/temp — by device
- ▸commands/bedroom/fan — commands separate from telemetry
Reconnection Handling
The most common mistake: not handling disconnections. WiFi drops. Brokers restart. Implement reconnect with exponential backoff and re-subscribe to all topics after reconnecting.
💡 Tip: For production: use TLS/SSL (port 8883), unique credentials per device, and ACLs to limit what each device can publish/subscribe.