---
title: "What Is Rate Limiting? Algorithms and Design"
url: https://www.khanwaseem.com/blog/high-level-design/what-is-rate-limiting
author: "khan Waseem"
published: 2026-11-25
updated: 2026-11-25
topics: ["High Level Design", "Blog"]
description: "Why APIs limit how many requests a client can make, how the fixed window, sliding window and token bucket algorithms work (with tested JavaScript code), how to return 429 responses from Express, and how to rate limit…"
---

# What Is Rate Limiting? Algorithms and Design

Table of Contents

[Toggle](#)

- [Introduction:](#introduction)
- [Why Rate Limiting Is Important](#why-rate-limiting-is-important)
- [What Do We Limit By?](#what-do-we-limit-by)
- [Rate Limiting Algorithms](#rate-limiting-algorithms)[1. Fixed Window Counter:](#1-fixed-window-counter)
- [2. Sliding Window Log:](#2-sliding-window-log)
- [3. Sliding Window Counter:](#3-sliding-window-counter)
- [4. Token Bucket:](#4-token-bucket)
- [5. Leaky Bucket:](#5-leaky-bucket)

- [Which Algorithm Should You Choose?](#which-algorithm-should-you-choose)
- [Telling Clients They Are Limited](#telling-clients-they-are-limited)
- [Rate Limiting Across Many Servers](#rate-limiting-across-many-servers)
- [Conclusion:](#conclusion)

## Introduction:

Imagine your API suddenly receives 50,000 requests per second from a single client. Maybe it’s a bug in someone’s app that calls your API in an endless loop, a bot trying thousands of passwords, or a scraper copying your whole site. Without protection, your servers slow down or crash, and **every** user suffers.

**Rate limiting** is the solution. A rate limiter controls how many requests a client can make in a period of time, for example “100 requests per minute per user”. Requests within the limit go through; extra requests are rejected (usually with the HTTP status **429 Too Many Requests**) until the client slows down.

Every large API uses rate limiting: GitHub, Twitter/X, Stripe and Google Maps all publish their limits. In this lesson we will see why rate limiting matters, how the main algorithms work (with tested JavaScript code), and how to design a rate limiter that works across many servers. It builds on what we learned about [load balancers](https://blog.khanwaseem.com/what-is-load-balancer/) and [caching](https://blog.khanwaseem.com/what-is-cache/).

## Why Rate Limiting Is Important

- **Protects against abuse:** it slows down brute-force login attempts, credential stuffing, spam and scraping.

- **Prevents overload:** one noisy client can’t use all the servers’ capacity and starve everyone else.

- **Keeps costs under control:** if every request costs money (cloud functions, paid third-party APIs, AI models), a limit stops a bug from producing a huge bill.

- **Enables fair usage and pricing:** a free plan might allow 1,000 requests per day and a paid plan 100,000.

Note that rate limiting alone can’t stop a large distributed denial-of-service (DDoS) attack from thousands of machines. That needs network-level protection from a CDN or cloud provider. But it is an essential layer.

## What Do We Limit By?

A rate limiter counts requests per **key**. Common choices are:

- **IP address:** simple, works for anonymous users. But many people can share one IP (an office or a mobile network), and attackers can switch IPs.

- **User ID:** fair for logged-in users.

- **API key:** the standard for public APIs, and the basis of pricing plans.

- **Endpoint:** stricter limits for expensive or sensitive routes, such as `/login` (to stop password guessing) or `/search`.

Real systems often combine them: for example 5 login attempts per minute per IP **and** 1,000 API calls per hour per API key.

## Rate Limiting Algorithms

There are several ways to decide whether a request is allowed. Each one is a trade-off between accuracy, memory use and how it handles **bursts** (many requests arriving at once). In the code below, every limiter has an `allow(key, now)` method that returns `true` or `false`. We pass the time in as `now`, which makes the behaviour easy to test.

### 1. Fixed Window Counter:

Divide time into fixed windows, for example 10 seconds each, and count the requests in the current window. When a new window starts, the count resets to zero.

```javascript
class FixedWindowLimiter {
  constructor(limit, windowMs) {
    this.limit = limit;
    this.windowMs = windowMs;
    this.counters = new Map(); // key -> { windowStart, count }
  }
  allow(key, now = Date.now()) {
    const windowStart = Math.floor(now / this.windowMs) * this.windowMs;
    const c = this.counters.get(key);
    if (!c || c.windowStart !== windowStart) {
      this.counters.set(key, { windowStart, count: 1 });
      return true;
    }
    if (c.count < this.limit) {
      c.count++;
      return true;
    }
    return false;
  }
}Code language: JavaScript (javascript)
```

With a limit of 5 requests per 10 seconds, requests at 0, 1, 2, 3, 4, 5, 9 and 10 seconds give:

```javascript
const run = (limiter, times) =>
  times.map((t) => (limiter.allow("user-42", t) ? "✓" : "✗")).join(" ");

const fw = new FixedWindowLimiter(5, 10000);
console.log(run(fw, [0, 1000, 2000, 3000, 4000, 5000, 9000, 10000]));
// ✓ ✓ ✓ ✓ ✓ ✗ ✗ ✓Code language: JavaScript (javascript)
```

The 6th and 7th requests are rejected, and at 10 seconds a new window starts, so the request is allowed again.

**Pros:** very simple, and needs just one counter per key. **Cons:** the **boundary problem**. A client can send 5 requests at the very end of one window and 5 more at the start of the next one, which is 10 requests in a tenth of a second, double the intended rate:

```javascript
const burst = [9900, 9910, 9920, 9930, 9940, 10000, 10010, 10020, 10030, 10040];
console.log(run(new FixedWindowLimiter(5, 10000), burst));
// ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓   <- all 10 allowed!Code language: JavaScript (javascript)
```

### 2. Sliding Window Log:

Keep the timestamp of every request. To decide, remove timestamps older than the window and count the rest. The window “slides” with the current time, so there are no boundaries to exploit.

```javascript
class SlidingWindowLog {
  constructor(limit, windowMs) {
    this.limit = limit;
    this.windowMs = windowMs;
    this.logs = new Map(); // key -> array of timestamps
  }
  allow(key, now = Date.now()) {
    const log = (this.logs.get(key) || []).filter((t) => t > now - this.windowMs);
    if (log.length >= this.limit) {
      this.logs.set(key, log);
      return false;
    }
    log.push(now);
    this.logs.set(key, log);
    return true;
  }
}

console.log(run(new SlidingWindowLog(5, 10000), burst));
// ✓ ✓ ✓ ✓ ✓ ✗ ✗ ✗ ✗ ✗Code language: JavaScript (javascript)
```

**Pros:** perfectly accurate. **Cons:** it stores one timestamp per request, so a limit of 10,000 requests per hour means up to 10,000 timestamps per client. That uses a lot of memory at scale.

### 3. Sliding Window Counter:

A clever middle ground. Keep only two counters, for the current and the previous fixed window, and **estimate** the number of requests in the sliding window by weighting the previous window by how much of it still overlaps:

```javascript
estimate = previousCount × (1 − fraction of current window elapsed) + currentCountCode language: JavaScript (javascript)
```

```javascript
class SlidingWindowCounter {
  constructor(limit, windowMs) {
    this.limit = limit;
    this.windowMs = windowMs;
    this.state = new Map(); // key -> { windowStart, current, previous }
  }
  allow(key, now = Date.now()) {
    const windowStart = Math.floor(now / this.windowMs) * this.windowMs;
    let s = this.state.get(key) || { windowStart, current: 0, previous: 0 };
    if (s.windowStart !== windowStart) {
      const previous = windowStart - s.windowStart === this.windowMs ? s.current : 0;
      s = { windowStart, current: 0, previous };
    }
    const elapsed = (now - windowStart) / this.windowMs; // 0..1
    const estimate = s.previous * (1 - elapsed) + s.current;
    this.state.set(key, s);
    if (estimate >= this.limit) return false;
    s.current++;
    return true;
  }
}

console.log(run(new SlidingWindowCounter(5, 10000), burst));
// ✓ ✓ ✓ ✓ ✓ ✗ ✓ ✗ ✗ ✗Code language: JavaScript (javascript)
```

The burst is blocked almost completely. One request slips through at 10.01 seconds because the estimate assumes the previous window’s requests were spread evenly, when really they all came at the end. That small inaccuracy is the price of using two numbers instead of a full log, and in practice it is usually acceptable. Cloudflare has described using this approach at very large scale.

### 4. Token Bucket:

Picture a bucket that holds up to `capacity` tokens. Tokens are added at a steady rate, say 1 per second, and the bucket never holds more than its capacity. Each request takes one token; if the bucket is empty, the request is rejected.

```javascript
class TokenBucket {
  constructor(capacity, refillPerSecond) {
    this.capacity = capacity;
    this.refillPerMs = refillPerSecond / 1000;
    this.buckets = new Map(); // key -> { tokens, last }
  }
  allow(key, now = Date.now()) {
    const b = this.buckets.get(key) || { tokens: this.capacity, last: now };
    // Add the tokens earned since the last request
    b.tokens = Math.min(this.capacity, b.tokens + (now - b.last) * this.refillPerMs);
    b.last = now;
    this.buckets.set(key, b);
    if (b.tokens >= 1) {
      b.tokens -= 1;
      return true;
    }
    return false;
  }
}

// Capacity 5, refills 1 token per second
const tb = new TokenBucket(5, 1);
console.log(run(tb, [0, 0, 0, 0, 0, 0, 1000, 1500, 2000, 7000, 7000, 7000, 7000, 7000, 7000]));
// ✓ ✓ ✓ ✓ ✓ ✗ ✓ ✗ ✓ ✓ ✓ ✓ ✓ ✓ ✗Code language: JavaScript (javascript)
```

Let’s read the result: the client bursts 6 requests at time 0, and 5 succeed (the full bucket). At 1 second one token has been refilled, so one request succeeds; at 1.5 seconds only half a token has refilled, so it fails; at 2 seconds it succeeds again. After a 5-second pause the bucket is full again, allowing another burst of 5.

Notice that we don’t need a timer to add tokens. We simply calculate how many tokens were earned since the last request. This makes the token bucket cheap: just two numbers per key.

**Pros:** allows short bursts (good for real users, whose apps often send several requests at once) while enforcing an average rate; memory-efficient. **Cons:** two settings (capacity and refill rate) to tune. Amazon API Gateway and Stripe use token buckets.

### 5. Leaky Bucket:

The leaky bucket is the opposite view: requests go **into** a queue (the bucket) and are processed **out** of it at a fixed rate, like water leaking from a hole. If the queue is full, new requests are dropped. It produces a perfectly smooth output rate, which is useful when the system behind it (for example a payment processor or a database) can only handle a steady flow. The downside is that a burst of requests waits in the queue, adding delay.

## Which Algorithm Should You Choose?

- **Fixed window:** simplest; fine for rough limits where bursts at the boundary don’t matter, such as daily quotas.

- **Sliding window log:** when you need exact limits and the number of requests per window is small (for example login attempts).

- **Sliding window counter:** a great default for high-traffic APIs: accurate enough and very cheap.

- **Token bucket:** when you want to allow short bursts but control the average rate. The most popular choice for public APIs.

- **Leaky bucket:** when the downstream system needs a steady, smooth flow of work.

## Telling Clients They Are Limited

A good rate limiter tells the client what is happening, so well-behaved clients can slow down instead of retrying blindly:

- Respond with status **`429 Too Many Requests`**.

- Add a **`Retry-After`** header saying how many seconds to wait.

- Many APIs also send headers showing the limit and how much is left, such as **`RateLimit-Limit`** and **`RateLimit-Remaining`** (older APIs use `X-RateLimit-Limit` and `X-RateLimit-Remaining`).

Here is a token-bucket rate limiter as **Express** middleware. It limits each IP to a burst of 3 requests, refilling one request every 2 seconds:

```javascript
const express = require("express");

function rateLimit({ capacity, refillPerSecond }) {
  const buckets = new Map();
  return (req, res, next) => {
    const key = req.ip; // or the user ID / API key
    const now = Date.now();
    const b = buckets.get(key) || { tokens: capacity, last: now };
    b.tokens = Math.min(capacity, b.tokens + ((now - b.last) / 1000) * refillPerSecond);
    b.last = now;
    buckets.set(key, b);

    res.set("RateLimit-Limit", String(capacity));
    if (b.tokens < 1) {
      const retryAfter = Math.ceil((1 - b.tokens) / refillPerSecond);
      res.set("Retry-After", String(retryAfter));
      res.set("RateLimit-Remaining", "0");
      return res.status(429).json({ error: "Too many requests, please slow down." });
    }
    b.tokens -= 1;
    res.set("RateLimit-Remaining", String(Math.floor(b.tokens)));
    next();
  };
}

const app = express();
app.use("/api", rateLimit({ capacity: 3, refillPerSecond: 0.5 }));
app.get("/api/products", (req, res) => res.json([{ id: 1, name: "Keyboard" }]));
app.listen(3000, () => console.log("Listening on http://localhost:3000"));Code language: JavaScript (javascript)
```

Calling the endpoint four times quickly:

```javascript
$ for i in 1 2 3 4; do curl -s -w " %{http_code}\n" localhost:3000/api/products; done
[{"id":1,"name":"Keyboard"}] 200
[{"id":1,"name":"Keyboard"}] 200
[{"id":1,"name":"Keyboard"}] 200
{"error":"Too many requests, please slow down."} 429Code language: JavaScript (javascript)
```

The fourth response also carries `Retry-After: 2`. In a real project you would usually use a tested package such as `express-rate-limit`, but writing one yourself shows exactly what it does. One important detail: if your app runs behind a load balancer or proxy, `req.ip` is the proxy’s address unless you configure Express’s `trust proxy` setting correctly.

## Rate Limiting Across Many Servers

The middleware above keeps its counters in the memory of one server. In production, your API runs on several servers behind a load balancer, and each request may reach a different server. If each server counts separately, a client could get the limit multiplied by the number of servers.

The usual solution is to keep the counters in a **shared, fast store**, most often **Redis**. A fixed-window limiter in Redis needs only two commands:

```css
INCR   rate:user-42:2026-11-25T10:15     -> returns the new count
EXPIRE rate:user-42:2026-11-25T10:15 60  -> delete the key after the windowCode language: CSS (css)
```

If the returned count is greater than the limit, reject the request. Because Redis’s `INCR` is **atomic**, two servers can never read the same old value and both let a request through. For token buckets and sliding windows, the read-calculate-write steps are wrapped in a small **Lua script**, which Redis runs atomically. We covered Redis in the [What is Redis](https://blog.khanwaseem.com/what-is-redis/) lesson.

Some other design questions to think about:

- **Where to put the limiter:** in the API gateway or load balancer (protects everything, and rejected requests never reach your app), in a middleware of the app itself (can use user IDs and plans), or both.

- **Fail open or fail closed:** if Redis is down, should requests be allowed (keep the service up) or rejected (stay safe)? Most public APIs fail open; login endpoints may fail closed.

- **Latency:** checking a remote store adds a millisecond or two to every request. Some systems keep a local counter and sync it with Redis periodically, accepting slight inaccuracy.

- **Different limits for different plans:** store each API key’s limit along with it, and look it up in the limiter.

## Conclusion:

Rate limiting protects your services from abuse, overload and runaway costs by capping how many requests a client can make in a period of time. The fixed window is simple but allows bursts at boundaries, the sliding window log is exact but memory-hungry, the sliding window counter is a cheap and accurate compromise, and the token bucket allows short bursts while enforcing an average rate. Return `429` with a `Retry-After` header so clients can back off, and when you run more than one server, keep the counters in a shared store such as Redis.

In the next system design lesson we will look at **database sharding and partitioning**, which is how large systems split their data across many machines.

### Related posts:

[Hash Tables: How Hashing Gives O(1) Lookups](https://blog.khanwaseem.com/hash-table-data-structure/)
[Middleware in Next.js](https://blog.khanwaseem.com/middleware-in-next-js/)
[API Routes in Next.js](https://blog.khanwaseem.com/api-routes-in-next-js/)
[Incremental Static Regeneration (ISR) in Next.js](https://blog.khanwaseem.com/incremental-static-regeneration-isr-in-next-js/)

Powered by [YARPP](https://yarpp.com).
