Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Field-level Cost Analysis in GraphQL
📖 Scenario: You work for an online store that uses GraphQL to fetch product data. The company wants to analyze the cost impact of fetching specific fields in product queries to optimize performance and reduce server load.
🎯 Goal: Build a GraphQL query and configuration that tracks the cost of fetching each field in a product query. You will create a simple cost map, apply it to a query, and finalize the cost analysis setup.
📋 What You'll Learn
Create a GraphQL query for products with specific fields
Define a cost map for each field in the product query
Apply the cost map to calculate total query cost
Complete the cost analysis configuration
💡 Why This Matters
🌍 Real World
Companies use field-level cost analysis to optimize GraphQL queries, reducing server load and improving response times.
💼 Career
Understanding query cost helps backend developers and API designers create efficient and scalable GraphQL APIs.
Progress0 / 4 steps
1
Create the Product Query
Write a GraphQL query called productQuery that fetches id, name, and price fields from products.
GraphQL
Hint
Use backticks to create a multi-line string for the query. Include the fields exactly as id, name, and price.
2
Define Field Cost Map
Create a constant object called fieldCostMap that assigns the cost 1 to id, 2 to name, and 3 to price.
GraphQL
Hint
Create an object with keys id, name, and price and assign the costs as numbers.
3
Calculate Total Query Cost
Write a function called calculateQueryCost that takes an array of field names and returns the sum of their costs using fieldCostMap. Then, create a variable totalCost that calculates the cost of ['id', 'name', 'price'].
GraphQL
Hint
Loop over the array of fields, add each field's cost from fieldCostMap to a total, and return it.
4
Complete Cost Analysis Configuration
Create an object called costAnalysisConfig with two properties: query set to productQuery and totalCost set to the totalCost variable.
GraphQL
Hint
Create an object with keys query and totalCost assigned to the existing variables.
Practice
(1/5)
1. What is the main purpose of using the @cost directive in GraphQL field-level cost analysis?
easy
A. To rename a field in the schema
B. To define the data type of a field
C. To specify the default value of a field
D. To assign a numeric cost to each field to track resource usage
Solution
Step 1: Understand the purpose of field-level cost analysis
Field-level cost analysis helps monitor and limit resource use by assigning costs to fields.
Step 2: Identify the role of the @cost directive
The @cost directive assigns a numeric complexity cost to each field to estimate query cost.
Final Answer:
To assign a numeric cost to each field to track resource usage -> Option D
Quick Check:
@cost assigns cost = A [OK]
Hint: Remember: @cost tracks resource use per field [OK]
Common Mistakes:
Confusing cost with data type definition
Thinking @cost renames fields
Assuming it sets default values
2. Which of the following is the correct syntax to add a cost directive with complexity 5 to a GraphQL field named books?
easy
A. books: [Book] @cost(complexity: 5)
B. books: [Book] @cost(5)
C. books: [Book] @cost(complexity=5)
D. books: [Book] @cost { complexity: 5 }
Solution
Step 1: Recall the correct directive syntax
The @cost directive uses parentheses with named arguments, e.g., @cost(complexity: 5).
Step 2: Check each option's syntax
books: [Book] @cost(complexity: 5) uses correct syntax with named argument and colon. The other three options use incorrect syntax forms.
Final Answer:
books: [Book] @cost(complexity: 5) -> Option A
Quick Check:
Correct directive syntax = B [OK]
Hint: Use parentheses and colon for directive args: @cost(complexity: 5) [OK]
Common Mistakes:
Using equal sign instead of colon
Omitting parentheses
Using braces instead of parentheses
3. Given the schema snippet:
type Query {
users: [User] @cost(complexity: 2, multipliers: ["first"])
}
input UserFilter {
first: Int
}
And the query:
{ users(first: 3) { id name } }
What is the total cost of this query assuming id and name fields have cost 1 each?
medium
A. 3
B. 6
C. 8
D. 5
Solution
Step 1: Calculate base complexity and multipliers
Base complexity is 2. The multiplier is the argument "first" with value 3, so multiply 2 * 3 = 6.
Step 2: Add cost of requested fields
Fields id and name each cost 1, total 2. Add to 6 gives 8.
Final Answer:
8 -> Option C
Quick Check:
2 * 3 + 1 + 1 = 8 [OK]
Hint: Multiply complexity by argument, then add field costs [OK]
Common Mistakes:
Ignoring multipliers
Not adding field costs
Multiplying fields cost instead of adding
4. Consider this incorrect directive usage:
type Query {
posts: [Post] @cost(complexity: "high")
}
What is the main error here?
medium
A. The complexity value must be an integer, not a string
B. The field name posts is invalid
C. The directive @cost cannot be used on lists
D. The directive syntax is missing parentheses
Solution
Step 1: Check the type of complexity argument
The complexity argument expects an integer value, but "high" is a string.
Step 2: Verify other parts of the directive usage
The field name and directive usage are valid; parentheses are present.
Final Answer:
The complexity value must be an integer, not a string -> Option A
Quick Check:
Complexity expects integer = D [OK]
Hint: Complexity must be a number, not text [OK]
Common Mistakes:
Using string instead of integer for complexity
Thinking directive can't be on lists
Missing parentheses in directive
5. You have a GraphQL field comments with @cost(complexity: 1, multipliers: ["limit"]). The query requests comments(limit: 4) with subfields text and author, each costing 2. What is the total cost of this query?
hard
A. 12
B. 8
C. 10
D. 6
Solution
Step 1: Calculate base complexity with multiplier
Base complexity is 1. Multiplier is argument "limit" with value 4, so 1 * 4 = 4.
Step 2: Add cost of subfields
Subfields text and author each cost 2, total 4. Add to 4 gives 8.
Step 3: Verify the total
Subfields are added flatly without further multiplication by list size: 4 (base) + 4 (subfields) = 8.
Final Answer:
8 -> Option B
Quick Check:
1*4 + (2+2) = 8 [OK]
Hint: Add base cost times multiplier plus subfields cost [OK]
Common Mistakes:
Multiplying subfields cost by multiplier (e.g., getting 20)