API design

Understanding Rate Limiting and How to Handle It

How rate limiting algorithms work, how to enforce limits in one process or across servers with Redis, and how clients should respond to HTTP 429.

By the APIStack team··Updated ·12 min read

A hand holding a smartphone that shows a dashboard app, with a laptop and monitor behind it

Rate limiting restricts how many requests a client may make to an API in a given period. This article explains the common algorithms, shows how to enforce a limit on the server, and then covers the other side: how a client should behave when it is told to slow down. It is for developers who build APIs and for those who consume them, since most do both.

An API provider limits requests for three reasons. Limits stop one client, whether malicious or simply buggy, from consuming capacity that others need. They slow down abuse such as password guessing and scraping. And they define what each pricing plan includes.

Rate limits and quotas

Two kinds of limit are often applied together and are worth telling apart. A rate limit covers a short window, typically a second or a minute, and protects the service from bursts. A quota covers a long period, typically a month, and is a commercial allowance.

APIStack uses both. Each plan has a per-minute rate limit and a monthly quota, and a call over either one is rejected with 429 Too Many Requests and a Retry-After header.

PlanCalls per monthCalls per minute
Free1,00010
Pro100,000100
Enterprise1,000,000500

The current figures are kept under rate limits and quotas. The distinction matters to a client because the right reaction differs: after a rate limit, waiting a few seconds is enough, while after an exhausted quota, retrying is pointless until the period resets or the plan changes.

Rate limiting algorithms

Every algorithm answers the same question, which is whether this request is allowed, but they differ in how they treat bursts and how much state they keep per client.

Fixed window

A fixed window counter divides time into equal windows, such as each calendar minute, and counts requests in the current one. When the count reaches the limit, further requests are rejected until the next window begins. It needs one counter per client and is trivial to implement.

Its weakness is the window boundary. With a limit of 100 per minute, a client can send 100 requests in the last second of one window and 100 more in the first second of the next, which is twice the intended rate in a two-second span.

Sliding window

A sliding window removes the boundary problem by looking at the period ending now instead of a fixed calendar slot. The exact form, a sliding window log, stores the timestamp of every request and counts those newer than the window length. It is accurate, but memory grows with the limit.

The cheaper form, a sliding window counter, keeps the counts for the current and previous fixed windows and estimates the sliding count by weighting the previous window by how much of it still overlaps. It is an approximation that assumes requests were evenly spread, and it is close enough for most uses.

Token bucket

A token bucket holds up to a fixed number of tokens and is refilled at a steady rate. Each request removes one token, and a request that finds the bucket empty is rejected. The capacity sets how large a burst is allowed, and the refill rate sets the sustained rate, so the two can be tuned separately. A client that has been idle can make a burst of calls and is then held to the refill rate.

The implementation needs only two numbers per client, because the refill can be computed when a request arrives rather than on a timer.

JavaScript
class TokenBucket {
  constructor(capacity, refillPerSecond) {
    this.capacity = capacity;
    this.refillPerSecond = refillPerSecond;
    this.tokens = capacity;
    this.updatedAt = Date.now();
  }

  take() {
    const now = Date.now();
    const elapsedSeconds = (now - this.updatedAt) / 1000;
    this.tokens = Math.min(this.capacity, this.tokens + elapsedSeconds * this.refillPerSecond);
    this.updatedAt = now;

    if (this.tokens < 1) return false;
    this.tokens -= 1;
    return true;
  }
}

// Bursts of up to 20 requests, 5 per second sustained
const bucket = new TokenBucket(20, 5);

The leaky bucket is a related algorithm that queues requests and releases them at a constant rate. It smooths traffic rather than permitting bursts, which makes it more common in network equipment than in HTTP APIs.

Choosing between them

AlgorithmState per clientBurstsMain drawback
Fixed windowOne counterUp to twice the limit across a boundaryUneven enforcement at window edges
Sliding window logOne timestamp per requestNone beyond the limitMemory grows with the limit
Sliding window counterTwo countersClose to noneApproximate
Token bucketToken count and a timestampAllowed, up to the bucket capacityTwo parameters to tune

A fixed window is adequate for coarse limits such as a monthly quota. For per-second or per-minute limits, a token bucket or sliding window counter gives fairer behaviour for little extra cost.

Enforcing limits on the server

What to count against

The limit needs a key that identifies the client. For an authenticated API, use the API key or user ID. An IP address is a poor identifier: many users share one address behind a corporate network or mobile carrier, and an attacker can spread requests over many addresses. Keep IP-based limits for unauthenticated endpoints such as login, where there is nothing better.

Different endpoints can have different limits. An endpoint that triggers an expensive computation, or one that is a target for guessing such as password reset, deserves a tighter limit than a cheap read.

In a single process

For a single Express server, the express-rate-limit middleware is enough. This configuration allows 100 requests per client every 15 minutes on routes under /api/.

JavaScript
const { rateLimit } = require('express-rate-limit');

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000,   // 15 minutes
  limit: 100,                 // requests per window, per client
  standardHeaders: 'draft-7', // send RateLimit headers
  legacyHeaders: false,       // omit X-RateLimit-* headers
  message: { error: 'Too many requests, please try again later.' }
});

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

By default the middleware identifies clients by IP address and keeps counters in the memory of the process. Behind a reverse proxy, configure Express's trust proxy setting, otherwise every request appears to come from the proxy and all clients share one counter. To limit by API key instead, supply a keyGenerator function.

Across several servers

In-memory counters stop being correct as soon as there is more than one instance, because each instance counts only the requests it sees. With four instances behind a load balancer, a client effectively gets four times the limit. On serverless platforms, the counters also disappear whenever an instance is recycled. The counters have to live in a shared store, and Redis is the usual choice.

The check and the increment must be a single atomic operation. If two instances read the counter, both see 99 and both then write 100, one request too many gets through. A Lua script runs atomically inside Redis and avoids this. The script below implements a fixed window: it increments the counter, starts the expiry when the window opens, and returns the count with the seconds remaining.

Text
-- KEYS[1] = counter key, ARGV[1] = window length in seconds
local count = redis.call('INCR', KEYS[1])
if count == 1 then
  redis.call('EXPIRE', KEYS[1], ARGV[1])
end
return { count, redis.call('TTL', KEYS[1]) }

The middleware that calls it compares the count with the limit and, when the limit is exceeded, uses the remaining time as the Retry-After value. It uses a connected client from the redis package, version 4 or later, with the script above held as a string in FIXED_WINDOW_SCRIPT, and assumes that an earlier middleware has set req.apiKey.

JavaScript
const WINDOW_SECONDS = 60;
const LIMIT = 100;

async function rateLimitByKey(req, res, next) {
  try {
    const [count, ttl] = await redis.eval(FIXED_WINDOW_SCRIPT, {
      keys: [`ratelimit:${req.apiKey.id}`],
      arguments: [String(WINDOW_SECONDS)]
    });

    if (count > LIMIT) {
      res.set('Retry-After', String(Math.max(ttl, 1)));
      return res.status(429).json({ error: 'Rate limit exceeded' });
    }
    next();
  } catch (err) {
    next(); // Redis is unavailable: allow the request
  }
}

The catch branch is a decision you have to make deliberately. Failing open, as here, keeps the API available when Redis is down but leaves it unprotected. Failing closed protects the backend but turns a Redis outage into an API outage. Most public APIs fail open and alert on it.

An API gateway or CDN, such as Kong, AWS API Gateway or Cloudflare, can enforce limits before requests reach your application at all. That is the better place for coarse protection against floods. Limits that depend on your own data, such as a customer's plan, usually stay in the application.

Telling the client what happened

A rejected request should say why it was rejected and when to try again. The status code is 429 Too Many Requests, defined in RFC 6585, and the Retry-After header, defined in RFC 9110, gives the wait as a number of seconds or an HTTP date.

HTTP
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 30

{"error": "Rate limit exceeded", "message": "Limit of 100 requests per minute reached."}

Many APIs also report the client's standing on every response with X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset. These names are a widespread convention, not a standard, and their exact meaning varies between providers: the reset value may be a Unix timestamp, a date string or a number of seconds. An IETF draft, RateLimit header fields for HTTP, aims to standardize them. As a provider, document precisely what you send. As a consumer, read the provider's documentation before parsing these headers.

Handling limits in a client

A client that ignores 429 responses and retries immediately makes the situation worse for itself and for the provider. A well-behaved client does three things: it waits as long as it is told to, it backs off when it is not told, and it avoids making unnecessary calls to begin with.

Retry with backoff

When the response includes Retry-After, wait that long. When it does not, use exponential backoff: wait one second, then two, then four, so that repeated failures quickly reduce the load. Add a random amount, called jitter, to each wait. Without it, many clients that were limited at the same moment all retry at the same moment and are limited again.

The function below retries only on 429, prefers the server's Retry-After value when it is a number of seconds, and returns the last response once the retries are used up so the caller can inspect it.

JavaScript
async function fetchWithRetry(url, options = {}, maxRetries = 3) {
  for (let attempt = 0; ; attempt++) {
    const response = await fetch(url, options);
    if (response.status !== 429 || attempt === maxRetries) return response;

    const retryAfter = Number(response.headers.get('Retry-After'));
    const backoff = 2 ** attempt * 1000 + Math.random() * 1000;
    const delay = Number.isFinite(retryAfter) && retryAfter > 0
      ? retryAfter * 1000
      : backoff;

    await new Promise((resolve) => setTimeout(resolve, delay));
  }
}

The example below uses it to ask the APIStack Public Holidays API whether a date is a working day. The key goes in the x-api-key header.

JavaScript
const response = await fetchWithRetry(
  'https://apistack.online/api/data/public-holidays/v1/check?country=GB&date=2026-12-28',
  { headers: { 'x-api-key': process.env.APISTACK_API_KEY } }
);

if (!response.ok) {
  throw new Error(`Request failed with status ${response.status}`);
}
const result = await response.json();

Make fewer requests

The most reliable way to stay under a limit is to need fewer calls. Cache responses that do not change often: a list of public holidays for a year, a currency list or a geocoding result can be reused for hours or days. When several parts of an application request the same resource at once, share one in-flight request between them rather than sending duplicates. Where the API offers a batch or range endpoint, use it in place of a loop of single calls.

For background jobs that process many items, throttle on the client side. Sending requests through a queue at a rate just under the limit is faster overall than sending them as quickly as possible and spending the time in retries. A token bucket like the one shown earlier works equally well as a client-side throttle.

Monitoring rate limits

As a provider, record every rejection with the client's identity, the endpoint and the limit that applied. The useful figures are the number of 429 responses over time and the list of clients receiving them. A single client that is constantly limited either has a bug or has outgrown its plan, and both are worth an email. Many clients being limited at once suggests that the limit is too low for normal use or that the limiter itself is faulty. Review limits against real traffic periodically; a limit set before launch is a guess.

As a consumer, count the 429 responses you receive per provider and alert when they become regular. Occasional rejections that succeed on retry are harmless. Frequent ones mean users are waiting on your backoff delays, and you need more caching or a higher limit.

Summary

  • A rate limit protects against short bursts and a quota caps long-term usage. Clients should wait out the first and stop retrying on the second.
  • Fixed windows are simple but allow double the rate at boundaries. Token buckets and sliding windows enforce limits more evenly and let you decide how much burst to allow.
  • Count against an API key or user rather than an IP address, and keep counters in a shared store with atomic updates once you run more than one instance.
  • Reject with 429 and a Retry-After header, and document any other rate limit headers you send.
  • Clients should honour Retry-After, otherwise back off exponentially with jitter, cap retries, and reduce call volume with caching and batching.

Build with APIStack

One API key for validation, dates and holidays, web checks and reference data, over REST or as MCP tools for your AI agents. The free plan includes 1,000 calls a month.

Keep reading