graphql-armory 0.1.0.pre4 → 0.1.0.pre6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +18 -0
- data/README.md +6 -4
- data/docs/authorization.md +9 -1
- data/docs/encrypted-ids.md +20 -1
- data/docs/persisted-queries.md +23 -1
- data/docs/rate-limiting.md +344 -0
- data/docs/telemetry.md +226 -0
- data/lib/graphql/armory/authorization/configuration.rb +1 -0
- data/lib/graphql/armory/authorization.rb +5 -1
- data/lib/graphql/armory/encoder/null.rb +18 -0
- data/lib/graphql/armory/encoder/substitute.rb +47 -0
- data/lib/graphql/armory/encoder.rb +2 -0
- data/lib/graphql/armory/ids/controls.rb +24 -0
- data/lib/graphql/armory/ids.rb +32 -8
- data/lib/graphql/armory/persisted_queries/controls.rb +41 -0
- data/lib/graphql/armory/persisted_queries/store.rb +48 -0
- data/lib/graphql/armory/persisted_queries.rb +64 -30
- data/lib/graphql/armory/rate_limits/clock.rb +35 -0
- data/lib/graphql/armory/rate_limits/concurrency.rb +127 -0
- data/lib/graphql/armory/rate_limits/controls.rb +56 -0
- data/lib/graphql/armory/rate_limits/memory_store.rb +64 -0
- data/lib/graphql/armory/rate_limits/points.rb +126 -0
- data/lib/graphql/armory/rate_limits/redis_store.rb +133 -0
- data/lib/graphql/armory/rate_limits/store.rb +114 -0
- data/lib/graphql/armory/rate_limits/time.rb +209 -0
- data/lib/graphql/armory/rate_limits.rb +131 -0
- data/lib/graphql/armory/telemetry.rb +82 -0
- data/lib/graphql/armory/version.rb +1 -1
- data/lib/graphql/armory.rb +2 -0
- metadata +18 -2
- data/lib/graphql/armory/authorization/telemetry.rb +0 -42
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 1a108044cb6fe2eeb2557d7d315b3e16e4ff0d31d086b7421a958c3a1d4c664b
|
|
4
|
+
data.tar.gz: f756db6daa9fc11ec6b7f1de72757002f75555d9935d1876985aae9f4e6f7690
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: a4e6bd7f6cb48c4b2a864fbb06a2bf26fdf5a4944478092acfea14769cab1744696759fe930fd35409378f70844aa6a1397c552c3ee2561bf786c3121ddbff53
|
|
7
|
+
data.tar.gz: 44fa76ca88941a4ba55b604c04b61e2d5f52b8029e7b97bd918ce8e53f83e692c6f90de7f1bd4b3f4b82cf68f40412abc76cf21e0ddd1e5a9fbf2bf0fb682cb5
|
data/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,24 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 0.1.0.pre6 (2026-10-30)
|
|
6
|
+
|
|
7
|
+
Telemetry for every module, and the processing-time layer of rate limiting. Docs: `docs/telemetry.md`, `docs/rate-limiting.md`.
|
|
8
|
+
|
|
9
|
+
- Telemetry for every module. `GraphQL::Armory::Telemetry` (the class authorization already used, now shared; `Authorization::Telemetry` is the same class) takes `sinks:` in `use GraphQL::Armory::IDs` and `use GraphQL::Armory::PersistedQueries`, as it does in authorization. IDs record `:id_resolved` and `:id_refused` (with `reason`: `:invalid`, `:malformed`, `:unknown_type`, `:not_found`); persisted queries record `:operation_persisted`, `:operation_refused` (`:unknown_operation`, `:mismatch`, `:raw_query`), `:raw_query_run` and `:raw_query_allowed`. A signal never holds an ID, an operation id or a query. `Telemetry::Notifications` reports them to `ActiveSupport::Notifications` as `<signal>.graphql_armory`. A `sinks:` that is not an Array of callables now raises `Telemetry::ConfigurationError` at boot, also in authorization (before, at the first query); the message names the offending class and never prints the value. Every sink receives the same frozen data. New page `docs/telemetry.md`: every signal, what to watch for, how to test.
|
|
10
|
+
- Rate limiting, processing time: `use GraphQL::Armory::RateLimits::Time, store:, limit:, window: 60` charges each client the wall-clock milliseconds its operations took, against a bucket of milliseconds that refills over the window. A query analyzer refuses a client with no milliseconds left before any field resolves (`RATE_LIMITED`, with `retryAfter`); a trace measures the multiplex with a monotonic clock and charges it when it ends, even when it raises, split equally among its queries. Soft mode is the default; `extensions: true` adds `rateLimitTime` to the response and `Time.headers(result)` answers `RateLimit-Time-*`. It needs no store changes. `RateLimits::Clock::Substitute` and `Controls::Time.example` are there for your specs.
|
|
11
|
+
|
|
12
|
+
## 0.1.0.pre5 (2026-10-29)
|
|
13
|
+
|
|
14
|
+
Rate limiting (roadmap module 4). Docs: `docs/rate-limiting.md`. All four modules now follow the Useful Objects doctrine.
|
|
15
|
+
|
|
16
|
+
- Rate limiting, part 1: `use GraphQL::Armory::RateLimits::Points, store:, limit:, window:` charges each query its complexity against a bucket of points per client (`context[:rate_limit_key]`) that refills over the window. Over-limit queries are refused before running, with their cost, what remains and when to retry; soft mode (the default) only records. `RateLimits::MemoryStore` for tests and single processes. Docs: `docs/rate-limiting.md`.
|
|
17
|
+
- Rate limiting, part 2: `use GraphQL::Armory::RateLimits::Concurrency, store:, limit:, stale_after: 60` lets each client run at most `limit` operations at the same time. A query analyzer takes a slot before the operation runs (or refuses it, `RATE_LIMITED`); a trace releases every slot when the multiplex ends, even when it raises. Slots expire after `stale_after` seconds. `MemoryStore` gains `acquire` and `release`.
|
|
18
|
+
- Rate limiting, part 3: clients can see their budget on every response. `Points` takes `extensions: true` to add `rateLimit` (`cost`, `limit`, `remaining`, `resetIn`) to the response extensions, and `Points.headers(result)` answers `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`.
|
|
19
|
+
- Rate limiting, part 4: `RateLimits::RedisStore.new(redis:)` keeps buckets and slots in Redis, shared by every process. Each change is one Lua script and the time comes from Redis, so concurrent requests never race and servers agree on the clock. Keys expire on their own. The app adds the redis gem.
|
|
20
|
+
- Rate limiting follows the Useful Objects doctrine like authorization: `Points.new` and `Concurrency.new` are inert and refuse every query (`Store::Null`), `build` checks the settings and wires the store, `call` is the actuator. `RateLimits::Store::Substitute` (a MemoryStore on a test clock that records calls and fails when told) and `RateLimits::Controls` are there for your specs.
|
|
21
|
+
- Encrypted IDs and persisted queries follow the same doctrine: `IDs::Lookup.new` is inert (`Encoder::Null`) and `build` wires `Encoder.default`; `PersistedQueries::Gate` holds the decision, with an inert `new` (`Store::Null`, strict) and `build`. `Encoder::Substitute`, `PersistedQueries::Store::Substitute` and `Controls` for both are there for your specs. `IDs` now refuses at boot a `find:` that is not callable and an encoder without `encode` and `decode`.
|
|
22
|
+
|
|
5
23
|
## 0.1.0.pre4 (2026-10-29)
|
|
6
24
|
|
|
7
25
|
Persisted queries / operation allowlist (roadmap module 3). Docs: `docs/persisted-queries.md`.
|
data/README.md
CHANGED
|
@@ -6,12 +6,12 @@
|
|
|
6
6
|
|
|
7
7
|
Open-source extensions for [graphql-ruby](https://github.com/rmosolgo/graphql-ruby), built on its public extension points: no fork, no monkey patching. One gem, one module at a time; each module has its own page in [`docs/`](docs) with the problem it solves, how to use it, and its limits.
|
|
8
8
|
|
|
9
|
-
> **Status: early development.** Prereleases on RubyGems (`0.1.0.
|
|
9
|
+
> **Status: early development.** Prereleases on RubyGems (`0.1.0.pre6`). The API may change before 1.0.
|
|
10
10
|
|
|
11
11
|
## Install
|
|
12
12
|
|
|
13
13
|
```ruby
|
|
14
|
-
gem "graphql-armory", "~> 0.1.0.
|
|
14
|
+
gem "graphql-armory", "~> 0.1.0.pre6" # a prerelease: `gem install graphql-armory --pre`
|
|
15
15
|
gem "pundit" # or "cancancan", for the authorization module
|
|
16
16
|
```
|
|
17
17
|
|
|
@@ -26,7 +26,7 @@ Status: ✅ released, 🚧 in progress, ⬜ not started. Update this table in th
|
|
|
26
26
|
| 1 | Authorization (Pundit, CanCanCan) | ✅ | [docs/authorization.md](docs/authorization.md) | Released in 0.1.0.pre2 (prerelease). Pundit and CanCanCan (the audit checks less with CanCanCan). Global IDs in `loads:` decoded through `object_from_id`; `loads:` inside input objects scoped with `include Base`. `Execution::Next` needs graphql >= 2.6.2. |
|
|
27
27
|
| 2 | Encrypted, versioned IDs and cursors | ✅ | [docs/encrypted-ids.md](docs/encrypted-ids.md) | Released in 0.1.0.pre4 (prerelease). `Encoder` (AES-256-GCM), versioned chains and `Legacy`, `Encoder.default` (ENV or Rails), `use GraphQL::Armory::IDs`. Composite primary keys not supported. |
|
|
28
28
|
| 3 | Persisted queries / operation allowlist | ✅ | [docs/persisted-queries.md](docs/persisted-queries.md) | Released in 0.1.0.pre4 (prerelease). Allowlist from a build manifest (Apollo, Relay), `use GraphQL::Armory::PersistedQueries` with strict mode. A runtime store (database, sync endpoint) is planned for later. |
|
|
29
|
-
| 4 | Rate limiting |
|
|
29
|
+
| 4 | Rate limiting | ✅ | [docs/rate-limiting.md](docs/rate-limiting.md) | Released in 0.1.0.pre5 (prerelease); `RateLimits::Time` in 0.1.0.pre6. Points per client (query complexity) and operations at the same time, `MemoryStore` and `RedisStore`, the budget in response extensions and headers. `RateLimits::Time` charges the wall-clock milliseconds operations take. |
|
|
30
30
|
| 5 | Stable (keyset) connections | ⬜ | | Research not started. |
|
|
31
31
|
| 6 | Subscriptions over Pusher / Ably | ⬜ | | Research not started. |
|
|
32
32
|
| 7 | Response caching | ⬜ | | Research not started. |
|
|
@@ -38,6 +38,8 @@ Each module starts with its own research before design. A module is ✅ only whe
|
|
|
38
38
|
|
|
39
39
|
Every module page follows the same outline: **The problem**, **The solution**, **How to use it**, reference sections, **Guarantees and limits**.
|
|
40
40
|
|
|
41
|
+
Across modules: [Telemetry](docs/telemetry.md) shows how to see what the gem allowed, refused and ran, in your logs and metrics, without recording anything a client chose.
|
|
42
|
+
|
|
41
43
|
## Development
|
|
42
44
|
|
|
43
45
|
Ruby is not required on the host:
|
|
@@ -53,7 +55,7 @@ GRAPHQL_VERSION="~> 2.4.0" docker compose run --rm test # another graphq
|
|
|
53
55
|
Releases are published from GitHub Actions with RubyGems Trusted Publishing (`.github/workflows/release.yml`): no API key is stored and no OTP is asked. Bump `GraphQL::Armory::VERSION` and the CHANGELOG on `main`, then push the matching tag:
|
|
54
56
|
|
|
55
57
|
```
|
|
56
|
-
git tag v0.1.0.
|
|
58
|
+
git tag v0.1.0.pre6 && git push origin v0.1.0.pre6
|
|
57
59
|
```
|
|
58
60
|
|
|
59
61
|
The workflow checks that the tag matches the version, runs the specs and pushes the gem. It only publishes a tag on a commit of `main`. The `release` environment can require a maintainer's approval first (on a public repository, or a private one on a paid GitHub plan).
|
data/docs/authorization.md
CHANGED
|
@@ -234,7 +234,15 @@ What an interface adds is its fields, declared once and resolved on many types:
|
|
|
234
234
|
|
|
235
235
|
## Telemetry
|
|
236
236
|
|
|
237
|
-
|
|
237
|
+
The decisions are visible to you and not to the client. Pass `sinks:` to hear each one:
|
|
238
|
+
|
|
239
|
+
```ruby
|
|
240
|
+
use GraphQL::Armory::Authorization, adapter: :pundit,
|
|
241
|
+
sinks: [->(signal, data) { Rails.logger.info("armory #{signal} #{data}") }]
|
|
242
|
+
# armory denied {:type=>"Invoice", :action=>:read}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
Signals are `:allowed`, `:denied`, `:bypassed` (an `authorize :none` rule ran) and `:scoped` (a list went through the user's scope). Data holds only `type`, `action` and `reason`, never record attributes. `GraphQL::Armory::Telemetry::Notifications` reports them to `ActiveSupport::Notifications`. Every signal, what to watch for and how to test it: [Telemetry](telemetry.md). A `sinks:` that is not an Array of callables raises `Telemetry::ConfigurationError` at boot.
|
|
238
246
|
|
|
239
247
|
## Guarantees and limits
|
|
240
248
|
|
data/docs/encrypted-ids.md
CHANGED
|
@@ -103,6 +103,25 @@ return nil if encoder.nil? # nothing in the cha
|
|
|
103
103
|
log_legacy_id(id) if encoder == GraphQL::Armory::Encoder::Legacy
|
|
104
104
|
```
|
|
105
105
|
|
|
106
|
+
### Seeing what was refused
|
|
107
|
+
|
|
108
|
+
Every ID the schema does not honour answers `nil`, like a missing record, so the client learns nothing. You do not have to be as blind. Pass `sinks:` and each lookup says what happened:
|
|
109
|
+
|
|
110
|
+
```ruby
|
|
111
|
+
use GraphQL::Armory::IDs, sinks: [GraphQL::Armory::Telemetry::Notifications]
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
| Signal | Data |
|
|
115
|
+
|---|---|
|
|
116
|
+
| `:id_resolved` | `type` |
|
|
117
|
+
| `:id_refused` | `reason`: `:invalid` (did not decrypt), `:malformed` (not `Type/key`), `:unknown_type` (not in the schema, not visible, or not a `Node`), `:not_found` (missing or outside the user's scope, plus `type`) |
|
|
118
|
+
|
|
119
|
+
The signal never holds the ID, the key or the record. A rising `:invalid` is someone sending forged IDs, or clients still holding IDs from a key you rotated away; `:not_found` bursts from one client are an enumeration attempt. See [Telemetry](telemetry.md) for how to send them to your logs and metrics.
|
|
120
|
+
|
|
121
|
+
### Testing with IDs
|
|
122
|
+
|
|
123
|
+
`Encoder::Substitute` encodes reversibly without a key and records what it encoded and decoded, for specs of code that uses an encoder; never hand out real IDs with it. `IDs::Controls::Encoder.example` is an Encoder subclass with a fixed test key, and `IDs::Controls::Record.example(id:)` a record to build IDs from. `IDs::Lookup.new`, with nothing wired, hands out no ID and honours none (`Encoder::Null`); `IDs::Lookup.build(encoder:, find:)` takes the same settings as `use`.
|
|
124
|
+
|
|
106
125
|
## Reference
|
|
107
126
|
|
|
108
127
|
| Declaration | Meaning |
|
|
@@ -118,7 +137,7 @@ log_legacy_id(id) if encoder == GraphQL::Armory::Encoder::Legacy
|
|
|
118
137
|
| `decode(id)` / `decode(cursor, nonce: true)` | The text, or raises `GraphQL::Armory::Encoder::InvalidError` (a `GraphQL::ExecutionError`, so clients see `Invalid ID or cursor`). |
|
|
119
138
|
| `Encoder.versioned(newest, ..., oldest)` | A chain with the same `encode` and `decode`; encodes with `newest`. |
|
|
120
139
|
| `chain.decode_versioned(text, nonce: false)` | `[data, encoder]`, or `[nil, nil]` when no encoder accepts it. |
|
|
121
|
-
| `use GraphQL::Armory::IDs, encoder: nil, find: nil` | Defines `id_from_object` and `object_from_id`; `encoder` defaults to `Encoder.default`; `find:` loads types without `Base
|
|
140
|
+
| `use GraphQL::Armory::IDs, encoder: nil, find: nil, sinks: []` | Defines `id_from_object` and `object_from_id`; `encoder` defaults to `Encoder.default`; `find:` loads types without `Base`; `sinks:` hears `:id_resolved` and `:id_refused` ([Telemetry](telemetry.md)). |
|
|
122
141
|
| `Encoder.default` | An encoder keyed by `GRAPHQL_ARMORY_KEY`, else by a key derived with HKDF from Rails' `secret_key_base`; raises `ConfigurationError` without either. |
|
|
123
142
|
|
|
124
143
|
A subclass inherits `key`, `tag` and `codec`, and can override any of them. Passing `nil` to any of them raises `ConfigurationError`, so an unset environment variable fails at boot instead of being ignored.
|
data/docs/persisted-queries.md
CHANGED
|
@@ -136,6 +136,27 @@ Relay's example network layer sends the id as `doc_id`. Pass it yourself: `opera
|
|
|
136
136
|
|
|
137
137
|
Deploy the server with the new manifest before, or with, the clients that use its new operations: until then they get `Unknown operation id`. Keep old operations in the file while old app versions are still in use.
|
|
138
138
|
|
|
139
|
+
### Watching the rollout
|
|
140
|
+
|
|
141
|
+
A refused request tells the client only `Unknown operation id` or `Only persisted operations are allowed`. To know how many, and from whom, pass `sinks:`:
|
|
142
|
+
|
|
143
|
+
```ruby
|
|
144
|
+
use GraphQL::Armory::PersistedQueries, store: PERSISTED, sinks: [GraphQL::Armory::Telemetry::Notifications]
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
| Signal | When |
|
|
148
|
+
|---|---|
|
|
149
|
+
| `:operation_persisted` | A request ran the stored operation its id names |
|
|
150
|
+
| `:operation_refused` | Refused, with `reason`: `:unknown_operation`, `:mismatch` or `:raw_query` |
|
|
151
|
+
| `:raw_query_run` | A raw query ran because you are not strict yet |
|
|
152
|
+
| `:raw_query_allowed` | A raw query ran in strict mode because the context holds `armory_allow_raw_query: true` |
|
|
153
|
+
|
|
154
|
+
While you are in `strict: false`, `:raw_query_run` is the traffic still to migrate: turn on `strict: true` when it reaches zero. After a deploy, `:operation_refused` with `:unknown_operation` is a client build whose operations are not in the manifest. Signals never hold the operation id or the query. See [Telemetry](telemetry.md).
|
|
155
|
+
|
|
156
|
+
### Testing with persisted queries
|
|
157
|
+
|
|
158
|
+
`PersistedQueries::Store::Substitute.new(*queries)` holds the given queries under their SHA-256, like an Apollo manifest, and records the ids it was asked for (`fetched`). `PersistedQueries::Controls::Operations`, `Query.example` and `Root.example` are a small schema and its operations to test against. The decision itself is `PersistedQueries::Gate`: `Gate.build(store:, strict:)` takes the same settings as `use`, and `gate.(context, query_text, document)` answers `[refusal, document]`. `Gate.new`, with nothing wired, refuses every request (`Store::Null`, strict).
|
|
159
|
+
|
|
139
160
|
## Reference
|
|
140
161
|
|
|
141
162
|
`Manifest.new(data, digest: :sha256)`, `Manifest.load(path, digest: :sha256)`
|
|
@@ -145,10 +166,11 @@ Deploy the server with the new manifest before, or with, the clients that use it
|
|
|
145
166
|
- `fetch(id)` answers the operation (`id`, `name`, `body`, `document`, all frozen) or nil. `size` counts them.
|
|
146
167
|
- Raises `PersistedQueries::ConfigurationError` at boot for: invalid JSON, an unreadable file, an unknown format or version, an id that is not the digest of its query, a query that does not parse, a duplicate id, an entry that is not an object, or an empty manifest. Messages never quote the file's queries.
|
|
147
168
|
|
|
148
|
-
`use GraphQL::Armory::PersistedQueries, store:, strict: false`
|
|
169
|
+
`use GraphQL::Armory::PersistedQueries, store:, strict: false, sinks: []`
|
|
149
170
|
|
|
150
171
|
- `store:` answers `fetch(id)` with an object that has `body` and `document`, or nil. A Manifest, or your own store.
|
|
151
172
|
- `strict:` is `true` or `false`.
|
|
173
|
+
- `sinks:` an Array of callables taking `(signal, data)`; see [Watching the rollout](#watching-the-rollout).
|
|
152
174
|
- Works with your own `query_class`, whether it is set before `use`, after it, or in a child schema: the plugin subclasses it.
|
|
153
175
|
- `use` it once per schema hierarchy. A second `use`, on the same schema or a child, raises instead of replacing the first one's settings.
|
|
154
176
|
- A store whose `fetch` raises or answers something without `document` makes the request raise: it fails closed, as an exception.
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
# Rate limiting
|
|
2
|
+
|
|
3
|
+
Each client gets a budget of work per minute, measured in what its queries cost, not in how many requests it sends.
|
|
4
|
+
|
|
5
|
+
## The problem
|
|
6
|
+
|
|
7
|
+
A REST API can limit requests per minute because requests cost roughly the same. GraphQL requests do not:
|
|
8
|
+
|
|
9
|
+
```graphql
|
|
10
|
+
{ me { name } } # almost free
|
|
11
|
+
{ invoices(first: 1000) { lines { product { reviews { author { name } } } } } } # seconds of work
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
A limit of 100 requests per minute lets a client send 100 of the second kind, by mistake or on purpose, and keep your servers busy while everyone else waits. Counting requests does not stop it.
|
|
15
|
+
|
|
16
|
+
## The solution
|
|
17
|
+
|
|
18
|
+
`GraphQL::Armory::RateLimits::Points` charges every query its **complexity**: the score graphql-ruby already computes from the fields a query asks for, before running it. Each client has a bucket of points that refills over a window:
|
|
19
|
+
|
|
20
|
+
- **Refused before running.** A query that costs more than the client has left is refused before any field resolves, so it costs your servers nothing. It is not charged either.
|
|
21
|
+
- **Predictable for clients.** The refusal says what the query cost, what remains and when to retry, so a client can adapt.
|
|
22
|
+
- **Per client.** Each client key (a user, an API token, an IP) has its own bucket; you can give each key its own limit.
|
|
23
|
+
- **Safe to roll out.** Soft mode, the default, charges and records but refuses nothing, so you can watch real traffic before turning it on.
|
|
24
|
+
|
|
25
|
+
`GraphQL::Armory::RateLimits::Concurrency` adds a second rule: at most N operations running at the same time per client ([Operations at the same time](#operations-at-the-same-time)). Both keep their state in a store: `MemoryStore` for tests and one process, `RedisStore` for production ([Sharing limits between processes](#sharing-limits-between-processes)). `GraphQL::Armory::RateLimits::Time` adds a third: a budget of wall-clock milliseconds per client, charged for the time its operations really took ([Time spent running](#time-spent-running)).
|
|
26
|
+
|
|
27
|
+
## How to use it
|
|
28
|
+
|
|
29
|
+
```ruby
|
|
30
|
+
class AppSchema < GraphQL::Schema
|
|
31
|
+
use GraphQL::Armory::RateLimits::Points,
|
|
32
|
+
store: GraphQL::Armory::RateLimits::MemoryStore.new,
|
|
33
|
+
limit: 1_000, # points
|
|
34
|
+
window: 60, # seconds: the bucket refills 1,000 points every minute
|
|
35
|
+
soft: false # refuse; leave it out (soft mode) while you measure
|
|
36
|
+
end
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Name the client in the context:
|
|
40
|
+
|
|
41
|
+
```ruby
|
|
42
|
+
context = {
|
|
43
|
+
current_user: current_user,
|
|
44
|
+
rate_limit_key: current_user ? "user:#{current_user.id}" : "ip:#{request.remote_ip}"
|
|
45
|
+
}
|
|
46
|
+
AppSchema.execute(params[:query], variables: params[:variables], context: context)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
A query without a key raises `RateLimits::ConfigurationError`, so a forgotten controller is caught at once instead of running unlimited. To build the key another way, pass `key: ->(query) { ... }`.
|
|
50
|
+
|
|
51
|
+
### What a query costs
|
|
52
|
+
|
|
53
|
+
graphql-ruby scores a query before running it:
|
|
54
|
+
|
|
55
|
+
- Every field costs **1 point**, unless you give it another score.
|
|
56
|
+
- Inside a connection, the fields selected under each node cost **page size × their points** (`first:` or `last:`, variables included).
|
|
57
|
+
- Fractional complexities are charged in whole points, rounded up.
|
|
58
|
+
|
|
59
|
+
A worked example:
|
|
60
|
+
|
|
61
|
+
```graphql
|
|
62
|
+
query {
|
|
63
|
+
viewer { # 1
|
|
64
|
+
invoices(first: 50) { # 1
|
|
65
|
+
nodes { # 1
|
|
66
|
+
number # 50 invoices × 1
|
|
67
|
+
lines(first: 20) { # 50 × 1
|
|
68
|
+
nodes { # 50 × 1
|
|
69
|
+
product # 50 × 20 lines × 1
|
|
70
|
+
comments(first: 10) { # 50 × 20 × 1
|
|
71
|
+
nodes { # 50 × 20 × 1
|
|
72
|
+
body # 50 × 20 × 10 comments × 1
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
followers(first: 10) { # 1
|
|
80
|
+
nodes { # 1
|
|
81
|
+
name # 10 followers × 1
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Calculation:
|
|
89
|
+
|
|
90
|
+
```
|
|
91
|
+
3 = viewer, invoices, nodes
|
|
92
|
+
+ 50 × 3 = 150 = number, lines, nodes, for each invoice
|
|
93
|
+
+ 50 × 20 × 3 = 3,000 = product, comments, nodes, for each line
|
|
94
|
+
+ 50 × 20 × 10 × 1 = 10,000 = body, for each comment
|
|
95
|
+
+ 2 + 10 × 1 = 12 = followers, nodes, and name for each follower
|
|
96
|
+
= 13,165 points
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
With `limit: 1_000` this query can never run; asking for `invoices(first: 5)` instead costs about a tenth. The numbers were measured with graphql-ruby's own analysis, so they are exactly what the limiter charges.
|
|
100
|
+
|
|
101
|
+
Give expensive fields a higher score where you define them, so their cost reflects real work:
|
|
102
|
+
|
|
103
|
+
```ruby
|
|
104
|
+
field :report, ReportType, null: false, complexity: 40 # 40 points instead of 1
|
|
105
|
+
field :create_invoice, mutation: Mutations::CreateInvoice, complexity: 10 # 10 points plus its selections
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Three settings make the scores fair. Large public APIs (GitHub, Shopify, see [References](#references)) do the same:
|
|
109
|
+
|
|
110
|
+
- **Paginate every list.** A plain list field (`[Invoice]`) costs its fields **once**, however many items it returns, so 10,000 invoices cost like one. Use connections for anything that can grow. A connection asked for without `first:` or `last:` is sized by the schema's `default_page_size`, or else by `default_max_page_size`. If neither is set, graphql-ruby raises `GraphQL::Error` while scoring the query (a server error, not a refusal), so set one of them. GitHub goes further and requires `first:` or `last:` on every connection.
|
|
111
|
+
- **Cap a single query.** graphql-ruby's `max_complexity 1_000` refuses any query above that score, whatever the client's budget. Shopify caps single queries at 1,000 points.
|
|
112
|
+
- **Make writes cost more.** Give mutations a higher `complexity:`: `complexity: 10` charges 10 points for the mutation field itself, plus the fields it selects. Shopify charges 10 points per mutation by default.
|
|
113
|
+
|
|
114
|
+
See graphql-ruby's [complexity and depth guide](https://graphql-ruby.org/queries/complexity_and_depth) for computed costs.
|
|
115
|
+
|
|
116
|
+
### When a client runs out
|
|
117
|
+
|
|
118
|
+
The response holds only the refusal:
|
|
119
|
+
|
|
120
|
+
```json
|
|
121
|
+
{
|
|
122
|
+
"errors": [{
|
|
123
|
+
"message": "Rate limit exceeded: this query costs 40 points and 20 remain (1000 every 60 seconds). Retry in 2 seconds.",
|
|
124
|
+
"extensions": { "code": "RATE_LIMITED", "cost": 40, "remaining": 20, "retryAfter": 2 }
|
|
125
|
+
}]
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
A query that costs more than the whole limit can never run, and says so: `this query costs 1200 points and the limit is 1000 every 60 seconds, so it can never run.` Its extensions hold `cost` and `limit`.
|
|
130
|
+
|
|
131
|
+
### Showing clients their budget
|
|
132
|
+
|
|
133
|
+
A client that only learns its budget when it is refused cannot pace itself. GitHub sends the budget in headers on every response; Shopify puts it in the response's `extensions`. You can do either, or both.
|
|
134
|
+
|
|
135
|
+
In the response, with `extensions: true`:
|
|
136
|
+
|
|
137
|
+
```ruby
|
|
138
|
+
use GraphQL::Armory::RateLimits::Points, store: store, limit: 1_000, window: 60, soft: false, extensions: true
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
```json
|
|
142
|
+
{
|
|
143
|
+
"data": { "report": { "total": 120 } },
|
|
144
|
+
"extensions": { "rateLimit": { "cost": 40, "limit": 1000, "remaining": 960, "resetIn": 3 } }
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
`resetIn` is the number of seconds until the bucket is full again. It is on refused responses too, and absent for a client with no limit. It is off by default, so responses do not change until you turn it on.
|
|
149
|
+
|
|
150
|
+
In HTTP headers, from your controller:
|
|
151
|
+
|
|
152
|
+
```ruby
|
|
153
|
+
result = AppSchema.execute(params[:query], variables: params[:variables], context: context)
|
|
154
|
+
response.headers.merge!(GraphQL::Armory::RateLimits::Points.headers(result))
|
|
155
|
+
render json: result
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
That sets `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset` (seconds until the bucket is full), or nothing when the query had no limit. It works whether or not `extensions:` is on, and reads each query's own budget, also in a multiplex. The `rateLimit` key of the response extensions belongs to the limiter: do not write it yourself.
|
|
159
|
+
|
|
160
|
+
### Different limits per client
|
|
161
|
+
|
|
162
|
+
```ruby
|
|
163
|
+
use GraphQL::Armory::RateLimits::Points, store: store, window: 60,
|
|
164
|
+
limit: ->(key, query) { key.start_with?("partner:") ? 10_000 : 1_000 }
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
The callable answers a positive Integer, or nil for no limit (for example an internal service). Anything else raises.
|
|
168
|
+
|
|
169
|
+
### Operations at the same time
|
|
170
|
+
|
|
171
|
+
Points limit how much work a client asks for per minute. They do not stop a client that sends 30 cheap requests at once and occupies every server process while they run: GitHub, for one, also caps concurrent requests. Add `Concurrency` next to `Points`:
|
|
172
|
+
|
|
173
|
+
```ruby
|
|
174
|
+
class AppSchema < GraphQL::Schema
|
|
175
|
+
use GraphQL::Armory::RateLimits::Concurrency,
|
|
176
|
+
store: store, # the same store as Points
|
|
177
|
+
limit: 5, # operations running at once per client
|
|
178
|
+
soft: false
|
|
179
|
+
end
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
It uses the same `rate_limit_key`. Before an operation runs it takes one of the client's slots; when the operation ends, it gives the slot back, even if the operation raised or another analyzer refused it. A client whose slots are all taken is refused before any field resolves:
|
|
183
|
+
|
|
184
|
+
```json
|
|
185
|
+
{
|
|
186
|
+
"errors": [{
|
|
187
|
+
"message": "Too many operations at the same time: 5 are already running for this client (limit 5). Retry when one finishes.",
|
|
188
|
+
"extensions": { "code": "RATE_LIMITED", "limit": 5, "active": 5 }
|
|
189
|
+
}]
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
A process that crashes never gives its slots back, so each slot expires after `stale_after:` seconds (60 by default). Set it above your longest request timeout. Soft mode, per-key limits (`limit: ->(key, query) { ... }`) and `on_store_error:` work as for `Points`; what happened is in `result.context[:rate_limit_concurrency]` (`{ key:, limit:, active:, soft:, limited: }`).
|
|
194
|
+
|
|
195
|
+
### Time spent running
|
|
196
|
+
|
|
197
|
+
The cost of a query is an estimate made before it runs. A field scored 1 that waits three seconds on a slow service still occupies a server thread for three seconds, and points never see it. `Time` charges what really happened: the wall-clock milliseconds each operation took, against a bucket of milliseconds per client that refills over a window.
|
|
198
|
+
|
|
199
|
+
```ruby
|
|
200
|
+
class AppSchema < GraphQL::Schema
|
|
201
|
+
use GraphQL::Armory::RateLimits::Time,
|
|
202
|
+
store: store, # the same store as Points
|
|
203
|
+
limit: 10_000, # milliseconds per window, per client
|
|
204
|
+
window: 60,
|
|
205
|
+
soft: false
|
|
206
|
+
end
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
It uses the same `rate_limit_key`. Before an operation runs it asks the store for the client's balance; a client with no milliseconds left is refused before any field resolves, and charged nothing:
|
|
210
|
+
|
|
211
|
+
```json
|
|
212
|
+
{
|
|
213
|
+
"errors": [{
|
|
214
|
+
"message": "Rate limit exceeded: this client used its 10000 ms of processing time every 60 seconds. Retry in 1 seconds.",
|
|
215
|
+
"extensions": { "code": "RATE_LIMITED", "limit": 10000, "retryAfter": 1 }
|
|
216
|
+
}]
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
When the operation ends, even if it raised, the milliseconds it took (measured with a monotonic clock) are charged. The time is wall-clock, not CPU: waiting on a database or an external service counts, because that is what keeps a server thread busy. A running operation is never interrupted, so the one that spends the last milliseconds finishes and the next one is refused; the balance never goes below zero, and the client recovers `limit` milliseconds per `window`.
|
|
221
|
+
|
|
222
|
+
Soft mode (the default), per-key limits (`limit: ->(key, query) { ... }`) and `on_store_error:` work as for `Points`. To show clients their budget, pass `extensions: true`, which adds `"rateLimitTime" => { limit, remaining, elapsed, resetIn }` (milliseconds, and seconds for `resetIn`; `elapsed` appears once the operation ran, so a refused one has none) to the response, or send `Time.headers(result)`: `RateLimit-Time-Limit`, `RateLimit-Time-Remaining` and `RateLimit-Time-Reset`, prefixed so they never clash with the `Points` headers. What happened is in `result.context[:rate_limit_time]`: `{ key:, limit:, remaining:, elapsed:, window:, soft:, limited: }`, where `elapsed` is nil for an operation that was refused.
|
|
223
|
+
|
|
224
|
+
To test it, inject a clock: `Time` takes `clock:` (a callable answering seconds), and `RateLimits::Clock::Substitute` is one your test moves. `Controls::Time.example(clock, seconds: 0.25)` is a root for `Controls::Query.example` whose every field takes that long on the clock.
|
|
225
|
+
|
|
226
|
+
### Rolling it out
|
|
227
|
+
|
|
228
|
+
1. Install it in soft mode (leave out `soft:`). Queries run as before; each one records what it cost.
|
|
229
|
+
2. Send what it recorded to your metrics: `result.context[:rate_limit_points]` is `{ key:, cost:, limit:, remaining:, window:, soft:, limited: }`, and `limited: true` marks the queries that would have been refused.
|
|
230
|
+
3. When the limits fit your traffic, set `soft: false`.
|
|
231
|
+
|
|
232
|
+
Rate limiting reports through the query context rather than through `sinks:`, because the context is also where the budget for the response comes from. To see its decisions next to the other modules' signals, send those records to the same place: [Telemetry](telemetry.md#rate-limiting).
|
|
233
|
+
|
|
234
|
+
### Sharing limits between processes
|
|
235
|
+
|
|
236
|
+
`MemoryStore` keeps buckets in one process: with four Puma workers on two servers, a client gets the limit eight times over, and a restart refills every bucket. In production use `RedisStore`, which keeps them in Redis, shared by every process:
|
|
237
|
+
|
|
238
|
+
```ruby
|
|
239
|
+
# Gemfile: gem "redis"
|
|
240
|
+
RATE_LIMIT_STORE = GraphQL::Armory::RateLimits::RedisStore.new(redis: Redis.new(url: ENV.fetch("REDIS_URL")))
|
|
241
|
+
|
|
242
|
+
class AppSchema < GraphQL::Schema
|
|
243
|
+
use GraphQL::Armory::RateLimits::Points, store: RATE_LIMIT_STORE, limit: 1_000, window: 60, soft: false
|
|
244
|
+
use GraphQL::Armory::RateLimits::Concurrency, store: RATE_LIMIT_STORE, limit: 5, soft: false
|
|
245
|
+
end
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
- **Atomic.** Each charge, slot taken and slot released is one Lua script, so two requests of the same client never both spend the last points.
|
|
249
|
+
- **One clock.** The time comes from Redis (`TIME`), not from each server, so servers whose clocks drift still agree on when a bucket refills.
|
|
250
|
+
- **Small.** A client costs two keys, `graphql-armory:rate-limits:points:<key>` and `...:slots:<key>`; both expire once they no longer matter (a window, or `stale_after`, after the last use). Pass `prefix:` to share one Redis with other apps.
|
|
251
|
+
- **Fails open.** When Redis is down or slow, the client raises, the query runs, and `on_store_error` is called: make that hook alert. Set the client's timeouts (for example `Redis.new(url: ..., timeout: 0.2)`) so a slow Redis cannot slow every request.
|
|
252
|
+
|
|
253
|
+
The gem does not depend on the redis gem: add it to your Gemfile. A single `Redis` client is safe to share between threads.
|
|
254
|
+
|
|
255
|
+
### Testing your limits
|
|
256
|
+
|
|
257
|
+
`RateLimits::Store::Substitute` is a `MemoryStore` on a clock your test moves, that records its calls and fails when told, so specs need no mocks and no sleeping:
|
|
258
|
+
|
|
259
|
+
```ruby
|
|
260
|
+
store = GraphQL::Armory::RateLimits::Store::Substitute.new
|
|
261
|
+
schema = Class.new(AppSchema) { use GraphQL::Armory::RateLimits::Points, store: store, limit: 100, window: 60, soft: false }
|
|
262
|
+
|
|
263
|
+
store.now += 30 # half a window later
|
|
264
|
+
store.fail_with(IOError.new("down"), on: :take) # the next charges raise, as a broken Redis would
|
|
265
|
+
store.answer(:take, [0, 0]) # an answer no real store gives
|
|
266
|
+
store.calls # [[:take, "user:1", { cost: 40, limit: 100, window: 60, force: false }], ...]
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
`occupy(key)` holds a slot for an operation running elsewhere and `held(key)` counts the slots held. `RateLimits::Controls::Query.example`, `Root.example` and `Context.example` are a small schema and context to test against. `Points.new` and `Concurrency.new`, with nothing wired, refuse every query (`Store::Null`), and check every setting they are given: `soft: true` with no store raises, since it would count nothing; `Points.build(...)` and `Concurrency.build(...)` take the same settings as `use`.
|
|
270
|
+
|
|
271
|
+
## Reference
|
|
272
|
+
|
|
273
|
+
`use GraphQL::Armory::RateLimits::Points, store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, extensions: false`
|
|
274
|
+
|
|
275
|
+
- `store:` answers `take(key, cost:, limit:, window:, force:)` with `[taken, remaining]`. `MemoryStore.new(clock: ...)` keeps buckets in the process; `RedisStore` shares them (below).
|
|
276
|
+
- `limit:` a positive Integer, or a callable `(key, query)` answering a positive Integer or nil.
|
|
277
|
+
- `window:` positive seconds over which `limit` points refill, continuously.
|
|
278
|
+
- `soft:` `true` (default) charges and records without refusing; `false` refuses.
|
|
279
|
+
- `key:` a callable `(query)` answering the client key; by default `context[:rate_limit_key]`. It must be a non-empty String.
|
|
280
|
+
- `on_store_error:` a callable `(error, query)` called when the store raises; the query then runs (fails open). By default it warns.
|
|
281
|
+
- `extensions:` `true` adds `"rateLimit" => { cost, limit, remaining, resetIn }` to every response of a limited client; `false` (default) leaves responses unchanged.
|
|
282
|
+
- `Points.headers(result)` answers the `RateLimit-*` headers for a result, or `{}`.
|
|
283
|
+
- Instrumentation: `context[:rate_limit_points]`.
|
|
284
|
+
|
|
285
|
+
`use GraphQL::Armory::RateLimits::Concurrency, store:, limit:, stale_after: 60, soft: true, key: nil, on_store_error: nil`
|
|
286
|
+
|
|
287
|
+
- `store:` answers `acquire(key, token:, limit:, ttl:, force:)` with `[acquired, active]` and `release(key, token:)`. `MemoryStore` does both.
|
|
288
|
+
- `limit:` operations at once per client: a positive Integer, or a callable `(key, query)` answering a positive Integer or nil.
|
|
289
|
+
- `stale_after:` positive seconds after which a slot that was never released expires.
|
|
290
|
+
- `soft:`, `key:` and `on_store_error:` as for `Points`. When the store raises on release, `on_store_error` is called and the slot expires after `stale_after`.
|
|
291
|
+
- Instrumentation: `context[:rate_limit_concurrency]`.
|
|
292
|
+
|
|
293
|
+
`use GraphQL::Armory::RateLimits::Time, store:, limit:, window: 60, soft: true, key: nil, on_store_error: nil, clock: Clock.monotonic, extensions: false`
|
|
294
|
+
|
|
295
|
+
- `store:` as for `Points`: it is asked for the balance with `take(key, cost: 0, ...)` and charged with `take(key, cost: milliseconds, ..., force: true)`. No store changes are needed.
|
|
296
|
+
- `limit:` milliseconds per `window` per client: a positive Integer, or a callable `(key, query)` answering a positive Integer or nil.
|
|
297
|
+
- `window:`, `soft:`, `key:` and `on_store_error:` as for `Points`.
|
|
298
|
+
- `clock:` a callable answering seconds, read when a multiplex starts and when it ends. By default a monotonic clock.
|
|
299
|
+
- `extensions:` `true` adds `"rateLimitTime" => { limit, remaining, elapsed, resetIn }` to the response of a limited client.
|
|
300
|
+
- `Time.headers(result)` answers the `RateLimit-Time-*` headers for a result, or `{}`.
|
|
301
|
+
- Instrumentation: `context[:rate_limit_time]`.
|
|
302
|
+
|
|
303
|
+
`GraphQL::Armory::RateLimits::RedisStore.new(redis:, prefix: "graphql-armory:rate-limits:", clock: nil)`
|
|
304
|
+
|
|
305
|
+
- `redis:` a redis-rb client (>= 4.8), or anything answering `eval(script, keys:, argv:)` and `evalsha(sha, keys:, argv:)` the same way. Needs Redis 5 or later. Works with Redis Cluster: each script touches one key.
|
|
306
|
+
- `prefix:` a non-empty String put before every key.
|
|
307
|
+
- `clock:` nil (default) reads Redis's clock; a callable answering seconds replaces it, for tests.
|
|
308
|
+
|
|
309
|
+
Invalid settings raise `RateLimits::ConfigurationError` at boot.
|
|
310
|
+
|
|
311
|
+
## Guarantees and limits
|
|
312
|
+
|
|
313
|
+
- A query this limiter refuses resolves no field and is not charged. A query that fails validation is not charged. A query refused by another analyzer (`max_depth`, `max_complexity`) is still charged: graphql-ruby runs every analyzer.
|
|
314
|
+
- Each query in a multiplex is charged on its own.
|
|
315
|
+
- `Concurrency` takes one slot per query of a multiplex, and releases them all when the multiplex ends, even when the queries share one context hash. If a release fails, that slot expires after `stale_after`; the others are still released.
|
|
316
|
+
- A query run with its own trace (`context: { trace: ... }`) cannot be released by `Concurrency`, so it raises `ConfigurationError` instead of taking a slot.
|
|
317
|
+
- A resolver that runs another query for the same client (a nested `execute`) takes a second slot while the first is held.
|
|
318
|
+
- A subscription holds a slot only while its first result runs, not while it stays subscribed.
|
|
319
|
+
- When queries of a multiplex share one context hash, `context[:rate_limit_points]`, `context[:rate_limit_concurrency]` and `context[:rate_limit_time]` hold the last query's record: give each query its own context hash to read every record.
|
|
320
|
+
- The cost is graphql-ruby's estimate before running, not the time a query really takes: a field that is slow but scored 1 costs 1. Score expensive fields, and add `Time` to charge what queries really take.
|
|
321
|
+
- Field scores are yours: graphql-ruby treats a negative or NaN complexity as 0, so such a field is free, like `complexity: 0`. A complexity that is nil or a String makes graphql-ruby raise before the limiter runs, so the query does not run.
|
|
322
|
+
- When the store fails, queries run unlimited and `on_store_error` is called. Choose that hook to alert. `RedisStore` also counts a bucket whose fields were changed into something that is not a number as a store failure, rather than reading it as full.
|
|
323
|
+
- `MemoryStore` keeps buckets and slots in one process and forgets them on restart: with several processes, each one gives a client the full limit. It keeps one entry per client key it has seen. Use `RedisStore` in production.
|
|
324
|
+
|
|
325
|
+
### Limits of `Time`
|
|
326
|
+
|
|
327
|
+
- A running operation is never interrupted: the one that exhausts the budget finishes, and only the next one is refused. Operations that start while a long one is still running all see the balance before it is charged, so together they can spend more than the client has; the balance then stops at zero (there is no debt).
|
|
328
|
+
- `retryAfter` is the time the client needs to regain one millisecond (`window / limit` seconds, at least 1). It lets the client in again, not necessarily for an operation that takes long.
|
|
329
|
+
- A multiplex has one measured time, split equally among the queries this limiter charges, rounded up to whole milliseconds: fields of different queries interleave, so their time cannot be told apart. A query refused by `Time`, and one whose key has no limit (`nil`), are not part of the split, so the time of a query with no limit is carried by the limited ones.
|
|
330
|
+
- A schema may `use Time` more than once (for example per user and per IP, with different stores and keys): each limiter charges only its own. `context[:rate_limit_time]`, the response extension and `Time.headers` then hold the record of the last one.
|
|
331
|
+
- The clock must answer a finite number of seconds: one that does not is refused at boot, and one that breaks later raises instead of letting operations run uncharged. A clock that stands still or goes backwards charges 0.
|
|
332
|
+
- Time spent before analysis finishes (parsing, validation) is charged to no one, and inside a multiplex it ends up on the queries that did run. A query that never reaches analysis (a syntax error) costs the client nothing.
|
|
333
|
+
- The time is wall-clock, so it grows when the server is loaded: the same query costs a client more on a busy server. Choose `limit` with that in mind, and start in soft mode.
|
|
334
|
+
- A query run with its own trace (`context: { trace: ... }`) cannot be charged, so it raises `ConfigurationError`, as with `Concurrency`.
|
|
335
|
+
- When the store fails, operations run unlimited and `on_store_error` is called; a failed charge never raises into the query (unless your hook does).
|
|
336
|
+
|
|
337
|
+
## References
|
|
338
|
+
|
|
339
|
+
The same technique, charging queries a calculated cost against a budget per client, is used by large public GraphQL APIs:
|
|
340
|
+
|
|
341
|
+
- GitHub: [Rate limits and query limits for the GraphQL API](https://docs.github.com/en/graphql/overview/rate-limits-and-query-limits-for-the-graphql-api): a points budget per hour, where connections' `first`/`last` drive the cost, and a `rateLimit` field showing what remains.
|
|
342
|
+
- Shopify: [GraphQL Admin API rate limits](https://shopify.dev/docs/apps/build/apis/graphql-admin/rate-limits): a calculated query cost against a bucket that refills continuously; Shopify also refunds the difference when the real cost is lower than the estimate.
|
|
343
|
+
- Cha et al., [A Principled Approach to GraphQL Query Cost Analysis](https://arxiv.org/abs/2009.05632) (ESEC/FSE 2020, IBM Research): estimating a query's cost statically, before running it, and why naive estimates over- or under-count.
|
|
344
|
+
- graphql-ruby: [Complexity and depth](https://graphql-ruby.org/queries/complexity_and_depth), the cost this limiter charges.
|