Rate limiting an API route – return 429 Too Many Requests before abuse costs you

By Abheesht Tripathi · Published

Risk: login, sign-up, password-reset, contact-form and AI endpoints with no per-user or per-IP limit (expected answer: HTTP 429 Too Many Requests)

Why it matters

Without a limit, one script can try thousands of passwords, send thousands of reset emails from your domain, fill your database with junk sign-ups, or run up your AI bill in an afternoon. A rate limit counts requests per key (user id, API key or IP) in a time window and answers 429 Too Many Requests with a Retry-After header once the key is over its budget. Supabase Auth has its own limits for its endpoints (configurable in the dashboard); your own routes need theirs.

Option 1: a counter in Postgres

Good enough for most apps that already use Supabase, with no extra service. One row per key per window, incremented atomically:

create schema if not exists private;

create table if not exists private.rate_limits (
  key          text        not null,
  window_start timestamptz not null,
  hits         int         not null default 0,
  primary key (key, window_start)
);

create or replace function public.check_rate_limit(p_key text, p_limit int, p_window_seconds int)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
  v_window timestamptz := date_bin(make_interval(secs => p_window_seconds), now(), timestamptz '2000-01-01');
  v_hits   int;
begin
  insert into private.rate_limits as r (key, window_start, hits)
  values (p_key, v_window, 1)
  on conflict (key, window_start) do update set hits = r.hits + 1
  returning r.hits into v_hits;
  return v_hits <= p_limit;
end;
$$;

-- only trusted server code may call it
revoke execute on function public.check_rate_limit(text, int, int) from public, anon, authenticated;
grant execute on function public.check_rate_limit(text, int, int) to service_role;

The insert … on conflict do update is a single atomic statement, so parallel requests can't both slip under the limit. Clean old windows with a daily pg_cron job: delete from private.rate_limits where window_start < now() - interval '1 day'.

Use it in a route

// app/api/chat/route.ts (server only; supabaseAdmin uses the secret key)
export async function POST(req: Request) {
  const user = await getUserFromSession(req);            // your auth helper
  const ip = req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown';
  const key = user ? `chat:user:${user.id}` : `chat:ip:${ip}`;

  const { data: allowed, error } = await supabaseAdmin.rpc('check_rate_limit', {
    p_key: key, p_limit: 20, p_window_seconds: 60,
  });
  if (error) return new Response('Server error', { status: 500 });
  if (!allowed) {
    return new Response('Too Many Requests', { status: 429, headers: { 'Retry-After': '60' } });
  }
  // ... the real work
}

Prefer the user id when there is a session; use the IP for anonymous endpoints such as login and sign-up. Read the client IP only from the header your host sets; a client can send any X-Forwarded-For value it likes, so behind an unknown proxy the first entry is not trustworthy.

Option 2: Redis (Upstash) for high traffic or middleware

When every request is rate limited, or you want the check in edge middleware, a Redis counter avoids a database round trip:

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

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

const { success, reset } = await ratelimit.limit(key);
if (!success) {
  const retryAfter = Math.max(1, Math.ceil((reset - Date.now()) / 1000));
  return new Response('Too Many Requests', { status: 429, headers: { 'Retry-After': String(retryAfter) } });
}

What limits to start with

A fixed window allows up to twice the limit across a window boundary; that is fine for abuse control. Use a sliding window when the exact rate matters.

How to verify

for i in $(seq 1 25); do
  curl -s -o /dev/null -w "%{http_code}\n" -X POST https://your-app.example.com/api/chat \
    -H 'Content-Type: application/json' -d '{"message":"hi"}'
done

The first 20 return 200 (or 401 if the route needs a session), the rest return 429 with a Retry-After header. After the window passes, requests succeed again. Calling check_rate_limit with the anon key returns a permission error.

Related guides

More in Edge Functions, webhooks and APIs · all guides