Skip to content

Practical software architecture · Part 4 of 10

Rate limiting: fixed window, sliding window and token bucket

Rate limits protect a service from abuse and overload. Compare fixed window, sliding window and token bucket and see how to answer with a 429.

· 2 min read

architectureapi

A rate limiter caps how many requests a client may make in a period. It protects against abuse, accidents such as a client stuck in a retry loop, and overload.

Fixed window

Count requests per client in a fixed interval, for example 100 per minute, and reset at the boundary. It is trivial to implement and cheap. The weakness is bursts at the edge: a client can send 100 requests at 12:00:59 and another 100 at 12:01:00, which is 200 within two seconds.

Sliding window

Count requests in the last N seconds relative to now. This removes the boundary burst. It needs more memory, either storing timestamps or combining the current and previous window with a weighted count.

Token bucket

Imagine a bucket that holds up to capacity tokens and refills at a steady rate. Each request takes one token. If the bucket is empty the request is rejected. Clients can burst up to the capacity but the long-term rate is limited by the refill speed. This is the most popular choice for APIs.

Python
import time

class TokenBucket:
    def __init__(self, capacity, refill_per_second):
        self.capacity = capacity
        self.refill = refill_per_second
        self.tokens = capacity
        self.updated = time.monotonic()

    def allow(self):
        now = time.monotonic()
        self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.refill)
        self.updated = now
        if self.tokens >= 1:
            self.tokens -= 1
            return True
        return False

bucket = TokenBucket(capacity=5, refill_per_second=1)
print([bucket.allow() for _ in range(7)])

Answering the client

Respond with status 429 Too Many Requests and a Retry-After header saying how many seconds to wait. Many APIs also expose the limit and the remaining quota in headers so well-behaved clients can slow down by themselves.

Practical advice

  • Pick the key carefully: API key, user id, or IP address. IP addresses are shared behind NAT, so they punish innocent users.
  • Use different limits for different endpoints. Login and password reset deserve stricter limits than reads.
  • In a cluster, keep counters in a shared store such as Redis, or accept per-node limits as an approximation.

Takeaway

Token bucket is a good default: it allows short bursts, enforces a steady average and is simple to explain. Always tell clients how long to wait.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.