Skip to content
Back to Blog
nextjstypescriptredisserverless

Next.js API Rate Limiting with Upstash Redis (Tested)

Pixel Anas··14 min read

Learn Next.js API rate limiting with Upstash Redis, tested 429 responses, safe authentication, and the timeout trap that can bypass your limiter.

Sponsored by Upstash. The implementation, testing, and opinions in this article are my own.

Say you've built a free-trial feature in Next.js. Each request calls a database or an AI model, returns a result, and costs a little bit of money. Everything looks fine until someone starts hitting that endpoint over and over. The app might keep running, but those requests still cost you.

That's why I wanted to add rate limiting to a Next.js App Router API. I used Upstash Redis and @upstash/ratelimit, but the interesting part wasn't installing the package. It was figuring out who should be limited, what to return when someone hits the limit, and what happens when Redis can't be reached.

That last question matters more than I expected. Notes from an earlier local test without Redis credentials describe a 200 OK response without an enforced limit. That specific result has not been reproduced in the final implementation. Later tests focused on making failure handling explicit and checking the limiter with a real database. Here's how the example works and why I changed the error handling.

Why Next.js API Routes Need Rate Limiting

An endpoint with no request limit can cause problems in a few different ways:

  • Money. If the route calls a paid service, such as an AI model, every extra request is a charge.
  • Load. Each request uses your database, your function time and your connections.
  • Fairness. One heavy user can slow the service down for everyone else.

On serverless hosting, your app can spin up more functions to handle traffic. That's useful when the traffic comes from real customers. It's less useful when one script sends hundreds of unnecessary requests. For a broader look at securing an app like this, see my Next.js SaaS build guide, which covers API protection alongside authentication and deployment.

With rate limiting, you decide how many requests a caller gets during a certain period. Once they reach that number, your API responds with 429 Too Many Requests instead of doing more work.

Why Use Upstash Redis for Next.js Rate Limiting?

The first challenge is keeping track of requests. On a serverless app, the next request might run on a different function instance. Counting requests in a local variable won't reliably work across those instances. The count needs to live somewhere they can all reach.

Redis is useful for that. I used Upstash Redis, a managed Redis service with an HTTP API, for this example. Here is what made it practical for this setup:

  • It works over HTTP. The Upstash Redis client talks to a REST API, so it does not need a long-lived TCP connection, which suits short-lived serverless functions.
  • There is a ready-made library. @upstash/ratelimit handles the counting logic, so I did not write my own Lua scripts or window math.
  • Setup is small. Two environment variables and a few lines of code.

There are tradeoffs, though:

  • Every limited request makes a network call to Redis. That adds latency to each request.
  • Your API now depends on another service. What happens when it is slow or down is a design decision you have to make.
  • It is billed by usage. The Upstash docs say cost is measured in commands, and point to a separate costs page. I have not separately measured how many commands one limit() call uses, so check the current pricing before you commit.

Set Up Upstash Redis in Next.js App Router

Create a Next.js App Router project with TypeScript, then install the two packages:

npm install @upstash/ratelimit @upstash/redis

The live-tested demo used Next.js 16.4.6, @upstash/ratelimit 2.2.3, and @upstash/redis 1.41.1. Check the versions installed in your own project, since SDK behavior can change.

Next, create an Upstash Redis database and copy its REST URL and token into .env.local. These are the variable names from the Upstash getting started guide:

# .env.local  (never commit this file)
UPSTASH_REDIS_REST_URL=
UPSTASH_REDIS_REST_TOKEN=

A few things worth checking before moving on:

  • Do not prefix them with NEXT_PUBLIC_. Next.js sends variables with that prefix to the browser.
  • Keep .env.local in .gitignore, and commit only an .env.example with empty values.
  • Add the same variables in your hosting dashboard for production, instead of copying a file.

The files in the demo:

app/api/chat/route.ts  the protected route
lib/ratelimit.ts       the limiter configuration
lib/identify.ts        authenticated account identifier
lib/auth.ts            authentication integration point
scripts/test-limit.mjs local test script

Implement API Rate Limiting with TypeScript

The limiter

// lib/ratelimit.ts
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";

export const ratelimit = new Ratelimit({
  redis: Redis.fromEnv(),
  // 5 requests per 60 seconds for each identifier.
  limiter: Ratelimit.slidingWindow(5, "60 s"),
  // Namespaces the keys in Redis, so limiters can share a database.
  prefix: "demo:chat",
  // The SDK allows requests on timeout; the route below rejects those results.
  timeout: 1000,
});

This configuration applies a five-request limit using a weighted sliding-window algorithm with 60-second buckets per identifier. I chose a sliding window because it avoids some of the sharp boundaries you get with a fixed-window limit. With fixed windows, someone can send requests right before one window ends and again just after the next begins.

Upstash also provides other algorithms, including token bucket. The features documentation explains the differences.

Deciding who is being limited

// lib/identify.ts
// Never accept a user ID or API key from an unverified request header.
export function getIdentifier(authenticatedUserId: string | null): string {
  if (!authenticatedUserId) {
    throw new Error("An authenticated user is required for this endpoint");
  }
  return `user:${authenticatedUserId}`;
}

This decision is easy to overlook. Are you limiting a person, an account, or everyone coming from the same network?

For a paid API, I prefer the user ID from a trusted server-side session. I wouldn't take an ID directly from a request header and assume it's genuine. The getAuthenticatedUserId() function in this example is where your existing authentication provider needs to be connected. If you are organizing this code inside a larger project, my Next.js folder structure guide shows how I separate routes and server-side modules. Until then, the example rejects requests without a verified user.

An IP address can be useful for public routes such as sign-in, but it comes with problems. People on the same office or mobile network may share an IP, and a raw x-forwarded-for header isn't automatically trustworthy. Check how your hosting platform handles proxy headers before using one as an identifier.

The protected 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 });
  }
  const identifier = getIdentifier(userId);

  let result;
  try {
    result = await ratelimit.limit(identifier);
  } catch (error) {
    console.error("Rate limit check failed", error);
    return Response.json(
      { error: "Service temporarily unavailable. Please try again shortly." },
      { status: 503 }
    );
  }

  if (result.reason === "timeout") {
    console.error("Rate limiter timed out. Check Redis credentials and connectivity.");
    return Response.json(
      { error: "Service temporarily unavailable. Please try again shortly." },
      { status: 503 }
    );
  }

  const { success, limit, remaining, reset } = result;
  const retryAfterSeconds = Math.max(1, Math.ceil((reset - Date.now()) / 1000));

  const rateLimitHeaders = {
    "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: `Limit is ${limit} requests per minute. Try again in ${retryAfterSeconds} seconds.`,
      },
      {
        status: 429,
        headers: { ...rateLimitHeaders, "Retry-After": String(retryAfterSeconds) },
      }
    );
  }

  // The expensive work goes here.
  return Response.json(
    { ok: true, message: "Request accepted", remaining },
    { status: 200, headers: rateLimitHeaders }
  );
}

The result gives us the information needed to decide whether to allow the request: success, limit, remaining, and reset, along with fields such as reason for certain outcomes. The getAuthenticatedUserId() function is not built into Next.js; you'll need to connect it to your own server-side authentication. The companion demo uses signed development-only test identities and deliberately rejects those credentials in its production build. For a real deployment, connect a proper session provider.

Notice that reset is in milliseconds. For the HTTP Retry-After header, the code calculates the wait in seconds. That way, when the API returns a 429, the caller knows when to try again rather than seeing a vague error.

The Upstash Timeout Trap: When Rate Limiting Fails Open

Here's the part that made me rethink the error handling. In an earlier exploratory run, the route was started without Redis credentials. The earlier test notes recorded 200 OK with x-ratelimit-limit: 0 before the timeout reason was checked. That result was from the earlier version of the project; I have not reproduced it against the final code. The SDK source and documentation independently confirm its fail-open response on timeout.

According to Upstash's documentation, the SDK allows a request through if the Redis operation exceeds its timeout and marks the result with reason: "timeout". Its default timeout is five seconds. The missing-credentials result was one observation from that environment, not proof that every bad token or missing variable behaves that way. Some failures throw errors instead.

Allowing traffic through during a temporary Redis problem might be fine for a low-risk endpoint. But if the route calls a paid AI model, I'd rather stop the request than let it run without a working limit.

That's why the route checks both thrown errors and reason === "timeout". The live-tested demo now returns 503 Service Unavailable for missing and deliberately invalid credentials. A separate stalled local HTTP fixture verified the SDK timeout path. Logging the failure also gives you something to investigate. The important part is choosing the behavior deliberately.

Test the Next.js Rate Limiter: 200, 429, and Recovery

I've included a test script with the companion project. It uses separate test accounts so that one test doesn't use up the request quota for the next. Before running it, configure the local test-only authentication adapter. That adapter should never be enabled in production.

npm run dev
# in a second terminal, run the test command included with your demo
npm run test:integration
  1. Seven requests in a row. Expected: five 200 responses, then two 429 responses with a Retry-After value.
  2. Fifteen concurrent requests from one client. Expected: exactly five 200 and ten 429. This checks that parallel requests cannot slip past the counter.
  3. Reset check. Exhaust the limit, wait for the SDK-reported recovery window, and send one more. Because Upstash uses weighted sliding-window buckets, a fixed 61-second wait is not always sufficient.

The script doesn't rely on made-up x-forwarded-for values. For a real application, replace the development-only session adapter with your normal authentication system.

Real Upstash Redis Test Results

I ran an integration suite against an actual Upstash Redis REST database, using unique test-user identifiers so the test groups would not affect each other. Here is what the successful complete rerun recorded:

TestObserved result
First five sequential requestsFive HTTP 200 responses
Sixth and seventh requestsHTTP 429, with Retry-After: 24 seconds
Fifteen requests sent concurrentlyFive 200, ten 429
Different authenticated test user200 while the first user was limited
Rate-limit recovery200 once the weighted buckets aged out (83-second recovery wait in this run)
Deliberately invalid REST tokenHTTP 503
Missing Redis configurationHTTP 503
Stalled local HTTP endpointTimeout fallback converted into HTTP 503

The same project also passed 10 local tests, TypeScript checking, ESLint, and a production build. The timeout test used a local stalled HTTP fixture, not a live Upstash outage; it tested the SDK's actual timeout behavior without claiming that Upstash experienced an incident.

The first live integration attempt returned an unexplained 503 on its initial request. Later direct Redis diagnostics succeeded, and the full suite passed when rerun with fresh identifiers. I didn't capture the precise cause of that first failure, so I wouldn't treat one successful rerun as a reliability benchmark.

These are functional checks, not latency benchmarks. I haven't measured sustained throughput or production response times. Also, the tested demo uses a signed development-only identity adapter; production requests are intentionally denied until a real authentication/session integration is added.

What Worked Well

  • The code is small. The limiter is about ten lines, and the route logic is mostly about building a good response.
  • The response object is useful. remaining and reset give you everything you need for standard rate limit headers.
  • Fail-open behavior is configurable. The timeout option and the reason field let you choose your own policy.
  • Documentation covered the serverless case. The docs explain the pending promise and the waitUntil pattern for edge runtimes, which matters if you enable analytics or multi-region.

Production Considerations and Limitations

  • Added latency. Each limited request waits for a Redis round trip. Measure this in your own region before you decide where to apply the limiter.
  • A dependency on another service. Decide what your API does when Redis is slow or unreachable, as covered above.
  • Silent misconfiguration. The fail-open default can hide bad credentials. Add a check in your deployment process, or an alert on reason: "timeout" logs.
  • IP-based limits need care. Shared networks, proxies, and spoofable headers affect them. This example uses a server-verified user identity instead.
  • Multi-region is approximate. The docs say that with multi-region replication there is no way to guarantee the limit is not exceeded by a small margin.
  • Analytics and edge runtimes. If you enable analytics, send the pending promise to waitUntil on edge runtimes, so the background work is not cut off. The demo does not enable analytics.
  • A rate limit is not security. It slows abuse down. It does not replace authentication, input validation or spending limits at your provider.

When Should You Use Redis Rate Limiting?

It is a good fit when:

  • Your API runs on serverless functions and needs shared counters.
  • You want a ready-made limiter instead of writing your own.
  • You have endpoints that cost money, such as AI calls or email sends.

Consider something else when:

  • Your whole app runs as one long-lived server. In-process limiting can be enough, and avoids a network call.
  • Your hosting provider or CDN already offers rate limiting at the edge, which can stop abusive traffic before it reaches your code.
  • You need very strict, exact limits across regions.

Frequently Asked Questions

How do I return HTTP 429 in a Next.js App Router API?

Check the result of ratelimit.limit(identifier). When success is false because the quota was exceeded, return Response.json() with status: 429, plus a Retry-After header. The route above shows the complete response.

Can I rate limit by IP address instead of user ID?

Yes, but first verify how your hosting provider supplies the client IP. Don't trust a client-controlled x-forwarded-for value. For an endpoint that charges your account for each request, a server-verified user or account ID is usually the safer primary identifier.

What happens if Upstash Redis times out?

The SDK can return a result with reason: "timeout" and allow the request. The example checks that reason and responds with 503 instead, so a paid endpoint does not silently continue without an enforced limit. Whether to fail open or closed depends on the endpoint.

Final Thoughts

Adding the limiter itself is straightforward. The decisions around it take more thought: who gets a quota, what a blocked request should look like, and whether your API should continue when Redis can't respond.

If you're building a rate limit for an endpoint that costs money, test what happens when it fails—not just when everything is working. That's the part I would check before shipping.

If you need help with a Next.js API like this, you can find more about my work on my services page. For more on publishing the frontend and making your pages discoverable, I also wrote about Next.js metadata and SEO.

If you want to try this approach in your own project, you can explore Upstash Redis and follow the setup and test steps above. Make sure you also decide how your API should behave when Redis is unavailable.

Documentation used: getting started, features and the package repository.

Chat with me on WhatsApp