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.