Module 2 · Intermediate · Scaling and load balancing

Rate limiting: algorithms and examples

Rate limiting explained: why APIs limit requests, token bucket, leaky bucket and window algorithms in Python, 429 responses, and limits across servers.

By theprogrammers team · · 7 min read

Rate limiting means capping how many requests a user, an IP address or an app can make in a period of time: "100 requests per minute", "5 login attempts per 15 minutes", "3 OTPs per hour". When the limit is reached, further requests are rejected until the window resets.

Every serious API uses it, and "design a rate limiter" is a classic system design interview question. This lesson explains why rate limiting matters, walks through the four common algorithms with small Python implementations, and covers how to respond to clients and how to share limits across many servers.

Why rate limit?

  • Protect against overload. One buggy script in a loop, or a sudden spike, shouldn't take the service down for everyone.
  • Stop abuse. Password guessing, scraping, spam sign-ups and OTP flooding all depend on making many requests quickly.
  • Fairness. One heavy user shouldn't use up capacity that everyone shares.
  • Cost control. If each request costs you money (an SMS, an AI model call), limits cap the bill.
  • Business plans. Free plans get 1,000 calls a day; paid plans get more.

What to limit by

Choose a key that identifies who is making requests:

KeyGood forWatch out for
User ID or API keyLogged-in users and API customersDoesn't cover anonymous requests
IP addressLogin pages, anonymous trafficMany users can share one IP (a college network, mobile carriers)
Phone number or emailOTPs, password resetsMust be checked before sending
EndpointExpensive operations, like search or exportsCombine with a user key

Real systems often combine them: for example, 5 login attempts per account and 100 per IP per minute.

Algorithm 1: fixed window counter

Count requests in fixed blocks of time, such as each calendar minute. Reset the count when a new minute starts.

import time

class FixedWindow:
    def __init__(self, limit, window_seconds):
        self.limit = limit
        self.window = window_seconds
        self.counts = {}               # (key, window number) -> count

    def allow(self, key, now=None):
        now = time.time() if now is None else now
        slot = (key, int(now // self.window))
        self.counts[slot] = self.counts.get(slot, 0) + 1
        return self.counts[slot] <= self.limit

limiter = FixedWindow(limit=3, window_seconds=60)
print([limiter.allow("ahana", now=t) for t in (0, 10, 20, 30, 61)])
# [True, True, True, False, True]

The fourth request in the first minute is refused; at 61 seconds a new window starts.

It's simple and uses very little memory. The flaw is the boundary burst: a user can send 3 requests at 0:59 and 3 more at 1:00, which is 6 requests in two seconds, double the intended rate.

(A real version would also delete old windows, so memory doesn't grow forever.)

Algorithm 2: sliding window log

Store the time of each request, and count only those in the last 60 seconds, measured from now:

from collections import defaultdict, deque

class SlidingLog:
    def __init__(self, limit, window_seconds):
        self.limit = limit
        self.window = window_seconds
        self.log = defaultdict(deque)

    def allow(self, key, now):
        times = self.log[key]
        while times and times[0] <= now - self.window:
            times.popleft()            # forget requests older than the window
        if len(times) < self.limit:
            times.append(now)
            return True
        return False

limiter = SlidingLog(limit=3, window_seconds=60)
print([limiter.allow("ahana", t) for t in (55, 58, 59, 61, 116)])
# [True, True, True, False, True]

The burst at the boundary is now blocked: the request at 61 seconds is refused because three requests happened in the previous 60 seconds. It's exact, but stores one timestamp per request, which is a lot of memory for high limits.

A popular compromise, the sliding window counter, keeps just two fixed-window counts (this minute and last minute) and estimates the rolling total by weighting the previous window. It's accurate enough and very cheap.

Algorithm 3: token bucket

Imagine a bucket that holds up to capacity tokens and refills at a steady rate. Each request takes one token. No token, no entry.

class TokenBucket:
    def __init__(self, capacity, refill_per_second):
        self.capacity = capacity
        self.rate = refill_per_second
        self.tokens = capacity
        self.last = 0.0

    def allow(self, now):
        elapsed = now - self.last
        self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
        self.last = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False

bucket = TokenBucket(capacity=5, refill_per_second=1)
burst = [bucket.allow(now=0) for _ in range(7)]
print(burst)                 # 5 allowed at once, then refused
print(bucket.allow(now=2))   # True: 2 seconds refilled 2 tokens
[True, True, True, True, True, False, False]
True

The token bucket allows short bursts (up to the capacity) while enforcing an average rate (the refill rate). That matches how real users behave: opening an app fires several requests at once, then things go quiet. It needs only two numbers per user, and it's used by many cloud providers and API gateways.

Algorithm 4: leaky bucket

Requests join a queue (the bucket) that is processed at a fixed rate, like water dripping from a hole. If the queue is full, new requests are dropped. Unlike the token bucket, the output is perfectly smooth, with no bursts. It's good for protecting something that can only handle a steady flow, such as sending messages to a partner's API.

Comparing the algorithms

AlgorithmAllows bursts?Memory per userAccuracy
Fixed windowYes, up to 2× at boundariesOne counterRough
Sliding window logNoOne timestamp per requestExact
Sliding window counterSmallTwo countersVery close
Token bucketYes, up to the capacityTwo numbersGood
Leaky bucketNo, smooth outputA queueGood

If an interviewer asks which to use, token bucket is a strong default for APIs; explain why with bursts and averages.

Telling the client

When you refuse a request, return 429 Too Many Requests and tell the client when to try again:

HTTP/1.1 429 Too Many Requests
Retry-After: 30
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0

Good clients wait for Retry-After and retry with exponential backoff: wait 1 second, then 2, then 4, plus a little randomness, so thousands of clients don't all retry at the same moment.

Rate limiting across many servers

With one server, the counters can live in memory. With many servers behind a load balancer, a user's requests are spread out, so each server's local count is wrong. As with sessions, the counts must be shared.

The usual answer is Redis: each request increments a counter key like rate:user42:28567 with an expiry. Redis is fast enough to check on every request, and its increment is atomic, so two servers can't both read "99" and both allow request 100. For token buckets, a small script runs the read-and-update as one atomic step.

Where to put the limiter:

  • At the edge: a CDN, API gateway or load balancer can rate limit before traffic reaches your servers. Best for blocking floods.
  • In the application: for limits that need business knowledge, such as "3 OTPs per phone number per hour".

Decide what happens if Redis itself is down. Usually you fail open (let requests through) so a limiter outage doesn't become a full outage; for security limits like login attempts, you might fail closed.

Practice

  1. Design limits for an OTP login endpoint.
Show the answer

For example: 3 OTP requests per phone number per 10 minutes and 10 per day; 20 OTP requests per IP per hour; 5 wrong OTP attempts per code before it's invalidated. Return 429 with Retry-After, and use a shared store so limits hold across servers.

  1. With a fixed window of 100 requests per minute, what's the most a client can send in 2 seconds?
Show the answer

200: 100 in the last second of one window and 100 in the first second of the next. Sliding windows or a token bucket prevent this.

  1. In the TokenBucket above, a user sends nothing for an hour. How many requests can they then send at once?
Show the answer
  1. Tokens refill up to the capacity and no further, so idle time can't build up an unlimited burst.

Interview questions

How would you design a rate limiter?

Clarify the rules and key (per user, IP or API key; limits per window), choose an algorithm (often token bucket or sliding window counter), store counters in a fast shared store like Redis with atomic operations and expiries, enforce at the gateway and/or service, return 429 with Retry-After and rate-limit headers, and decide fail-open or fail-closed behaviour.

Compare token bucket and leaky bucket.

Token bucket allows bursts up to its capacity while enforcing an average refill rate. Leaky bucket queues requests and processes them at a constant rate, smoothing traffic and dropping overflow, with no bursts.

What's the problem with fixed window rate limiting?

Bursts at window boundaries: a client can send the full limit at the end of one window and again at the start of the next, up to twice the rate in a short time.

What status code signals rate limiting?

429 Too Many Requests, usually with a Retry-After header saying when to try again.

What to learn next

  1. Review the full request path in what happens when you type a URL.
  2. Design clean endpoints to protect in REST API design basics.