Subscription resolvers in GraphQL - Time & Space Complexity
When using subscription resolvers in GraphQL, it's important to understand how the time to process events grows as more clients subscribe or more events occur.
We want to know how the work done changes when the number of subscribers or events increases.
Analyze the time complexity of the following subscription resolver code snippet.
subscription {
messageAdded(roomId: "123") {
id
content
sender
}
}
// Resolver listens for new messages in a chat room and pushes updates to subscribers.
This code listens for new messages in a chat room and sends updates to all clients subscribed to that room.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Sending updates to each subscriber when a new message arrives.
- How many times: Once per new message, repeated for every subscriber in the room.
As the number of subscribers grows, the work to send updates grows too.
| Input Size (subscribers) | Approx. Operations (send updates) |
|---|---|
| 10 | 10 sends per message |
| 100 | 100 sends per message |
| 1000 | 1000 sends per message |
Pattern observation: The number of operations grows directly with the number of subscribers.
Time Complexity: O(n)
This means the time to send updates grows linearly with the number of subscribers.
[X] Wrong: "Sending updates to subscribers happens instantly no matter how many there are."
[OK] Correct: Each subscriber needs its own update, so more subscribers mean more work and more time.
Understanding how subscription resolvers scale helps you explain real-time data flow and performance in apps, a useful skill for many projects.
"What if we batch updates to subscribers instead of sending individually? How would the time complexity change?"