GraphQL

GraphQL (Apollo)

Per-operation rate limits through an Apollo Server plugin.

The GraphQL adapter is now published as halt-rate/graphql (formerly a deep import). It hooks into Apollo Server's plugin lifecycle to check Halt per operation and rejects with a GraphQL error when a limit is exceeded.

1. Installation

npm install halt-rate @apollo/server

2. Basic setup

import { ApolloServer } from '@apollo/server';
import { RateLimiter, InMemoryStore, presets } from 'halt-rate';
import { haltApolloPlugin } from 'halt-rate/graphql';

const limiter = new RateLimiter({
  store: new InMemoryStore(),
  policy: presets.PUBLIC_API,
});

const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [haltApolloPlugin({ limiter })],
});

3. Per-operation cost

Pass cost to charge expensive operations more works with the same weighted-endpoint mechanism Halt uses elsewhere:

plugins: [
  haltApolloPlugin({
    limiter,
    cost: (ctx) => ctx.operationName === 'ExpensiveReport' ? 10 : 1,
  }),
],

Production setup

Pair the adapter with the Redis store for atomic distributed limits and a telemetry hook so each GraphQL operation appears in metrics tagged with its name.