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 insrc/lib.
Layers
RateLimitProvideratomically 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 whyCacheProvider(get, then set) is not reused: two simultaneous requests would both read the same count.createRateLimiterturns hits into an allow or refuse decision withremainingandretryAfterMs.createMemoryRateLimitProviderkeeps windows in process memory. Use it for tests and local development only.createRedisRateLimitProviderrunsINCRandPEXPIREin one Lua script. It never owns the Redis connection.createRateLimitMiddlewarereads each procedure'srateLimitmeta and refuses calls over the limit with the error built by the caller and aretry-afterresponse 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