← Back to the chapter · Previous detail · Next detail →
Technical detail · MQTT Python: Reliable Client Patterns
Network-loop elapsed time, CPU use and energy
The Paho-mqtt Python client library processes traffic and runs application callbacks in its network loop.
CPU means the processor; TLS (Transport Layer Security) protects the connection.
Two common paho-mqtt loop approaches are loop_forever() and loop_start(); manual loop() and external-loop integration also exist. loop_forever() runs the network loop in the calling thread, while loop_start() runs it in a background thread. Both wait for socket activity; neither is inherently a busy poll.
Elapsed time per loop cycle (illustrative):
Where: Interpret the terms in execution order. Start with , elapsed time waiting on socket activity or a timeout; this is generally not CPU processing time. Next add to parse MQTT packets and acknowledgements, then for application work. Measure CPU use separately from elapsed wait time.
Busy or near-zero timeout loop:
A busy or near-zero timeout loop wakes frequently even when there is no useful MQTT work. Follow the consequence from wake-up rate to compute load and then energy: an accidental busy poll can consume a full core, and a battery-powered device loses the long sleep intervals that normally control average current.
Background loop with an ordinary socket wait:
A background loop with an ordinary socket wait sleeps until socket activity or a timeout while the calling thread remains available for other work. That is a concurrency choice; it does not by itself lower the network loop’s idle wake-up rate relative to loop_forever().
Battery impact:
For battery impact, compare the two paths directly. Constant wake-ups keep the CPU and possibly the radio path active more often than necessary; sleeping between packets creates more opportunities for lower-power states. The exact saving still depends on the board, radio state, TLS configuration, and sensor duty cycle, so the final step is measurement on the target hardware rather than treating the loop API as a power guarantee.
Recommendation:
Use loop_forever() when the calling thread can be devoted to MQTT. For applications that do other work in that thread, use loop_start() or integrate loop() with a disciplined main loop. Measure idle CPU and energy in the final design.