Rate Limiting

Cap how many requests a client can make in a set time window.

What is it?

Without a limit, one client (malicious, buggy or just very active) could send so many requests that the service slows down for everyone.

Rate limiting caps how many requests a client (by user, API key or IP address) can make in a time window. Requests over the cap are rejected or delayed.

Explain like I'm 10

It's like a nightclub bouncer who lets in only so many people per minute, however long the line. Not because the club dislikes visitors, but because letting everyone in at once would be a disaster for those already inside.

Examples

A simple fixed-window rate limiter

const requestCounts = new Map(); // key: userId, value: { count, windowStart }

function isAllowed(userId, limit = 100, windowMs = 60000) {
  const now = Date.now();
  const entry = requestCounts.get(userId);

  if (!entry || now - entry.windowStart > windowMs) {
    requestCounts.set(userId, { count: 1, windowStart: now });
    return true;
  }

  if (entry.count >= limit) return false; // over the limit
  entry.count++;
  return true;
}

How it works

Each request is checked against a counter for that client over a time window: fixed windows (like "per minute") or smoother sliding windows.

If the client is under the limit, the counter goes up and the request proceeds. At or over the limit, the request is rejected, usually with HTTP 429 "Too Many Requests", until the window resets.

Why does it exist?

Rate limiting stops a service from being overwhelmed, whether by a real traffic spike, a buggy client stuck in a retry loop, or deliberate abuse. It also stops one client's heavy use from hurting everyone else.

When to use it

Add rate limiting to any public API, especially for expensive operations (search, sending emails, calling a paid third-party service) or ones open to abuse (login attempts, password resets).

When not to use it

Don't set limits so tight that normal use gets rejected. Base them on real usage, and tell clients clearly how long until the limit resets so well-behaved ones can adapt.

Common mistakes

  • Setting limits so low that normal use gets rejected, frustrating real users.

  • Limiting only by IP address. That fails when many users share one IP (like an office) and is easy to dodge with many IPs.

  • Not telling the client why the request was rejected and when to retry, so the limit feels arbitrary.

Practice exercises

  1. Easy:

    Explain why an API with no rate limit is vulnerable to a single misbehaving client.

  2. Medium:

    Describe the difference between rate limiting by IP address and by authenticated user id, and a downside of each.

  3. Hard:

    Explain why a 'fixed window' rate limiter can allow twice the intended limit at the boundary between two windows, and how a 'sliding window' avoids that.

Interview questions

What problem does rate limiting solve?

It stops one client from overwhelming a service with too many requests, whether from abuse, bugs or unexpectedly heavy legitimate use.

What HTTP status code typically indicates a rate limit was hit?

429 Too Many Requests.

What's a weakness of rate limiting purely by IP address?

Many legitimate users can share one IP (like an office network), and an attacker can fairly easily spread requests across many IPs to dodge the limit.

What is the token bucket algorithm, mechanically?

A bucket holds tokens and is refilled at a steady rate up to a maximum capacity. Each request uses one token; if the bucket is empty, the request is rejected (or queued). It allows short bursts up to the capacity while the refill rate enforces a steady average.

What does the token bucket's capacity (burst size) control, separately from its refill rate?

The refill rate sets the long-run average rate. The capacity sets how big a burst can be spent at once before the client must wait for tokens to come back. One knob for sustained rate, one for burst tolerance.

What is the leaky bucket algorithm, and how does it differ from token bucket in the traffic pattern it produces?

Requests enter a queue (the bucket) and are processed (leak out) at a strictly constant rate, however bursty the input. Token bucket lets a burst through immediately up to its capacity; leaky bucket smooths bursts into a steady output. That suits a downstream system that needs even load, not just a fair average.

Scenario: an API should allow occasional bursts but enforce a steady average rate. Token bucket or leaky bucket, and why?

Token bucket. It's designed to let saved-up capacity be spent in a burst while the refill rate caps the long-run average. Leaky bucket would flatten that burst into a steady trickle, the wrong fit when real bursts should go through immediately.

What's the fixed window counter's boundary problem? Walk through it with a concrete example.

With 100 requests per minute, a client could send 100 in the last second of one window (11:00:59) and 100 more in the first second of the next (11:01:00): 200 requests in about 2 seconds, while each window's limit is technically respected. Fixed windows only look at aligned clock-minute buckets, not any rolling one-minute span.

What is the sliding window log algorithm, and why is it the most accurate but least memory-efficient approach?

It stores a timestamp for every request in the current window. On each new request, it drops timestamps older than the window and counts the rest. It's exact because it uses a true rolling window, but storing one timestamp per request instead of a single counter gets expensive at high volume.

What is the sliding window counter, and how does it approximate the log algorithm cheaply?

It keeps only two fixed-window counters (current and previous) and estimates the rolling count by weighting the previous window's count by how much of it still overlaps the sliding window. Close to the log's accuracy with two numbers instead of a list of timestamps.

Walk through the sliding window counter's formula with a concrete example.

If we're 25% into the current 1-minute window (15 seconds in), the estimate is current window count + previous window count × (1 − 0.25). That counts 75% of the previous window's requests toward the present rolling view, a close approximation without storing every timestamp.

Why is distributed rate limiting harder than single-server rate limiting?

One server can keep a counter in memory. But if a client's traffic is spread across many servers, each local counter sees only part of it and none knows the true total, so the effective limit is quietly multiplied by the number of servers handling that client.

Scenario: an API is rate-limited per-user, but requests are load-balanced across 10 stateless app servers, each keeping counts in local memory. What goes wrong?

The user's requests spread roughly evenly across the 10 servers, and each only counts what it saw. The user can effectively make up to 10× the intended limit without any one server seeing them go over.

What's the standard fix for distributed rate limiting?

Move the counter out of each server's memory into one shared, fast store (commonly Redis) that every server checks and updates, so the count reflects the client's true total.

Why must the increment-and-check operation in a shared Redis-based rate limiter be atomic, and what race condition happens if it's not?

If two servers both read the count, both see it under the limit, and both increment, both requests are allowed even though the total is now over the limit. That's a classic check-then-act race. Making read-check-increment one atomic operation closes it.

What Redis feature is commonly used to make this atomic?

Either INCR (atomically increments and returns the new value, so you check the returned value) together with EXPIRE for the window, or a small Lua script that Redis runs atomically so the whole check-and-increment is one indivisible step.

What impact does clock skew have on distributed rate limiting across multiple servers or regions?

If servers disagree slightly on the time, window boundaries shift depending on whose clock is used. A client's requests can fall into what one server sees as a new window while another sees the old one, giving a little extra allowance. Use the shared store's own clock for window math instead of each server's local clock.

What's the difference between rate limiting and backpressure/load shedding?

Rate limiting caps how much a given client may send, by a policy set in advance, regardless of current server load. Backpressure/load shedding is the server slowing or rejecting requests based on its own real-time capacity, whichever client they're from. A rate limit can still let through traffic that overwhelms an already struggling server.

Why might you rate limit by API key or user id rather than IP address for an authenticated API, and when would you still also want IP-based limiting?

An API key or user id is stable and tied to one real client, avoiding IP sharing and evasion problems. You still want IP-based limits in front of authentication, e.g. on login, where there's no user id yet and you must limit unauthenticated abuse.

What should a 429 response ideally include, and why does that matter for well-behaved clients?

How long to wait before retrying (usually a Retry-After header), and ideally how much quota remains and when it resets. Without it, a client can't know when to retry: it may hammer the API right away (making things worse) or back off far longer than needed.

What is the `Retry-After` header, and how should a client be expected to use it?

It tells the client, in seconds or as a timestamp, when it's safe to retry. A well-behaved client waits at least that long instead of retrying immediately or on its own schedule, so it recovers without adding to the overload.

Scenario: a legitimate client (e.g. a batch job clearing a backlog) gets rate-limited during a real, valid traffic spike. What's a better strategy than a flat hard reject?

Use a burst-tolerant algorithm (token bucket) that allows a temporary spike above the steady rate, or give known bulk/batch clients a separate higher-throughput tier or queue. Capping every client at a rate designed for interactive use unfairly penalizes a different but legitimate traffic pattern.

What is a "leaky bucket as a queue" implementation, and how does it differ from leaky bucket purely as a rate limiter?

As a rate limiter, requests beyond the drain rate are rejected. As a queue, they're held and processed later at the drain rate instead of dropped. You trade rejection for added latency, useful when a request should be delayed, not lost.

Why doesn't rate limiting alone fully protect against a DDoS attack distributed across many different IPs or accounts?

It caps each client's rate, but an attack from thousands of IPs or fake accounts can keep each one under its limit while the total still overwhelms the service. Rate limiting bounds per-client abuse, not total volume from many coordinated sources, which needs other defenses (traffic filtering, anomaly detection, a CDN/DDoS mitigation layer).

What layers of a system might apply rate limiting, and why might you want it at more than one?

The client SDK (self-throttling before sending), an API gateway (one central enforcement point for external traffic), and individual services (protecting a specific expensive operation however the request arrived). Layers catch different problems: well-behaved clients that self-throttle avoid wasted traffic, while gateway and service limits protect against clients that don't.

Scenario: login attempts are rate-limited per account to prevent brute-force password guessing. What's a subtlety if you naively lock the account out after N failed attempts?

An attacker can deliberately fail logins on a victim's account to lock the real user out: a denial of service using the very protection meant to help them. Mitigations: increasing delays instead of a hard lockout, also limiting by source (IP/device), or requiring an extra verification step instead of blocking login.

What's the tradeoff between rate limiting enforced on the server versus asking the client to self-throttle?

Server-side enforcement is authoritative and can't be bypassed, but each rejected request still costs the server something to receive and reject. Client self-throttling avoids sending extra requests at all, but any client can ignore it. In practice the server is the real guarantee and client throttling is an optimization on top.

Why is choosing the rate-limiting window size (1 second vs 1 minute vs 1 hour) a real design decision, not an arbitrary one?

A short window reacts to abuse quickly but leaves less room for legitimate bursts. A long window absorbs short bursts but lets an abusive client keep a higher instant rate for longer before the limit catches up. Pick it based on what bursts are normal for real users versus what signals abuse.

What happens to a token bucket's burst allowance if a client is idle for a long period and then suddenly sends a large batch?

Tokens build up to the bucket's capacity while the client is idle, so it can spend all of them in one large burst as soon as it starts again. That's by design, but be deliberate: a very large capacity plus long idle periods can allow bursts far beyond the steady rate.

Common misconception: "rate limiting is only about stopping malicious abuse." Why is this incomplete?

It just as often protects a service from its own legitimate clients: a buggy retry loop, a misconfigured cron job, or simply more real usage than a downstream dependency (like a third-party API with its own limits) can handle. It's basic self-protection against ordinary bugs and success, not only an anti-abuse tool.

Scenario: an internal microservice calls another at a high, bursty rate that occasionally exceeds what the downstream service can handle, causing cascading failures. Is client-imposed rate limiting or something else the better fix?

Client self-throttling helps but relies on every caller cooperating and knowing the right limit. A sturdier fix is usually the downstream service enforcing its own rate limit or applying backpressure based on its real current capacity, plus a circuit breaker in the caller so it fails fast instead of piling on retries.

Follow-up: how does rate limiting relate to a circuit breaker — are they solving the same problem?

Related but different. Rate limiting proactively caps traffic by policy, whether or not the downstream is healthy. A circuit breaker reacts when a downstream is already failing and stops sending it traffic until it recovers. One prevents overload; the other responds once something is wrong.

Why can a sliding window log's memory usage become an operational concern at high request volume, and what does the sliding window counter trade for cheaper memory?

The log keeps one timestamp per request for the whole window, so at high rates (e.g. thousands of requests per second per key) that's a lot of memory per client. The sliding window counter uses just two integers per client (current and previous counts), giving up exactness for a close approximation and far less memory.