Subscription lifecycle in GraphQL - Time & Space Complexity
When working with subscription lifecycles in GraphQL, it is important to understand how the time to process events grows as more subscriptions or events occur.
We want to know how the system handles increasing numbers of subscription events over time.
Analyze the time complexity of the following subscription lifecycle snippet.
subscription onNewMessage {
messageAdded {
id
content
sender {
id
name
}
}
}
This subscription listens for new messages and fetches details about each message and its sender when a new message is added.
In this subscription lifecycle, the main repeating operation is the event trigger for each new message.
- Primary operation: Processing each new message event and resolving its fields.
- How many times: Once per new message event received by the subscription.
As the number of new messages increases, the system processes each event one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 message events processed |
| 100 | 100 message events processed |
| 1000 | 1000 message events processed |
Pattern observation: The number of operations grows directly with the number of new messages received.
Time Complexity: O(n)
This means the time to process subscription events grows linearly with the number of new messages.
[X] Wrong: "The subscription processes all messages at once regardless of how many arrive."
[OK] Correct: Each message event triggers processing separately, so time grows with the number of messages, not fixed.
Understanding how subscription events scale helps you design responsive real-time systems and shows you can reason about event-driven data flow.
"What if the subscription also fetched a list of all previous messages on each event? How would the time complexity change?"