Topic-based messaging in Firebase - Time & Space Complexity
When sending messages to many devices using topics, it is important to know how the time to send grows as more devices subscribe.
We want to understand how the number of devices affects the work done by Firebase when sending a topic message.
Analyze the time complexity of the following operation sequence.
const message = {
topic: 'news',
notification: {
title: 'Hello',
body: 'World'
}
};
admin.messaging().send(message)
.then(response => console.log('Sent message:', response))
.catch(error => console.error('Error sending message:', error));
This code sends a notification message to all devices subscribed to the 'news' topic.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: Sending one message to the topic via Firebase API.
- How many times: The send call is made once per message, but Firebase internally delivers to all subscribed devices.
As the number of devices subscribed to the topic grows, Firebase must deliver the message to each device.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 1 send call, 10 device deliveries |
| 100 | 1 send call, 100 device deliveries |
| 1000 | 1 send call, 1000 device deliveries |
Pattern observation: The single API call triggers work that grows linearly with the number of subscribed devices.
Time Complexity: O(n)
This means the work to deliver messages grows in direct proportion to the number of devices subscribed to the topic.
[X] Wrong: "Sending one message to a topic is always a single quick operation regardless of subscribers."
[OK] Correct: Although the API call is one, Firebase must deliver the message to every subscribed device, so the total work grows with the number of devices.
Understanding how message delivery scales with subscribers helps you design efficient notification systems and answer questions about system behavior under load.
"What if we send messages to multiple topics at once? How would the time complexity change?"