Sponsored by Upstash. The implementation and opinions in this article are my own.
A rate limiter is supposed to stop requests when someone goes over the limit. So the 200 OK response recorded in an earlier local test without Redis credentials caught my attention.
The notes from that earlier test also recorded x-ratelimit-limit: 0. In that run, the endpoint was accepting requests without an effective limit. That was an exploratory observation, not the result from the final implementation.
I used Upstash Redis with its rate-limiting SDK for this Next.js example. That sent me back to the SDK's timeout behavior. Here's the small Next.js setup, what the documentation says, and the failure case I'd check before using it on a paid API.
Set Up Rate Limiting in Next.js with Upstash Redis
The live-tested demo used Next.js 16.4.6, @upstash/ratelimit 2.2.3, and @upstash/redis 1.41.1. Check your own installed versions, then install the two Upstash packages in a TypeScript App Router project:
npm install @upstash/ratelimit @upstash/redis To follow along, create a database in the Upstash console, then add the REST URL and token to .env.local:
UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN= Do not use NEXT_PUBLIC_ for these secrets. Keep .env.local out of version control and configure production values in your hosting environment.
The Limiter
// lib/ratelimit.ts import { Ratelimit } from "@upstash/ratelimit"; import { Redis } from "@upstash/redis"; export const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(5, "60 s"), prefix: "demo:chat", timeout: 1000, }); Here, each authenticated account has a five-request limit enforced through a weighted sliding-window algorithm configured with 60-second buckets. The count needs to be shared across requests, even when Next.js runs them on different serverless instances.
Who Are You Limiting?
Before counting requests, you need to decide what counts as one caller. For an endpoint that costs money, I'd use an authenticated account ID from a trusted server-side session, rather than a header the client can change.
The getAuthenticatedUserId() function shown below is an integration point. It needs to be connected to your real authentication provider before you deploy it.
// lib/identify.ts export function getIdentifier(authenticatedUserId: string | null): string { if (!authenticatedUserId) throw new Error("Authentication required"); return `user:${authenticatedUserId}`; } IP-based limits still have a place on public routes, but be careful: office networks can share addresses, and x-forwarded-for isn't safe to trust unless your hosting setup guarantees where it came from.
The Route
// app/api/chat/route.ts import { ratelimit } from "../../../lib/ratelimit"; import { getIdentifier } from "../../../lib/identify"; import { getAuthenticatedUserId } from "../../../lib/auth"; export async function POST(_request: Request) { const userId = await getAuthenticatedUserId(); if (!userId) return Response.json({ error: "Authentication required" }, { status: 401 }); let result; try { result = await ratelimit.limit(getIdentifier(userId)); } catch (error) { console.error("Rate limit check failed", error); return Response.json({ error: "Service temporarily unavailable" }, { status: 503 }); } if (result.reason === "timeout") { console.error("Rate limiter timed out"); return Response.json({ error: "Service temporarily unavailable" }, { status: 503 }); } const { success, remaining, limit, reset } = result; const retryAfter = Math.max(1, Math.ceil((reset - Date.now()) / 1000)); const headers = { "X-RateLimit-Limit": String(limit), "X-RateLimit-Remaining": String(remaining), "X-RateLimit-Reset": String(Math.ceil(reset / 1000)), }; if (!success) { return Response.json( { error: "Too many requests", message: `Try again in ${retryAfter} seconds` }, { status: 429, headers: { ...headers, "Retry-After": String(retryAfter) } }, ); } return Response.json({ ok: true, remaining }, { status: 200, headers }); } reset comes back in milliseconds, while Retry-After needs a wait in seconds. The other reset header uses a Unix timestamp in seconds. Also, remember that this route needs a real server-side session adapter in lib/auth.ts; the demo uses signed development-only test identities and rejects those test credentials in production.
Why Upstash Rate Limiting Can Fail Open on Timeout
The Upstash features documentation explains that a rate-limit call can time out and still let the request through. In that case, the result is marked with reason: "timeout". Unless you change it, the timeout is five seconds.
In an earlier exploratory run without credentials, the test notes recorded 200 and limit: 0. I did not reproduce that precise old behavior against the final code; the SDK documentation and source confirm that a timeout can produce a successful fail-open result. The finished demo explicitly rejects such results. That's what happened in that setup; it doesn't mean every invalid credential or network failure will behave identically. Some errors can throw.
I can see why the SDK offers a fail-open fallback. You might not want a temporary Redis problem to block everyone. But for a paid API endpoint, allowing unlimited requests could be worse. In this example, both thrown errors and timeout results return 503 instead.
Live Rate Limiting Test Results
After connecting to a real Upstash Redis REST database, the final complete integration rerun produced these results:
| Scenario | Observed result |
|---|---|
| First five requests | Five 200 responses |
| Requests six and seven | Two 429 responses, each with Retry-After: 24 |
| Fifteen simultaneous requests from one test identity | Five allowed, ten rejected |
| A different authenticated test identity | Allowed independently |
| Recovery after the limit window aged out | 200 after an 83-second wait |
| Deliberately invalid credentials | 503 |
The project also passed 10 local tests, TypeScript, ESLint, and a production build. A stalled local HTTP fixture tested the SDK's timeout response and confirmed that the route returns 503 with the fail-closed check.
One caveat: the first live integration attempt returned an unexplained 503. A full rerun passed after direct Redis diagnostics, but the original failure's cause wasn't established. I'm including that detail because one green run isn't proof of perfect reliability. I didn't conduct latency or throughput benchmarks either.
The older no-credentials 200 observation came from an earlier exploratory implementation; the final demo instead returns 503 for missing credentials. It also blocks production traffic until real server-side authentication is connected.
Production Limitations to Know
- Every checked request incurs Redis-related work and may add network latency; measure it near your deployment region.
- An external dependency needs a deliberate outage policy.
- The authenticated identifier must come from a real session. A client-controlled header is not proof of identity.
- Distributed and multi-region configurations have tradeoffs; test the specific setup you deploy.
- Rate limiting does not replace authentication, validation, or provider spending caps.
Final Thoughts
A few lines of configuration can give you a rate limiter. That doesn't answer the harder question: what should happen when the limiter itself stops working?
For an API that can run up a bill, that's something I'd decide and test before deploying. The full version on Pixel Anas walks through the implementation and its tradeoffs.
If Redis couldn't answer, would you let the request through or return an error? I'd be interested to hear how you handle it.
Anas — Next.js developer. X: @ASheikh69751
