0306. Global rate limits: local token buckets with a periodic Postgres sync
Status: Accepted (2026-11-28). Supersedes the rate-limit part of 0301 (“per-replica buckets plus edge LB caps are enough”). Also covers SR-06 (trusted proxies), SR-10 (IPv6 keys, eviction) and SR-13 (lockout keys).
Context
API rate limits were per replica: with N replicas a client got N times the rate, and the brute-force lockout allowed N times the attempts. They must become global with a tiny hot-path cost, at 100k+ users per instance. The options:
- a Postgres write per request;
- a shared counter in the realtime tier;
- local buckets that sync periodically.
Decision
Option 3: local token buckets, synced through an UNLOGGED Postgres table every 250 ms.
- Request path: unchanged and synchronous: refill, take, note the consumption (one Map lookup, one Set add). Measured at 19 ns/op. No I/O.
- Sync: every
LINORA_API_RATE_SYNC_MS (250), each replica sends ONE statement for all its limiters: an INSERT ... ON CONFLICT DO UPDATE over unnest arrays, holding the consumption of every key it touched since the last tick.
- Postgres applies the token-bucket refill with its own clock, subtracts, floors the level at -burst (debt), and returns each key’s global level. The replica adopts it, minus whatever it consumed while the statement was in flight.
- Rows are sent sorted by key: a consistent lock order across replicas, so no deadlocks.
- Table
api_rate_buckets (migration 0004) is UNLOGGED: no WAL, not replicated. A crash or failover only resets limits.
-
| Keys are 16 bytes of sha256(limiter |
key), so no IPs or emails are stored. Rows idle for longer than twice the slowest refill are deleted (bounded batches). |
- Overshoot is bounded and repaid: within one tick, each replica can admit what its local view allows. The excess becomes global debt, and the next tick blocks every replica until it is refilled. Lockout limiters (
follow) also keep syncing every non-full bucket, so a replica sees failures counted elsewhere within one tick. Measured: 10 failures allowed, plus at most 1 per other replica.
- Fail open to local: if the sync fails, the buckets keep working per replica and the consumption is retried (
linora_api_rate_sync_errors_total). LINORA_API_RATE_STORE=local turns the sync off for single-replica setups.
- Keys (SR-10, SR-06):
- Client address: the socket peer, unless it is in
LINORA_TRUSTED_PROXIES (IPs/CIDRs). In that case the right-most untrusted X-Forwarded-For hop. Spoofed headers from untrusted peers are ignored. The same rule and name are used by realtime (SR-05).
- IPv6 is bucketed by its /64; IPv4 by address.
- The sweep drops only full buckets with nothing to sync, never a depleted one. If the map is still full, new keys are refused (
linora_api_rate_refused_new_total) rather than evicting an attacker’s empty bucket.
- Lockout (SR-13): failures per (account, client /64): 10, then 1/min, so an attacker can lock out only themselves. Plus a loose per-account cap of 100 failures per hour from anywhere. Only failures consume.
Alternatives
- Write per request: about 1k writes/s per replica, plus a round trip on the request path. Rejected.
- Counter in the realtime tier: realtime is the scarcest CPU (WP-H: gateways at 97-99%), and this would add a second protocol and a dependency from the API onto it.
- Static split (rate/N per replica): wrong for sticky clients, and N changes with autoscaling.
- Redis: a new tier and a dependency for state Postgres already holds cheaply.
Consequences
- Measured on an M4 Pro at 1k RPS, 200 active users (
npm run bench -w @linorahq/api, 2 runs each): p99 5.9 ms with the sync vs 5.0 ms local; CPU 17% vs 15% of one core. Hot path 19 ns/op.
- Postgres cost: at most one statement per replica per 250 ms, with one row per key touched (coalesced per tick).
- In-flight caps (SR-01 search) stay per replica.
- Tests:
apps/api/test/global-limits.test.ts:
- two replicas share a user bucket (6-7 of 12 allowed vs 12 with
local);
- spoofed XFF is ignored from untrusted peers, and trusted proxies give per-client and per-/64 buckets;
- lockout per (account, client), global across replicas, with the per-account cap;
- eviction never resets a depleted bucket, a full map refuses new keys, and a failing store keeps limits local.