Deutsch
GuideSecurity · AI apps

Rate limiting for AI-built apps: what to limit and where

Which endpoints of a Lovable or Supabase app need rate limits, what Supabase Auth already limits for you, and a tested Postgres counter for AI endpoints.

By Tim GeithnerPublished 7 min read

Short answer

Rate limit every endpoint that costs you money or protects an account: sign-in, sign-up, password reset, every AI call and public forms or webhooks. Supabase Auth already limits its own endpoints, and you can tune those limits in the dashboard. Your own Edge Functions get nothing for free: add a per-user counter in Postgres (tested SQL below), return 429 when it runs out, and keep provider-side spend limits as the last line.

Ask an AI about this page:ChatGPTClaude

On this page

Key takeaways

  • Limit what costs money (AI calls, e-mails, SMS) and what protects accounts (sign-in, sign-up, password reset).
  • Supabase Auth already limits its own endpoints. Check the values under Authentication → Rate Limits and leave them strict.
  • Your own Edge Functions have no per-user limit until you build one. A small Postgres counter does the job and is safe under concurrent requests.
  • Key limits by user ID when someone is signed in, and by IP only where you have nothing better.
  • Return 429 Too Many Requests with a Retry-After header, and keep a spend limit at your AI provider as the last line.

Why AI apps need rate limits more than most

A classic web app that forgets rate limiting mostly risks slow pages. An AI app pays real money for every request. If your “summarise this” button calls a model for every click, anyone who finds the endpoint can loop it, and the bill lands on you. OWASP calls this unrestricted resource consumption in its API Top 10, with an example of a password reset flow whose paid SMS messages were triggered tens of thousands of times by a script. The OWASP Top 10 for LLM applications lists the same risk as unbounded consumption, including “denial of wallet”: running up a provider’s pay-per-use bill on purpose.

Rate limiting does not replace authentication or spend caps. It sits between them: authentication decides who may call an endpoint, rate limiting decides how often, and a provider spend limit decides how much in total. You want all three. The guide to calling AI APIs safely covers the other two.

What to limit

EndpointKeyWhyWhere
Sign-inIP and e-mailCredential stuffing, password guessingSupabase Auth (built in)
Sign-upIPFake accounts that each get free AI creditsSupabase Auth (built in)
Password reset, magic link, OTPUser, IPE-mail and SMS cost, inbox floodingSupabase Auth (built in)
AI endpointsUserEvery call costs moneyYour Edge Function + Postgres counter
Contact forms, invites, exportsUser or IPE-mail cost, spam, heavy queriesYour Edge Function, host or CDN
Public webhooksSourceFloods of fake eventsVerify the signature first; host or CDN for volume

What Supabase Auth already does for you

Supabase Auth ships with rate limits on its own endpoints, and you can change most of them in your dashboard under Authentication → Rate Limits. According to Supabase’s documentation (checked on 3 December 2026):

  • Sign-ups and sign-ins (/signup, /recover, /otp and others): 30 requests per 5 minutes per IP address.
  • Token endpoint (password sign-in, refresh): 150 requests per 5 minutes per IP address.
  • Password reset, magic link and sign-up confirmation: one request per 60 seconds per user.
  • E-mails sent by Auth: 2 per hour across the whole project with the built-in e-mail provider; more only with your own SMTP server.

So the basics of account protection are covered as long as your users sign in through Supabase Auth. Two things to check: that nobody raised the limits far above what your app needs, and that you don’t have a second, home-made login or “send magic link” endpoint in an Edge Function that bypasses them.

A per-user counter in Postgres

Your Edge Functions get no limit for free. The simplest robust option for a Supabase app is a counter table in Postgres, keyed by user and time window. It needs no extra service, and Postgres takes care of concurrent requests.

Saferate_limit.sql
create schema if not exists private;

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

create function public.check_rate_limit(_key text, _max_hits integer, _window interval)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
  _start timestamptz := date_bin(_window, now(), timestamptz '2000-01-01');
  _hits integer;
begin
  insert into private.rate_limits as r (key, window_start, hits)
  values (_key, _start, 1)
  on conflict (key, window_start)
    do update set hits = r.hits + 1
  returning r.hits into _hits;

  return _hits <= _max_hits;
end;
$$;

revoke execute on function public.check_rate_limit(text, integer, interval)
  from public, anon, authenticated;
grant execute on function public.check_rate_limit(text, integer, interval)
  to service_role;

How it works:

  • date_bin rounds the current time down to the start of the window, so all requests in the same hour (or minute, or day) share one row.
  • on conflict … do update inserts the first hit or adds one to an existing row in a single atomic step. The PostgreSQL manual guarantees an atomic insert-or-update outcome “even under high concurrency”, so two parallel requests cannot both read “4” and both write “5”.
  • The table lives in private, a schema the Data API does not expose. Users can neither read nor reset their counters.
  • Only service_role may call the function. If signed-in users could call it, they could fill up other people’s counters or probe them. It is a security definer function with an empty search_path, following the rules in the guide to SECURITY DEFINER functions.

Call it from your Edge Function

Check the limit after you have verified the user and before you call the model:

supabase/functions/ai-summary/index.ts (excerpt)
const userId = ctx.userClaims?.id;
if (!userId) return Response.json({ error: "Not signed in" }, { status: 401 });

const { data: allowed, error } = await ctx.supabaseAdmin.rpc("check_rate_limit", {
  _key: `ai-hour:${userId}`,
  _max_hits: 20,
  _window: "1 hour",
});
if (error) return Response.json({ error: "Please try again later." }, { status: 503 });
if (!allowed) {
  return Response.json(
    { error: "You have reached the limit for this hour." },
    { status: 429, headers: { "Retry-After": "3600" } },
  );
}

ctx comes from withSupabase({ auth: "user" }, …) in Supabase’s @supabase/server package, which verifies the caller’s token and gives you both a user-scoped client and an admin client. The full function, with input limits and the model call, is in the guide to calling AI APIs safely.

429 Too Many Requests is the standard status for this; MDN describes Retry-After as the optional header that tells the client how long to wait. If the database call itself fails, this code refuses the request (503). For an endpoint that costs money, failing closed is the safer choice.

What we tested

We ran the SQL above in Postgres with Supabase’s roles, as service_role, as two signed-in users and as anon:

  • With a limit of 3 per hour, the first three calls returned true and the fourth false.
  • A second user had their own count and was not affected.
  • Refused calls were still counted, so hammering the endpoint does not reset anything.
  • With a 1-second window, the next window started fresh.
  • Signed-in users and anon got permission denied for function check_rate_limit, and reading private.rate_limits failed with permission denied for schema private.

Fixed window or token bucket?

The counter above is a fixed window. It is easy to reason about and easy to debug: one row per user and window. Its known weakness is the edge between two windows. A user can use up the full allowance at 10:59 and again at 11:00, so for a moment they get twice the rate.

A token bucket avoids that: each user has a bucket that refills at a steady rate, and each request takes one token. Anthropic, for example, documents that its own API limits work this way, with capacity “continuously replenished” rather than reset at fixed times. For an app with a few hundred users, the two-window approach from the tip above usually gets you close enough with less code. Switch to a token bucket when bursts at window edges show up in your bills or logs.

Keep the table small

Old windows are useless after a day. Delete them on a schedule; a daily cron job is enough:

cleanup.sql
delete from private.rate_limits where window_start < now() - interval '1 day';

If you use windows longer than a day, keep rows at least as long as your longest window.

A fix prompt for your AI builder

Add per-user rate limits to AI endpoints

Add rate limiting to every Supabase Edge Function in this project that calls an AI model or sends e-mail.

  1. Create a migration with a table private.rate_limits (key text, window_start timestamptz, hits integer, primary key (key, window_start)) and a SECURITY DEFINER function public.check_rate_limit(_key text, _max_hits integer, _window interval) returns boolean, with SET search_path = ‘’, that upserts the hit for date_bin(_window, now(), ‘2000-01-01’) and returns true while hits are at most _max_hits. Revoke EXECUTE from public, anon and authenticated; grant it to service_role only.
  2. In each function, after verifying the signed-in user and before any paid API call, call check_rate_limit twice with the admin client: key “ai-min:” plus the user id with 5 per minute, and key “ai-day:” plus the user id with 100 per day. Return HTTP 429 with a Retry-After header when either returns false, and 503 if the check itself fails.
  3. Never take the user id from the request body.

Show me the migration and every function you changed.

Frequently asked questions

Does Supabase rate limit my Edge Functions?

Supabase Auth documents rate limits for its own endpoints, such as sign-up, sign-in, password reset and e-mail sending. Your own Edge Functions are your code, so a per-user limit for them is something you add yourself, for example with the Postgres counter in this guide.

What limit should I set for an AI feature?

Start from cost. Work out what one request costs at your maximum input and output size, decide how much one free user may cost you per day, and divide. Add a short per-minute limit on top so a script cannot burn the daily budget in seconds. Then watch real usage for a week and adjust.

Is a fixed window good enough, or do I need a token bucket?

For most small apps a fixed window is enough. Its known weakness is the boundary: a user can spend a full window’s allowance at the end of one window and again at the start of the next. If that double burst matters, use a shorter window next to the long one, or a token bucket, which refills gradually.

Should I limit by IP address or by user?

By user wherever someone is signed in: IPs are shared by offices and mobile networks and are cheap to change for an attacker. For signed-out endpoints such as sign-up or a contact form, the IP is the only key you have, and that is where Supabase Auth’s per-IP limits and your host’s or CDN’s rate limiting fit best.

Sources

  1. 1.Rate limits — Supabase Docs
  2. 2.API4:2023 Unrestricted Resource Consumption — OWASP API Security Top 10
  3. 3.LLM10:2025 Unbounded Consumption — OWASP Top 10 for LLM Applications
  4. 4.INSERT … ON CONFLICT — PostgreSQL Documentation
  5. 5.429 Too Many Requests — MDN Web Docs
  6. 6.Rate limits — Anthropic Docs

Find this in your own app

ShipRely reads your repository (read-only), proves each finding with file and line, and gives you a fix prompt to paste into your AI builder.

Run a demo audit
  • Read-only access to your repository
  • Every finding with file and line
  • Fix prompts for Lovable, Cursor, Claude Code and Bolt