0
0
Raspberry Piprogramming~5 mins

MQTT with QoS levels in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: MQTT with QoS levels
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

Look at what repeats as we send messages.

  • Primary operation: Sending each message and waiting for acknowledgment.
  • How many times: Exactly n times, once per message.
How Execution Grows With Input

As the number of messages n increases, the total steps to send and confirm messages grow directly with n.

Input Size (n)Approx. Operations
10About 10 send-and-acknowledge steps
100About 100 send-and-acknowledge steps
1000About 1000 send-and-acknowledge steps

Pattern observation: The work grows evenly as you send more messages.

Final Time Complexity

Time Complexity: O(n)

This means the time to send messages grows in a straight line with the number of messages.

Common Mistake

[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.

Interview Connect

Understanding how message delivery steps grow with QoS levels helps you explain real-world network communication delays and reliability trade-offs clearly.

Self-Check

What if we changed the QoS level from 1 to 0? How would the time complexity change?