GraphQL Rate Limiting and Depth Limiting Setup

GraphQL gives clients great flexibility, but that same flexibility makes the API vulnerable. A single query with 50 levels of nesting and hundreds of aliases can generate millions of objects, hammering the CPU and database. We've encountered cases where an unrestricted endpoint collapsed under just

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:

Frequently Asked Questions

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1414
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1285
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    982
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1241
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    982
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    995

GraphQL gives clients great flexibility, but that same flexibility makes the API vulnerable. A single query with 50 levels of nesting and hundreds of aliases can generate millions of objects, hammering the CPU and database. We've encountered cases where an unrestricted endpoint collapsed under just a couple of requests per minute. According to the official GraphQL documentation, protection against such aspects is mandatory for production releases. Comprehensive protection demands depth limiting (nesting restriction), query complexity (operation cost), and rate limiting (request throttling) – three key mechanisms we implement. Depth limiting is 3× more effective than naive time-based restrictions. Within 1-2 business days, we configure these limits for your API.

What Problems We Solve

Without limits, a GraphQL API is prone to DoS attacks. An attacker can send a single query with recursive nesting (user → friends → friends...) that forces the database to execute thousands of JOINs. Or via aliases, they request the same field 500 times, simulating a DDoS. Another vector is expensive operations like search or export that consume many resources. We solve these problems comprehensively using depth limiting, query complexity, and rate limiting. The combination of these three methods is 10× more effective against DoS attacks than any single layer. The cost of such attacks can reach lost revenue due to downtime — for example, a 30-minute outage may cost $10,000 for an e-commerce site, so protection pays off quickly. For a medium-sized deployment, this setup reduces hosting costs by approximately $5,000 per year.

How to Configure Depth Limiting?

Depth limiting restricts the maximum nesting level of the query's AST tree. We set a threshold of 7 levels — enough for typical schemas but blocking recursive queries. For most schemas, a threshold of 7 is optimal: it covers 99% of legitimate queries.

import depthLimit from 'graphql-depth-limit' import { ApolloServer } from '@apollo/server' const server = new ApolloServer({ typeDefs, resolvers, validationRules: [ depthLimit(7) ] }) 

An attack without depth limit looks like:

{ user { friends { friends { friends { friends { friends { id name } } } } } } } 

Why Is Query Complexity Check Important?

Depth does not account for query breadth: a query with depth 2 but requesting 10,000 records via pagination is also dangerous. Query complexity calculates the total cost using multipliers for pagination arguments. Compare three approaches in the table:

Method What It Limits Example Effectiveness Against Recursion Effectiveness Against Breadth
Depth Limiting Nesting depth user → friends → posts → comments High Low
Query Complexity Total cost posts(first: 100) × 2 (child) + ... Medium High
Rate Limiting Operations count and complexity budget 200 requests/min, 10,000 complexity Low (complementary) Medium (complementary)

Query complexity is 5× more effective for breadth attacks than depth limiting alone.

import { createComplexityLimitRule } from 'graphql-query-complexity' import { fieldExtensionsEstimator, simpleEstimator } from 'graphql-query-complexity' const complexityRule = createComplexityLimitRule(1000, { estimators: [ fieldExtensionsEstimator(), ({ type, field, args, childComplexity }) => { if (args.limit) return args.limit * childComplexity if (args.first) return args.first * childComplexity return 1 + childComplexity }, simpleEstimator({ defaultComplexity: 1 }) ], onSuccess: (complexity) => console.log(`Query complexity: ${complexity}`), formatErrorMessage: (complexity) => `Query too complex (${complexity}). Max allowed: 1000` }) 

Comparison of GraphQL protection libraries:

Library Depth Complexity Aliases Setup Time
graphql-depth-limit + - - 1 hour
graphql-query-complexity - + - 2 hours
graphql-armor + + + 3 hours

Rate Limiting with Redis

Rate limiting in GraphQL considers both request count and complexity. We use Redis for counters: a limit on operations (200 ops/min) and on total complexity (10,000). For expensive operations (SearchUsers, ExportData), we set separate limits — up to 5 calls per minute.

class GraphQLRateLimiter { constructor(redis) { this.r = redis } async checkRequest(userId, operationName, complexity) { const now = Math.floor(Date.now() / 1000) const minute = now - (now % 60) const opsKey = `gql:ops:${userId}:${minute}` const ops = await this.r.incr(opsKey) this.r.expire(opsKey, 120) if (ops > 200) { throw new GraphQLError('Too many requests', { extensions: { code: 'RATE_LIMITED', retryAfter: 60 } }) } const complexityKey = `gql:complexity:${userId}:${minute}` const totalComplexity = await this.r.incrby(complexityKey, complexity) this.r.expire(complexityKey, 120) if (totalComplexity > 10000) { throw new GraphQLError('Query complexity budget exceeded', { extensions: { code: 'COMPLEXITY_LIMITED', retryAfter: 60 } }) } const expensiveOps = ['SearchUsers', 'ExportData', 'GenerateReport'] if (expensiveOps.includes(operationName)) { const expKey = `gql:expensive:${userId}:${minute}` const expCount = await this.r.incr(expKey) this.r.expire(expKey, 120) if (expCount > 5) { throw new GraphQLError(`Too many ${operationName} calls`, { extensions: { code: 'RATE_LIMITED' } }) } } return { allowed: true, remainingOps: 200 - ops } } } 
Example graphql-armor configuration
import { createArmor } from '@escape.tech/graphql-armor' const armor = createArmor({ maxAliases: { n: 15 }, maxDirectives: { n: 50 }, maxDepth: { n: 7 }, maxTokens: { n: 1000 }, costLimit: { maxCost: 5000, objectCost: 2, scalarCost: 1, depthCostFactor: 1.5, ignoreIntrospection: true } }) const server = new ApolloServer({ typeDefs, resolvers, plugins: [...armor.plugins], validationRules: [...armor.validationRules] }) 

We also disable introspection in production so the schema is not public.

Process Overview

  1. Analysis — Study the GraphQL schema, identify expensive fields and typical query patterns. Determine critical points.
  2. Design — Set depth, complexity, and frequency thresholds based on your traffic patterns and peak loads.
  3. Implementation — Deploy depth limiting, query complexity, rate limiting with Redis, and aliases protection. Configure monitoring.
  4. Testing — Simulate attacks and verify legitimate queries pass. Use load testing tools.
  5. Deployment — Set up alerts for limit breaches and document the configuration.

What's Included

  • Library setup (graphql-depth-limit, graphql-query-complexity, graphql-armor)
  • Redis integration for rate limiting
  • Custom limit configuration for your schema
  • Operations documentation
  • Team training (1 hour)
  • Post-deployment support (2 weeks)

Timeline and Pricing

Setup takes from 1 to 2 business days. Pricing is individual — depends on schema complexity and number of endpoints. Typical projects range from $1,500 to $4,000. Protection can save up to 30% on infrastructure budget — for example, reducing server costs by $500/month, or $6,000 per year. Contact us for a free consultation and detailed analysis.

We guarantee: after implementation, no query will exceed limits without a clear error. Backed by years of experience and 50+ projects.