How to handle rate limiting in modern APIs

updated
27 November 2026
27 November 2026
5 min read

A SaaS app lets users generate ad ideas through an external AI API. The page looks frozen after the first click, so one user clicks “Generate” five more times. That’s six paid AI calls and six heavy jobs. If the whole team does it, the provider’s daily quota is gone by lunch.

AI API request generation in a web application
Six clicks on Generate mean six paid AI calls

To a request counter, six clicks are just six requests. It has no idea that each one starts a model and calls an outside API. Opening a profile page would count the same, though it only reads one database row. An IP limit is no help here either, since that team likely works from a single office address.

This guide covers what to count and by which key, how to build a proper 429 response, how the main algorithms compare, and how to implement limits in Express and Redis.

{{banner}}

Why rate limiting matters

Rate limiting sets how many requests or operations a client can make in a given period. The count can be kept per user, IP address, API key, tenant, or endpoint, or for one expensive operation.

The first limit often goes on the login form, against password guessing. Others follow as the product grows, usually after something goes wrong: a traffic surge slows the database, or an external AI API runs out of quota halfway through the day.

The “Generate” button needs one too. A user can click it again and again, by accident or on purpose, and each click becomes a heavy task. With a limit, the extra clicks get a 429 and a short explanation, and the queue stays the same length.

A few repeated clicks can consume expensive capacity just as quickly as deliberate abuse.

Deciding what counts as a request

Before implementing anything, the team has to agree on what counts as a “request”. In simple cases, it’s an HTTP request. In a real product, it’s often more accurate to count business operations or resource costs.

Common ways to scope and measure limits include:

Limit typeWhat it limitsExample
Per IPRequests from one IP address100 requests per minute for a public endpoint
Per userActions of an authorized user10 report generations per minute
Per API keyPublic API usage by one client10,000 requests per day per key
Per workspaceTotal usage of a workspace or team1,000 AI operations per day
Per endpointLoad on a specific routeA strict limit for /login or /password-reset
Weighted (cost-based)The cost of each operationOne AI generation = 20 quota units

In practice, a combination of several limits is often used, for example, 60 requests per minute per IP, 10 heavy operations per minute per user, and 5,000 operations per day per workspace. This protects against random spam and against abuse within a single organization.

Different operations also have very different costs. A simple GET /profile request may only read a small database record, while POST /ai/generate-report may trigger an AI model, create background jobs, write to storage, and call external APIs. For cost-based limiting, the system can assign a weight to each operation instead of counting every request as one unit.

Here’s an example of how the weights can be set:

OperationExample cost
Reading a profile1 unit
Listing small records1–2 units
Exporting a large report10 units
Generating AI content20 units
Importing data from an external API50 units

Users can still make plenty of cheap requests, while expensive operations reach the limit much sooner.

Choosing the rate limit key

The key decides who or what the limit applies to, which makes it one of the most important design choices. IP limits are the default for public endpoints and stop a lot of scraping. Shared addresses are their weak point, from office NAT to mobile networks.

User-based or workspace-based limits are usually better for authenticated endpoints. A userId limit protects the system from one user making too many requests, and a workspaceId limit protects it from a whole organization consuming too many resources.

For integrations authenticated with API keys, the key becomes a useful identifier for applying per-client quotas and tracking usage. If a key leaks or needs to be revoked, access tied to that key can be disabled without affecting other clients.

How the main keys compare:

KeyBest forMain problem
IPAnonymous traffic, login, public endpointsShared IPs, VPNs, spoofed headers
userIdAuthenticated user actionsNo protection against workspace-level abuse
workspaceIdSaaS and team-level limitsOne user can use up the quota for the whole team
API keyPublic APIs and integrationsRequires key management
endpoint + userIdExpensive user operationsMore complex policy management

Production systems often combine these keys. For the “Generate” button, a sensible pair is endpoint + userId for each generation and workspaceId for the daily total.

HTTP 429 and a clear API contract

Once a client goes over the limit, the API answers with HTTP 429 Too Many Requests. The status comes from RFC 6585, which reserves it for a user sending too many requests in a given period. A Retry-After header can tell the client how many seconds to wait.

Here is what such a response looks like:

HTTP/1.1 429 Too Many Requests
Retry-After: 30
RateLimit-Limit: 100
RateLimit-Remaining: 0
RateLimit-Reset: 30
Content-Type: application/json

{
  "error": "rate_limit_exceeded",
  "message": "Too many requests. Try again in 30 seconds.",
  "retryAfterSeconds": 30
}

The current IETF draft defines two fields, RateLimit and RateLimit-Policy. Many libraries and APIs still use the older RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset pattern shown above.

A frontend developer who gets “Something went wrong” has no idea whether to retry, wait or show an error. A third-party integrator is in the same spot. A clear contract gives them the answer: the limit was hit, this is the limit, and this is when to try again.

What each header and field is for:

Header of fieldPurpose
Retry-AfterHow many seconds to wait, or until what date, before trying again
RateLimit-LimitThe total limit in the current window
RateLimit-RemainingHow many requests or units remain
RateLimit-ResetWhen or how soon the current limit window resets, depending on the implementation
error / code in JSONA machine-readable error code for the frontend and SDKs
messageA human-readable explanation

Teams that still send the non-standard X-RateLimit-* headers should keep a readable JSON body as well, since frontend developers will most often read the body.

The client should respect Retry-After and can add jitter to avoid synchronized retries. If many clients retry at exactly the same moment, they can create a “thundering herd” and overload the API again.

Rate limiting algorithms

Rate limiters commonly use four main approaches, with sliding windows implemented in two common variants. Here is how they compare at a glance:

AlgorithmAllows burstsMemory useGood fit
Fixed windowYes, at window edgesLow, one counter per keySimple API quotas
Sliding window logNoHigh, one timestamp per requestSecurity-sensitive endpoints such as login
Sliding window counterSlightly, within the estimateLow, two counters per keyHigh-traffic distributed APIs
Token bucketYes, up to the bucket capacityLow, a token count and the last refill timePublic APIs that tolerate short bursts
Leaky bucketNo, output stays constantDepends on the queue sizeBackground jobs and third-party APIs with strict quotas

Those differences come from how each algorithm counts time and requests. Here is what happens inside each one, starting with the simplest.

Fixed window

The simplest option counts requests in a set period, for example, 100 requests per 60 seconds. On the first request, the limiter creates a key in Redis, increments the counter and sets a TTL. Each new request adds one to the count until the TTL expires.

Its weak point is the window boundary. A client might send 100 requests in the last second of one window and another 100 in the first second of the next. Formally, the limit holds, but the backend takes 200 requests almost at once.

Sliding window

A sliding window reduces the boundary problem that fixed windows have. The log variant saves a timestamp for each request and removes records that fall outside the window. Counting this way is accurate. On a high-traffic API, though, memory use grows with the number of requests, and each check takes longer.

The counter variant estimates the load from the current and previous intervals. That costs much less, though the result is an approximation and can drift slightly from the exact limit.

Token bucket

APIs that need to absorb small bursts while keeping moderate throughput are a good match for this approach. For example, a bucket holds up to 20 tokens and refills at 1 token per second.

With a full bucket, a client can fire 20 requests in one go. After that, it gets one new request per second as tokens come back. The tricky part is the refill code: if two requests read the token count at the same moment, the same token can end up spent twice.

Leaky bucket

The leaky bucket works the other way round from algorithms that allow bursts. Requests wait in a queue and leave it at a constant rate, which shields databases from sudden IOPS spikes.

That makes it a good fit for queue workers, like the ones running AI generation jobs behind the “Generate” button. The price is latency: a request can wait in line even when the system has idle capacity, and the queue needs a defined capacity so it cannot grow without bound.

Choosing an algorithm mostly comes down to whether bursts are a feature or a threat for that endpoint.

Where to set limits

Production systems usually spread limits across several layers rather than keeping them in one place. Edge limits protect the infrastructure, and backend limits enforce product rules. Queue-level limits take care of expensive asynchronous work.

What each level is good at and where it falls short:

LevelMain goalBest forCaveats
CDN, edge or WAFShielding the infrastructureReducing abusive traffic, scraping, and volumetric spikes at the network perimeterWorks mostly with IP and geo data, usually without access to userId or workspaceId
API Gateway or reverse proxyCentral controlApplying the same global limits across several microservices, e.g. in Nginx, Kong or AWS API GatewayNeeds reliable header forwarding (e.g. X-Forwarded-For) and shared state for accurate counts
Backend middlewareBusiness rulesFine-grained limits by user, subscription tier or expensive endpointNeeds shared state such as Redis when limits must stay consistent across multiple app instances
Queue workerProtecting expensive jobsControlling concurrency for heavy jobs and staying within strict third-party API quotasNeeds backoff with jitter and a dead letter queue (DLQ) for rejected tasks, or retries pile up
Database constraints / quotasHard business limitsEnforcing quotas like “1,000 reports per month”Not ideal for high-frequency request counting; better suited to durable business quotas and final checks

For the “Generate” button, two layers can work well together. Backend middleware applies the per-user limit when the click arrives, while the queue worker paces AI jobs to help stay within the provider’s quota.

Practical implementation with Node.js and Express

The examples below start with a bare-bones limiter and end with a ready-made library, adding one piece at each step.

A simple in-memory limiter to show the idea

This example demonstrates the core algorithm behind rate limiting. It stores request data in the memory of a single Node.js process, so the data disappears when the app restarts. If the backend runs on several instances, each one counts requests separately.

A demonstration limiter based on the sliding window log:

// src/rate-limit/rate-limit-memory.ts

// Demonstrational Sliding Window Log limiter.

type RequestRecord = number;

const requests = new Map<string, RequestRecord[]>();

export function checkRateLimit(
  key: string,
  options = { limit: 10, windowMs: 60_000 },
) {
  const now = Date.now();
  const existing = requests.get(key) ?? [];

  // Keep only requests inside the current time window.
  const fresh = existing.filter((timestamp) => {
    return now - timestamp < options.windowMs;
  });

  if (fresh.length >= options.limit) {
    const oldest = fresh[0];
    const retryAfterMs = options.windowMs - (now - oldest);

    return {
      allowed: false,
      limit: options.limit,
      remaining: 0,
      retryAfterSeconds: Math.ceil(retryAfterMs / 1000),
    };
  }

  fresh.push(now);
  requests.set(key, fresh);

  return {
    allowed: true,
    limit: options.limit,
    remaining: options.limit - fresh.length,
    retryAfterSeconds: 0,
  };
}

Here, key is the client identifier. It can be an IP address, userId, workspaceId, API key, or a combination of several values. The simplest option is to limit requests by IP.

Express middleware for IP-based rate limiting

Express middleware runs before the route handler, which makes it a natural place for a rate limit. A request that fits within the limit moves on through next(). One that doesn’t get HTTP 429 Too Many Requests right away and never reaches the handler.

The middleware that applies the limiter to each incoming IP:

// src/middlewares/ip-rate-limit.middleware.ts

import { Request, Response, NextFunction } from "express";
import { checkRateLimit } from "../rate-limit/rate-limit-memory";

function getClientIp(req: Request) {

// req.ip uses Express's "trust proxy" configuration.
// Make sure only trusted proxies can supply forwarded client IPs.
  return req.ip || req.socket.remoteAddress || "unknown";
}

export function ipRateLimit(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  const ip = getClientIp(req);

  const result = checkRateLimit(`ip:${ip}`, {
    limit: 10,
    windowMs: 60_000,
  });

  res.setHeader("RateLimit-Limit", String(result.limit));
  res.setHeader("RateLimit-Remaining", String(result.remaining));

  if (!result.allowed) {
    res.setHeader("Retry-After", String(result.retryAfterSeconds));
    res.setHeader("RateLimit-Reset", String(result.retryAfterSeconds));

    return res.status(429).json({
      error: "rate_limit_exceeded",
      message: `Too many requests. Try again in ${result.retryAfterSeconds} seconds.`,
      retryAfterSeconds: result.retryAfterSeconds,
    });
  }

  next();
}

Connecting it to a regular Express app takes one argument in the route:

// src/app.ts

import express from "express";
import { ipRateLimit } from "./middlewares/ip-rate-limit.middleware";

const app = express();

app.use(express.json());

app.get("/api/demo", ipRateLimit, (req, res) => {
  res.json({
    ok: true,
    message: "Request passed rate limit",
  });
});

app.listen(3000, () => {
  console.log("API is running on http://localhost:3000");
});

Each IP now gets 10 requests per 60 seconds. The eleventh one receives the same 429 response as before, only with RateLimit-Limit set to 10.

The catch is that the counter lives in the memory of one process. Scale the app out to three instances, and each keeps its own count, so a client can get up to 30 requests through. Production needs a shared store for the counters: Redis, a managed KV store, or a dedicated rate limiting service.

Rate limiting by userId or API key

Once a user is logged in, an IP address is too rough a key. This middleware checks for a userId first and falls back to the API key. Anonymous requests are still counted by IP:

function getRateLimitKey(req: AuthenticatedRequest) {
  const userId = req.user?.id;
  const apiKey = req.header("x-api-key");

  if (userId) {
    return `user:${userId}`;
  }

  if (apiKey) {
    return `api-key:${apiKey}`;
  }

  return `ip:${req.ip}`;
}

export function userOrApiKeyRateLimit(
  req: AuthenticatedRequest,
  res: Response,
  next: NextFunction,
) {
  const key = getRateLimitKey(req);

  const result = checkRateLimit(key, {
    limit: 50,
    windowMs: 60_000,
  });

  res.setHeader("RateLimit-Limit", String(result.limit));
  res.setHeader("RateLimit-Remaining", String(result.remaining));

  if (!result.allowed) {
    res.setHeader("Retry-After", String(result.retryAfterSeconds));
    res.setHeader("RateLimit-Reset", String(result.retryAfterSeconds));

    return res.status(429).json({
      error: "rate_limit_exceeded",
      message: "You reached the request limit. Please try again later.",
      retryAfterSeconds: result.retryAfterSeconds,
    });
  }

  next();
}

This assumes the API key has already been validated earlier in the chain. Otherwise, a client could send a made-up key with each request and get a fresh limit every time.

On a route, it looks like this:

app.post("/api/reports/export", userOrApiKeyRateLimit, (req, res) => {
  res.json({
    message: "Report export started",
  });
});

Using the express-rate-limit library

A real Express project doesn’t always need a hand-written limiter. For a basic scenario, the express-rate-limit library does the job, and it installs with one command:

npm install express-rate-limit

A basic setup that limits all /api routes to 100 requests per minute:

// src/app.ts

import express from "express";
import rateLimit from "express-rate-limit";

const app = express();

app.use(express.json());

const limiter = rateLimit({
  windowMs: 60 * 1000,
  limit: 100,

  // Modern RateLimit headers.
  standardHeaders: "draft-7",

  // Old X-RateLimit-* headers can be disabled.
  legacyHeaders: false,

  message: {
    error: "rate_limit_exceeded",
    message: "Too many requests. Please try again later.",
  },
});

app.use("/api", limiter);

app.get("/api/products", (req, res) => {
  res.json({
    data: ["CPU", "GPU", "RAM"],
  });
});

app.listen(3000, () => {
  console.log("API is running on http://localhost:3000");
});

APIs behind a proxy such as Nginx, Cloudflare, or AWS ALB need Express trust proxy configured to match the actual proxy chain. Otherwise, req.ip may resolve to the proxy rather than the client, and IP-based limits can affect the wrong users.

Redis and atomic limits

Redis is often used for rate limiting because it is fast, supports TTL and can work as shared storage for all backend instances. A basic fixed-window limiter can use INCR to increment the counter and EXPIRE to set the TTL on the first request. If the counter is greater than the limit, the API returns 429.

Redis fixed-window limiter

The limiter function that talks to Redis:

// src/rate-limit/rate-limit-redis-fixed-window.ts

import Redis from "ioredis";

const redis = new Redis(process.env.REDIS_URL!);

type RateLimitOptions = {
  limit: number;
  windowSeconds: number;
};

export async function fixedWindowRateLimit(
  key: string,
  options: RateLimitOptions,
) {
  const redisKey = `rate-limit:${key}`;

  const current = await redis.incr(redisKey);

  if (current === 1) {
    await redis.expire(redisKey, options.windowSeconds);
  }

  const ttl = await redis.ttl(redisKey);
  const remaining = Math.max(options.limit - current, 0);

  return {
    allowed: current <= options.limit,
    limit: options.limit,
    remaining,
    retryAfterSeconds: ttl > 0 ? ttl : options.windowSeconds,
  };
}

The middleware wraps it in a factory, so each route can get its own limit and key prefix:

// src/middlewares/redis-rate-limit.middleware.ts

import { Request, Response, NextFunction } from "express";
import { fixedWindowRateLimit } from "../rate-limit/rate-limit-redis-fixed-window";

export function createRedisRateLimit(options: {
  limit: number;
  windowSeconds: number;
  keyPrefix: string;
}) {
  return async function redisRateLimit(req: Request, res: Response, next: NextFunction) {
    try {
      const key = `${options.keyPrefix}:ip:${req.ip || "unknown"}`;

      const rate = await fixedWindowRateLimit(key, {
        limit: options.limit,
        windowSeconds: options.windowSeconds,
      });

      res.setHeader("RateLimit-Limit", String(rate.limit));
      res.setHeader("RateLimit-Remaining", String(rate.remaining));
      res.setHeader("RateLimit-Reset", String(rate.retryAfterSeconds));

      if (!rate.allowed) {
        res.setHeader("Retry-After", String(rate.retryAfterSeconds));

        return res.status(429).json({
          error: "rate_limit_exceeded",
          message: "You reached the request limit. Please try again later.",
          retryAfterSeconds: rate.retryAfterSeconds,
        });
      }

      next();
    } catch (error) {
      next(error);
    }
  };

With a shared Redis store, all backend instances can read and update the same counter for a given key. That matters for Docker, Kubernetes, autoscaling, serverless, and any other setup where the app runs in more than one process.

Why INCR + EXPIRE isn’t always enough

INCR is atomic, but INCR and EXPIRE are two separate commands. If the process crashes between them, the key may stay in Redis without a TTL. It’s a rare case, but a key without a TTL never resets, and the client stays blocked until someone deletes it.

A Lua script solves this by running the increment and the TTL setup as one atomic operation:

// src/rate-limit/rate-limit-redis-lua.ts

import Redis from "ioredis";

const redis = new Redis(process.env.REDIS_URL!);

const script = `
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])

local current = redis.call("INCR", key)

if current == 1 then
  redis.call("EXPIRE", key, window)
end

local ttl = redis.call("TTL", key)
local remaining = limit - current

if remaining < 0 then
  remaining = 0
end

if current > limit then
  return {0, limit, remaining, ttl}
else
  return {1, limit, remaining, ttl}
end
`;

export async function atomicFixedWindowRateLimit(
  key: string,
  options: { limit: number; windowSeconds: number },
) {
  const redisKey = `rate-limit:${key}`;

  const [allowed, limit, remaining, ttl] = (await redis.eval(
    script,
    1,
    redisKey,
    options.limit,
    options.windowSeconds,
  )) as [number, number, number, number];

  return {
    allowed: allowed === 1,
    limit,
    remaining,
    retryAfterSeconds: ttl > 0 ? ttl : options.windowSeconds,
  };
}

The critical part is keeping the limiter’s read, decision, and update steps atomic under concurrency. Two requests arriving at the same moment shouldn’t each see spare capacity and start an expensive operation after the limit has effectively run out. For the “Generate” button, that difference decides whether the second click becomes a second AI job.

The right policy matters more than the number

A working limit rests on several decisions made earlier: what to count, how to count it, which key to use, and where to stop the request. The numbers in the code examples, such as 10 requests per minute or 20 units for an AI generation, are placeholders, and in a live product they should come from traffic.

A practical way to find them is to run the limiter in log-only mode long enough to capture representative traffic and record who would have received a 429, without blocking anyone. If paying teams hit the workspace cap on ordinary days, the cap needs revisiting together with the pricing plans. A good rate limit is therefore less about picking one number and more about matching the policy to the cost, identity, and traffic pattern of each operation.

{{banner-2}}

Building an API for real-world traffic?

Halo Lab develops APIs designed to stay stable under load.

Discuss your API

Need limits tuned to your real traffic?

Halo Lab’s Node.js team can build rate limiting around your actual usage.

Get a Node.js estimate

copy iconcopy icon
copy iconcopy icon
Sum UP
Get a free checklist
Please, enter your full name
Please, enter your email
Please, enter your job title
Download now
Check out your email inbox
Oops! Something went wrong while submitting the form.
Get a free guide
Please, enter your full name
Please, enter your email
Please, enter your job title
Download now
Check out your email inbox
Download guide
Oops! Something went wrong while submitting the form.