Field-level cost analysis helps you understand how much work each part of a GraphQL query takes. This helps keep your server fast and avoid overload.
0
0
Field-level cost analysis in GraphQL
Introduction
When you want to find which fields in a query use the most resources.
When you need to limit expensive queries to protect your server.
When you want to optimize your GraphQL API for better performance.
When you want to give feedback to clients about costly queries.
When you want to monitor and track query costs over time.
Syntax
GraphQL
type Query {
fieldName: FieldType @cost(complexity: Int, multipliers: [String])
}The @cost directive is used to assign a cost to a field.
complexity is the base cost number for the field.
Examples
This sets the cost of the
books field to 5.GraphQL
type Query {
books: [Book] @cost(complexity: 5)
}The cost depends on the
id argument, multiplying the base cost.GraphQL
type Query {
author(id: ID!): Author @cost(complexity: 2, multipliers: ["id"])
}Sample Program
This schema assigns costs to users and posts fields. The posts cost multiplies by the userId argument.
The sample query fetches users and posts for user 123.
GraphQL
type Query {
users: [User] @cost(complexity: 3)
posts(userId: ID!): [Post] @cost(complexity: 2, multipliers: ["userId"])
}
# Sample query
{
users {
id
name
}
posts(userId: "123") {
title
}
}OutputSuccess
Important Notes
Costs help prevent very expensive queries from slowing down your server.
Multipliers let you adjust cost based on input values, like list sizes.
Always test your cost settings to balance protection and usability.
Summary
Field-level cost analysis assigns a cost number to each GraphQL field.
This helps track and limit query resource use.
Use @cost directive with complexity and optional multipliers.