Files
CatoandClaude 7fc0b7e731 Rate limit: limitkit decides, the windows live in Postgres (#569)
* Rate limit: limitkit decides, the windows live in Postgres

The assistants' limiter was a per-process Map: every deploy gave everyone a
fresh allowance and each instance counted on its own. The decision is now
@bitbaum/limitkit's sliding window, and the windows are held in
rate_limit_windows (migration 0035, additive), one transaction per decision,
serialized per key.

- Seven routes take their bucket from one table of numbers (unchanged).
- Retry-After and the RateLimit headers come from the window, not a constant.
- The address is the hop the proxy wrote (limitkit clientIp), not the first
  X-Forwarded-For entry, which the caller chooses.
- Stored keys are keyed digests; no address or account id is held.
- Without a database, or while it is unreachable, the same rule runs from
  memory and the store is retried after 30 seconds.

Replaces #563, whose migration number collided with 0034_member_person_tag.

Claude-Session: https://claude.ai/code/session_019MDtmup8GiNe1XJoj1caTC

* Rate limit: refusals never reach the database; the limiter has its own pool

Review of this change found that every check, refused or not, ran a
transaction on the app's only pool and waited on the advisory lock while
holding a connection: a flood from one address made unrelated queries wait
seconds. And a database that hangs never fell back to memory.

- A refusal is remembered per process until its window opens (other
  instances can only add hits, so it cannot open earlier), and writes
  nothing when it is decided by the database.
- Decisions for one key run one at a time per process, so a burst from one
  caller takes one connection, not all of them.
- The limiter has its own pool (3 connections, 1 s to get one), lock and
  statement timeouts, and a 1.5 s deadline per decision; past it, memory
  decides. The 30 s back-off is measured from the failure.
- Memory shadows this process's allowed requests, so a fallback continues
  the count instead of starting a fresh one.
- No session secret, no shared store: the keys would be plain digests of
  addresses. The digest input is domain-separated.
- The sweep compares on the database's clock, the one that wrote touched_at.
- The warning log carries an error code, never the query or its parameters.

Measured on Postgres 16: 3000 concurrent requests from one refused caller
allow none, and an unrelated query on another pool answers in 4 ms (it
waited 2.5-6.8 s before).

Claude-Session: https://claude.ai/code/session_019MDtmup8GiNe1XJoj1caTC

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-12 18:34:07 +01:00
..