Mustlist

Rate limiting for a Next.js + Postgres app

VerifiedLast verified 15 Nov 2026R@RIDAM7v1.0.0
Suggest a change

Rate-limit auth, costly and public API endpoints per account or API key plus IP, in Route Handlers and Server Actions, with counters in a shared store (a Postgres upsert by default). Return 429 with Retry-After and trust only your platform's client-IP header.

Forweb-appsaaspublic-api
Not forstatic-site-without-server-endpoints

Must-have checklist

10 must · 4 should

Must

01

Rate-limit login, sign-up, password reset, OTP send and verify, and verification-email resend, per submitted identifier and per IP.

Stops credential stuffing, OTP brute force, and email or SMS bombing.

Security
02

Limit AI calls, email and SMS sends, and exports per account, with both a short-window limit and a daily quota.

One script can run up a provider bill in minutes (OWASP API4:2023).

Cost
03

Key limits by account id or API key when known, plus the client IP; never by IP alone.

Users behind one NAT share an IP, and attackers spread attempts across many IPs.

Security
04

Read the client IP only from a header your platform sets (for example x-real-ip on Vercel, CF-Connecting-IP behind Cloudflare); never the leftmost X-Forwarded-For value.

Clients can set X-Forwarded-For, so trusting it lets an attacker choose their own bucket.

Security
05

Keep counters in a shared store (Postgres, Redis, or the platform's limiter), never in process memory.

Each serverless instance has its own memory, and in-memory counts reset on restart.

Performance
06

Increment and read the counter in one atomic statement (INSERT ... ON CONFLICT DO UPDATE ... RETURNING); never SELECT then UPDATE.

Read-then-write lets concurrent requests slip past the limit.

Data
07

Check the limit inside each Route Handler and Server Action before any expensive work; treat proxy.ts and WAF rules as an extra, coarse layer.

A proxy matcher that skips a path also skips the Server Functions on that path.

Security
08

Return 429 with Retry-After (seconds) from Route Handlers, and a typed rate-limited result with the retry time from Server Actions.

UX
09

Set a short timeout on limiter calls and choose fail-open or fail-closed per endpoint; fail closed on auth and costly endpoints and alert on store errors.

Some limiter libraries allow requests by default when the store times out.

Security
10

Delete expired counter rows with a scheduled job and index the window column; don't rely on in-process timers in serverless.

Data

Should

11

When keying by IP, group IPv6 addresses by prefix (at least /64) instead of using the full address.

One customer usually gets a whole /56 or /48 and can rotate addresses inside it.

Security
12

Store an HMAC of emails and IPs in counter keys instead of raw values, and keep rows only as long as the longest window.

The counter table then holds no readable personal data.

Data
13

Set spending caps or billing alerts with your SMS, email and AI providers.

Rate limits cap request rates, not total spend.

Cost
14

Log rate-limit rejections per endpoint and key type, and alert on spikes.

Spikes reveal attacks, and steady rejections of real users reveal limits set too low.

Security

Decisions to make

Asked before building

01Where does the app run, and what sits in front of it?

02Will any limited endpoint take sustained high traffic, such as a public API with many clients?

03Do you already run Redis or a managed Redis-compatible service?

04Which counting algorithm fits the limited endpoints?

05What should happen when the limiter store is down or times out?

06Do you need to block request floods before they reach your functions and database?

Options

3 compared
Recommended

Postgres counter table with an atomic upsert

Examples, not endorsements: rate-limiter-flexible (Postgres store)

Best fit when
  • You already run Postgres and don't want another service
  • Limits guard auth and costly endpoints at modest request rates
  • You want counters in the same database, region and backups as your data
Avoid when
  • Limited endpoints take sustained high request rates (each check is a write)
  • Your database is already the bottleneck
Trade-offs
  • Adds one indexed write and a database round trip per limited request
  • Needs a scheduled cleanup job and some vacuum headroom

Redis or a managed Redis-compatible store

Examples, not endorsements: Upstash Ratelimit, rate-limiter-flexible (Redis or Valkey store)

Best fit when
  • A public API or other endpoint takes high request rates
  • You already run Redis, or want sliding-window and token-bucket algorithms built in
Avoid when
  • You would add a new service only to limit a few auth endpoints
Trade-offs
  • Another service to pay for, secure and monitor
  • Check what the library does on a store timeout; some allow the request

Platform or WAF rate limiting at the edge

Examples, not endorsements: Vercel WAF rate limiting, Cloudflare rate limiting rules, AWS WAF rate-based rules

Best fit when
  • You want to drop per-IP floods before they reach functions and the database
  • You want limits without writing or running counter code
Avoid when
  • You need per-account or per-API-key limits and your plan only counts by IP
  • You need exact global counts (counters are kept per region or data center)
Trade-offs
  • Keys, window lengths and rule counts depend on the plan
  • Configuration lives in a dashboard, outside the repo and code review

Why this approach

A Postgres counter table with one atomic upsert per check works across every serverless instance, adds no new service, and is enough for auth and costly endpoints, which see modest request rates. Run the check inside the Route Handler or Server Action, where you know the account or API key, not in proxy.ts. Add platform or WAF rate limiting in front when you need to drop per-IP floods before they reach your functions. Move counters to Redis or a managed Redis-compatible service when a public API or other high-volume endpoint makes one database write per request too expensive.

Lenses

Limit login, sign-up, password reset, OTP send and verify, and verification-email resend by both the submitted identifier (normalised email or account id) and the client IP. The OWASP Authentication Cheat Sheet ties failed-login counters to the account, because per-IP limits alone miss attacks spread across many addresses. Key public APIs by API key. Take the IP only from a header your platform sets: Vercel overwrites X-Forwarded-For and also sends x-real-ip; Cloudflare recommends CF-Connecting-IP; behind your own proxy, scan X-Forwarded-For from the right and take the first address your proxies didn't add. The leftmost value is whatever the client sent. Run the check inside each Server Action, because a proxy.ts matcher that skips a path also skips its Server Functions. Fail closed on auth and costly endpoints so a store outage can't open them to brute force. Rate limits slow attackers but don't stop them; OWASP treats them as one layer next to MFA and monitoring.

Version notes

next>=16.0.0
  • middleware.ts is renamed to proxy.ts; Proxy runs on Node.js by default but is not meant for slow data fetching, so keep store lookups in handlers.
  • Server Functions are POST requests to the route that uses them; a Proxy matcher that excludes the path also skips them, so check limits inside each action.
  • NextRequest.ip was removed in v15; read the client IP from your host's trusted header or helper.
  • In-memory counters are per instance and reset on restart; keep counts in a shared store or use your host's rate limiting.
postgresql>=14.0.0
  • date_bin(), used here to bucket timestamps into windows, exists from PostgreSQL 14.
  • INSERT ... ON CONFLICT DO UPDATE guarantees an atomic insert-or-update outcome under concurrency; add RETURNING to read the new count in the same statement.
  • UNLOGGED tables are faster but are truncated after a crash and are not replicated to standby servers.
Official docswww.postgresql.org
@upstash/ratelimit>=2.0.0
  • If Redis doesn't answer within the timeout (default 5 s), the request is allowed; set a shorter timeout and handle the fail mode yourself on sensitive endpoints.
  • The ephemeral cache of blocked identifiers lives in instance memory; create the limiter outside the handler so it is reused.
  • Multi-region mode syncs asynchronously and can exceed the limit slightly; token bucket is not supported there.
@vercel/firewall>=1.0.0
  • checkRateLimit needs a matching rate limit ID configured as a rule in the Vercel Firewall dashboard.
  • A custom rateLimitKey replaces the default client-IP bucket; build a compound key yourself to limit by IP and account together.
  • Counters are tracked per region, so a key hit from several regions can exceed the configured limit.
  • The timeout option exists from 1.2.6; decide per endpoint what a timeout means.
Official docsvercel.com

Verify checks

11 checks
01

Failed logins for one email sent from several different IPs are rejected with 429 once the per-account limit is reached.

integrationSecurity
02

Login attempts for many different emails from one IP are rejected with 429 once the per-IP limit is reached.

integrationSecurity
03

Every 429 response has a Retry-After header with a positive whole number of seconds that matches when the window resets.

integrationUX
04

The client-IP helper ignores client-supplied X-Forwarded-For entries and returns only the address set by the trusted platform or proxy.

unitSecurity
05

With a limit of N, sending 5N concurrent requests for one key allows exactly N and rejects the rest.

integrationData
06

The limit still holds when requests alternate between two app instances, and after an instance restarts.

integrationPerformance
07

Calling a limited Server Action or Route Handler directly, without passing through proxy.ts, is still rate limited.

integrationSecurity
08

With the limiter store unreachable, endpoints follow the chosen fail mode (for example 503 on auth and costly endpoints), and an error is logged.

integrationSecurity
09

An account that reaches its daily quota on an AI, SMS or email endpoint is blocked until the quota resets, whatever IP it uses.

integrationCost
10

The cleanup job deletes counter rows older than the longest window and keeps rows for current windows.

integrationData
11

Counter keys contain no raw email addresses or IP addresses.

unitData

Common mistakes

  • Counting in process memory (a Map or an LRU cache): each serverless instance keeps its own count, which resets on restart.
  • Keying only by IP, so users behind one NAT block each other while attackers rotate IPs.
  • Trusting the leftmost X-Forwarded-For value, which any client can set.
  • Reading the count and then writing it in two statements, so concurrent requests slip past the limit.
  • Limiting only in proxy.ts, leaving Server Actions and Route Handlers that the matcher skips unprotected.
  • Returning 200 with an error body, or a 500, instead of 429 with Retry-After.
  • Never deleting old counter rows, so the table and its indexes grow forever.
  • Using a library's default timeout without knowing that it lets requests through when the store is down.
  • Limiting OTP sends but not OTP verification, so short codes can be brute-forced.
  • Caching a limited route publicly, so a CDN serves it without running the limiter.

Sources

19 sources