0301. API service: one request pipeline, per-replica caches invalidated by NOTIFY, bounded limits
Status: Accepted (2026-11-27). Builds on 0022, 0023, 0021. Rate limits superseded by 0306: buckets are now global across replicas (local buckets synced through Postgres every 250 ms).
Context
The API must hold p99 < 20 ms at 1k RPS on one instance with minimal memory. It must also stay stateless across replicas: a revoked credential or a removed member must lose access everywhere, immediately. Every route needs the same auth, scope, role, tenant and limit checks, with nothing configured per handler that could be forgotten.
Decision
- One pipeline in
router.ts, driven only by the RouteDef in shared/src/api.ts. Order:
- CORS/preflight
- IP bucket
- authenticate (Bearer PAT wins over the cookie)
- session-only check
- CSRF for cookie mutations
- user + PAT buckets
- PAT scope
- tenant + role from
:projectId/:fileId
- body/query size + schema + uuid/email formats
- handler
In tests every JSON response is checked against its route schema (LINORA_API_VALIDATE_RESPONSES).
- Per-replica TTL caches (30 s, bounded at 50k entries each):
- sessions (keyed by credential id, full hash compared), PATs (by hash)
- memberships (
user|project -> role or “none”), file -> project, page -> file
Every replica LISTENs on linora_auth: cred_revoked, member_*, role_changed, project_deleted and file_deleted drop the matching entries. A LISTEN reconnect clears all caches. The writing replica also applies the event locally right after commit, so its own next request is never stale.
- No writes on the read path:
- Session sliding expiry at most once per hour per session.
- PAT
last_used_at in one UPDATE per 30 s.
- Login failures aggregated per (email, IP) per minute.
- Bounded memory:
- Token buckets per IP, user (shared across all sessions and PATs) and PAT; idle buckets swept and maps capped.
- Per-route body caps and a process-wide budget for buffered bodies over 64 KiB (503 when full).
- argon2id limited to
LINORA_ARGON2_CONCURRENCY (default 2, 64 MiB each) with a bounded queue. The allocator keeps that memory after a login burst, so concurrency x 64 MiB is the RSS ceiling it adds.
Alternatives
- No caches: 2 extra queries per request, about 2x the DB round trips at 1k RPS.
- Shared cache (Redis): another tier and network hop for data Postgres already serves in microseconds.
- Cookie-signed sessions (no DB): revocation would need a denylist anyway.
- Global rate limits in Postgres/Redis: a write per request. Per-replica buckets plus edge LB caps are enough for abuse control.
Consequences
- After a revoke, another replica may serve the credential only for the NOTIFY delivery time (milliseconds; tested < 1 s). If the LISTEN connection drops, caches are cleared, so the worst case is one TTL only when Postgres NOTIFY itself is lost.
- Rate limits scale with the replica count. Measured: p99 5.6 ms at 1k RPS, 17-20% of one core (
npm run bench -w @linorahq/api).