Publish-subscribe for broadcasting in RabbitMQ - Time & Space Complexity
We want to understand how the work grows when broadcasting messages using publish-subscribe in RabbitMQ.
Specifically, how does the number of messages and subscribers affect the processing time?
Analyze the time complexity of the following RabbitMQ publish-subscribe setup.
channel.exchange_declare(exchange='logs', exchange_type='fanout')
result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue
channel.queue_bind(exchange='logs', queue=queue_name)
channel.basic_publish(exchange='logs', routing_key='', body=message)
This code declares a fanout exchange, binds a temporary queue to it, and publishes a message to broadcast to all bound queues.
Look at what repeats when a message is published.
- Primary operation: Delivering the message to each bound queue (subscriber).
- How many times: Once per subscriber queue bound to the exchange.
As the number of subscribers grows, the work to deliver the message grows too.
| Number of Subscribers (n) | Approx. Operations |
|---|---|
| 10 | 10 message deliveries |
| 100 | 100 message deliveries |
| 1000 | 1000 message deliveries |
Pattern observation: The number of deliveries grows directly with the number of subscribers.
Time Complexity: O(n)
This means the time to broadcast a message grows linearly with the number of subscribers.
[X] Wrong: "Publishing one message always takes the same time, no matter how many subscribers there are."
[OK] Correct: Each subscriber queue must receive a copy, so more subscribers mean more work and more time.
Understanding how message delivery scales helps you explain system behavior and design choices clearly in real projects.
"What if we changed the exchange type from fanout to direct with multiple routing keys? How would the time complexity change?"