|
| 1 | +--- |
| 2 | +title: Rate Limit |
| 3 | +description: Rate limiting features for oRPC with multiple adapters support. |
| 4 | +--- |
| 5 | + |
| 6 | +# Rate Limit |
| 7 | + |
| 8 | +The Rate Limit package provides flexible rate limiting for oRPC with multiple storage backend support. It includes adapters for in-memory, Redis, and Upstash, along with middleware and plugin helpers for seamless integration. |
| 9 | + |
| 10 | +## Installation |
| 11 | + |
| 12 | +::: code-group |
| 13 | + |
| 14 | +```sh [npm] |
| 15 | +npm install @orpc/experimental-ratelimit@latest |
| 16 | +``` |
| 17 | + |
| 18 | +```sh [yarn] |
| 19 | +yarn add @orpc/experimental-ratelimit@latest |
| 20 | +``` |
| 21 | + |
| 22 | +```sh [pnpm] |
| 23 | +pnpm add @orpc/experimental-ratelimit@latest |
| 24 | +``` |
| 25 | + |
| 26 | +```sh [bun] |
| 27 | +bun add @orpc/experimental-ratelimit@latest |
| 28 | +``` |
| 29 | + |
| 30 | +```sh [deno] |
| 31 | +deno add npm:@orpc/experimental-ratelimit@latest |
| 32 | +``` |
| 33 | + |
| 34 | +::: |
| 35 | + |
| 36 | +## Available Adapters |
| 37 | + |
| 38 | +### Memory Adapter |
| 39 | + |
| 40 | +A simple in-memory rate limiter using a sliding window log algorithm. Ideal for single-instance applications or development. |
| 41 | + |
| 42 | +```ts |
| 43 | +import { MemoryRatelimiter } from '@orpc/experimental-ratelimit/memory' |
| 44 | + |
| 45 | +const limiter = new MemoryRatelimiter({ |
| 46 | + maxRequests: 10, // Maximum requests allowed |
| 47 | + window: 60000, // Time window in milliseconds (60 seconds) |
| 48 | +}) |
| 49 | +``` |
| 50 | + |
| 51 | +### Redis Adapter |
| 52 | + |
| 53 | +Redis-based rate limiter using atomic Lua scripts for distributed rate limiting. |
| 54 | + |
| 55 | +```ts |
| 56 | +import { RedisRatelimiter } from '@orpc/experimental-ratelimit/redis' |
| 57 | +import { Redis } from 'ioredis' |
| 58 | + |
| 59 | +const redis = new Redis('redis://localhost:6379') |
| 60 | + |
| 61 | +const limiter = new RedisRatelimiter({ |
| 62 | + eval: async (script, numKeys, ...rest) => { |
| 63 | + return redis.eval(script, numKeys, ...rest) |
| 64 | + }, |
| 65 | + maxRequests: 100, |
| 66 | + window: 60000, |
| 67 | + prefix: 'orpc:ratelimit:', // Optional key prefix |
| 68 | +}) |
| 69 | +``` |
| 70 | + |
| 71 | +::: info |
| 72 | +You can use any Redis client that supports Lua script evaluation by providing an `eval` function. |
| 73 | +::: |
| 74 | + |
| 75 | +### Upstash Adapter |
| 76 | + |
| 77 | +Adapter for [@upstash/ratelimit](https://www.npmjs.com/package/@upstash/ratelimit), optimized for serverless environments like Vercel Edge and Cloudflare Workers. |
| 78 | + |
| 79 | +```ts |
| 80 | +import { Ratelimit } from '@upstash/ratelimit' |
| 81 | +import { Redis } from '@upstash/redis' |
| 82 | +import { UpstashRatelimiter } from '@orpc/experimental-ratelimit/upstash-ratelimit' |
| 83 | + |
| 84 | +const redis = Redis.fromEnv() |
| 85 | + |
| 86 | +const ratelimit = new Ratelimit({ |
| 87 | + redis, |
| 88 | + limiter: Ratelimit.slidingWindow(10, '60 s'), |
| 89 | + prefix: 'my-app:', |
| 90 | +}) |
| 91 | + |
| 92 | +const limiter = new UpstashRatelimiter(ratelimit) |
| 93 | +``` |
| 94 | + |
| 95 | +::: tip Edge Runtime Support |
| 96 | +For Edge runtime like Vercel Edge or Cloudflare Workers, pass the `waitUntil` function to better handle background tasks: |
| 97 | + |
| 98 | +```ts |
| 99 | +const limiter = new UpstashRatelimiter(ratelimit, { |
| 100 | + waitUntil: ctx.waitUntil.bind(ctx), |
| 101 | +}) |
| 102 | +``` |
| 103 | + |
| 104 | +::: |
| 105 | + |
| 106 | +## Blocking Mode |
| 107 | + |
| 108 | +Some adapters support blocking mode, which waits for the rate limit to reset instead of immediately rejecting requests. |
| 109 | + |
| 110 | +```ts |
| 111 | +const limiter = new MemoryRatelimiter({ |
| 112 | + maxRequests: 10, |
| 113 | + window: 60000, |
| 114 | + blockingUntilReady: { |
| 115 | + enabled: true, |
| 116 | + timeout: 5000, // Wait up to 5 seconds |
| 117 | + }, |
| 118 | +}) |
| 119 | +``` |
| 120 | + |
| 121 | +## Manual Usage |
| 122 | + |
| 123 | +You can use adapters directly without middleware for custom rate limiting logic: |
| 124 | + |
| 125 | +```ts twoslash |
| 126 | +import { MemoryRatelimiter } from '@orpc/experimental-ratelimit/memory' |
| 127 | +import { ORPCError } from '@orpc/server' |
| 128 | + |
| 129 | +const limiter = new MemoryRatelimiter({ |
| 130 | + maxRequests: 5, |
| 131 | + window: 60000, |
| 132 | +}) |
| 133 | + |
| 134 | +const result = await limiter.limit('user:123') |
| 135 | + |
| 136 | +if (!result.success) { |
| 137 | + throw new ORPCError('TOO_MANY_REQUESTS', { |
| 138 | + data: { |
| 139 | + limit: result.limit, |
| 140 | + remaining: result.remaining, |
| 141 | + reset: result.reset, |
| 142 | + }, |
| 143 | + }) |
| 144 | +} |
| 145 | +``` |
| 146 | + |
| 147 | +## `createRatelimitMiddleware` |
| 148 | + |
| 149 | +The `createRatelimitMiddleware` helper creates middleware for oRPC procedures to enforce rate limits. |
| 150 | + |
| 151 | +```ts twoslash |
| 152 | +import { call, os } from '@orpc/server' |
| 153 | +import { MemoryRatelimiter } from '@orpc/experimental-ratelimit/memory' |
| 154 | +import { createRatelimitMiddleware, Ratelimiter } from '@orpc/experimental-ratelimit' |
| 155 | +import { z } from 'zod' |
| 156 | + |
| 157 | +const loginProcedure = os |
| 158 | + .$context<{ ratelimiter: Ratelimiter }>() |
| 159 | + .input(z.object({ email: z.email() })) |
| 160 | + .use( |
| 161 | + createRatelimitMiddleware({ |
| 162 | + limiter: ({ context }) => context.ratelimiter, |
| 163 | + key: ({ context }, input) => `login:${input.email}`, |
| 164 | + }), |
| 165 | + ) |
| 166 | + .handler(({ input }) => { |
| 167 | + return { success: true } |
| 168 | + }) |
| 169 | + |
| 170 | +const ratelimiter = new MemoryRatelimiter({ |
| 171 | + maxRequests: 10, |
| 172 | + window: 60000, |
| 173 | +}) |
| 174 | + |
| 175 | +const result = await call( |
| 176 | + loginProcedure, |
| 177 | + { email: 'user@example.com' }, |
| 178 | + { context: { ratelimiter } } |
| 179 | +) |
| 180 | +``` |
| 181 | + |
| 182 | +::: info Automatic Deduplication |
| 183 | +The `createRatelimitMiddleware` automatically deduplicates rate limit checks when the same `limiter` and `key` combination is used multiple times in a request chain. This behavior follows the [Dedupe Middleware Best Practice](/docs/best-practices/dedupe-middleware). To disable deduplication, set the `dedupe: false` option. |
| 184 | +::: |
| 185 | + |
| 186 | +::: tip Conditional Limiter |
| 187 | +You can dynamically choose different limiters based on context: |
| 188 | + |
| 189 | +```ts |
| 190 | +const premiumLimiter = new MemoryRatelimiter({ |
| 191 | + maxRequests: 100, |
| 192 | + window: 60000, |
| 193 | +}) |
| 194 | + |
| 195 | +const standardLimiter = new MemoryRatelimiter({ |
| 196 | + maxRequests: 10, |
| 197 | + window: 60000, |
| 198 | +}) |
| 199 | + |
| 200 | +const result = await call( |
| 201 | + loginProcedure, |
| 202 | + { email: 'user@example.com' }, |
| 203 | + { |
| 204 | + context: { |
| 205 | + ratelimiter: isPremiumUser ? premiumLimiter : standardLimiter, |
| 206 | + }, |
| 207 | + }, |
| 208 | +) |
| 209 | +``` |
| 210 | + |
| 211 | +::: |
| 212 | + |
| 213 | +## Handler Plugin |
| 214 | + |
| 215 | +The `RatelimitHandlerPlugin` automatically adds HTTP rate-limiting headers (`RateLimit-*` and `Retry-After`) to responses when used with middleware created by [`createRatelimitMiddleware`](#createratelimitmiddleware). |
| 216 | + |
| 217 | +```ts |
| 218 | +import { RatelimitHandlerPlugin } from '@orpc/experimental-ratelimit' |
| 219 | + |
| 220 | +const handler = new RPCHandler(router, { |
| 221 | + plugins: [ |
| 222 | + new RatelimitHandlerPlugin(), |
| 223 | + ], |
| 224 | +}) |
| 225 | +``` |
| 226 | + |
| 227 | +::: info |
| 228 | +The `handler` can be any supported oRPC handler, such as [RPCHandler](/docs/rpc-handler), [OpenAPIHandler](/docs/openapi/openapi-handler), or other custom handlers. |
| 229 | +::: |
0 commit comments