Skip to content
BoogeyCodesPublic

About

Zero-dependency keyed rate limiting for TypeScript: token-bucket and sliding-window algorithms, LRU key eviction, ESM + CJS

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ratekit

CI TypeScript Zero dependencies ESM + CJS License: MIT

Keyed rate limiting for TypeScript with no runtime dependencies — and a rate-limiting reverse-proxy gateway built on top of it, with a live dashboard, admin API and CLI.

  • The library — two classic algorithms (token bucket, sliding window) behind one small interface, an injectable clock for deterministic tests, and bounded memory for untrusted key spaces. Drops into Express, Fastify, a worker or a CLI. Ships as ESM + CJS with type definitions.
  • The gateway — put ratekit in front of any HTTP upstream without touching its code. Define named policies, map routes to them, key by IP / header / query, and watch it live. Built on Node built-ins only, so the "zero dependencies" promise holds for the product too.

Ratekit Gateway

A standalone reverse proxy that enforces rate policies per route and streams every allowed request through to your upstream, attaching the standard RateLimit-* headers and answering 429 with Retry-After when a key is over budget. A built-in dashboard shows traffic, per-policy allow/deny, the busiest denied keys, and the live state of every tracked key — with a one-click reset.

The Ratekit Gateway dashboard

Quickstart

# Put a 60-req burst / 10-per-second limit in front of an existing service
npx ratekit-gateway --upstream http://localhost:3000 --port 8080

#   → gateway on :8080, dashboard at http://localhost:8080/__ratekit

For anything beyond a single catch-all rule, point it at a config file:

npx ratekit-gateway --config gateway.config.json
{
  "port": 8080,
  "upstream": "http://localhost:3000",
  "policies": {
    "auth":   { "type": "slidingWindow", "limit": 5, "windowMs": 60000 },
    "api":    { "type": "tokenBucket", "capacity": 60, "refillPerSecond": 10 },
    "search": { "type": "tokenBucket", "capacity": 10, "refillPerSecond": 1 }
  },
  "routes": [
    { "pattern": "/api/login", "methods": ["POST"], "policy": "auth",   "key": "ip" },
    { "pattern": "/api/search",                      "policy": "search", "key": "header:x-api-key" },
    { "pattern": "/api/**",                          "policy": "api",    "key": "header:x-api-key" }
  ]
}
  • Routes are matched top to bottom; the first whose pattern and methods match wins. Patterns use * (within a path segment) and ** (across segments). Unmatched requests pass straight through, unlimited.
  • Keys decide who shares a budget: ip, global, header:<name>, query:<name>, or a literal string. Missing values fall back to anonymous.
  • Policies are the two core algorithms, named once and reused.

Embed it

The gateway is also a library. Build one in-process — handy for tests or custom servers:

import { createGateway } from 'ratekit/gateway'

const { server, gate } = createGateway(config)
server.listen(8080)

gate.metrics.snapshot()        // live totals, per-policy stats, timeline
gate.keyStates('api')          // current remaining for each tracked key

Admin API

Served under adminPath (default /__ratekit):

Route Description
GET /__ratekit The dashboard (self-contained HTML)
GET /__ratekit/api/metrics Totals, per-policy breakdown, top denied keys, 60s timeline
GET /__ratekit/api/config Upstream, policies and routes in effect
GET /__ratekit/api/keys?policy=<name> Live state of the keys recently seen under a policy
POST /__ratekit/api/reset { "policy", "key" } — forget a key's state

Docker

docker build -t ratekit-gateway .
docker run -p 8080:8080 -v "$PWD/gateway.config.json:/app/config.json:ro" ratekit-gateway

The core library

import { tokenBucket, rateLimitHeaders } from 'ratekit'

// 10 requests per key, refilling 2 per second (so bursts up to 10, then 2/s sustained)
const limiter = tokenBucket({ capacity: 10, refillPerSecond: 2 })

const result = limiter.check(request.ip)
if (!result.allowed) {
  // result.retryAfterMs tells the caller exactly how long to wait
  return respond(429, rateLimitHeaders(result))
}
handle(request)

Why

Most rate-limiter packages either pull in Redis and a framework, or hide the algorithm behind a decorator. ratekit is the small, explicit alternative for the common in-process case: limit by user, IP or API key, in memory, with the maths visible and tested. It is framework-agnostic — check() returns a plain result and rateLimitHeaders() gives you standard headers to spread onto any response — so it drops into Express, Fastify, a queue worker or a CLI equally well.

Install

npm install ratekit

Node 18+. No runtime dependencies.

The two algorithms

Token bucket Sliding window (log)
Shape of limiting Allows bursts up to capacity, then a steady refillPerSecond A hard ceiling of limit in any trailing windowMs
Good for Smoothing traffic while tolerating short spikes Strict quotas ("100 requests per minute, no exceptions")
Memory per key Two numbers Up to limit timestamps
Boundary spikes None None (unlike a fixed window)

Pick token bucket when a short burst is fine as long as the average holds; pick sliding window when the cap must never be exceeded within the window.

Usage

Token bucket

import { tokenBucket } from 'ratekit'

const limiter = tokenBucket({ capacity: 5, refillPerSecond: 1 })

limiter.check('user-42')        // { allowed: true, remaining: 4, ... }
limiter.check('user-42', 3)     // cost 3 units in one call
limiter.peek('user-42')         // same shape, but consumes nothing

Sliding window

import { slidingWindow } from 'ratekit'

// at most 100 requests in any 60-second window, per key
const limiter = slidingWindow({ limit: 100, windowMs: 60_000 })

const { allowed, remaining, retryAfterMs } = limiter.check(apiKey)

The result

Every check() returns the same shape:

interface RateLimitResult {
  allowed: boolean      // is this request permitted?
  limit: number         // the configured ceiling
  remaining: number     // whole units left right now
  retryAfterMs: number  // how long until a retry would succeed (0 when allowed)
  resetMs: number       // until the key is fully replenished / the window clears
}

When a request is denied, nothing is consumed, and retryAfterMs is the real wait: advance a clock by that amount in a test and the next check() passes.

HTTP headers

import { rateLimitHeaders } from 'ratekit'

for (const [name, value] of Object.entries(rateLimitHeaders(result))) {
  res.setHeader(name, value)
}

Emits RateLimit-Limit, RateLimit-Remaining and RateLimit-Reset (seconds, per the IETF draft), plus Retry-After when denied.

Express example

import express from 'express'
import { slidingWindow, rateLimitHeaders } from 'ratekit'

const limiter = slidingWindow({ limit: 60, windowMs: 60_000 })

app.use((req, res, next) => {
  const result = limiter.check(req.ip ?? 'anonymous')
  for (const [k, v] of Object.entries(rateLimitHeaders(result))) res.setHeader(k, v)
  if (!result.allowed) return res.status(429).json({ error: 'Too many requests' })
  next()
})

Bounded memory

Both limiters keep per-key state in a least-recently-used map. Pass maxKeys (default 10,000) and the least-recently-used key is evicted once the limit is reached, so an untrusted key space (one entry per client IP, say) cannot grow memory without bound. peek(key) reports the same result as check without consuming anything; reset(key) forgets a key explicitly; limiter.size reports how many are tracked.

Deterministic testing

Time is taken from an injectable Clock. The default is the system clock; pass a ManualClock to test limiting without waiting:

import { tokenBucket, ManualClock } from 'ratekit'

const clock = new ManualClock()
const limiter = tokenBucket({ capacity: 1, refillPerSecond: 4, clock })

limiter.check('a').allowed            // true
limiter.check('a').allowed            // false
clock.advance(250)                    // 1 token at 4/second
limiter.check('a').allowed            // true

ratekit's own suite is built this way: every timing assertion advances a manual clock, so the tests are fast and never flaky. The gateway tests go one step further and exercise a real proxy against an in-process upstream over HTTP.

Development

npm install
npm run typecheck
npm test           # 51 tests: limiters, metrics, config, and a live proxy integration suite
npm run build      # dual ESM + CJS + .d.ts via tsup; builds the library, gateway and CLI

API

Library (ratekit)

Export Description
tokenBucket(options) Create a token-bucket Limiter. Options: capacity, refillPerSecond, clock?, maxKeys?
slidingWindow(options) Create a sliding-window Limiter. Options: limit, windowMs, clock?, maxKeys?
rateLimitHeaders(result) Standard rate-limit response headers for a result
systemClock / ManualClock The default clock, and a manual one for tests
Limiter / RateLimitResult The core types

A Limiter is { check(key, cost?), peek(key, cost?), reset(key), size }.

Gateway (ratekit/gateway)

Export Description
createGateway(config, { clock? }) Build an HTTP gateway; returns { server, gate }
startGateway(config) Create and start listening; resolves when bound
RateGate The HTTP-free decision core: evaluate, keyStates, resetKey
MetricsCollector Rolling allow/deny metrics and timeline
validateConfig(config) Throw a descriptive error on a bad config

License

MIT

About

Zero-dependency keyed rate limiting for TypeScript: token-bucket and sliding-window algorithms, LRU key eviction, ESM + CJS

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages