Publish-subscribe architecture in IOT Protocols - Time & Space Complexity
We want to understand how the work done by a publish-subscribe system grows as more devices or messages are involved.
How does the system handle more subscribers or more messages efficiently?
Analyze the time complexity of the following publish-subscribe message dispatch code.
// Pseudocode for message dispatch in publish-subscribe
function publish(topic, message) {
subscribers = getSubscribers(topic);
for each subscriber in subscribers {
sendMessage(subscriber, message);
}
}
This code sends a message to all subscribers of a given topic.
Look for repeated actions that take most time.
- Primary operation: Loop over all subscribers to send messages.
- How many times: Once for each subscriber subscribed to the topic.
As the number of subscribers grows, the number of send operations grows the same way.
| Input Size (subscribers) | Approx. Operations (sendMessage calls) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows directly with the number of subscribers.
Time Complexity: O(n)
This means the time to send messages grows linearly with the number of subscribers.
[X] Wrong: "Sending one message to a topic always takes the same time, no matter how many subscribers there are."
[OK] Correct: Each subscriber must receive the message, so more subscribers mean more send operations and more time.
Understanding how message dispatch scales helps you design systems that handle many devices smoothly. This skill shows you can think about system growth and efficiency.
What if the system cached messages and sent them in batches? How would that change the time complexity?