GraphQL rate limiting and depth limiting setup

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
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:
Development stages
Latest works
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    847
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    451

Rate Limiting and Depth Limiting for GraphQL API

GraphQL allows clients to form arbitrarily complex queries. Without restrictions, single query can request millions of records through nested relations or create CPU-killer query with nesting depth of 50 levels. GraphQL rate limiting differs from REST: cannot just count requests — must account for complexity.

Depth Limiting

Limit maximum AST tree nesting depth:

import depthLimit from 'graphql-depth-limit'
import { ApolloServer } from '@apollo/server'

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [
    depthLimit(7)  // maximum 7 levels nesting
  ]
})

Attack without depth limit:

# This query is legal but recursively creates millions of objects
{
  user {
    friends {
      friends {
        friends {
          friends {
            friends { id name }
          }
        }
      }
    }
  }
}

Query Complexity

Depth doesn't account for query width. graphql-query-complexity counts total cost:

import { createComplexityLimitRule } from 'graphql-query-complexity'
import { fieldExtensionsEstimator, simpleEstimator } from 'graphql-query-complexity'

const complexityRule = createComplexityLimitRule(1000, {
  estimators: [
    // Take complexity from SDL @complexity directive
    fieldExtensionsEstimator(),

    // Account for pagination arguments
    ({
      type, field, args, childComplexity
    }) => {
      if (args.limit) {
        return args.limit * childComplexity
      }
      if (args.first) {
        return args.first * childComplexity
      }
      return 1 + childComplexity
    },

    // Base field cost = 1
    simpleEstimator({ defaultComplexity: 1 })
  ],

  onSuccess: (complexity) => {
    console.log(`Query complexity: ${complexity}`)
  },

  formatErrorMessage: (complexity) =>
    `Query too complex (${complexity}). Max allowed: 1000`
})

const server = new ApolloServer({
  typeDefs,
  resolvers,
  validationRules: [
    depthLimit(7),
    complexityRule
  ]
})

Complexity in SDL with Directives

directive @complexity(value: Int!, multipliers: [String!]) on FIELD_DEFINITION

type Query {
  # Simple field: complexity 1
  user(id: ID!): User

  # List: complexity = first * childComplexity
  posts(first: Int = 10): [Post!]! @complexity(value: 1, multipliers: ["first"])

  # Expensive operation: complexity 10
  searchUsers(query: String!): [User!]! @complexity(value: 10)
}

Rate Limiting by Operation

// Different limits for different operation types
class GraphQLRateLimiter {
  constructor(redis) {
    this.r = redis
  }

  async checkRequest(userId, operationName, complexity) {
    const now = Math.floor(Date.now() / 1000)
    const minute = now - (now % 60)

    // 1. Limit by number of operations (requests) per minute
    const opsKey = `gql:ops:${userId}:${minute}`