Mao NakamotoandClaude Opus 5 9010598cab feat: limitkit — rate limiting as a decision, extracted from twelve copies
Twelve near-identical rate limiters existed across nine repos of this fleet.
orangecat alone carried four, and its ADR-0002 to unify them sat "Proposed" for
seven months while the count doubled — the measured proof that writing a plan
down is not the same as extracting the code.

What actually varied between the twelve was ONE thing: where the counts live
(eleven in process memory, one in Upstash). Everything else — window
arithmetic, refusal shape, headers, client-IP extraction — was the same idea
written twelve slightly different ways, with independently re-invented bugs.
So the algorithm is fixed and the store is the seam:

  slidingWindow / fixedWindow  pure over store + clock. Both shapes shipped in
                               the fleet, and they refuse differently; the
                               choice is now named at the call site instead of
                               implied by whichever file got copied.
  Store / MemoryStore          two methods. The default is BOUNDED (LRU past
                               maxKeys): one replaced implementation kept a
                               bare Map keyed by stranger IPs with no eviction
                               — a slow memory leak fed by the public
                               internet, now impossible by construction.
  toHeaders / clientIp         the HTTP edges everyone also rewrote. Standard
                               X-RateLimit-* trio, Retry-After on refusals
                               only — exactly what orangecat's ADR specified.

Two decisions worth naming:

  A REFUSAL COUNTS NOTHING. Several replaced implementations let refused
  requests extend the window, so a scripted attacker hammering a key locked
  the legitimate user behind the same NAT out indefinitely. Here a hammered
  key recovers the moment the attacker stops; there is a test for exactly
  this shape.

  retryAfterSeconds IS DERIVED, never fabricated — computed from when the
  oldest counted hit ages out. "Try again shortly" on a window that opens in
  an hour is the same lie ai-ration's 429 classifier exists to prevent, one
  layer down.

Deliberately not included, per SHARED.md's extraction rules: no HTTP client,
no middleware, no framework types, no distributed store (the seam is two
methods; your Redis is your ops posture), and NO LIMIT VALUES — how many
attempts a login route allows is app semantics, asserted locally.

Every function takes `now` as an argument, so all of it is testable without
sleeping — which is why this package has 14 tests and the twelve files it
replaces, collectively, had almost none. Tests import the package BY NAME, so
the exports map is exercised on every run, not at the first consumer's
install.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 15:55:38 +02:00

limitkit

Rate limiting as a decision, not a middleware.

npm install github:maonakamoto/limitkit#v0.1.0

Why this exists

Twelve near-identical rate limiters were found across nine repos of one fleet — orangecat alone carried four, and its ADR to unify them sat "Proposed" for seven months while the count doubled. What actually varied between the twelve was one thing: where the counts live. Everything else — the window arithmetic, the refusal shape, the headers, the client-IP dance — was the same idea written twelve slightly different ways, with independently re-invented bugs (one kept an unbounded Map keyed by stranger IPs: a slow memory leak fed by the public internet).

So the algorithm is fixed and the store is the seam.

Use

import { slidingWindow, clientIp, toHeaders } from 'limitkit';

const loginLimiter = slidingWindow({ limit: 5, windowMs: 15 * 60_000 });

export async function POST(req: Request) {
  const result = loginLimiter.check(`login:${clientIp(req.headers)}`);
  if (!result.allowed) {
    return Response.json(
      { error: 'Too many attempts' },
      { status: 429, headers: toHeaders(result) },
    );
  }
  // ... the actual work, with toHeaders(result) on the success path too if you like
}
  • slidingWindow(rule, store?) — N hits per trailing window. The default; it is what most hand-rolled "fixed" windows actually meant.
  • fixedWindow(rule, store?) — N hits per aligned bucket. Cheaper, burstier at the boundary (up to 2N around a roll). Choose it by name, not by accident.
  • check counts the hit when allowed and counts nothing when refused — a hammered key recovers the moment the attacker stops, instead of locking the legitimate user behind the same NAT out forever.
  • The refusal's retryAfterSeconds is derived from the actual oldest hit, never fabricated. "Try again shortly" on a window that opens in an hour is a lie; this package refuses to tell it.

The store seam

interface Store {
  get(key: string): { hits: number[] } | undefined;
  set(key: string, state: { hits: number[] }): void;
}

The default MemoryStore is bounded (LRU past maxKeys, default 5 000) — the unbounded-Map leak is impossible by construction. It is per-process: behind N workers the effective limit multiplies by N, which is fine for blunting scripted abuse and wrong for billing enforcement. For shared state, implement those two methods over Redis/Postgres — an adapter is a dozen lines, because the store holds and the algorithm decides.

HTTP edges

  • toHeaders(result) — X-RateLimit-Limit / -Remaining / -Reset, plus Retry-After on refusals only. A plain object you spread into your own response; constructing a Response would mean choosing your framework for you.
  • clientIp(headers) — first x-forwarded-for hop, then x-real-ip, then "unknown". Only as honest as the proxy in front of you; the "unknown" fallback throttles anonymous traffic collectively rather than throwing.

Deliberately not included

  • No HTTP client, no middleware, no framework types — the package supplies the decision; your app keeps its conventions.
  • No limit values — how many attempts a login route allows is app semantics. Centralize the rule; assert the numbers locally.
  • No distributed store — that is your Redis and your ops posture. The seam is two methods.

Everything takes now as an argument, so all of it is testable without sleeping — which is why this package has tests and the twelve files it replaces, collectively, had almost none.

Development

npm run verify   # lint + typecheck + build + test (tests import by package name)

MIT.

S
Description
No description provided
Readme MIT
243 KiB
0 Stars 2 Watchers 0 Forks
Languages
TypeScript 61.5%
JavaScript 38.5%