Why MQTT is the IoT standard in Raspberry Pi - Performance Analysis
We want to understand how the time it takes to send and receive messages using MQTT grows as more devices connect.
How does MQTT handle many devices efficiently?
Analyze the time complexity of this simple MQTT publish-subscribe example on a Raspberry Pi.
import paho.mqtt.client as mqtt
def on_message(client, userdata, message):
print(f"Received message: {message.payload.decode()}")
client = mqtt.Client()
client.on_message = on_message
client.connect("broker.hivemq.com", 1883)
client.subscribe("home/temperature")
client.loop_start()
for i in range(100):
client.publish("home/temperature", f"Temp {i}")
This code connects to an MQTT broker, subscribes to a topic, and publishes 100 messages.
Look at what repeats in this code.
- Primary operation: Publishing messages in a loop.
- How many times: 100 times, once per loop iteration.
As the number of messages to send grows, the time to send them grows roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 publish calls |
| 100 | 100 publish calls |
| 1000 | 1000 publish calls |
Pattern observation: The time grows directly with the number of messages sent.
Time Complexity: O(n)
This means if you double the messages, the time to send them roughly doubles too.
[X] Wrong: "MQTT sends all messages instantly no matter how many devices or messages there are."
[OK] Correct: Each message takes some time to send, so more messages mean more time. MQTT is efficient but not instant.
Understanding how MQTT scales with message count helps you explain real IoT system behavior clearly and confidently.
"What if we changed the code to publish messages in parallel using multiple threads? How would the time complexity change?"