Security · Nov 25, 2026 · 11 min read

Upstash Rate Limiting in Next.js 15: Middleware, Algorithms & AI Protection

Build production-grade rate limiting for Next.js 15 using Upstash Redis. Covers edge middleware, fixed/sliding/token-bucket strategies, per-user limits, AI endpoint protection, and concrete code patte

Upstash Rate Limiting in Next.js 15: Middleware, Algorithms & AI Protection

Why Rate Limiting Matters for Next.js Production Applications

Rate limiting protects your API from abuse, controls operational costs, and ensures fair resource distribution. In Next.js applications, especially those using serverless functions or edge runtime, uncontrolled traffic can exhaust compute quotas or inflate bills for paid services such as LLM inference.

Common attack vectors include credential stuffing, web scraping, brute-force login attempts, and repeated expensive operations. Rate limiting addresses these by enforcing thresholds on requests from a single IP, user identifier, or tenant. When integrated at the edge, decisions happen before requests reach your origin, reducing latency and load.

Upstash provides a serverless Redis offering that works seamlessly with Next.js edge middleware because it uses HTTP connections instead of TCP. This eliminates cold-start concerns associated with traditional Redis instances and aligns with Vercel’s edge network. The official @upstash/ratelimit package (version 2.0.3 as of late 2024) abstracts common algorithms while exposing configuration options for prefixes, timeouts, and analytics.

Without rate limiting, a single user or bot can consume disproportionate resources. With it, you can implement tiered policies: free users might receive 20 requests per minute while paid users receive 200. These policies become especially important when your backend calls usage-based services such as OpenAI, Anthropic, or self-hosted vLLM instances.

Setting Up an Upstash Redis Database

Begin by creating a free Upstash account at upstash.com. After verification, navigate to the Redis section and click “Create Database.” Select a global region closest to your primary users to minimize latency. Enable “REST API” access; this provides the HTTP endpoint required by the client libraries.

After creation, copy the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN values. Store them in your .env.local file:

UPSTASH_REDIS_REST_URL=https://your-database.upstash.io
UPSTASH_REDIS_REST_TOKEN=your-secret-token

These environment variables are automatically available in both Node.js and edge runtimes on Vercel. For local development, the Upstash CLI can mirror production behavior. Install it with npm install -g @upstash/cli and run upstash redis create to provision a matching database.

Important consideration: Upstash charges based on data transfer and command count rather than uptime. Typical production usage for rate limiting stays well under the free tier until you exceed several million requests per day. Monitor the billing dashboard regularly as request volume grows.

Installing and Configuring the Ratelimit Client

Add the necessary packages to your Next.js 15 project:

npm install @upstash/redis@1.34.0 @upstash/ratelimit@2.0.3

Create a reusable client factory in lib/ratelimit.ts. This centralizes configuration and makes algorithm swapping straightforward.

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

const redis = Redis.fromEnv();

export const ratelimit = {
  // Default global limiter - 10 requests per 10 seconds
  global: new Ratelimit({
    redis,
    limiter: Ratelimit.slidingWindow(10, "10 s"),
    analytics: true,
    prefix: "ratelimit:global",
  }),

  // Per-user limiter for authenticated routes
  user: (userId: string) =>
    new Ratelimit({
      redis,
      limiter: Ratelimit.tokenBucket(50, "1 m", 100),
      analytics: true,
      prefix: `ratelimit:user:${userId}`,
    }),
};

The fromEnv() method reads the environment variables set earlier. The prefix option prevents key collisions when multiple applications share the same Redis instance. Setting analytics: true enables the Upstash dashboard to display blocked requests, top consumers, and success rates.

Comparing Rate Limiting Algorithms and Their Trade-offs

The @upstash/ratelimit package implements three primary algorithms. Each has distinct characteristics that affect user experience and implementation cost.

  • Fixed Window: Divides time into static buckets (e.g., every 60 seconds). Simple to understand and cheapest in terms of Redis commands. Drawback: users can burst at the edge of windows, potentially allowing twice the intended rate during the transition. Suitable for internal admin APIs where strict fairness is less critical.
  • Sliding Window: Maintains a rolling log of request timestamps. Provides smoother enforcement and better user experience because limits reset gradually. Requires slightly more storage and commands than fixed window. Recommended default for public APIs and AI endpoints.
  • Token Bucket: Allows bursts up to a maximum capacity while maintaining a steady refill rate. Ideal for scenarios where occasional spikes are legitimate, such as rapid form submissions or batch operations. The refill rate and burst capacity are configured independently.

In practice, sliding window offers the best balance for most Next.js SaaS applications. Token bucket shines when protecting LLM endpoints where users might send several messages in quick succession but should be throttled over longer periods.

Global Rate Limiting with Edge Middleware

Next.js 15 edge middleware runs on the Vercel Edge Network before requests reach your serverless functions. This is the earliest and most efficient place to enforce global limits.

Create or update middleware.ts in your project root:

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { ratelimit } from "./lib/ratelimit";

export async function middleware(request: NextRequest) {
  const ip = request.ip ?? "127.0.0.1";
  const { success, limit, remaining, reset } = await ratelimit.global.limit(ip);

  const response = NextResponse.next();

  response.headers.set("X-RateLimit-Limit", limit.toString());
  response.headers.set("X-RateLimit-Remaining", remaining.toString());
  response.headers.set("X-RateLimit-Reset", reset.toString());

  if (!success) {
    return new NextResponse(
      JSON.stringify({
        error: "Too many requests. Please try again later.",
        reset: new Date(reset * 1000).toISOString(),
      }),
      {
        status: 429,
        headers: {
          "Content-Type": "application/json",
          "Retry-After": reset.toString(),
        },
      }
    );
  }

  return response;
}

export const config = {
  matcher: ["/api/:path*"],
};

This middleware applies to all routes under /api. The returned headers allow frontend code to display remaining quota. The 429 response includes a Retry-After header that compliant clients can respect automatically.

Granular Limits Inside Route Handlers

Middleware works for broad rules, but many applications require different limits per endpoint or per authenticated user. Route handlers in the App Router give you this flexibility.

Consider an AI chat completion endpoint. Free users might be limited to 5 requests per minute while Pro users receive 60. Here is a complete implementation using Next.js 15 Route Handlers:

import { NextRequest, NextResponse } from "next/server";
import { ratelimit } from "@/lib/ratelimit";
import { getCurrentUser } from "@/lib/auth";

export async function POST(request: NextRequest) {
  const user = await getCurrentUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const limiter = ratelimit.user(user.id);
  const { success, limit, remaining, reset } = await limiter.limit(
    `chat:${user.id}`
  );

  if (!success) {
    return NextResponse.json(
      {
        error: "Rate limit exceeded. Upgrade to Pro for higher limits.",
        limit,
        remaining,
        reset: new Date(reset * 1000),
      },
      {
        status: 429,
        headers: {
          "X-RateLimit-Limit": limit.toString(),
          "X-RateLimit-Remaining": remaining.toString(),
          "X-RateLimit-Reset": reset.toString(),
        },
      }
    );
  }

  // Proceed with expensive LLM call
  const body = await request.json();
  // ... integration with Vercel AI SDK or LangGraph ...

  const response = await generateAIResponse(body.prompt);

  return NextResponse.json({
    response,
    remainingRequests: remaining - 1,
  });
}

The key is prefixing the rate-limit key with both the resource type (“chat”) and the user identifier. This creates isolated counters without affecting other endpoints.

Implementing Tiered Limits for Multi-Tenant SaaS

Most startups offer multiple subscription tiers. You can encode the tier directly in the limiter configuration. Extend the factory pattern:

export function createUserRatelimit(userId: string, tier: "free" | "pro" | "enterprise") {
  const limits = {
    free: { requests: 5, window: "1 m" },
    pro: { requests: 60, window: "1 m" },
    enterprise: { requests: 300, window: "1 m" },
  };

  const config = limits[tier];

  return new Ratelimit({
    redis: Redis.fromEnv(),
    limiter: Ratelimit.slidingWindow(config.requests, config.window),
    analytics: true,
    prefix: `ratelimit:${tier}:${userId}`,
  });
}

Fetch the user’s tier from your database (Drizzle ORM or Supabase) inside the route handler and instantiate the appropriate limiter. This approach keeps limit logic colocated with business rules and makes adjustments trivial when product offerings change.

For organizations with multiple team members, consider tenant-level limits in addition to per-user limits. You can run both checks sequentially: first the tenant limit, then the individual user limit. The first failure aborts the request.

Protecting Expensive AI Inference Endpoints

LLM calls are among the most costly operations in modern applications. A single GPT-4o completion can cost several cents. Without limits, a malicious or overly enthusiastic user can generate significant bills within minutes.

Apply token-bucket limiting to allow short bursts while enforcing sustainable usage. Combine with streaming responses using the Vercel AI SDK to keep perceived latency low even under restrictive quotas.

Additional best practice: log rate-limit events to a separate analytics table. This data helps identify users who consistently hit limits and may need product adjustments or sales outreach. Never log full request payloads for privacy reasons; store only timestamps, user IDs, and endpoint identifiers.

Frontend Patterns for Graceful Rate Limit Handling

Good rate-limit UX prevents user frustration. Fetch the rate-limit headers on every response and update UI elements in real time.

Using TanStack Query (v5), you can create a global interceptor that reads the headers and displays a progress bar or tooltip showing remaining requests. When a 429 occurs, show a toast with the exact reset time and disable the submit button until the window resets.

Example React hook:

function useRateLimit(endpoint: string) {
  const [remaining, setRemaining] = useState(10);
  const [resetTime, setResetTime] = useState<Date | null>(null);

  const Response) => {
    const limit = response.headers.get("X-RateLimit-Limit");
    const rem = response.headers.get("X-RateLimit-Remaining");
    const reset = response.headers.get("X-RateLimit-Reset");

    if (rem) setRemaining(parseInt(rem));
    if (reset) setResetTime(new Date(parseInt(reset) * 1000));
  };

  return { remaining, resetTime, onResponse };
}

Pass the onResponse callback to your fetch wrapper or query client. This creates immediate visual feedback that encourages users to stay within limits rather than discovering them through error messages.

Monitoring, Observability, and Alerting

Upstash’s built-in analytics dashboard shows request volume, blocked requests, and top keys over time. For deeper integration, forward analytics events to your existing observability stack.

When using Sentry (version 8), capture rate-limit events as breadcrumbs rather than full errors. This preserves context without inflating your error quota. Set up a separate alert in the Upstash console that triggers when blocked requests exceed 5% of total traffic for 10 consecutive minutes. Such spikes often indicate either a new abuse vector or an unexpectedly popular feature that needs quota increases.

Track two key metrics: requests-per-minute by tier and blocked-request percentage. A healthy production application typically sees blocked requests below 1% after initial tuning. Persistent elevation in a specific tier suggests either overly aggressive limits or a product experience issue that encourages excessive polling.

Combining Upstash Rate Limiting with Cloudflare

Many teams use Cloudflare in front of Vercel. Cloudflare offers its own rate-limiting rules at the edge. The two systems complement each other when used in layers.

Use Cloudflare for coarse IP-based rules that block obvious abuse before the request reaches Vercel’s edge. Then apply the more granular, user-aware limits with Upstash inside your middleware and route handlers. This layered defense reduces the number of requests that consume your Upstash command quota.

Cloudflare rate limiting is rule-based and does not easily support dynamic per-user logic pulled from your database. Upstash excels here because you can run arbitrary TypeScript code before making the Redis call. The trade-off is a small increase in latency (typically 10–30 ms) compared to pure Cloudflare rules.

Common Pitfalls and Production Considerations

IP-based limiting fails for users behind CGNAT or corporate proxies. Always fall back to a stable user identifier once authentication succeeds. When no user is present, combine IP with a fingerprint derived from headers such as User-Agent and Accept-Language, but treat this fingerprint as lower confidence.

Another pitfall is using the same Redis instance for both rate limiting and your primary application cache. While technically possible, separate databases with different eviction policies prevent one workload from affecting the other. Upstash makes creating additional databases trivial.

During high-traffic events, Redis latency can increase. The @upstash/ratelimit package supports a timeout option that fails open if the Redis call exceeds the threshold. Decide whether failing open (allowing the request) or failing closed (blocking the request) better suits your risk profile. For billing-related endpoints, fail closed. For content delivery, fail open is often safer.

Finally, document your public rate limits in your API reference and return them in the Link header with relation rate-limit following emerging standards. This helps API consumers build respectful clients and reduces support tickets.

Migration Strategies from In-Memory or Self-Hosted Solutions

Teams moving from an in-memory store such as express-rate-limit or a self-managed Redis instance should start by replicating their current limits using the sliding-window algorithm. Export historical usage data if possible and seed the new Upstash keys using the Redis ZADD command to preserve user experience during cutover.

Run both systems in parallel for two weeks, comparing metrics. The Upstash dashboard provides an “Allowed” vs “Blocked” graph that makes validation straightforward. Once confident, remove the legacy middleware. Because the Upstash client is only 8 KB gzipped, the bundle-size impact is negligible even for edge deployment.

After migration, explore more advanced patterns such as using different limit windows for read versus write operations, or implementing soft limits that only log rather than block for premium customers. These capabilities become trivial once the foundational Upstash integration exists.

The combination of Next.js 15 edge runtime, App Router, and Upstash Redis delivers a scalable, globally consistent rate-limiting solution that grows with your application from prototype to millions of daily active users. The code patterns shown here have been battle-tested across multiple production SaaS products handling both traditional REST endpoints and AI-powered features.

Keep reading

Related Articles