Query Cost Analysis and Rate Limiting
What you'll learn: How to assign cost scores to GraphQL operations and use rate limiting to prevent resource exhaustion attacks.
The Problem
In the previous lesson, you learned attackers can craft deeply nested or complex GraphQL queries. But how do you measure and control that complexity in practice? Simply blocking deep queries isn't enough—attackers can send many medium-complexity queries that together overwhelm your server.
Query Complexity Scoring
Each GraphQL field operation consumes server resources (database calls, CPU cycles, memory). Query cost analysis assigns a numerical "cost" to each field based on its resource intensity.
Simple example scoring:
user.name= 1 point (simple field lookup)user.orders= 5 points (database query for list)user.orders.items= 3 points per order (nested query multiplier)
A query fetching 100 orders with items each might score: 5 + (100 × 3) = 305 points. You set a maximum threshold (e.g., 1000 points per query) and reject anything exceeding it.
Rate Limiting Strategies
Beyond per-query limits, you need rate limiting across time windows:
- Request-based: Maximum 100 queries per minute per API key
- Cost-based: Maximum 10,000 cost points per hour (allows flexibility—cheap queries can run more often)
- Sliding window: Track usage over rolling time periods to prevent burst attacks
This prevents attackers from repeatedly hammering your API with moderately expensive queries.
Combined Defense
Use both together: reject individual expensive queries and limit cumulative resource consumption over time. Track costs per user, IP address, or API token. Adjust scoring based on real performance metrics from your infrastructure.
Key Takeaway: Query cost analysis assigns resource scores to GraphQL operations, while rate limiting controls cumulative usage over time—together they prevent both single-query and sustained resource exhaustion attacks.