Directive-based authorization in GraphQL - Time & Space Complexity
When using directive-based authorization in GraphQL, it's important to understand how the time to check permissions grows as the number of fields or queries increases.
We want to know how the authorization checks affect the overall execution time.
Analyze the time complexity of this GraphQL schema snippet using directive-based authorization.
directive @auth(role: String) on FIELD_DEFINITION
type Query {
user(id: ID!): User @auth(role: "ADMIN")
posts: [Post] @auth(role: "USER")
}
type User {
id: ID!
name: String
}
This snippet shows fields protected by an @auth directive that checks user roles before returning data.
Look for repeated checks or loops in the authorization process.
- Primary operation: Authorization check for each field with @auth directive.
- How many times: Once per field requested in the query that has the directive.
As the number of fields requested with @auth increases, the number of authorization checks grows linearly.
| Input Size (fields with @auth) | Approx. Operations (auth checks) |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The number of authorization checks grows directly with the number of protected fields requested.
Time Complexity: O(n)
This means the time to check authorization grows in a straight line as more protected fields are requested.
[X] Wrong: "Authorization checks happen once per query, no matter how many fields are protected."
[OK] Correct: Each protected field triggers its own check, so more fields mean more checks and more time.
Understanding how authorization scales helps you design efficient APIs and explain your reasoning clearly in interviews.
What if the authorization directive cached results per user session? How would that change the time complexity?