MQTT with QoS levels in Raspberry Pi - Time & Space Complexity
When using MQTT with different Quality of Service (QoS) levels, the time it takes to send messages can change. We want to understand how the message delivery steps grow as we send more messages.
How does the number of message exchanges grow when using various QoS levels?
Analyze the time complexity of the following MQTT publish code with QoS.
client = mqtt.Client()
client.connect("broker.hivemq.com", 1883)
for i in range(n):
client.publish("topic/test", f"Message {i}", qos=1)
client.disconnect()
This code sends n messages to a topic with QoS level 1, which requires acknowledgment for each message.
Look at what repeats as we send messages.
- Primary operation: Sending each message and waiting for acknowledgment.
- How many times: Exactly
ntimes, once per message.
As the number of messages n increases, the total steps to send and confirm messages grow directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 send-and-acknowledge steps |
| 100 | About 100 send-and-acknowledge steps |
| 1000 | About 1000 send-and-acknowledge steps |
Pattern observation: The work grows evenly as you send more messages.
Time Complexity: O(n)
This means the time to send messages grows in a straight line with the number of messages.
[X] Wrong: "QoS 1 sends messages instantly without waiting, so time does not grow with more messages."
[OK] Correct: QoS 1 requires waiting for an acknowledgment for each message, so sending more messages means more waiting steps, making time grow with n.
Understanding how message delivery steps grow with QoS levels helps you explain real-world network communication delays and reliability trade-offs clearly.
What if we changed the QoS level from 1 to 0? How would the time complexity change?