Topic exchange (pattern matching) in RabbitMQ - Time & Space Complexity
We want to understand how the time to route messages grows as more bindings and messages are involved in a topic exchange.
Specifically, how does RabbitMQ match routing keys to patterns as the system scales?
Analyze the time complexity of the following topic exchange routing logic.
channel.exchangeDeclare("topic_logs", "topic");
channel.queueBind(queueName, "topic_logs", "kern.*");
channel.queueBind(queueName, "topic_logs", "*.critical");
channel.basicPublish("topic_logs", "kern.critical", null, message.getBytes());
channel.basicPublish("topic_logs", "auth.info", null, message.getBytes());
This code declares a topic exchange, binds queues with patterns, and publishes messages with routing keys.
When a message is published, RabbitMQ checks each binding pattern to see if it matches the routing key.
- Primary operation: Pattern matching of routing keys against all binding keys.
- How many times: Once per binding pattern for each message.
As the number of binding patterns (n) increases, the number of pattern checks grows roughly in direct proportion.
| Input Size (n bindings) | Approx. Operations (pattern matches) |
|---|---|
| 10 | 10 pattern checks |
| 100 | 100 pattern checks |
| 1000 | 1000 pattern checks |
Pattern observation: Doubling the number of bindings doubles the matching work per message.
Time Complexity: O(n)
This means the time to route a message grows linearly with the number of binding patterns.
[X] Wrong: "Routing a message takes constant time regardless of bindings."
[OK] Correct: Each message must be checked against all binding patterns, so more bindings mean more work.
Understanding how message routing scales helps you design efficient messaging systems and shows you can reason about system performance.
"What if RabbitMQ used a hash map to index binding patterns? How would that affect the time complexity?"