Skip to Content
gentlemans-stack
ReferenceLibs

rate-limit

Fixed-window rate limiting with pluggable stores and an oRPC middleware driven by procedure metadata.

API

  • createRateLimiter, createRateLimitMiddleware: the limiter and its oRPC middleware.
  • createMemoryRateLimitProvider, createRedisRateLimitProvider: storage providers.
  • assertValidRateLimit: validates a rule at startup.
  • Types: RateLimitRule, RateLimitMeta, RateLimitProvider, RateLimitMiddleware, and others in src/lib.

Layers

  • RateLimitProvider atomically adds one hit to a window and returns the new count and the window's reset time. This is the only operation the limiter needs, which is why CacheProvider (get, then set) is not reused: two simultaneous requests would both read the same count.
  • createRateLimiter turns hits into an allow or refuse decision with remaining and retryAfterMs.
  • createMemoryRateLimitProvider keeps windows in process memory. Use it for tests and local development only.
  • createRedisRateLimitProvider runs INCR and PEXPIRE in one Lua script. It never owns the Redis connection.
  • createRateLimitMiddleware reads each procedure's rateLimit meta and refuses calls over the limit with the error built by the caller and a retry-after response header.

The library has no database dependency. The MongoDB provider lives in connectors/mongodb-connector.

Usage

import { createRateLimiter } from "@gentlemans-stack/rate-limit/rate-limiter";
import { createRedisRateLimitProvider } from "@gentlemans-stack/rate-limit/redis-rate-limit-provider";

const rateLimiter = createRateLimiter(createRedisRateLimitProvider(redis, { namespace: "my-service", now: undefined }));

Declare the metadata on the contract, then per procedure. Each rule names a dimension (by), a limit and a windowMs.

const create = base.route({ ... }).meta({
	rateLimit: {
		onStoreFailure: "open",
		rules: [{ by: "ip", limit: 30, windowMs: 60_000 }],
	},
});

Every rule is checked in order and the call is refused if any one is over its limit. Give each dimension at most one rule. The middleware asks resolveSubject for each dimension's subject. Returning undefined skips that dimension. Keep raw personal data out of the subject: hash it before it reaches the store.

const rateLimit = createRateLimitMiddleware<AppContext>({
	createLimitExceededError: ({ retryAfterSeconds }) => new AppError("RATE_LIMIT_EXCEEDED", { cause: "too_many_requests" }),
	resolveSubject: ({ context, dimension, input }) => ...,
});
const implementer = implement(contract).$context<AppContext>().use(rateLimit);

AppContext must provide logger, rateLimiter, and responseHeaders (a Headers the transport copies onto the response).

When the store fails, a procedure with onStoreFailure: "open" (the default) logs an error and lets the call through. "closed" rethrows the store error.

Commands

pnpm nx run rate-limit:typecheck   # type-check the package
pnpm nx run rate-limit:test        # run the Vitest suite

On this page