GuidesWeb app

Tutorial: rate limiting an API

By the Banzai Labs teamUpdated on 2 min read

5 / min200429Requests from one clientOver quota: “too many requests”, retry later
Beyond the quota, the API answers 429 instead of processing the request.

1. The code

import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

export async function limit(key: string, max = 60, window = 60) {
  const k = `rl:${key}:${Math.floor(Date.now() / 1000 / window)}`;
  const n = await redis.incr(k);
  if (n === 1) await redis.expire(k, window);
  return { ok: n <= max, left: Math.max(0, max - n) };
}
const { ok } = await limit(`ip:${ip}`, 5, 60);
if (!ok) return new Response('Too many requests', { status: 429, headers: { 'Retry-After': '60' } });

2. Where to put a limit

Entry point Example rule
Login, magic link 5 per minute per address
Contact form 3 per hour per IP
Call to an AI model A quota per user per day
Public API According to each customer’s plan

3. The right responses

  1. 1Code 429“Too Many Requests”, the code made for this.
  2. 2Retry-AfterThe delay before retrying, in seconds.
  3. 3A clear messageIn the interface, not a technical error.

For AI costs: capping your AI API bill.

Frequently asked questions

Per IP or per user?
Per user when signed in, per IP otherwise. Behind a proxy or CDN, read the real IP from the header your host provides.
Fixed or sliding window?
A fixed window is simple and often enough. A sliding window or a token bucket smooths out peaks at the edge of the minute.
Can the web server do it?
Yes, Nginx and most CDNs have a built-in limit. A limit in the code is still useful for per-user or per-feature rules.

Read next

All guides