From 58811638e725bb52d16fd53ce055e6c61b61cf9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Sat, 21 Nov 2026 15:46:53 +0700 Subject: [PATCH 01/11] fix(ratelimit)!: align limiter semantics, reset header unit, and default Redis prefix - RateLimitHandlerPlugin sends ratelimit-reset as seconds until reset instead of a Unix timestamp in milliseconds - Memory and Redis-based limiters share one algorithm: per-key fixed windows starting at the key's first hit, and rejected requests do not consume quota - Redis-based limiters default prefix to 'orpc:ratelimit:' instead of '' - RateLimitResult optional fields accept undefined --- apps/content/docs/helpers/ratelimit.mdx | 37 ++++++-- apps/content/docs/migrations/from-v1.mdx | 4 + packages/bun/src/redis-ratelimit.test.ts | 40 +++++++- .../ratelimit/src/adapters/base-redis.test.ts | 76 +++++++++++++++ packages/ratelimit/src/adapters/base-redis.ts | 23 +++-- .../ratelimit/src/adapters/memory.test.ts | 93 ++++++++++++++++--- packages/ratelimit/src/adapters/memory.ts | 58 ++++++++---- packages/ratelimit/src/adapters/redis.test.ts | 36 ++++++- .../ratelimit/src/adapters/upstash.test.ts | 42 ++++++++- packages/ratelimit/src/handler-plugin.test.ts | 38 +++++++- packages/ratelimit/src/handler-plugin.ts | 22 +++-- packages/ratelimit/src/types.ts | 9 +- packages/ratelimit/tests/e2e.test.ts | 4 +- 13 files changed, 411 insertions(+), 71 deletions(-) create mode 100644 packages/ratelimit/src/adapters/base-redis.test.ts diff --git a/apps/content/docs/helpers/ratelimit.mdx b/apps/content/docs/helpers/ratelimit.mdx index 8b44644ba..b6e9febfe 100644 --- a/apps/content/docs/helpers/ratelimit.mdx +++ b/apps/content/docs/helpers/ratelimit.mdx @@ -48,9 +48,19 @@ if (!result.success) { } ``` +### Algorithm + +The memory and Redis-based adapters share the same fixed-window algorithm, so switching between them does not change behavior: + +- **Per-key windows**: each key has its own window of `window` milliseconds, starting at the first request that consumes quota for that key. When it ends, the next request starts a new one. +- **Rejected requests are free**: a request passes only when its `weight` still fits in the key's window. One that does not fit is rejected without consuming anything, so a client that keeps retrying does not push its own reset further away, and a smaller request can still use what is left. +- **Result**: `limit` is `maxRequests`, `remaining` is the quota left in the key's window, and `reset` is the Unix timestamp in milliseconds at which that window ends. + +[`CloudflareRateLimiter`](#cloudflare) is the exception: the Workers Rate Limiting binding runs its own algorithm and only reports `success`. + ### Blocking Mode -Some adapters support blocking mode, which waits until capacity becomes available instead of rejecting requests immediately. Set `timeout` to how long a request may wait, in milliseconds. A request still fails right away when its window will not reset before the timeout elapses. +Some adapters support blocking mode, which waits until capacity becomes available instead of rejecting requests immediately. Set `timeout` to how long a request may wait, in milliseconds. A request still fails right away when its window will not reset before the timeout elapses. Waiting consumes no quota. ```ts const limiter = new MemoryRateLimiter({ @@ -145,6 +155,15 @@ const handler = new RPCHandler(router, { }) ``` +| Header | Value | +| --------------------- | ---------------------------------------------------------------------- | +| `RateLimit-Limit` | Maximum number of requests allowed within a window | +| `RateLimit-Remaining` | Requests left in the current window | +| `RateLimit-Reset` | Seconds until the window resets, rounded up | +| `Retry-After` | Same value as `RateLimit-Reset`, only on a rejected request's response | + +`RateLimit-Reset` is a number of seconds from now, as in the [IETF RateLimit header drafts](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/), not the timestamp found in `result.reset`. A header is omitted when the limiter does not report its value. + :::info You can combine this plugin with [Retry After Plugin](/docs/plugins/retry-after) to enable automatic client-side retries based on server rate limiting headers. ::: @@ -185,7 +204,7 @@ const limiter = new MemoryRateLimiter({ ### Redis -Stores counters in Redis, so every instance using the same server enforces the same limits. +Stores counters in Redis, so every instance using the same server enforces the same limits. Keys are stored as `prefix + key`, and limiters with the same prefix share counters. ```ts import { RedisRateLimiter } from '@orpc/ratelimit/redis' @@ -201,9 +220,9 @@ const limiter = new RedisRateLimiter(client, { /** * The prefix to use for Redis keys. * - * @default '' + * @default 'orpc:ratelimit:' */ - prefix: '', + prefix: 'orpc:ratelimit:', /** * Maximum number of requests allowed within the window. @@ -242,9 +261,9 @@ const limiter = new UpstashRateLimiter(redis, { /** * The prefix to use for Redis keys. * - * @default '' + * @default 'orpc:ratelimit:' */ - prefix: '', + prefix: 'orpc:ratelimit:', /** * Maximum number of requests allowed within the window. @@ -281,9 +300,9 @@ const limiter = new BunRedisRateLimiter(redis, { /** * The prefix to use for Redis keys. * - * @default '' + * @default 'orpc:ratelimit:' */ - prefix: '', + prefix: 'orpc:ratelimit:', /** * Maximum number of requests allowed within the window. @@ -310,7 +329,7 @@ const tenantLimiter = limiter.prefix('tenant:123:') ### Cloudflare -Uses the Workers Rate Limiting binding, so limits are configured in your Worker settings rather than in the adapter. +Uses the Workers Rate Limiting binding, so limits are configured in your Worker settings rather than in the adapter. The binding decides how requests are counted, so the [algorithm](#algorithm) above does not apply: it reports only `success`, and a request with a `weight` above `1` that gets rejected partway has already consumed part of it. ```ts import { CloudflareRateLimiter } from '@orpc/cloudflare' diff --git a/apps/content/docs/migrations/from-v1.mdx b/apps/content/docs/migrations/from-v1.mdx index fee840ee1..22998aa27 100644 --- a/apps/content/docs/migrations/from-v1.mdx +++ b/apps/content/docs/migrations/from-v1.mdx @@ -1344,6 +1344,10 @@ const example = os Blocking mode is now a flat `timeout` option: replace `blockingUntilReady: { enabled: true, timeout }` with `timeout`. +The memory and Redis-based adapters now share one [algorithm](/docs/helpers/ratelimit#algorithm): each key has its own fixed window starting at its first request, and rejected requests no longer consume quota. Redis-based adapters also default `prefix` to `'orpc:ratelimit:'` instead of `''`, so pass `prefix: ''` to keep reading existing keys. + +`RateLimitHandlerPlugin` now sends `RateLimit-Reset` as the number of seconds until the reset, like `Retry-After`, instead of a Unix timestamp in milliseconds. + `UpstashRateLimiter` now takes an Upstash `Redis` client, like the other Upstash adapters, instead of an `@upstash/ratelimit` instance. It enforces a fixed window with `maxRequests` and `window`, shares counters with `RedisRateLimiter`, and no longer takes `waitUntil`. diff --git a/packages/bun/src/redis-ratelimit.test.ts b/packages/bun/src/redis-ratelimit.test.ts index 0cef4f570..5f7f7b2c5 100644 --- a/packages/bun/src/redis-ratelimit.test.ts +++ b/packages/bun/src/redis-ratelimit.test.ts @@ -136,7 +136,7 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => { ) it( - 'uses an empty prefix when none is provided', + 'uses the default prefix when none is provided', async () => { const limiter = await createTestingRateLimiter({ prefix: undefined, @@ -213,6 +213,42 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => { { timeout: 20_000 }, ) + it( + 'does not count rejected requests', + async () => { + const limiter = await createTestingRateLimiter() + const key = 'rejected-not-counted' + + await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ + success: true, + remaining: 1, + }) + + for (let i = 0; i < 5; i++) { + await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ + success: false, + limit: 3, + remaining: 1, + }) + } + + await expect(limiter.limit(key)).resolves.toMatchObject({ + success: true, + remaining: 0, + }) + + // a request that can never fit does not start a window for a new key + const oversized = await limiter.limit('oversized', { weight: 4 }) + expect(oversized).toMatchObject({ success: false, limit: 3, remaining: 3 }) + expect(oversized.reset).toBeGreaterThan(Date.now()) + await expect(limiter.limit('oversized', { weight: 3 })).resolves.toMatchObject({ + success: true, + remaining: 0, + }) + }, + { timeout: 20_000 }, + ) + describe('timeout', () => { it( 'waits until the next window when capacity is unavailable', @@ -288,7 +324,7 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => { await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ success: false, limit: 2, - remaining: 0, + remaining: 1, // the rejected request consumed nothing }) }, { timeout: 20_000 }, diff --git a/packages/ratelimit/src/adapters/base-redis.test.ts b/packages/ratelimit/src/adapters/base-redis.test.ts new file mode 100644 index 000000000..fda9b33c9 --- /dev/null +++ b/packages/ratelimit/src/adapters/base-redis.test.ts @@ -0,0 +1,76 @@ +import { BaseRedisRateLimiter } from './base-redis' + +class TestingRateLimiter extends BaseRedisRateLimiter { + evalScript = vi.fn<(script: string, keys: string[], args: string[]) => Promise>() +} + +describe('baseRedisRateLimiter', () => { + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(10_000) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('sends the weight, window and limit, so the script can check before it consumes', async () => { + const limiter = new TestingRateLimiter({ maxRequests: 5, window: 1000, prefix: 'app:' }) + limiter.evalScript.mockResolvedValueOnce([1, 2, 1000]) + + await expect(limiter.limit('key', { weight: 2 })).resolves.toEqual({ + success: true, + limit: 5, + remaining: 3, + reset: 11_000, + }) + + expect(limiter.evalScript).toHaveBeenCalledTimes(1) + expect(limiter.evalScript).toHaveBeenCalledWith( + expect.any(String), + ['app:key'], + ['2', '1000', '5'], + ) + }) + + it('reports a rejection from the script with the untouched counter', async () => { + const limiter = new TestingRateLimiter({ maxRequests: 5, window: 1000 }) + limiter.evalScript.mockResolvedValueOnce([0, 4, 300]) + + await expect(limiter.limit('key', { weight: 2 })).resolves.toEqual({ + success: false, + limit: 5, + remaining: 1, + reset: 10_300, + }) + }) + + it("defaults the key prefix to 'orpc:ratelimit:'", async () => { + const limiter = new TestingRateLimiter({ maxRequests: 5, window: 1000 }) + limiter.evalScript.mockResolvedValueOnce([1, 1, 1000]) + + await limiter.limit('key') + + expect(limiter.evalScript).toHaveBeenCalledWith( + expect.any(String), + ['orpc:ratelimit:key'], + expect.any(Array), + ) + }) + + it('retries after the window resets when a timeout is set', async () => { + const limiter = new TestingRateLimiter({ maxRequests: 1, window: 500, timeout: 1000 }) + limiter.evalScript.mockResolvedValueOnce([0, 1, 200]).mockResolvedValueOnce([1, 1, 500]) + + const pending = limiter.limit('key') + await vi.advanceTimersByTimeAsync(200) + + await expect(pending).resolves.toEqual({ + success: true, + limit: 1, + remaining: 0, + reset: 10_700, + }) + expect(limiter.evalScript).toHaveBeenCalledTimes(2) + }) +}) diff --git a/packages/ratelimit/src/adapters/base-redis.ts b/packages/ratelimit/src/adapters/base-redis.ts index 2da3ae43f..ccace5de6 100644 --- a/packages/ratelimit/src/adapters/base-redis.ts +++ b/packages/ratelimit/src/adapters/base-redis.ts @@ -2,11 +2,13 @@ import type { RateLimiter, RateLimitOptions, RateLimitResult } from '../types' import { blockUntilReady, resolveWeight } from '../utils' /** - * Consumes `ARGV[1]` points from the counter at `KEYS[1]`, starts a window of - * `ARGV[2]` milliseconds when the counter is new, and replies with `[used, ttl]`. + * Consumes `ARGV[1]` points from the counter at `KEYS[1]` when that keeps it within + * the limit `ARGV[3]`, and leaves the counter untouched otherwise, so a rejected + * request costs nothing. A window of `ARGV[2]` milliseconds starts when the key + * gets its first points. Replies with `[success, used, ttl]`. * Kept on one line because `EVAL` sends it with every call. */ -const FIXED_WINDOW_SCRIPT = `local c=redis.call('INCRBY',KEYS[1],ARGV[1]) if c==tonumber(ARGV[1]) then redis.call('PEXPIRE',KEYS[1],ARGV[2]) end return {c,redis.call('PTTL',KEYS[1])}` +const FIXED_WINDOW_SCRIPT = `local w=tonumber(ARGV[1]) local c=tonumber(redis.call('GET',KEYS[1]) or 0) local t=redis.call('PTTL',KEYS[1]) local s=0 if c+w<=tonumber(ARGV[3]) then c=redis.call('INCRBY',KEYS[1],w) s=1 end if t<0 then t=tonumber(ARGV[2]) if c>0 then redis.call('PEXPIRE',KEYS[1],t) end end return {s,c,t}` /** * Options shared by every Redis-backed rate limiter adapter. @@ -17,7 +19,7 @@ export interface BaseRedisRateLimiterOptions { /** * The prefix to use for Redis keys. * - * @default '' + * @default 'orpc:ratelimit:' */ prefix?: string | undefined @@ -45,6 +47,9 @@ export interface BaseRedisRateLimiterOptions { * the fixed-window script, and the blocking logic, so every adapter built on * it shares counters with the others regardless of the Redis client in use. * + * Each key has its own fixed window, which starts at the first request that + * consumes quota. A rejected request does not consume quota. + * * Extend it and implement `evalScript` to support another Redis client. * * @see {@link https://orpc.dev/docs/helpers/ratelimit#adapters | Rate Limit Helpers - Adapters} @@ -56,7 +61,7 @@ export abstract class BaseRedisRateLimiter implements RateLimiter { protected readonly timeout: number constructor(options: BaseRedisRateLimiterOptions) { - this.keyPrefix = options.prefix ?? '' + this.keyPrefix = options.prefix ?? 'orpc:ratelimit:' this.maxRequests = options.maxRequests this.window = options.window this.timeout = options.timeout ?? 0 @@ -75,14 +80,14 @@ export abstract class BaseRedisRateLimiter implements RateLimiter { } private async checkLimit(key: string, weight: number): Promise> { - const [used, ttl] = (await this.evalScript( + const [success, used, ttl] = (await this.evalScript( FIXED_WINDOW_SCRIPT, [key], - [String(weight), String(this.window)], - )) as [used: number, ttl: number] + [String(weight), String(this.window), String(this.maxRequests)], + )) as [success: number, used: number, ttl: number] return { - success: used <= this.maxRequests, + success: success === 1, limit: this.maxRequests, remaining: Math.max(0, this.maxRequests - used), reset: Date.now() + ttl, diff --git a/packages/ratelimit/src/adapters/memory.test.ts b/packages/ratelimit/src/adapters/memory.test.ts index 54c1d142e..401a63662 100644 --- a/packages/ratelimit/src/adapters/memory.test.ts +++ b/packages/ratelimit/src/adapters/memory.test.ts @@ -91,7 +91,55 @@ describe('memoryRateLimiter', () => { }) }) - it('denies within window and resets counter on new epoch', async () => { + it('starts each key window at that key first hit', async () => { + const limiter = new MemoryRateLimiter({ maxRequests: 1, window: 1000 }) + + expect(await limiter.limit('alice')).toMatchObject({ success: true, reset: 1000 }) + + vi.setSystemTime(400) + expect(await limiter.limit('bob')).toMatchObject({ success: true, reset: 1400 }) + + vi.setSystemTime(1000) // alice's window is over, bob's is not + expect(await limiter.limit('alice')).toMatchObject({ success: true, reset: 2000 }) + expect(await limiter.limit('bob')).toMatchObject({ success: false, reset: 1400 }) + + vi.setSystemTime(1400) + expect(await limiter.limit('bob')).toMatchObject({ success: true, reset: 2400 }) + }) + + it('does not count rejected requests', async () => { + const limiter = new MemoryRateLimiter({ maxRequests: 3, window: 1000 }) + + expect(await limiter.limit('key', { weight: 2 })).toMatchObject({ success: true, remaining: 1 }) + + for (let i = 0; i < 5; i++) { + expect(await limiter.limit('key', { weight: 2 })).toEqual({ + success: false, + limit: 3, + remaining: 1, + reset: 1000, + }) + } + + expect(await limiter.limit('key')).toMatchObject({ success: true, remaining: 0 }) + }) + + it('does not start a window for a request that can never fit', async () => { + const limiter = new MemoryRateLimiter({ maxRequests: 2, window: 1000 }) + + expect(await limiter.limit('key', { weight: 3 })).toEqual({ + success: false, + limit: 2, + remaining: 2, + reset: 1000, + }) + expect((limiter as any).entries.size).toBe(0) + + vi.setSystemTime(500) + expect(await limiter.limit('key', { weight: 2 })).toMatchObject({ success: true, reset: 1500 }) + }) + + it('denies within window and resets counter on new window', async () => { const limiter = new MemoryRateLimiter({ maxRequests: 2, window: 1000 }) expect(await limiter.limit('key')).toEqual({ @@ -115,7 +163,7 @@ describe('memoryRateLimiter', () => { reset: 1000, }) - await vi.advanceTimersByTimeAsync(1) // t=1000 — new epoch + await vi.advanceTimersByTimeAsync(1) // t=1000 — new window expect(await limiter.limit('key', { weight: 2 })).toEqual({ success: true, limit: 2, @@ -130,7 +178,7 @@ describe('memoryRateLimiter', () => { }) }) - it('reset is pegged to epoch start and does not shift mid-window', async () => { + it('reset is pegged to window start and does not shift mid-window', async () => { vi.setSystemTime(200) const limiter = new MemoryRateLimiter({ maxRequests: 3, window: 1000 }) @@ -196,7 +244,7 @@ describe('memoryRateLimiter', () => { }) const pending = limiter.limit('key') - await vi.advanceTimersByTimeAsync(500) // new epoch at t=500 + await vi.advanceTimersByTimeAsync(500) // new window at t=500 expect(await pending).toEqual({ success: true, limit: 1, remaining: 0, reset: 1000 }) }) @@ -216,11 +264,29 @@ describe('memoryRateLimiter', () => { }) const pending = limiter.limit('key', { weight: 2 }) - await vi.advanceTimersByTimeAsync(500) // new epoch at t=500 + await vi.advanceTimersByTimeAsync(500) // new window at t=500 expect(await pending).toEqual({ success: true, limit: 3, remaining: 1, reset: 1000 }) }) + it('does not consume quota while waiting', async () => { + const limiter = new MemoryRateLimiter({ + maxRequests: 2, + window: 500, + timeout: 1000, + }) + + expect(await limiter.limit('key', { weight: 2 })).toMatchObject({ success: true }) + + const pending = [limiter.limit('key'), limiter.limit('key')] + await vi.advanceTimersByTimeAsync(500) + + expect(await Promise.all(pending)).toEqual([ + { success: true, limit: 2, remaining: 1, reset: 1000 }, + { success: true, limit: 2, remaining: 0, reset: 1000 }, + ]) + }) + it('gives up immediately when the wait would exceed the timeout', async () => { const limiter = new MemoryRateLimiter({ maxRequests: 1, @@ -263,17 +329,22 @@ describe('memoryRateLimiter', () => { }) }) - describe('epoch rotation', () => { - it('drops stale keys from memory when the epoch rotates', async () => { + describe('cleanup', () => { + it('drops expired keys from memory', async () => { const limiter = new MemoryRateLimiter({ maxRequests: 5, window: 1000 }) await limiter.limit('key1') + await vi.advanceTimersByTimeAsync(500) await limiter.limit('key2') - expect((limiter as any).current.size).toBe(2) + expect((limiter as any).entries.size).toBe(2) - await vi.advanceTimersByTimeAsync(1000) - await limiter.limit('other') // triggers rotation - expect((limiter as any).current.size).toBe(1) // only 'other' is in current + await vi.advanceTimersByTimeAsync(500) // t=1000 — key1 expired, key2 did not + await limiter.limit('other') // triggers a sweep + expect([...(limiter as any).entries.keys()]).toEqual(['key2', 'other']) + + await vi.advanceTimersByTimeAsync(1000) // t=2000 — everything expired + await limiter.limit('key2') + expect([...(limiter as any).entries.keys()]).toEqual(['key2']) }) }) }) diff --git a/packages/ratelimit/src/adapters/memory.ts b/packages/ratelimit/src/adapters/memory.ts index 6834d003b..5bc6af9ce 100644 --- a/packages/ratelimit/src/adapters/memory.ts +++ b/packages/ratelimit/src/adapters/memory.ts @@ -25,6 +25,9 @@ export interface MemoryRateLimiterOptions { * Rate limiter adapter backed by in-memory storage. Enforces a fixed-window * limit, with optional blocking mode. * + * Each key has its own fixed window, which starts at the first request that + * consumes quota. A rejected request does not consume quota. + * * @see {@link https://orpc.dev/docs/helpers/ratelimit#adapters | Rate Limit Helpers - Adapters} */ export class MemoryRateLimiter implements RateLimiter { @@ -32,8 +35,8 @@ export class MemoryRateLimiter implements RateLimiter { private readonly window: number private readonly timeout: number - private current: Map = new Map() - private currentEpochStart: number = Date.now() + private readonly entries: Map = new Map() + private nextSweepAt: number = 0 constructor(options: MemoryRateLimiterOptions) { this.maxRequests = options.maxRequests @@ -47,38 +50,59 @@ export class MemoryRateLimiter implements RateLimiter { return blockUntilReady(() => this.checkLimit(key, weight), this.timeout) } - private rotateIfNeeded(now: number): void { - if (now < this.currentEpochStart + this.window) { + /** + * Drops expired windows at most once per window, so keys that are never + * seen again do not stay in memory. + */ + private sweepIfNeeded(now: number): void { + if (now < this.nextSweepAt) { return } - this.current = new Map() - this.currentEpochStart = now + for (const [key, entry] of this.entries) { + if (entry.reset <= now) { + this.entries.delete(key) + } + } + + this.nextSweepAt = now + this.window } private checkLimit(key: string, weight: number): Required { const now = Date.now() - this.rotateIfNeeded(now) + this.sweepIfNeeded(now) - let entry = this.current.get(key) + let entry = this.entries.get(key) - if (!entry) { - entry = { used: 0 } - this.current.set(key, entry) + if (entry && entry.reset <= now) { + this.entries.delete(key) + entry = undefined } - const reset = this.currentEpochStart + this.window - const success = entry.used + weight <= this.maxRequests + const used = entry?.used ?? 0 + const success = used + weight <= this.maxRequests - if (success) { - entry.used += weight + if (!success) { + return { + success, + limit: this.maxRequests, + remaining: Math.max(0, this.maxRequests - used), + reset: entry?.reset ?? now + this.window, + } } + if (!entry) { + entry = { used: 0, reset: now + this.window } + this.entries.set(key, entry) + } + + entry.used += weight + return { success, limit: this.maxRequests, - remaining: Math.max(0, this.maxRequests - entry.used), - reset, + remaining: this.maxRequests - entry.used, + reset: entry.reset, } } } diff --git a/packages/ratelimit/src/adapters/redis.test.ts b/packages/ratelimit/src/adapters/redis.test.ts index 3cbe02a45..e6e6638ab 100644 --- a/packages/ratelimit/src/adapters/redis.test.ts +++ b/packages/ratelimit/src/adapters/redis.test.ts @@ -121,7 +121,7 @@ describe.concurrent( expect(Math.abs(denied.reset - first.reset)).toBeLessThanOrEqual(tolerance) }) - it('uses an empty prefix when none is provided', async () => { + it('uses the default prefix when none is provided', async () => { const limiter = await createTestingRateLimiter({ prefix: undefined, maxRequests: 3, @@ -195,6 +195,38 @@ describe.concurrent( }) }) + it('does not count rejected requests', async () => { + const limiter = await createTestingRateLimiter() + const key = 'rejected-not-counted' + + await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ + success: true, + remaining: 1, + }) + + for (let i = 0; i < 5; i++) { + await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ + success: false, + limit: 3, + remaining: 1, + }) + } + + await expect(limiter.limit(key)).resolves.toMatchObject({ + success: true, + remaining: 0, + }) + + // a request that can never fit does not start a window for a new key + const oversized = await limiter.limit('oversized', { weight: 4 }) + expect(oversized).toMatchObject({ success: false, limit: 3, remaining: 3 }) + expect(oversized.reset).toBeGreaterThan(Date.now()) + await expect(limiter.limit('oversized', { weight: 3 })).resolves.toMatchObject({ + success: true, + remaining: 0, + }) + }) + describe('timeout', () => { it('waits until the next window when capacity is unavailable', async () => { const limiter = await createTestingRateLimiter({ @@ -260,7 +292,7 @@ describe.concurrent( await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ success: false, limit: 2, - remaining: 0, + remaining: 1, // the rejected request consumed nothing }) }) }) diff --git a/packages/ratelimit/src/adapters/upstash.test.ts b/packages/ratelimit/src/adapters/upstash.test.ts index c239b1891..f3d67009b 100644 --- a/packages/ratelimit/src/adapters/upstash.test.ts +++ b/packages/ratelimit/src/adapters/upstash.test.ts @@ -143,6 +143,38 @@ describe.concurrent( }) }) + it('does not count rejected requests', async () => { + const limiter = await createTestingRateLimiter() + const key = 'rejected-not-counted' + + await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ + success: true, + remaining: 1, + }) + + for (let i = 0; i < 5; i++) { + await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ + success: false, + limit: 3, + remaining: 1, + }) + } + + await expect(limiter.limit(key)).resolves.toMatchObject({ + success: true, + remaining: 0, + }) + + // a request that can never fit does not start a window for a new key + const oversized = await limiter.limit('oversized', { weight: 4 }) + expect(oversized).toMatchObject({ success: false, limit: 3, remaining: 3 }) + expect(oversized.reset).toBeGreaterThan(Date.now()) + await expect(limiter.limit('oversized', { weight: 3 })).resolves.toMatchObject({ + success: true, + remaining: 0, + }) + }) + describe('timeout', () => { it('waits until the next window when capacity is unavailable', async () => { const limiter = createTestingRateLimiter({ @@ -202,7 +234,7 @@ describe.concurrent( await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ success: false, limit: 2, - remaining: 0, + remaining: 1, // the rejected request consumed nothing }) }) }) @@ -210,7 +242,7 @@ describe.concurrent( ) it('prefix creates a limiter that appends the prefix and shares the client', async () => { - const redis = { eval: vi.fn(async () => [1, 1000]) } + const redis = { eval: vi.fn(async () => [1, 1, 1000]) } const limiter = new UpstashRateLimiter(redis as any, { maxRequests: 1, window: 1000, @@ -218,5 +250,9 @@ it('prefix creates a limiter that appends the prefix and shares the client', asy }).prefix('tenant:') await expect(limiter.limit('key')).resolves.toMatchObject({ success: true, remaining: 0 }) - expect(redis.eval).toHaveBeenCalledWith(expect.any(String), ['app:tenant:key'], ['1', '1000']) + expect(redis.eval).toHaveBeenCalledWith( + expect.any(String), + ['app:tenant:key'], + ['1', '1000', '1'], + ) }) diff --git a/packages/ratelimit/src/handler-plugin.test.ts b/packages/ratelimit/src/handler-plugin.test.ts index 85cf46cfe..c8c2939e0 100644 --- a/packages/ratelimit/src/handler-plugin.test.ts +++ b/packages/ratelimit/src/handler-plugin.test.ts @@ -31,7 +31,7 @@ describe('ratelimitHandlerPlugin', () => { expect(response!.headers.get('ratelimit-limit')).toBe('100') expect(response!.headers.get('ratelimit-remaining')).toBe('50') - expect(response!.headers.get('ratelimit-reset')).toBe(reset.toString()) + expect(response!.headers.get('ratelimit-reset')).toBe('60') // seconds until reset expect(response!.headers.get('retry-after')).toBe(null) }) @@ -57,10 +57,42 @@ describe('ratelimitHandlerPlugin', () => { expect(response!.headers.get('ratelimit-limit')).toBe('100') expect(response!.headers.get('ratelimit-remaining')).toBe('50') - expect(response!.headers.get('ratelimit-reset')).toBe(reset.toString()) + expect(response!.headers.get('ratelimit-reset')).toBe('60') // seconds until reset expect(response!.headers.get('retry-after')).toBe('60') // 60s }) + it('reports ratelimit-reset as seconds until reset, rounded up and never negative', async () => { + vi.useFakeTimers() + vi.setSystemTime(1_700_000_000_000) + + try { + for (const [offset, expected] of [ + [1500, '2'], + [1000, '1'], + [1, '1'], + [0, '0'], + [-5000, '0'], + ] as const) { + handlerFn.mockImplementationOnce(({ context, path, procedure }) => { + context[RATELIMIT_HANDLER_PLUGIN_CONTEXT_SYMBOL].checks.push({ + path, + procedure, + result: { success: false, limit: 10, remaining: 0, reset: Date.now() + offset }, + }) + + throw new ORPCError('TOO_MANY_REQUESTS') + }) + + const { response } = await handler.handle(new Request('http://localhost:3000')) + + expect(response!.headers.get('ratelimit-reset')).toBe(expected) + expect(response!.headers.get('retry-after')).toBe(expected) + } + } finally { + vi.useRealTimers() + } + }) + it('skips rate limit headers when no limit check ran for the request', async () => { const { response } = await handler.handle(new Request('http://localhost:3000')) @@ -129,7 +161,7 @@ describe('ratelimitHandlerPlugin', () => { expect(response!.headers.get('ratelimit-limit')).toBe('100') expect(response!.headers.get('ratelimit-remaining')).toBe('2') - expect(response!.headers.get('ratelimit-reset')).toBe(reset.toString()) + expect(response!.headers.get('ratelimit-reset')).toBe('60') // seconds until reset expect(response!.headers.get('retry-after')).toBe(null) }) }) diff --git a/packages/ratelimit/src/handler-plugin.ts b/packages/ratelimit/src/handler-plugin.ts index 494ab595c..d1ccfb2e6 100644 --- a/packages/ratelimit/src/handler-plugin.ts +++ b/packages/ratelimit/src/handler-plugin.ts @@ -26,6 +26,9 @@ export interface RateLimitHandlerPluginContext { * Automatically adds HTTP rate limiting headers (`RateLimit-*` and `Retry-After`) * to responses when used with the `ratelimit` middleware. * + * `RateLimit-Reset` and `Retry-After` are both the number of seconds until the + * limit resets, rounded up, as in the IETF RateLimit header drafts. + * * @see {@link https://orpc.dev/docs/helpers/ratelimit#handler-plugin | Rate Limit Helpers - Handler Plugin} */ export class RateLimitHandlerPlugin implements StandardHandlerPlugin { @@ -58,22 +61,21 @@ export class RateLimitHandlerPlugin implements StandardHandle (a.result.remaining ?? Infinity) <= (b.result.remaining ?? Infinity) ? a : b, ) + const { reset } = mostConstrained.result + const secondsUntilReset = + reset === undefined + ? undefined + : Math.max(0, Math.ceil((reset - Date.now()) / 1000)).toString() + const headers: StandardHeaders = { ...result.response.headers, 'ratelimit-limit': mostConstrained.result.limit?.toString(), 'ratelimit-remaining': mostConstrained.result.remaining?.toString(), - 'ratelimit-reset': mostConstrained.result.reset?.toString(), + 'ratelimit-reset': secondsUntilReset, } - if ( - result.response.status >= 400 && - !mostConstrained.result.success && - mostConstrained.result.reset !== undefined - ) { - headers['retry-after'] = Math.max( - 0, - Math.ceil((mostConstrained.result.reset - Date.now()) / 1000), - ).toString() + if (result.response.status >= 400 && !mostConstrained.result.success) { + headers['retry-after'] = secondsUntilReset } return { diff --git a/packages/ratelimit/src/types.ts b/packages/ratelimit/src/types.ts index 66b7eb489..b447dc02c 100644 --- a/packages/ratelimit/src/types.ts +++ b/packages/ratelimit/src/types.ts @@ -6,15 +6,15 @@ export interface RateLimitResult { /** * Maximum number of requests allowed within a window. */ - limit?: number + limit?: number | undefined /** * How many requests the user has left within the current window. */ - remaining?: number + remaining?: number | undefined /** * Unix timestamp in milliseconds when the limits are reset. */ - reset?: number + reset?: number | undefined } export interface RateLimitOptions { @@ -31,6 +31,9 @@ export interface RateLimitOptions { * Standard interface for checking and enforcing rate limits. * Implement it for custom strategies, or use one of the provided adapters. * + * A rejected request should not consume quota, which is what the built-in + * fixed-window adapters do. + * * @see {@link https://orpc.dev/docs/helpers/ratelimit | Rate Limit Helpers} */ export interface RateLimiter { diff --git a/packages/ratelimit/tests/e2e.test.ts b/packages/ratelimit/tests/e2e.test.ts index 2b438826e..4a22d0ca9 100644 --- a/packages/ratelimit/tests/e2e.test.ts +++ b/packages/ratelimit/tests/e2e.test.ts @@ -61,6 +61,6 @@ it('works', async () => { expect(response?.status).toBe(429) expect(response?.headers.get('RateLimit-Limit')).toBe('5') expect(response?.headers.get('RateLimit-Remaining')).toBe('0') - expect(response?.headers.get('RateLimit-Reset')).toBeTypeOf('string') - expect(response?.headers.get('Retry-After')).toBeTypeOf('string') + expect(response?.headers.get('RateLimit-Reset')).toBe('1') // seconds left in the 1s window + expect(response?.headers.get('Retry-After')).toBe('1') }) From 50a3373d42278197cc0b24dfc43571e52a04dab7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Sun, 22 Nov 2026 11:14:28 +0700 Subject: [PATCH 02/11] fix(ratelimit): keep the default Redis key prefix empty --- apps/content/docs/helpers/ratelimit.mdx | 12 ++++++------ apps/content/docs/migrations/from-v1.mdx | 2 +- packages/bun/src/redis-ratelimit.test.ts | 2 +- packages/ratelimit/src/adapters/base-redis.test.ts | 8 ++------ packages/ratelimit/src/adapters/base-redis.ts | 4 ++-- packages/ratelimit/src/adapters/redis.test.ts | 2 +- 6 files changed, 13 insertions(+), 17 deletions(-) diff --git a/apps/content/docs/helpers/ratelimit.mdx b/apps/content/docs/helpers/ratelimit.mdx index b6e9febfe..e9681d32d 100644 --- a/apps/content/docs/helpers/ratelimit.mdx +++ b/apps/content/docs/helpers/ratelimit.mdx @@ -220,9 +220,9 @@ const limiter = new RedisRateLimiter(client, { /** * The prefix to use for Redis keys. * - * @default 'orpc:ratelimit:' + * @default '' */ - prefix: 'orpc:ratelimit:', + prefix: '', /** * Maximum number of requests allowed within the window. @@ -261,9 +261,9 @@ const limiter = new UpstashRateLimiter(redis, { /** * The prefix to use for Redis keys. * - * @default 'orpc:ratelimit:' + * @default '' */ - prefix: 'orpc:ratelimit:', + prefix: '', /** * Maximum number of requests allowed within the window. @@ -300,9 +300,9 @@ const limiter = new BunRedisRateLimiter(redis, { /** * The prefix to use for Redis keys. * - * @default 'orpc:ratelimit:' + * @default '' */ - prefix: 'orpc:ratelimit:', + prefix: '', /** * Maximum number of requests allowed within the window. diff --git a/apps/content/docs/migrations/from-v1.mdx b/apps/content/docs/migrations/from-v1.mdx index 22998aa27..d46ae6030 100644 --- a/apps/content/docs/migrations/from-v1.mdx +++ b/apps/content/docs/migrations/from-v1.mdx @@ -1344,7 +1344,7 @@ const example = os Blocking mode is now a flat `timeout` option: replace `blockingUntilReady: { enabled: true, timeout }` with `timeout`. -The memory and Redis-based adapters now share one [algorithm](/docs/helpers/ratelimit#algorithm): each key has its own fixed window starting at its first request, and rejected requests no longer consume quota. Redis-based adapters also default `prefix` to `'orpc:ratelimit:'` instead of `''`, so pass `prefix: ''` to keep reading existing keys. +The memory and Redis-based adapters now share one [algorithm](/docs/helpers/ratelimit#algorithm): each key has its own fixed window starting at its first request, and rejected requests no longer consume quota. `RateLimitHandlerPlugin` now sends `RateLimit-Reset` as the number of seconds until the reset, like `Retry-After`, instead of a Unix timestamp in milliseconds. diff --git a/packages/bun/src/redis-ratelimit.test.ts b/packages/bun/src/redis-ratelimit.test.ts index 5f7f7b2c5..98cd40433 100644 --- a/packages/bun/src/redis-ratelimit.test.ts +++ b/packages/bun/src/redis-ratelimit.test.ts @@ -136,7 +136,7 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => { ) it( - 'uses the default prefix when none is provided', + 'uses an empty prefix when none is provided', async () => { const limiter = await createTestingRateLimiter({ prefix: undefined, diff --git a/packages/ratelimit/src/adapters/base-redis.test.ts b/packages/ratelimit/src/adapters/base-redis.test.ts index fda9b33c9..330a1e59b 100644 --- a/packages/ratelimit/src/adapters/base-redis.test.ts +++ b/packages/ratelimit/src/adapters/base-redis.test.ts @@ -45,17 +45,13 @@ describe('baseRedisRateLimiter', () => { }) }) - it("defaults the key prefix to 'orpc:ratelimit:'", async () => { + it('uses an empty prefix when none is provided', async () => { const limiter = new TestingRateLimiter({ maxRequests: 5, window: 1000 }) limiter.evalScript.mockResolvedValueOnce([1, 1, 1000]) await limiter.limit('key') - expect(limiter.evalScript).toHaveBeenCalledWith( - expect.any(String), - ['orpc:ratelimit:key'], - expect.any(Array), - ) + expect(limiter.evalScript).toHaveBeenCalledWith(expect.any(String), ['key'], expect.any(Array)) }) it('retries after the window resets when a timeout is set', async () => { diff --git a/packages/ratelimit/src/adapters/base-redis.ts b/packages/ratelimit/src/adapters/base-redis.ts index ccace5de6..f31703d59 100644 --- a/packages/ratelimit/src/adapters/base-redis.ts +++ b/packages/ratelimit/src/adapters/base-redis.ts @@ -19,7 +19,7 @@ export interface BaseRedisRateLimiterOptions { /** * The prefix to use for Redis keys. * - * @default 'orpc:ratelimit:' + * @default '' */ prefix?: string | undefined @@ -61,7 +61,7 @@ export abstract class BaseRedisRateLimiter implements RateLimiter { protected readonly timeout: number constructor(options: BaseRedisRateLimiterOptions) { - this.keyPrefix = options.prefix ?? 'orpc:ratelimit:' + this.keyPrefix = options.prefix ?? '' this.maxRequests = options.maxRequests this.window = options.window this.timeout = options.timeout ?? 0 diff --git a/packages/ratelimit/src/adapters/redis.test.ts b/packages/ratelimit/src/adapters/redis.test.ts index e6e6638ab..ed93da1c3 100644 --- a/packages/ratelimit/src/adapters/redis.test.ts +++ b/packages/ratelimit/src/adapters/redis.test.ts @@ -121,7 +121,7 @@ describe.concurrent( expect(Math.abs(denied.reset - first.reset)).toBeLessThanOrEqual(tolerance) }) - it('uses the default prefix when none is provided', async () => { + it('uses an empty prefix when none is provided', async () => { const limiter = await createTestingRateLimiter({ prefix: undefined, maxRequests: 3, From 0b38593979141b1a86e20b4bbaf212e5375560e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Sun, 22 Nov 2026 15:30:37 +0700 Subject: [PATCH 03/11] docs(ratelimit): shorten the algorithm and header notes --- apps/content/docs/helpers/ratelimit.mdx | 24 ++++++------------- apps/content/docs/migrations/from-v1.mdx | 4 ++-- packages/ratelimit/src/adapters/base-redis.ts | 10 ++++---- packages/ratelimit/src/adapters/memory.ts | 6 ++--- packages/ratelimit/src/handler-plugin.ts | 3 +-- packages/ratelimit/src/types.ts | 3 --- 6 files changed, 16 insertions(+), 34 deletions(-) diff --git a/apps/content/docs/helpers/ratelimit.mdx b/apps/content/docs/helpers/ratelimit.mdx index e9681d32d..50f4aedb5 100644 --- a/apps/content/docs/helpers/ratelimit.mdx +++ b/apps/content/docs/helpers/ratelimit.mdx @@ -50,17 +50,14 @@ if (!result.success) { ### Algorithm -The memory and Redis-based adapters share the same fixed-window algorithm, so switching between them does not change behavior: +The memory and Redis-based adapters use the same fixed-window algorithm: -- **Per-key windows**: each key has its own window of `window` milliseconds, starting at the first request that consumes quota for that key. When it ends, the next request starts a new one. -- **Rejected requests are free**: a request passes only when its `weight` still fits in the key's window. One that does not fit is rejected without consuming anything, so a client that keeps retrying does not push its own reset further away, and a smaller request can still use what is left. -- **Result**: `limit` is `maxRequests`, `remaining` is the quota left in the key's window, and `reset` is the Unix timestamp in milliseconds at which that window ends. - -[`CloudflareRateLimiter`](#cloudflare) is the exception: the Workers Rate Limiting binding runs its own algorithm and only reports `success`. +- Each key has its own window, starting at its first request. +- Rejected requests do not consume quota. ### Blocking Mode -Some adapters support blocking mode, which waits until capacity becomes available instead of rejecting requests immediately. Set `timeout` to how long a request may wait, in milliseconds. A request still fails right away when its window will not reset before the timeout elapses. Waiting consumes no quota. +Some adapters support blocking mode, which waits until capacity becomes available instead of rejecting requests immediately. Set `timeout` to how long a request may wait, in milliseconds. A request still fails right away when its window will not reset before the timeout elapses. ```ts const limiter = new MemoryRateLimiter({ @@ -155,14 +152,7 @@ const handler = new RPCHandler(router, { }) ``` -| Header | Value | -| --------------------- | ---------------------------------------------------------------------- | -| `RateLimit-Limit` | Maximum number of requests allowed within a window | -| `RateLimit-Remaining` | Requests left in the current window | -| `RateLimit-Reset` | Seconds until the window resets, rounded up | -| `Retry-After` | Same value as `RateLimit-Reset`, only on a rejected request's response | - -`RateLimit-Reset` is a number of seconds from now, as in the [IETF RateLimit header drafts](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/), not the timestamp found in `result.reset`. A header is omitted when the limiter does not report its value. +`RateLimit-Reset` and `Retry-After` are the number of seconds until the limit resets. :::info You can combine this plugin with [Retry After Plugin](/docs/plugins/retry-after) to enable automatic client-side retries based on server rate limiting headers. @@ -204,7 +194,7 @@ const limiter = new MemoryRateLimiter({ ### Redis -Stores counters in Redis, so every instance using the same server enforces the same limits. Keys are stored as `prefix + key`, and limiters with the same prefix share counters. +Stores counters in Redis, so every instance using the same server enforces the same limits. ```ts import { RedisRateLimiter } from '@orpc/ratelimit/redis' @@ -329,7 +319,7 @@ const tenantLimiter = limiter.prefix('tenant:123:') ### Cloudflare -Uses the Workers Rate Limiting binding, so limits are configured in your Worker settings rather than in the adapter. The binding decides how requests are counted, so the [algorithm](#algorithm) above does not apply: it reports only `success`, and a request with a `weight` above `1` that gets rejected partway has already consumed part of it. +Uses the Workers Rate Limiting binding, so limits are configured in your Worker settings rather than in the adapter. The binding counts requests its own way, so the [algorithm](#algorithm) above does not apply. ```ts import { CloudflareRateLimiter } from '@orpc/cloudflare' diff --git a/apps/content/docs/migrations/from-v1.mdx b/apps/content/docs/migrations/from-v1.mdx index d46ae6030..b22947053 100644 --- a/apps/content/docs/migrations/from-v1.mdx +++ b/apps/content/docs/migrations/from-v1.mdx @@ -1344,9 +1344,9 @@ const example = os Blocking mode is now a flat `timeout` option: replace `blockingUntilReady: { enabled: true, timeout }` with `timeout`. -The memory and Redis-based adapters now share one [algorithm](/docs/helpers/ratelimit#algorithm): each key has its own fixed window starting at its first request, and rejected requests no longer consume quota. +The memory and Redis-based adapters now share one [algorithm](/docs/helpers/ratelimit#algorithm): windows are per key, and rejected requests no longer consume quota. -`RateLimitHandlerPlugin` now sends `RateLimit-Reset` as the number of seconds until the reset, like `Retry-After`, instead of a Unix timestamp in milliseconds. +`RateLimitHandlerPlugin` now sends `RateLimit-Reset` in seconds until the reset, not as a Unix timestamp in milliseconds. `UpstashRateLimiter` now takes an Upstash `Redis` client, like the other Upstash adapters, instead of an `@upstash/ratelimit` instance. It enforces a fixed window with `maxRequests` and `window`, shares counters with `RedisRateLimiter`, and no longer takes `waitUntil`. diff --git a/packages/ratelimit/src/adapters/base-redis.ts b/packages/ratelimit/src/adapters/base-redis.ts index f31703d59..3dc63b98f 100644 --- a/packages/ratelimit/src/adapters/base-redis.ts +++ b/packages/ratelimit/src/adapters/base-redis.ts @@ -2,10 +2,9 @@ import type { RateLimiter, RateLimitOptions, RateLimitResult } from '../types' import { blockUntilReady, resolveWeight } from '../utils' /** - * Consumes `ARGV[1]` points from the counter at `KEYS[1]` when that keeps it within - * the limit `ARGV[3]`, and leaves the counter untouched otherwise, so a rejected - * request costs nothing. A window of `ARGV[2]` milliseconds starts when the key - * gets its first points. Replies with `[success, used, ttl]`. + * Consumes `ARGV[1]` points from the counter at `KEYS[1]` if it stays within the + * limit `ARGV[3]`, starts a window of `ARGV[2]` milliseconds when the counter is + * new, and replies with `[success, used, ttl]`. * Kept on one line because `EVAL` sends it with every call. */ const FIXED_WINDOW_SCRIPT = `local w=tonumber(ARGV[1]) local c=tonumber(redis.call('GET',KEYS[1]) or 0) local t=redis.call('PTTL',KEYS[1]) local s=0 if c+w<=tonumber(ARGV[3]) then c=redis.call('INCRBY',KEYS[1],w) s=1 end if t<0 then t=tonumber(ARGV[2]) if c>0 then redis.call('PEXPIRE',KEYS[1],t) end end return {s,c,t}` @@ -47,8 +46,7 @@ export interface BaseRedisRateLimiterOptions { * the fixed-window script, and the blocking logic, so every adapter built on * it shares counters with the others regardless of the Redis client in use. * - * Each key has its own fixed window, which starts at the first request that - * consumes quota. A rejected request does not consume quota. + * Windows are per key, and rejected requests do not consume quota. * * Extend it and implement `evalScript` to support another Redis client. * diff --git a/packages/ratelimit/src/adapters/memory.ts b/packages/ratelimit/src/adapters/memory.ts index 5bc6af9ce..fe94d5fcf 100644 --- a/packages/ratelimit/src/adapters/memory.ts +++ b/packages/ratelimit/src/adapters/memory.ts @@ -25,8 +25,7 @@ export interface MemoryRateLimiterOptions { * Rate limiter adapter backed by in-memory storage. Enforces a fixed-window * limit, with optional blocking mode. * - * Each key has its own fixed window, which starts at the first request that - * consumes quota. A rejected request does not consume quota. + * Windows are per key, and rejected requests do not consume quota. * * @see {@link https://orpc.dev/docs/helpers/ratelimit#adapters | Rate Limit Helpers - Adapters} */ @@ -51,8 +50,7 @@ export class MemoryRateLimiter implements RateLimiter { } /** - * Drops expired windows at most once per window, so keys that are never - * seen again do not stay in memory. + * Drops expired windows, at most once per window. */ private sweepIfNeeded(now: number): void { if (now < this.nextSweepAt) { diff --git a/packages/ratelimit/src/handler-plugin.ts b/packages/ratelimit/src/handler-plugin.ts index d1ccfb2e6..870debd99 100644 --- a/packages/ratelimit/src/handler-plugin.ts +++ b/packages/ratelimit/src/handler-plugin.ts @@ -26,8 +26,7 @@ export interface RateLimitHandlerPluginContext { * Automatically adds HTTP rate limiting headers (`RateLimit-*` and `Retry-After`) * to responses when used with the `ratelimit` middleware. * - * `RateLimit-Reset` and `Retry-After` are both the number of seconds until the - * limit resets, rounded up, as in the IETF RateLimit header drafts. + * `RateLimit-Reset` and `Retry-After` are in seconds until the limit resets. * * @see {@link https://orpc.dev/docs/helpers/ratelimit#handler-plugin | Rate Limit Helpers - Handler Plugin} */ diff --git a/packages/ratelimit/src/types.ts b/packages/ratelimit/src/types.ts index b447dc02c..f1bec4c19 100644 --- a/packages/ratelimit/src/types.ts +++ b/packages/ratelimit/src/types.ts @@ -31,9 +31,6 @@ export interface RateLimitOptions { * Standard interface for checking and enforcing rate limits. * Implement it for custom strategies, or use one of the provided adapters. * - * A rejected request should not consume quota, which is what the built-in - * fixed-window adapters do. - * * @see {@link https://orpc.dev/docs/helpers/ratelimit | Rate Limit Helpers} */ export interface RateLimiter { From 4567ddb13375b4368231d2b3037e012ce7750f7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Sun, 22 Nov 2026 15:31:07 +0700 Subject: [PATCH 04/11] docs(ratelimit): remove the algorithm section --- apps/content/docs/helpers/ratelimit.mdx | 9 +-------- apps/content/docs/migrations/from-v1.mdx | 2 +- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/apps/content/docs/helpers/ratelimit.mdx b/apps/content/docs/helpers/ratelimit.mdx index 50f4aedb5..677ff825d 100644 --- a/apps/content/docs/helpers/ratelimit.mdx +++ b/apps/content/docs/helpers/ratelimit.mdx @@ -48,13 +48,6 @@ if (!result.success) { } ``` -### Algorithm - -The memory and Redis-based adapters use the same fixed-window algorithm: - -- Each key has its own window, starting at its first request. -- Rejected requests do not consume quota. - ### Blocking Mode Some adapters support blocking mode, which waits until capacity becomes available instead of rejecting requests immediately. Set `timeout` to how long a request may wait, in milliseconds. A request still fails right away when its window will not reset before the timeout elapses. @@ -319,7 +312,7 @@ const tenantLimiter = limiter.prefix('tenant:123:') ### Cloudflare -Uses the Workers Rate Limiting binding, so limits are configured in your Worker settings rather than in the adapter. The binding counts requests its own way, so the [algorithm](#algorithm) above does not apply. +Uses the Workers Rate Limiting binding, so limits are configured in your Worker settings rather than in the adapter. ```ts import { CloudflareRateLimiter } from '@orpc/cloudflare' diff --git a/apps/content/docs/migrations/from-v1.mdx b/apps/content/docs/migrations/from-v1.mdx index b22947053..bb81ff0aa 100644 --- a/apps/content/docs/migrations/from-v1.mdx +++ b/apps/content/docs/migrations/from-v1.mdx @@ -1344,7 +1344,7 @@ const example = os Blocking mode is now a flat `timeout` option: replace `blockingUntilReady: { enabled: true, timeout }` with `timeout`. -The memory and Redis-based adapters now share one [algorithm](/docs/helpers/ratelimit#algorithm): windows are per key, and rejected requests no longer consume quota. +The memory and Redis-based adapters now use per-key windows, and rejected requests no longer consume quota. `RateLimitHandlerPlugin` now sends `RateLimit-Reset` in seconds until the reset, not as a Unix timestamp in milliseconds. From c3c1316a13486786707007e9a7cb677aef5aa9a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Sun, 22 Nov 2026 15:31:28 +0700 Subject: [PATCH 05/11] docs(ratelimit): remove the reset header note --- apps/content/docs/helpers/ratelimit.mdx | 2 -- 1 file changed, 2 deletions(-) diff --git a/apps/content/docs/helpers/ratelimit.mdx b/apps/content/docs/helpers/ratelimit.mdx index 677ff825d..8b44644ba 100644 --- a/apps/content/docs/helpers/ratelimit.mdx +++ b/apps/content/docs/helpers/ratelimit.mdx @@ -145,8 +145,6 @@ const handler = new RPCHandler(router, { }) ``` -`RateLimit-Reset` and `Retry-After` are the number of seconds until the limit resets. - :::info You can combine this plugin with [Retry After Plugin](/docs/plugins/retry-after) to enable automatic client-side retries based on server rate limiting headers. ::: From 12d3614ce2f37b196a5f25c762f27d4fbb292941 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Sun, 22 Nov 2026 15:31:54 +0700 Subject: [PATCH 06/11] docs(ratelimit): remove the migration notes --- apps/content/docs/migrations/from-v1.mdx | 4 ---- 1 file changed, 4 deletions(-) diff --git a/apps/content/docs/migrations/from-v1.mdx b/apps/content/docs/migrations/from-v1.mdx index bb81ff0aa..fee840ee1 100644 --- a/apps/content/docs/migrations/from-v1.mdx +++ b/apps/content/docs/migrations/from-v1.mdx @@ -1344,10 +1344,6 @@ const example = os Blocking mode is now a flat `timeout` option: replace `blockingUntilReady: { enabled: true, timeout }` with `timeout`. -The memory and Redis-based adapters now use per-key windows, and rejected requests no longer consume quota. - -`RateLimitHandlerPlugin` now sends `RateLimit-Reset` in seconds until the reset, not as a Unix timestamp in milliseconds. - `UpstashRateLimiter` now takes an Upstash `Redis` client, like the other Upstash adapters, instead of an `@upstash/ratelimit` instance. It enforces a fixed window with `maxRequests` and `window`, shares counters with `RedisRateLimiter`, and no longer takes `waitUntil`. From 34e5cde77d16523e9409ad1332365dc86029f187 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Sun, 22 Nov 2026 15:34:45 +0700 Subject: [PATCH 07/11] refactor(ratelimit): simplify the memory limiter and dedupe tests --- packages/bun/src/redis-ratelimit.test.ts | 49 +---------- .../ratelimit/src/adapters/memory.test.ts | 86 +------------------ packages/ratelimit/src/adapters/memory.ts | 49 ++++------- packages/ratelimit/src/adapters/redis.test.ts | 37 +------- .../ratelimit/src/adapters/upstash.test.ts | 17 +--- 5 files changed, 22 insertions(+), 216 deletions(-) diff --git a/packages/bun/src/redis-ratelimit.test.ts b/packages/bun/src/redis-ratelimit.test.ts index 98cd40433..175d77bcd 100644 --- a/packages/bun/src/redis-ratelimit.test.ts +++ b/packages/bun/src/redis-ratelimit.test.ts @@ -30,21 +30,6 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => { }) } - it( - 'accepts weighted requests', - async () => { - const limiter = await createTestingRateLimiter() - const key = 'weighted' - - await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ - success: true, - limit: 3, - remaining: 1, - }) - }, - { timeout: 20_000 }, - ) - it( 'tracks counters independently for each key', async () => { @@ -135,24 +120,6 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => { { timeout: 20_000 }, ) - it( - 'uses an empty prefix when none is provided', - async () => { - const limiter = await createTestingRateLimiter({ - prefix: undefined, - maxRequests: 3, - window: 10_000, - }) - - await expect(limiter.limit(`no-prefix-${crypto.randomUUID()}`)).resolves.toMatchObject({ - success: true, - limit: 3, - remaining: 2, - }) - }, - { timeout: 20_000 }, - ) - it( 'rejects invalid weights', async () => { @@ -171,7 +138,7 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => { ) it( - 'consumes quota across multiple requests', + 'consumes quota, then rejects requests that exceed the limit', async () => { const limiter = await createTestingRateLimiter() const key = 'quota' @@ -190,19 +157,6 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => { success: true, remaining: 0, }) - }, - { timeout: 20_000 }, - ) - - it( - 'rejects requests that exceed the limit', - async () => { - const limiter = await createTestingRateLimiter() - const key = 'exceeded' - - await limiter.limit(key) - await limiter.limit(key) - await limiter.limit(key) await expect(limiter.limit(key)).resolves.toMatchObject({ success: false, @@ -324,7 +278,6 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => { await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ success: false, limit: 2, - remaining: 1, // the rejected request consumed nothing }) }, { timeout: 20_000 }, diff --git a/packages/ratelimit/src/adapters/memory.test.ts b/packages/ratelimit/src/adapters/memory.test.ts index 401a63662..66caa9783 100644 --- a/packages/ratelimit/src/adapters/memory.test.ts +++ b/packages/ratelimit/src/adapters/memory.test.ts @@ -39,7 +39,7 @@ describe('memoryRateLimiter', () => { }) }) - it('consumes weight and denies when accumulated weight exceeds the limit', async () => { + it('consumes weight and does not count rejected requests', async () => { const limiter = new MemoryRateLimiter({ maxRequests: 5, window: 1000 }) expect(await limiter.limit('key', { weight: 3 })).toEqual({ @@ -68,29 +68,6 @@ describe('memoryRateLimiter', () => { }) }) - it('tracks limits independently per key', async () => { - const limiter = new MemoryRateLimiter({ maxRequests: 1, window: 1000 }) - - expect(await limiter.limit('alice')).toEqual({ - success: true, - limit: 1, - remaining: 0, - reset: 1000, - }) - expect(await limiter.limit('alice')).toEqual({ - success: false, - limit: 1, - remaining: 0, - reset: 1000, - }) - expect(await limiter.limit('bob')).toEqual({ - success: true, - limit: 1, - remaining: 0, - reset: 1000, - }) - }) - it('starts each key window at that key first hit', async () => { const limiter = new MemoryRateLimiter({ maxRequests: 1, window: 1000 }) @@ -107,23 +84,6 @@ describe('memoryRateLimiter', () => { expect(await limiter.limit('bob')).toMatchObject({ success: true, reset: 2400 }) }) - it('does not count rejected requests', async () => { - const limiter = new MemoryRateLimiter({ maxRequests: 3, window: 1000 }) - - expect(await limiter.limit('key', { weight: 2 })).toMatchObject({ success: true, remaining: 1 }) - - for (let i = 0; i < 5; i++) { - expect(await limiter.limit('key', { weight: 2 })).toEqual({ - success: false, - limit: 3, - remaining: 1, - reset: 1000, - }) - } - - expect(await limiter.limit('key')).toMatchObject({ success: true, remaining: 0 }) - }) - it('does not start a window for a request that can never fit', async () => { const limiter = new MemoryRateLimiter({ maxRequests: 2, window: 1000 }) @@ -142,18 +102,7 @@ describe('memoryRateLimiter', () => { it('denies within window and resets counter on new window', async () => { const limiter = new MemoryRateLimiter({ maxRequests: 2, window: 1000 }) - expect(await limiter.limit('key')).toEqual({ - success: true, - limit: 2, - remaining: 1, - reset: 1000, - }) - expect(await limiter.limit('key')).toEqual({ - success: true, - limit: 2, - remaining: 0, - reset: 1000, - }) + await limiter.limit('key', { weight: 2 }) await vi.advanceTimersByTimeAsync(999) // still inside window expect(await limiter.limit('key')).toEqual({ @@ -164,16 +113,10 @@ describe('memoryRateLimiter', () => { }) await vi.advanceTimersByTimeAsync(1) // t=1000 — new window - expect(await limiter.limit('key', { weight: 2 })).toEqual({ - success: true, - limit: 2, - remaining: 0, - reset: 2000, - }) expect(await limiter.limit('key')).toEqual({ - success: false, + success: true, limit: 2, - remaining: 0, + remaining: 1, reset: 2000, }) }) @@ -306,27 +249,6 @@ describe('memoryRateLimiter', () => { expect(await pending).toEqual({ success: false, limit: 1, remaining: 0, reset: 2000 }) }) - - it('does not block when timeout is 0', async () => { - const limiter = new MemoryRateLimiter({ - maxRequests: 1, - window: 1000, - timeout: 0, - }) - - expect(await limiter.limit('key')).toEqual({ - success: true, - limit: 1, - remaining: 0, - reset: 1000, - }) - expect(await limiter.limit('key')).toEqual({ - success: false, - limit: 1, - remaining: 0, - reset: 1000, - }) - }) }) describe('cleanup', () => { diff --git a/packages/ratelimit/src/adapters/memory.ts b/packages/ratelimit/src/adapters/memory.ts index fe94d5fcf..28cd24629 100644 --- a/packages/ratelimit/src/adapters/memory.ts +++ b/packages/ratelimit/src/adapters/memory.ts @@ -35,7 +35,6 @@ export class MemoryRateLimiter implements RateLimiter { private readonly timeout: number private readonly entries: Map = new Map() - private nextSweepAt: number = 0 constructor(options: MemoryRateLimiterOptions) { this.maxRequests = options.maxRequests @@ -50,57 +49,39 @@ export class MemoryRateLimiter implements RateLimiter { } /** - * Drops expired windows, at most once per window. + * Drops expired windows. Entries are in reset order, so it stops at the first live one. */ - private sweepIfNeeded(now: number): void { - if (now < this.nextSweepAt) { - return - } - + private sweep(now: number): void { for (const [key, entry] of this.entries) { - if (entry.reset <= now) { - this.entries.delete(key) + if (entry.reset > now) { + break } - } - this.nextSweepAt = now + this.window + this.entries.delete(key) + } } private checkLimit(key: string, weight: number): Required { const now = Date.now() - this.sweepIfNeeded(now) + this.sweep(now) let entry = this.entries.get(key) + const success = (entry?.used ?? 0) + weight <= this.maxRequests - if (entry && entry.reset <= now) { - this.entries.delete(key) - entry = undefined - } - - const used = entry?.used ?? 0 - const success = used + weight <= this.maxRequests - - if (!success) { - return { - success, - limit: this.maxRequests, - remaining: Math.max(0, this.maxRequests - used), - reset: entry?.reset ?? now + this.window, + if (success) { + if (!entry) { + entry = { used: 0, reset: now + this.window } + this.entries.set(key, entry) } - } - if (!entry) { - entry = { used: 0, reset: now + this.window } - this.entries.set(key, entry) + entry.used += weight } - entry.used += weight - return { success, limit: this.maxRequests, - remaining: this.maxRequests - entry.used, - reset: entry.reset, + remaining: this.maxRequests - (entry?.used ?? 0), + reset: entry?.reset ?? now + this.window, } } } diff --git a/packages/ratelimit/src/adapters/redis.test.ts b/packages/ratelimit/src/adapters/redis.test.ts index ed93da1c3..fcc956cf1 100644 --- a/packages/ratelimit/src/adapters/redis.test.ts +++ b/packages/ratelimit/src/adapters/redis.test.ts @@ -32,17 +32,6 @@ describe.concurrent( }) } - it('accepts weighted requests', async () => { - const limiter = await createTestingRateLimiter() - const key = 'weighted' - - await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ - success: true, - limit: 3, - remaining: 1, - }) - }) - it('tracks counters independently for each key', async () => { const limiter = await createTestingRateLimiter() @@ -121,20 +110,6 @@ describe.concurrent( expect(Math.abs(denied.reset - first.reset)).toBeLessThanOrEqual(tolerance) }) - it('uses an empty prefix when none is provided', async () => { - const limiter = await createTestingRateLimiter({ - prefix: undefined, - maxRequests: 3, - window: 10_000, - }) - - await expect(limiter.limit(`no-prefix-${crypto.randomUUID()}`)).resolves.toMatchObject({ - success: true, - limit: 3, - remaining: 2, - }) - }) - it('propagates client errors', async () => { const disconnectedRedis = createClient({ url: 'rediss://invalid', @@ -160,7 +135,7 @@ describe.concurrent( ) }) - it('consumes quota across multiple requests', async () => { + it('consumes quota, then rejects requests that exceed the limit', async () => { const limiter = await createTestingRateLimiter() const key = 'quota' @@ -178,15 +153,6 @@ describe.concurrent( success: true, remaining: 0, }) - }) - - it('rejects requests that exceed the limit', async () => { - const limiter = await createTestingRateLimiter() - const key = 'exceeded' - - await limiter.limit(key) - await limiter.limit(key) - await limiter.limit(key) await expect(limiter.limit(key)).resolves.toMatchObject({ success: false, @@ -292,7 +258,6 @@ describe.concurrent( await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ success: false, limit: 2, - remaining: 1, // the rejected request consumed nothing }) }) }) diff --git a/packages/ratelimit/src/adapters/upstash.test.ts b/packages/ratelimit/src/adapters/upstash.test.ts index f3d67009b..1d682afa3 100644 --- a/packages/ratelimit/src/adapters/upstash.test.ts +++ b/packages/ratelimit/src/adapters/upstash.test.ts @@ -35,16 +35,6 @@ describe.concurrent( }) } - it('accepts weighted requests', async () => { - const limiter = createTestingRateLimiter() - - await expect(limiter.limit('weighted', { weight: 2 })).resolves.toMatchObject({ - success: true, - limit: 3, - remaining: 1, - }) - }) - it('tracks counters independently for each key', async () => { const limiter = createTestingRateLimiter() @@ -234,7 +224,6 @@ describe.concurrent( await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ success: false, limit: 2, - remaining: 1, // the rejected request consumed nothing }) }) }) @@ -250,9 +239,5 @@ it('prefix creates a limiter that appends the prefix and shares the client', asy }).prefix('tenant:') await expect(limiter.limit('key')).resolves.toMatchObject({ success: true, remaining: 0 }) - expect(redis.eval).toHaveBeenCalledWith( - expect.any(String), - ['app:tenant:key'], - ['1', '1000', '1'], - ) + expect(redis.eval).toHaveBeenCalledWith(expect.any(String), ['app:tenant:key'], expect.any(Array)) }) From dd326c22c6dd1e62af60e64c0d8bc0e078e68f2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Sun, 22 Nov 2026 15:43:14 +0700 Subject: [PATCH 08/11] test(ratelimit): cover a limiter that reports no reset --- packages/ratelimit/src/handler-plugin.test.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/packages/ratelimit/src/handler-plugin.test.ts b/packages/ratelimit/src/handler-plugin.test.ts index c8c2939e0..85eea89ee 100644 --- a/packages/ratelimit/src/handler-plugin.test.ts +++ b/packages/ratelimit/src/handler-plugin.test.ts @@ -93,6 +93,24 @@ describe('ratelimitHandlerPlugin', () => { } }) + it('omits ratelimit-reset and retry-after when the limiter reports no reset', async () => { + handlerFn.mockImplementationOnce(({ context, path, procedure }) => { + context[RATELIMIT_HANDLER_PLUGIN_CONTEXT_SYMBOL].checks.push({ + path, + procedure, + result: { success: false }, + }) + + throw new ORPCError('TOO_MANY_REQUESTS') + }) + + const { response } = await handler.handle(new Request('http://localhost:3000')) + + expect(response!.status).toBe(429) + expect(response!.headers.get('ratelimit-reset')).toBe(null) + expect(response!.headers.get('retry-after')).toBe(null) + }) + it('skips rate limit headers when no limit check ran for the request', async () => { const { response } = await handler.handle(new Request('http://localhost:3000')) From 62ab9fea15aabc1d5ce2accebff7dfc85ecff2d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Sun, 22 Nov 2026 15:49:05 +0700 Subject: [PATCH 09/11] fix(ratelimit): address review feedback on expiry, retry-after and test clocks --- .../ratelimit/src/adapters/memory.test.ts | 13 +++++ packages/ratelimit/src/adapters/memory.ts | 7 +++ packages/ratelimit/src/handler-plugin.test.ts | 52 ++++++++++--------- packages/ratelimit/src/handler-plugin.ts | 6 ++- packages/ratelimit/tests/e2e.test.ts | 8 +++ 5 files changed, 60 insertions(+), 26 deletions(-) diff --git a/packages/ratelimit/src/adapters/memory.test.ts b/packages/ratelimit/src/adapters/memory.test.ts index 66caa9783..9833fec03 100644 --- a/packages/ratelimit/src/adapters/memory.test.ts +++ b/packages/ratelimit/src/adapters/memory.test.ts @@ -252,6 +252,19 @@ describe('memoryRateLimiter', () => { }) describe('cleanup', () => { + it('resets an expired key even when the clock moved backward', async () => { + const limiter = new MemoryRateLimiter({ maxRequests: 1, window: 1000 }) + + vi.setSystemTime(1000) + expect(await limiter.limit('a')).toMatchObject({ success: true, reset: 2000 }) + + vi.setSystemTime(0) + expect(await limiter.limit('b')).toMatchObject({ success: true, reset: 1000 }) + + vi.setSystemTime(1000) // b expired, but a is still first in the map + expect(await limiter.limit('b')).toMatchObject({ success: true, reset: 2000 }) + }) + it('drops expired keys from memory', async () => { const limiter = new MemoryRateLimiter({ maxRequests: 5, window: 1000 }) diff --git a/packages/ratelimit/src/adapters/memory.ts b/packages/ratelimit/src/adapters/memory.ts index 28cd24629..627ceb4b4 100644 --- a/packages/ratelimit/src/adapters/memory.ts +++ b/packages/ratelimit/src/adapters/memory.ts @@ -66,6 +66,13 @@ export class MemoryRateLimiter implements RateLimiter { this.sweep(now) let entry = this.entries.get(key) + + // the sweep can miss it when the clock moved backward + if (entry && entry.reset <= now) { + this.entries.delete(key) + entry = undefined + } + const success = (entry?.used ?? 0) + weight <= this.maxRequests if (success) { diff --git a/packages/ratelimit/src/handler-plugin.test.ts b/packages/ratelimit/src/handler-plugin.test.ts index 85eea89ee..01b2f28ae 100644 --- a/packages/ratelimit/src/handler-plugin.test.ts +++ b/packages/ratelimit/src/handler-plugin.test.ts @@ -11,6 +11,15 @@ describe('ratelimitHandlerPlugin', () => { plugins: [new RateLimitHandlerPlugin()], }) + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(1_700_000_000_000) + }) + + afterEach(() => { + vi.useRealTimers() + }) + it('adds rate limit headers to a successful response after a limit check', async () => { const reset = Date.now() + 60000 @@ -62,34 +71,27 @@ describe('ratelimitHandlerPlugin', () => { }) it('reports ratelimit-reset as seconds until reset, rounded up and never negative', async () => { - vi.useFakeTimers() - vi.setSystemTime(1_700_000_000_000) - - try { - for (const [offset, expected] of [ - [1500, '2'], - [1000, '1'], - [1, '1'], - [0, '0'], - [-5000, '0'], - ] as const) { - handlerFn.mockImplementationOnce(({ context, path, procedure }) => { - context[RATELIMIT_HANDLER_PLUGIN_CONTEXT_SYMBOL].checks.push({ - path, - procedure, - result: { success: false, limit: 10, remaining: 0, reset: Date.now() + offset }, - }) - - throw new ORPCError('TOO_MANY_REQUESTS') + for (const [offset, expected] of [ + [1500, '2'], + [1000, '1'], + [1, '1'], + [0, '0'], + [-5000, '0'], + ] as const) { + handlerFn.mockImplementationOnce(({ context, path, procedure }) => { + context[RATELIMIT_HANDLER_PLUGIN_CONTEXT_SYMBOL].checks.push({ + path, + procedure, + result: { success: false, limit: 10, remaining: 0, reset: Date.now() + offset }, }) - const { response } = await handler.handle(new Request('http://localhost:3000')) + throw new ORPCError('TOO_MANY_REQUESTS') + }) + + const { response } = await handler.handle(new Request('http://localhost:3000')) - expect(response!.headers.get('ratelimit-reset')).toBe(expected) - expect(response!.headers.get('retry-after')).toBe(expected) - } - } finally { - vi.useRealTimers() + expect(response!.headers.get('ratelimit-reset')).toBe(expected) + expect(response!.headers.get('retry-after')).toBe(expected) } }) diff --git a/packages/ratelimit/src/handler-plugin.ts b/packages/ratelimit/src/handler-plugin.ts index 870debd99..5b2620bf2 100644 --- a/packages/ratelimit/src/handler-plugin.ts +++ b/packages/ratelimit/src/handler-plugin.ts @@ -73,7 +73,11 @@ export class RateLimitHandlerPlugin implements StandardHandle 'ratelimit-reset': secondsUntilReset, } - if (result.response.status >= 400 && !mostConstrained.result.success) { + if ( + result.response.status >= 400 && + !mostConstrained.result.success && + secondsUntilReset !== undefined + ) { headers['retry-after'] = secondsUntilReset } diff --git a/packages/ratelimit/tests/e2e.test.ts b/packages/ratelimit/tests/e2e.test.ts index 4a22d0ca9..c2b93b8bd 100644 --- a/packages/ratelimit/tests/e2e.test.ts +++ b/packages/ratelimit/tests/e2e.test.ts @@ -6,6 +6,14 @@ import { MemoryRateLimiter } from '../src/adapters/memory' import type { RateLimiter } from '../src/index' import { ratelimit, RateLimitHandlerPlugin } from '../src/index' +beforeEach(() => { + vi.useFakeTimers() +}) + +afterEach(() => { + vi.useRealTimers() +}) + it('works', async () => { const router = { login: os From e3eb4c1b1cdc05b019498913226cff92adecb026 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Sun, 22 Nov 2026 17:19:33 +0700 Subject: [PATCH 10/11] fix(ratelimit): restore the original Redis window script --- packages/bun/src/redis-ratelimit.test.ts | 36 ------------------- .../ratelimit/src/adapters/base-redis.test.ts | 20 +++++------ packages/ratelimit/src/adapters/base-redis.ts | 17 ++++----- packages/ratelimit/src/adapters/redis.test.ts | 32 ----------------- .../ratelimit/src/adapters/upstash.test.ts | 34 +----------------- 5 files changed, 16 insertions(+), 123 deletions(-) diff --git a/packages/bun/src/redis-ratelimit.test.ts b/packages/bun/src/redis-ratelimit.test.ts index 175d77bcd..74697aae1 100644 --- a/packages/bun/src/redis-ratelimit.test.ts +++ b/packages/bun/src/redis-ratelimit.test.ts @@ -167,42 +167,6 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => { { timeout: 20_000 }, ) - it( - 'does not count rejected requests', - async () => { - const limiter = await createTestingRateLimiter() - const key = 'rejected-not-counted' - - await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ - success: true, - remaining: 1, - }) - - for (let i = 0; i < 5; i++) { - await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ - success: false, - limit: 3, - remaining: 1, - }) - } - - await expect(limiter.limit(key)).resolves.toMatchObject({ - success: true, - remaining: 0, - }) - - // a request that can never fit does not start a window for a new key - const oversized = await limiter.limit('oversized', { weight: 4 }) - expect(oversized).toMatchObject({ success: false, limit: 3, remaining: 3 }) - expect(oversized.reset).toBeGreaterThan(Date.now()) - await expect(limiter.limit('oversized', { weight: 3 })).resolves.toMatchObject({ - success: true, - remaining: 0, - }) - }, - { timeout: 20_000 }, - ) - describe('timeout', () => { it( 'waits until the next window when capacity is unavailable', diff --git a/packages/ratelimit/src/adapters/base-redis.test.ts b/packages/ratelimit/src/adapters/base-redis.test.ts index 330a1e59b..a50c265e6 100644 --- a/packages/ratelimit/src/adapters/base-redis.test.ts +++ b/packages/ratelimit/src/adapters/base-redis.test.ts @@ -14,9 +14,9 @@ describe('baseRedisRateLimiter', () => { vi.useRealTimers() }) - it('sends the weight, window and limit, so the script can check before it consumes', async () => { + it('sends the weight and window to the script', async () => { const limiter = new TestingRateLimiter({ maxRequests: 5, window: 1000, prefix: 'app:' }) - limiter.evalScript.mockResolvedValueOnce([1, 2, 1000]) + limiter.evalScript.mockResolvedValueOnce([2, 1000]) await expect(limiter.limit('key', { weight: 2 })).resolves.toEqual({ success: true, @@ -26,28 +26,24 @@ describe('baseRedisRateLimiter', () => { }) expect(limiter.evalScript).toHaveBeenCalledTimes(1) - expect(limiter.evalScript).toHaveBeenCalledWith( - expect.any(String), - ['app:key'], - ['2', '1000', '5'], - ) + expect(limiter.evalScript).toHaveBeenCalledWith(expect.any(String), ['app:key'], ['2', '1000']) }) - it('reports a rejection from the script with the untouched counter', async () => { + it('rejects when the counter exceeds the limit', async () => { const limiter = new TestingRateLimiter({ maxRequests: 5, window: 1000 }) - limiter.evalScript.mockResolvedValueOnce([0, 4, 300]) + limiter.evalScript.mockResolvedValueOnce([6, 300]) await expect(limiter.limit('key', { weight: 2 })).resolves.toEqual({ success: false, limit: 5, - remaining: 1, + remaining: 0, reset: 10_300, }) }) it('uses an empty prefix when none is provided', async () => { const limiter = new TestingRateLimiter({ maxRequests: 5, window: 1000 }) - limiter.evalScript.mockResolvedValueOnce([1, 1, 1000]) + limiter.evalScript.mockResolvedValueOnce([1, 1000]) await limiter.limit('key') @@ -56,7 +52,7 @@ describe('baseRedisRateLimiter', () => { it('retries after the window resets when a timeout is set', async () => { const limiter = new TestingRateLimiter({ maxRequests: 1, window: 500, timeout: 1000 }) - limiter.evalScript.mockResolvedValueOnce([0, 1, 200]).mockResolvedValueOnce([1, 1, 500]) + limiter.evalScript.mockResolvedValueOnce([2, 200]).mockResolvedValueOnce([1, 500]) const pending = limiter.limit('key') await vi.advanceTimersByTimeAsync(200) diff --git a/packages/ratelimit/src/adapters/base-redis.ts b/packages/ratelimit/src/adapters/base-redis.ts index 3dc63b98f..2da3ae43f 100644 --- a/packages/ratelimit/src/adapters/base-redis.ts +++ b/packages/ratelimit/src/adapters/base-redis.ts @@ -2,12 +2,11 @@ import type { RateLimiter, RateLimitOptions, RateLimitResult } from '../types' import { blockUntilReady, resolveWeight } from '../utils' /** - * Consumes `ARGV[1]` points from the counter at `KEYS[1]` if it stays within the - * limit `ARGV[3]`, starts a window of `ARGV[2]` milliseconds when the counter is - * new, and replies with `[success, used, ttl]`. + * Consumes `ARGV[1]` points from the counter at `KEYS[1]`, starts a window of + * `ARGV[2]` milliseconds when the counter is new, and replies with `[used, ttl]`. * Kept on one line because `EVAL` sends it with every call. */ -const FIXED_WINDOW_SCRIPT = `local w=tonumber(ARGV[1]) local c=tonumber(redis.call('GET',KEYS[1]) or 0) local t=redis.call('PTTL',KEYS[1]) local s=0 if c+w<=tonumber(ARGV[3]) then c=redis.call('INCRBY',KEYS[1],w) s=1 end if t<0 then t=tonumber(ARGV[2]) if c>0 then redis.call('PEXPIRE',KEYS[1],t) end end return {s,c,t}` +const FIXED_WINDOW_SCRIPT = `local c=redis.call('INCRBY',KEYS[1],ARGV[1]) if c==tonumber(ARGV[1]) then redis.call('PEXPIRE',KEYS[1],ARGV[2]) end return {c,redis.call('PTTL',KEYS[1])}` /** * Options shared by every Redis-backed rate limiter adapter. @@ -46,8 +45,6 @@ export interface BaseRedisRateLimiterOptions { * the fixed-window script, and the blocking logic, so every adapter built on * it shares counters with the others regardless of the Redis client in use. * - * Windows are per key, and rejected requests do not consume quota. - * * Extend it and implement `evalScript` to support another Redis client. * * @see {@link https://orpc.dev/docs/helpers/ratelimit#adapters | Rate Limit Helpers - Adapters} @@ -78,14 +75,14 @@ export abstract class BaseRedisRateLimiter implements RateLimiter { } private async checkLimit(key: string, weight: number): Promise> { - const [success, used, ttl] = (await this.evalScript( + const [used, ttl] = (await this.evalScript( FIXED_WINDOW_SCRIPT, [key], - [String(weight), String(this.window), String(this.maxRequests)], - )) as [success: number, used: number, ttl: number] + [String(weight), String(this.window)], + )) as [used: number, ttl: number] return { - success: success === 1, + success: used <= this.maxRequests, limit: this.maxRequests, remaining: Math.max(0, this.maxRequests - used), reset: Date.now() + ttl, diff --git a/packages/ratelimit/src/adapters/redis.test.ts b/packages/ratelimit/src/adapters/redis.test.ts index fcc956cf1..853cb7b99 100644 --- a/packages/ratelimit/src/adapters/redis.test.ts +++ b/packages/ratelimit/src/adapters/redis.test.ts @@ -161,38 +161,6 @@ describe.concurrent( }) }) - it('does not count rejected requests', async () => { - const limiter = await createTestingRateLimiter() - const key = 'rejected-not-counted' - - await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ - success: true, - remaining: 1, - }) - - for (let i = 0; i < 5; i++) { - await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ - success: false, - limit: 3, - remaining: 1, - }) - } - - await expect(limiter.limit(key)).resolves.toMatchObject({ - success: true, - remaining: 0, - }) - - // a request that can never fit does not start a window for a new key - const oversized = await limiter.limit('oversized', { weight: 4 }) - expect(oversized).toMatchObject({ success: false, limit: 3, remaining: 3 }) - expect(oversized.reset).toBeGreaterThan(Date.now()) - await expect(limiter.limit('oversized', { weight: 3 })).resolves.toMatchObject({ - success: true, - remaining: 0, - }) - }) - describe('timeout', () => { it('waits until the next window when capacity is unavailable', async () => { const limiter = await createTestingRateLimiter({ diff --git a/packages/ratelimit/src/adapters/upstash.test.ts b/packages/ratelimit/src/adapters/upstash.test.ts index 1d682afa3..994323be9 100644 --- a/packages/ratelimit/src/adapters/upstash.test.ts +++ b/packages/ratelimit/src/adapters/upstash.test.ts @@ -133,38 +133,6 @@ describe.concurrent( }) }) - it('does not count rejected requests', async () => { - const limiter = await createTestingRateLimiter() - const key = 'rejected-not-counted' - - await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ - success: true, - remaining: 1, - }) - - for (let i = 0; i < 5; i++) { - await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ - success: false, - limit: 3, - remaining: 1, - }) - } - - await expect(limiter.limit(key)).resolves.toMatchObject({ - success: true, - remaining: 0, - }) - - // a request that can never fit does not start a window for a new key - const oversized = await limiter.limit('oversized', { weight: 4 }) - expect(oversized).toMatchObject({ success: false, limit: 3, remaining: 3 }) - expect(oversized.reset).toBeGreaterThan(Date.now()) - await expect(limiter.limit('oversized', { weight: 3 })).resolves.toMatchObject({ - success: true, - remaining: 0, - }) - }) - describe('timeout', () => { it('waits until the next window when capacity is unavailable', async () => { const limiter = createTestingRateLimiter({ @@ -231,7 +199,7 @@ describe.concurrent( ) it('prefix creates a limiter that appends the prefix and shares the client', async () => { - const redis = { eval: vi.fn(async () => [1, 1, 1000]) } + const redis = { eval: vi.fn(async () => [1, 1000]) } const limiter = new UpstashRateLimiter(redis as any, { maxRequests: 1, window: 1000, From 06e91da148c0c723427a7e1589f623b71d02ad33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C4=90=E1=BB=8Bnh=20L=C3=AA?= Date: Sun, 22 Nov 2026 17:20:11 +0700 Subject: [PATCH 11/11] fix(ratelimit): keep the new Redis window script --- packages/bun/src/redis-ratelimit.test.ts | 36 +++++++++++++++++++ .../ratelimit/src/adapters/base-redis.test.ts | 20 ++++++----- packages/ratelimit/src/adapters/base-redis.ts | 17 +++++---- packages/ratelimit/src/adapters/redis.test.ts | 32 +++++++++++++++++ .../ratelimit/src/adapters/upstash.test.ts | 34 +++++++++++++++++- 5 files changed, 123 insertions(+), 16 deletions(-) diff --git a/packages/bun/src/redis-ratelimit.test.ts b/packages/bun/src/redis-ratelimit.test.ts index 74697aae1..175d77bcd 100644 --- a/packages/bun/src/redis-ratelimit.test.ts +++ b/packages/bun/src/redis-ratelimit.test.ts @@ -167,6 +167,42 @@ describe.skipIf(!REDIS_URL)('bun redis rate limiter integration', async () => { { timeout: 20_000 }, ) + it( + 'does not count rejected requests', + async () => { + const limiter = await createTestingRateLimiter() + const key = 'rejected-not-counted' + + await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ + success: true, + remaining: 1, + }) + + for (let i = 0; i < 5; i++) { + await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ + success: false, + limit: 3, + remaining: 1, + }) + } + + await expect(limiter.limit(key)).resolves.toMatchObject({ + success: true, + remaining: 0, + }) + + // a request that can never fit does not start a window for a new key + const oversized = await limiter.limit('oversized', { weight: 4 }) + expect(oversized).toMatchObject({ success: false, limit: 3, remaining: 3 }) + expect(oversized.reset).toBeGreaterThan(Date.now()) + await expect(limiter.limit('oversized', { weight: 3 })).resolves.toMatchObject({ + success: true, + remaining: 0, + }) + }, + { timeout: 20_000 }, + ) + describe('timeout', () => { it( 'waits until the next window when capacity is unavailable', diff --git a/packages/ratelimit/src/adapters/base-redis.test.ts b/packages/ratelimit/src/adapters/base-redis.test.ts index a50c265e6..330a1e59b 100644 --- a/packages/ratelimit/src/adapters/base-redis.test.ts +++ b/packages/ratelimit/src/adapters/base-redis.test.ts @@ -14,9 +14,9 @@ describe('baseRedisRateLimiter', () => { vi.useRealTimers() }) - it('sends the weight and window to the script', async () => { + it('sends the weight, window and limit, so the script can check before it consumes', async () => { const limiter = new TestingRateLimiter({ maxRequests: 5, window: 1000, prefix: 'app:' }) - limiter.evalScript.mockResolvedValueOnce([2, 1000]) + limiter.evalScript.mockResolvedValueOnce([1, 2, 1000]) await expect(limiter.limit('key', { weight: 2 })).resolves.toEqual({ success: true, @@ -26,24 +26,28 @@ describe('baseRedisRateLimiter', () => { }) expect(limiter.evalScript).toHaveBeenCalledTimes(1) - expect(limiter.evalScript).toHaveBeenCalledWith(expect.any(String), ['app:key'], ['2', '1000']) + expect(limiter.evalScript).toHaveBeenCalledWith( + expect.any(String), + ['app:key'], + ['2', '1000', '5'], + ) }) - it('rejects when the counter exceeds the limit', async () => { + it('reports a rejection from the script with the untouched counter', async () => { const limiter = new TestingRateLimiter({ maxRequests: 5, window: 1000 }) - limiter.evalScript.mockResolvedValueOnce([6, 300]) + limiter.evalScript.mockResolvedValueOnce([0, 4, 300]) await expect(limiter.limit('key', { weight: 2 })).resolves.toEqual({ success: false, limit: 5, - remaining: 0, + remaining: 1, reset: 10_300, }) }) it('uses an empty prefix when none is provided', async () => { const limiter = new TestingRateLimiter({ maxRequests: 5, window: 1000 }) - limiter.evalScript.mockResolvedValueOnce([1, 1000]) + limiter.evalScript.mockResolvedValueOnce([1, 1, 1000]) await limiter.limit('key') @@ -52,7 +56,7 @@ describe('baseRedisRateLimiter', () => { it('retries after the window resets when a timeout is set', async () => { const limiter = new TestingRateLimiter({ maxRequests: 1, window: 500, timeout: 1000 }) - limiter.evalScript.mockResolvedValueOnce([2, 200]).mockResolvedValueOnce([1, 500]) + limiter.evalScript.mockResolvedValueOnce([0, 1, 200]).mockResolvedValueOnce([1, 1, 500]) const pending = limiter.limit('key') await vi.advanceTimersByTimeAsync(200) diff --git a/packages/ratelimit/src/adapters/base-redis.ts b/packages/ratelimit/src/adapters/base-redis.ts index 2da3ae43f..3dc63b98f 100644 --- a/packages/ratelimit/src/adapters/base-redis.ts +++ b/packages/ratelimit/src/adapters/base-redis.ts @@ -2,11 +2,12 @@ import type { RateLimiter, RateLimitOptions, RateLimitResult } from '../types' import { blockUntilReady, resolveWeight } from '../utils' /** - * Consumes `ARGV[1]` points from the counter at `KEYS[1]`, starts a window of - * `ARGV[2]` milliseconds when the counter is new, and replies with `[used, ttl]`. + * Consumes `ARGV[1]` points from the counter at `KEYS[1]` if it stays within the + * limit `ARGV[3]`, starts a window of `ARGV[2]` milliseconds when the counter is + * new, and replies with `[success, used, ttl]`. * Kept on one line because `EVAL` sends it with every call. */ -const FIXED_WINDOW_SCRIPT = `local c=redis.call('INCRBY',KEYS[1],ARGV[1]) if c==tonumber(ARGV[1]) then redis.call('PEXPIRE',KEYS[1],ARGV[2]) end return {c,redis.call('PTTL',KEYS[1])}` +const FIXED_WINDOW_SCRIPT = `local w=tonumber(ARGV[1]) local c=tonumber(redis.call('GET',KEYS[1]) or 0) local t=redis.call('PTTL',KEYS[1]) local s=0 if c+w<=tonumber(ARGV[3]) then c=redis.call('INCRBY',KEYS[1],w) s=1 end if t<0 then t=tonumber(ARGV[2]) if c>0 then redis.call('PEXPIRE',KEYS[1],t) end end return {s,c,t}` /** * Options shared by every Redis-backed rate limiter adapter. @@ -45,6 +46,8 @@ export interface BaseRedisRateLimiterOptions { * the fixed-window script, and the blocking logic, so every adapter built on * it shares counters with the others regardless of the Redis client in use. * + * Windows are per key, and rejected requests do not consume quota. + * * Extend it and implement `evalScript` to support another Redis client. * * @see {@link https://orpc.dev/docs/helpers/ratelimit#adapters | Rate Limit Helpers - Adapters} @@ -75,14 +78,14 @@ export abstract class BaseRedisRateLimiter implements RateLimiter { } private async checkLimit(key: string, weight: number): Promise> { - const [used, ttl] = (await this.evalScript( + const [success, used, ttl] = (await this.evalScript( FIXED_WINDOW_SCRIPT, [key], - [String(weight), String(this.window)], - )) as [used: number, ttl: number] + [String(weight), String(this.window), String(this.maxRequests)], + )) as [success: number, used: number, ttl: number] return { - success: used <= this.maxRequests, + success: success === 1, limit: this.maxRequests, remaining: Math.max(0, this.maxRequests - used), reset: Date.now() + ttl, diff --git a/packages/ratelimit/src/adapters/redis.test.ts b/packages/ratelimit/src/adapters/redis.test.ts index 853cb7b99..fcc956cf1 100644 --- a/packages/ratelimit/src/adapters/redis.test.ts +++ b/packages/ratelimit/src/adapters/redis.test.ts @@ -161,6 +161,38 @@ describe.concurrent( }) }) + it('does not count rejected requests', async () => { + const limiter = await createTestingRateLimiter() + const key = 'rejected-not-counted' + + await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ + success: true, + remaining: 1, + }) + + for (let i = 0; i < 5; i++) { + await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ + success: false, + limit: 3, + remaining: 1, + }) + } + + await expect(limiter.limit(key)).resolves.toMatchObject({ + success: true, + remaining: 0, + }) + + // a request that can never fit does not start a window for a new key + const oversized = await limiter.limit('oversized', { weight: 4 }) + expect(oversized).toMatchObject({ success: false, limit: 3, remaining: 3 }) + expect(oversized.reset).toBeGreaterThan(Date.now()) + await expect(limiter.limit('oversized', { weight: 3 })).resolves.toMatchObject({ + success: true, + remaining: 0, + }) + }) + describe('timeout', () => { it('waits until the next window when capacity is unavailable', async () => { const limiter = await createTestingRateLimiter({ diff --git a/packages/ratelimit/src/adapters/upstash.test.ts b/packages/ratelimit/src/adapters/upstash.test.ts index 994323be9..1d682afa3 100644 --- a/packages/ratelimit/src/adapters/upstash.test.ts +++ b/packages/ratelimit/src/adapters/upstash.test.ts @@ -133,6 +133,38 @@ describe.concurrent( }) }) + it('does not count rejected requests', async () => { + const limiter = await createTestingRateLimiter() + const key = 'rejected-not-counted' + + await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ + success: true, + remaining: 1, + }) + + for (let i = 0; i < 5; i++) { + await expect(limiter.limit(key, { weight: 2 })).resolves.toMatchObject({ + success: false, + limit: 3, + remaining: 1, + }) + } + + await expect(limiter.limit(key)).resolves.toMatchObject({ + success: true, + remaining: 0, + }) + + // a request that can never fit does not start a window for a new key + const oversized = await limiter.limit('oversized', { weight: 4 }) + expect(oversized).toMatchObject({ success: false, limit: 3, remaining: 3 }) + expect(oversized.reset).toBeGreaterThan(Date.now()) + await expect(limiter.limit('oversized', { weight: 3 })).resolves.toMatchObject({ + success: true, + remaining: 0, + }) + }) + describe('timeout', () => { it('waits until the next window when capacity is unavailable', async () => { const limiter = createTestingRateLimiter({ @@ -199,7 +231,7 @@ describe.concurrent( ) it('prefix creates a limiter that appends the prefix and shares the client', async () => { - const redis = { eval: vi.fn(async () => [1, 1000]) } + const redis = { eval: vi.fn(async () => [1, 1, 1000]) } const limiter = new UpstashRateLimiter(redis as any, { maxRequests: 1, window: 1000,