Unsubscribing in GraphQL - Time & Space Complexity
When working with GraphQL subscriptions, it is important to understand how the time to unsubscribe grows as more subscriptions exist.
We want to know how the cost of stopping a subscription changes when there are many active subscriptions.
Analyze the time complexity of the following GraphQL unsubscribe operation.
mutation Unsubscribe($id: ID!) {
unsubscribe(subscriptionId: $id) {
success
message
}
}
This mutation stops a subscription by its unique ID, removing it from the active subscriptions list.
Look for loops or repeated checks during the unsubscribe process.
- Primary operation: Searching the list of active subscriptions to find the one with the matching ID.
- How many times: This search may check each subscription once until it finds the match.
As the number of active subscriptions grows, the time to find the one to unsubscribe grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of operations grows roughly in direct proportion to the number of subscriptions.
Time Complexity: O(n)
This means the time to unsubscribe grows linearly with the number of active subscriptions.
[X] Wrong: "Unsubscribing always takes the same time no matter how many subscriptions exist."
[OK] Correct: Because the system usually searches through the list to find the subscription, more subscriptions mean more checks and longer time.
Understanding how unsubscribe operations scale helps you design efficient real-time systems and shows you can think about performance in practical ways.
"What if the subscriptions were stored in a map keyed by ID instead of a list? How would the time complexity change?"