Rate limiting and cost analysis

Intermediate · 9 min

Request counts are the wrong unit for GraphQL. Limit per field, budget by query cost, choose the right key, and enforce limits in front of the server.

Before thisQuery depth and complexity limitsContext and resolver arguments

Ben Awad · 9 min

Rate limiting and cost analysis

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Ben AwadReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Counting HTTP requests treats a one-field query and a thousand-field query the same, so GraphQL needs limits that follow work, not requests.
  • A resolver-level rate limiter counts calls to a specific field per key, such as a user id or IP, within a time window.
  • A cost budget charges each operation by its estimated cost and refills over time, so heavy queries spend more than light ones.
  • Choose the key carefully: IP for anonymous callers, user id for signed-in ones, and watch for many users behind one address.
  • Enforce limits at a gateway or CDN as well, because anything that runs inside the resolver has already paid for parsing and validation.

Requests are the wrong unit

A REST API with a thousand endpoints can rate limit on the route: so many calls to /search per minute. GraphQL has one endpoint. Every request, cheap or ruinous, arrives at POST /graphql. A limit of sixty requests a minute lets a client send sixty { __typename } calls, which cost nothing, or sixty queries that each fan out across the database.

Depth and cost limits cap how big one query can be. A rate limit caps how much a client can spend over time. You need both, because a single legal query repeated fast is still a flood.

There are two practical ways to count in GraphQL: per field, and by cost.

Per-field limits

Some fields deserve their own limit regardless of query size: a login mutation, a password reset, an email sender, an expensive search. You attach the limit to the field and count calls per key in a time window.

I ran this with @envelop/rate-limiter 11.0.1 inside GraphQL Yoga 6.1.0. The directive has to exist in your SDL, because the plugin looks for it:

const typeDefs = `
  directive @rateLimit(max: Int, window: String, message: String) on FIELD_DEFINITION
  type Query { now: String! @rateLimit(max: 2, window: "1m", message: "slow down") }
`;

const yoga = createYoga({
  schema: createSchema({ typeDefs, resolvers }),
  plugins: [useRateLimiter({ identifyFn: (ctx) => "client-1" })],
});

Calling { now } three times produced two normal responses and then:

{"errors":[{"message":"slow down","locations":[{"line":1,"column":3}],"path":["now"]}]}

The first attempt failed with “Unknown directive @rateLimit”, so declaring the directive is not optional. The identifyFn is the important decision. It returns the key that gets counted, and I hard-coded one for the demo. Real code reads the context: user id when signed in, otherwise the client IP from a trusted proxy header. Keying only by IP penalises everyone behind a shared office address and does nothing against a botnet; keying only by user does nothing for login attempts, where there is no user yet. A login limiter commonly uses both the IP and the targeted account.

The built-in store is in memory. That is fine for one process and wrong for several, because each instance counts separately and a client gets max times the number of servers. Multiple instances need a shared store such as Redis, and the library exports a RedisStore next to its InMemoryStore (I found it in the package types and did not run it).

Ben Awad’s video builds the same idea from first principles in a resolver function: a key, a counter, a window and a rejection. Seeing it written by hand shows why the directive version works.

Cost budgets

Per-field limits do not stop a client from spending heavily across many different fields. A cost budget assigns each operation a cost, charges it to the caller’s bucket, and refuses when the bucket is empty. The bucket refills over time. A trivial query spends one unit, a deep fan-out spends hundreds.

The cost comes from the same static analysis as the previous lesson: field weights, list sizes from first arguments, depth factors. GitHub’s public API popularised this in the GraphQL world with a points system. A client can ask the API what a query would cost, and responses include how much budget remains. Reporting remaining budget in response extensions is friendly, because clients can slow themselves down before being refused.

The catch is accuracy. A static estimate is an upper bound, and it is only as good as your weights. The honest approach is to start with generous defaults, log the estimated cost beside the real latency, and tune the weights from that data. I did not build a bucket-based cost limiter in this session. This part is docs and the research literature, not a verified run, and the video does not cover it either.

Where to enforce it

Limits inside a resolver only run after the request was parsed, validated and routed. Put coarse protection in front: a CDN or gateway rate limit per IP stops floods before they reach Node. Then keep the GraphQL-aware limits, per field and per cost, in the server, where they can see operations. With a router, operation-aware limits can sit there so every subgraph benefits. For load numbers to set limits from, see load testing APIs.

Return something clients can act on: a clear message, an extensions.code such as RATE_LIMITED, and an HTTP Retry-After header where your transport allows. See errors and partial responses for the shape.

What the video covers

Ben Awad’s “How to Rate Limit GraphQL Resolvers” is an 8-minute video from May 2019. Its chapters are: intro, rate limit function, rate limit key, rate limit IP, rate limit increment, other options, and anonymous users. That is the per-field half of this lesson, written from scratch. It is seven years older than the plugin versions above and covers only per-resolver counting, not cost analysis, so the cost-budget section stands on the lesson’s prose alone. Denis Jannot’s gateway-level video under “go deeper” is a vendor demo of Gloo Gateway, included as the contrast case of enforcing limits outside the server. I could not read transcripts for either.

Where this fits

Rate limits bound how often a client can ask. Next, persisted queries narrow what a client is allowed to ask in the first place.

Check yourself

  1. 01Why is a requests-per-minute limit a poor fit for GraphQL?

    Every request hits one URL, and one request can contain a trivial query or a very expensive one, so the count does not reflect the work done.

  2. 02What key would you rate limit by for a login mutation, and why?

    The client IP or the targeted account name, because there is no signed-in user yet and the goal is to slow brute-force attempts.

  3. 03What is the difference between a depth or cost limit and a rate limit?

    The first caps the size of one query. The second caps how many queries, or how much total cost, one client can spend over time.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark