Skip to main content
All articles

/2 min read

Rate limiting serverless APIs with Upstash Redis

Token bucket vs sliding window, keys by IP or user id, @upstash/ratelimit in Vercel Edge, and false positives behind NAT.

By Juliano Alves

Serverless functions spin up per request—in-memory rate limits do not work across instances. A centralized store (Redis) tracks counters with low latency; Upstash offers HTTP Redis ideal for edge runtimes.

Sliding window#

import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';

const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  limiter: Ratelimit.slidingWindow(10, '10 s'),
});

const id = req.headers.get('x-forwarded-for') ?? 'anon';
const { success } = await ratelimit.limit(id);
if (!success) return new Response('Too Many Requests', { status: 429 });

Keying strategy#

  • IP: simple but noisy behind carrier-grade NAT (many users share one IP).
  • User id after auth: fairer; combine with IP for anonymous routes.

Headers#

Return Retry-After when possible so clients back off politely.

Summary#

Upstash + sliding windows is a pragmatic pattern for public APIs on edge. Tune limits from real traffic graphs, not guesswork, and document abuse contacts for false positives.

Have a project in mind?

contato@julianoalves.me

Rio de Janeiro · UTC−3