Skip to content

RateLimiterUpstash

Roman edited this page Dec 3, 2026 · 1 revision

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.

Usage

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')
      }
    });

Cloudflare Workers

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')
  },
}

Upstash specifics

Requests per call

  • consume, penalty and reward run one Lua script with EVALSHA, usually one HTTP request each. The first call, or a call after the script cache is flushed, makes an extra EVAL request.
  • get, set and block send one MULTI transaction request.
  • delete sends one DEL request.

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.

Retries, timeouts and Insurance limiter

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.

Clone this wiki locally