Shared types across subgraphs in GraphQL - Time & Space Complexity
When using shared types across subgraphs in GraphQL, it's important to understand how the execution time changes as the number of subgraphs and shared types grow.
We want to know how the system handles queries involving these shared types as the input size increases.
Analyze the time complexity of this GraphQL schema snippet using shared types across subgraphs.
type Product @key(fields: "id") {
id: ID!
name: String
price: Float
}
extend type Review @key(fields: "id") {
id: ID! @external
product: Product @requires(fields: "productId")
}
This snippet shows a shared type Product used in multiple subgraphs, with Review extending it by referencing Product.
Look for repeated actions that affect performance.
- Primary operation: Resolving shared type fields across subgraphs during query execution.
- How many times: Once per query involving the shared type, and once per related entity that references it.
As the number of entities referencing shared types grows, the operations increase proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 resolutions of shared type fields |
| 100 | About 100 resolutions |
| 1000 | About 1000 resolutions |
Pattern observation: The number of operations grows linearly with the number of entities referencing the shared type.
Time Complexity: O(n)
This means the time to resolve shared types grows in direct proportion to how many related entities are queried.
[X] Wrong: "Resolving shared types happens only once, so it doesn't affect performance much."
[OK] Correct: Each entity referencing the shared type triggers its own resolution, so the cost adds up with more entities.
Understanding how shared types affect query execution helps you design efficient GraphQL schemas and anticipate performance as your data grows.
What if we cached shared type resolutions? How would that change the time complexity?