Repository navigation
RateLimiterUpstash
Rate limiting with Upstash Redis using the @upstash/redis HTTP client.
It works where a TCP connection to Redis is not available: serverless functions and edge runtimes like Cloudflare Workers and Vercel Edge.
const { RateLimiterUpstash } = require('rate-limiter-flexible')
const { Redis } = require('@upstash/redis')
// Reads UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN from env
const upstashClient = Redis.fromEnv()
// or
// const upstashClient = new Redis({ url: 'https://...upstash.io', token: '...' })
const opts = {
storeClient: upstashClient,
points: 5, // Number of points
duration: 1, // Per second
}
const rateLimiterUpstash = new RateLimiterUpstash(opts)
rateLimiterUpstash.consume(userEmail)
.then((rateLimiterRes) => {
// ... Some app logic here ...
})
.catch((rejRes) => {
if (rejRes instanceof Error) {
// Some error happened.
// Never happen if `insuranceLimiter` is set up.
} else {
// Not enough points to consume.
// The promise is rejected with number of ms before current duration ends and points are reset.
const secs = Math.round(rejRes.msBeforeNext / 1000) || 1
res.set('Retry-After', String(secs))
res.status(429).send('Too Many Requests')
}
});import { Redis } from '@upstash/redis/cloudflare'
import { RateLimiterUpstash } from 'rate-limiter-flexible'
export default {
async fetch(request, env) {
const rateLimiter = new RateLimiterUpstash({
storeClient: Redis.fromEnv(env),
points: 5,
duration: 1,
})
const ip = request.headers.get('cf-connecting-ip')
try {
await rateLimiter.consume(ip)
} catch (rejRes) {
if (rejRes instanceof Error) throw rejRes
return new Response('Too Many Requests', {
status: 429,
headers: { 'Retry-After': String(Math.round(rejRes.msBeforeNext / 1000) || 1) },
})
}
return new Response('OK')
},
}-
consume,penaltyandrewardrun one Lua script withEVALSHA, usually one HTTP request each. The first call, or a call after the script cache is flushed, makes an extraEVALrequest. -
get,setandblocksend oneMULTItransaction request. -
deletesends oneDELrequest.
Upstash bills per command. The inMemoryBlockOnConsumed option stops requests from already-blocked keys before they reach Upstash, which saves both latency and commands. Its memory lives in one process or isolate, so on serverless and edge platforms it only helps within a warm instance.
By default @upstash/redis retries a failed request 5 times with exponential backoff, about 4 seconds in total. The insuranceLimiter only takes over after the client gives up. If you set up insuranceLimiter, tune the client so it fails fast:
const { Redis } = require('@upstash/redis')
const { RateLimiterUpstash, RateLimiterMemory } = require('rate-limiter-flexible')
const upstashClient = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL,
token: process.env.UPSTASH_REDIS_REST_TOKEN,
retry: {
retries: 1,
backoff: () => 50,
},
// A new timeout for every request
signal: () => AbortSignal.timeout(500),
})
const rateLimiter = new RateLimiterUpstash({
storeClient: upstashClient,
points: 5,
duration: 1,
insuranceLimiter: new RateLimiterMemory({
points: 5,
duration: 1,
}),
})Use retry: false to disable retries completely.
Get started
Middlewares and plugins
Migration from other packages
Limiters:
- Cluster
- Drizzle
- DynamoDB
- Etcd
- Memcached
- Memory
- MongoDB (with sharding support)
- MySQL
- PM2 Cluster
- PostgreSQL
- Prisma
- Redis
- SQLite
- Upstash Redis
- Valkey: iovalkey and Valkey Glide
- BurstyRateLimiter
- RateLimiterUnion
- RateLimiterQueue
Wrappers:
- AWS SDK v3 Client Rate Limiter
- RLWrapperBlackAndWhite Black and White lists
- RLWrapperTimeouts Timeouts
Knowledge base:
- Block Strategy in memory
- Insurance Strategy
- Periodic sync to reduce number of requests
- Comparative benchmarks
- Smooth out traffic peaks
-
Usage example
- Minimal protection against password brute-force
- Login endpoint protection
- Websocket connection prevent flooding
- Dynamic block duration
- Different limits for authorized users
- Different limits for different parts of application
- Block Strategy in memory
- Insurance Strategy
- Third-party API, crawler, bot rate limiting