A rate limiter caps how many requests a client can make in a period of time, such as 100 requests per minute per API key, and rejects or delays the rest. Four algorithms cover almost every interview version of the question. A fixed window counter is the simplest and lets twice the limit through at a window boundary. A sliding window log is exact but stores one timestamp per request. A sliding window counter approximates the log with two counters. A token bucket allows short bursts while holding a steady average rate. In Python each one is 15 to 25 lines with a dict, a collections.deque and time.monotonic().
This guide implements all four, runs them against the same traffic so you can see where they differ, and then walks through the follow-ups interviewers ask once the first version works. Every snippet is complete and runs on Python 3.12 or newer.
Which algorithm to pick
| Algorithm | Memory per client | Accuracy | Bursts | Pick it when |
|---|---|---|---|---|
| Fixed window counter | One counter | Up to 2x the limit at a boundary | Allowed at window edges | Rough limits where cost matters more than precision |
| Sliding window log | One timestamp per allowed request | Exact | Never above the limit in any window | The spec says "at most N in any W seconds" |
| Sliding window counter | Two counters | Close, assumes even spread in the previous window | Smoothed | High traffic, exactness not required |
| Token bucket | Two numbers | Exact for its own definition | Up to capacity at once, then rate per second |
Clients may burst, the long-run average must hold |
A leaky bucket is the fifth name you will hear. As a meter it is the token bucket seen from the other side. As a queue it releases requests at a fixed rate, which smooths output but adds latency. If the interviewer says "requests should be processed at a steady rate", they mean the queue form.
In an interview, ask which guarantee the spec wants before picking. "At most 5 per second" usually means a sliding window. "5 per second on average, short bursts are fine" means a token bucket.
Fixed window counter
Divide time into windows of window seconds and count allowed requests per client in the current window. When the window number changes, the count starts again.
from collections import defaultdict
class FixedWindowLimiter:
def __init__(self, limit: int, window: float) -> None:
self.limit = limit
self.window = window
self.counts: dict[str, tuple[int, int]] = defaultdict(lambda: (-1, 0))
def allow(self, key: str, now: float) -> bool:
current = int(now // self.window)
window_id, count = self.counts[key]
if window_id != current:
window_id, count = current, 0
if count >= self.limit:
return False
self.counts[key] = (window_id, count + 1)
return True
limiter = FixedWindowLimiter(limit=3, window=10)
print([limiter.allow("k", t) for t in (9.0, 9.5, 9.9, 10.0, 10.1, 10.2)])
# [True, True, True, True, True, True]Six requests got through in 1.2 seconds against a limit of 3 per 10 seconds, because three landed at the end of one window and three at the start of the next. That boundary burst is the standard follow-up question for this algorithm. The answer is either "that's acceptable here" or one of the next two algorithms.
Sliding window log
Keep the timestamps of each client's allowed requests in a deque. On every call, drop timestamps that have left the window from the left end, then allow the request if fewer than limit remain.
from collections import defaultdict, deque
class SlidingWindowLog:
def __init__(self, limit: int, window: float) -> None:
self.limit = limit
self.window = window
self.log: dict[str, deque[float]] = defaultdict(deque)
def allow(self, key: str, now: float) -> bool:
times = self.log[key]
while times and times[0] <= now - self.window:
times.popleft()
if len(times) >= self.limit:
return False
times.append(now)
return True
limiter = SlidingWindowLog(limit=3, window=10)
print([limiter.allow("k", t) for t in (9.0, 9.5, 9.9, 10.0, 10.1, 19.0)])
# [True, True, True, False, False, True]The same traffic now gets three requests through, then two rejections. At t=19.0 the request from t=9.0 sits exactly 10 seconds back, so times[0] <= now - window drops it and a slot opens. Whether a request exactly window seconds old still counts is a spec decision. Here the window is (now - window, now], open on the left. Say which one you chose out loud, because an off-by-one at the boundary is the most common failing test.
Each timestamp is appended once and popped at most once, so allow is amortized O(1) even though a single call can pop many entries. Memory is O(limit) per client, since only allowed requests are recorded. Recording rejected requests too is a classic bug. A client that keeps retrying would then lock itself out forever.
Sliding window counter
When storing a timestamp per request is too expensive, keep two counters per client: the count for the current fixed window and the count for the previous one. Estimate the rolling count by weighting the previous window by how much of it still overlaps the sliding window.
class SlidingWindowCounter:
def __init__(self, limit: int, window: float) -> None:
self.limit = limit
self.window = window
self.state: dict[str, tuple[int, int, int]] = {}
def allow(self, key: str, now: float) -> bool:
current = int(now // self.window)
window_id, cur, prev = self.state.get(key, (current, 0, 0))
if current == window_id + 1:
prev, cur = cur, 0
elif current > window_id + 1:
prev, cur = 0, 0
elapsed = (now % self.window) / self.window
estimate = prev * (1 - elapsed) + cur
if estimate >= self.limit:
self.state[key] = (current, cur, prev)
return False
self.state[key] = (current, cur + 1, prev)
return True
limiter = SlidingWindowCounter(limit=3, window=10)
print([limiter.allow("k", t) for t in (9.0, 9.5, 9.9, 10.0, 10.1, 19.0)])
# [True, True, True, False, True, True]At t=10.0 the previous window counts fully (3 x 1.0 = 3), so the request is rejected. At t=10.1 only 99% of the previous window still overlaps, the estimate is 2.97, and a fourth request passes even though the exact log would reject it. That is the approximation at work. The estimate assumes the previous window's requests were spread evenly, and these were bunched at its end, so the counter undercounts. By t=19.0 the estimate is 0.3 plus the one request at 10.1, and the request passes. This is the version most production gateways use, because its state is two integers and it fits in a single Redis hash.
Token bucket
A bucket holds up to capacity tokens and refills at rate tokens per second. Each request takes one token. If the bucket is empty, the request is rejected, or the caller waits until a token arrives. You don't need a background timer. Refill lazily from the elapsed time whenever someone asks.
class TokenBucket:
def __init__(self, rate: float, capacity: float, now: float = 0.0) -> None:
self.rate = rate
self.capacity = capacity
self.tokens = capacity
self.updated = now
def _refill(self, now: float) -> None:
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
def allow(self, now: float, cost: float = 1.0) -> bool:
self._refill(now)
if self.tokens < cost:
return False
self.tokens -= cost
return True
def retry_after(self, now: float, cost: float = 1.0) -> float:
self._refill(now)
return max(0.0, (cost - self.tokens) / self.rate)
bucket = TokenBucket(rate=0.3, capacity=3)
print([bucket.allow(t) for t in (9.0, 9.5, 9.9, 10.0, 10.1)])
# [True, True, True, False, False]
print(f"{bucket.retry_after(10.1):.2f}") # 2.23
print(bucket.allow(19.0)) # TrueThe bucket starts full, so three requests burst through. It refills at 0.3 tokens per second, and by t=10.1 it holds 0.33 tokens, so the next whole token is 2.23 seconds away. retry_after is the number you would put in an HTTP Retry-After header. The cost parameter handles weighted requests, such as charging an LLM call by its token count instead of counting calls.
Two parameters do different jobs. rate is the long-run average and capacity is the largest burst. Interviewers like asking what capacity=1 gives you. The answer is a strict spacing of one request every 1/rate seconds with no bursts at all.
Same traffic, four answers
Running all four on one burst at a window boundary shows the difference in one line each.
from collections import defaultdict, deque
class Fixed:
def __init__(self, limit, window):
self.limit, self.window, self.counts = limit, window, defaultdict(lambda: (-1, 0))
def allow(self, now):
wid, n = self.counts["k"]
cur = int(now // self.window)
if wid != cur:
wid, n = cur, 0
if n >= self.limit:
return False
self.counts["k"] = (wid, n + 1)
return True
class Log:
def __init__(self, limit, window):
self.limit, self.window, self.times = limit, window, deque()
def allow(self, now):
while self.times and self.times[0] <= now - self.window:
self.times.popleft()
if len(self.times) >= self.limit:
return False
self.times.append(now)
return True
class Counter:
def __init__(self, limit, window):
self.limit, self.window, self.state = limit, window, None
def allow(self, now):
cur_id = int(now // self.window)
wid, cur, prev = self.state or (cur_id, 0, 0)
if cur_id == wid + 1:
prev, cur = cur, 0
elif cur_id > wid + 1:
prev, cur = 0, 0
est = prev * (1 - (now % self.window) / self.window) + cur
ok = est < self.limit
self.state = (cur_id, cur + ok, prev)
return ok
class Bucket:
def __init__(self, limit, window):
self.rate, self.cap, self.tokens, self.t = limit / window, limit, limit, 0.0
def allow(self, now):
self.tokens = min(self.cap, self.tokens + (now - self.t) * self.rate)
self.t = now
if self.tokens < 1:
return False
self.tokens -= 1
return True
traffic = [9.6, 9.7, 9.8, 9.9, 10.0, 10.1, 10.2, 12.6, 19.65, 20.5]
for cls in (Fixed, Log, Counter, Bucket):
limiter = cls(limit=4, window=10)
passed = "".join("x" if limiter.allow(t) else "." for t in traffic)
print(f"{cls.__name__:8} {passed}")
# Fixed xxxxxxxx.x
# Log xxxx....xx
# Counter xxxx.x.xxx
# Bucket xxxx...xxxEach line is one limiter with a limit of 4 per 10 seconds, and x marks an allowed request.
- Fixed passes eight requests in 0.6 seconds, four on each side of
t=10. It then rejectst=19.65because the window[10, 20)is already full. - Log is the reference answer. Exactly four pass, and nothing else passes until
t=19.65, when the request fromt=9.6leaves the window. - Counter leaks one extra request at
t=10.1(estimate 3.96) and another att=12.6, because it assumes the four requests before the boundary were spread across the whole previous window. - Bucket refills 0.4 tokens per second, so by
t=12.6it has earned one token back and allows it. It enforces the average rate, not a hard cap per window.
If the interviewer's tests expect the Log line, only the log passes them. That is why asking about the exact guarantee comes first.
Follow-ups interviewers ask
Many clients and memory
A defaultdict keyed by client grows forever. Evict clients whose deque is empty after pruning, or whose bucket is full and idle. In an interview, delete the key when the deque empties inside allow, or run a periodic sweep. Mention that an attacker cycling through fake keys is exactly how this leaks.
Thread safety
The check and the update must be atomic. With threads, guard each client's state with a threading.Lock, a striped set of locks, or one lock if contention is low. Without the lock, two threads can both see len(times) == limit - 1 and both append, which lets the client over the limit.
asyncio and waiting instead of rejecting
In asyncio, code between two awaits runs without interruption, so a non-waiting allow needs no lock. A limiter that makes callers wait does need one, or two waiters both sleep and both take the same token. The asyncio interview guide has a complete async token bucket that sleeps (1 - tokens) / rate under an asyncio.Lock, which also serves waiters first come, first served.
A testable clock
Every limiter above takes now as an argument. That makes tests deterministic, because the test passes timestamps instead of sleeping. When the real class has to read the clock itself, inject a function like clock=time.monotonic and pass a fake in tests. Never use time.time() for intervals, since the wall clock can jump backwards when NTP corrects it.
Distributed rate limiting
With several servers, per-process limiters let each server admit the full limit. The usual answer is shared state in Redis. A fixed window is INCR key plus EXPIRE on first use. A sliding log is a sorted set with ZREMRANGEBYSCORE, ZCARD and ZADD. A token bucket or GCRA keeps two fields per client. The read and the write have to be atomic, so wrap them in a Lua script or a MULTI transaction. Mention the tradeoff, which is a network round trip per request, and the escape hatch, which is local buckets that each get a share of the global rate.
Per-tier limits and changing limits at runtime
Free, pro and enterprise clients get different limits. Store the limit per client or look it up per tier, and decide what happens to existing state when a limit changes. For a token bucket, clamp the current tokens to the new capacity. For a log, the new limit applies on the next call with no migration.
Common mistakes
- Closed instead of open boundary. Using
<where the spec wants<=when evicting, so a request exactlywindowseconds old still counts. - Recording rejected requests. Rejections should not use up quota.
list.pop(0)for eviction. It is O(n) per pop. Usedeque.popleft().- Rescanning the whole history. Filtering the full list on every call is O(history). The deque only ever touches its left end.
- Refilling with a timer task. Lazy refill on read is simpler and exact, and it avoids a background task per client.
- Unbounded per-client state. No eviction for idle clients means a memory leak.
Practise it
The Sliding Window Rate Limiter problem asks for the per-user log version with input validation, a whitespace-normalised user id and an amortized O(1) bound, and checks it against hidden tests on real CPython in your browser. Write it from a blank file in 25 minutes, then add a token bucket mode as your own follow-up.
- 06Sliding Window Rate Limitermedium
Build a per-user sliding window log rate limiter that allows at most N requests in any window of W seconds.
The rate limiting and sliding window topic pages collect the related problems. When a limiter rejects a request, the caller usually retries, which is the subject of the retries and exponential backoff guide. The practical coding interview guide covers how these rounds are graded.
Frequently asked questions
What is the best rate limiting algorithm?
It depends on the guarantee you need. A sliding window log is exact for "at most N requests in any W seconds" but stores one timestamp per request. A token bucket allows controlled bursts while holding an average rate. A sliding window counter approximates the log with two counters and is the common choice at high traffic. A fixed window is cheapest but can admit twice the limit at a window boundary.
What is the difference between a token bucket and a sliding window?
A sliding window counts requests in the last W seconds and never lets more than N through in any such span. A token bucket refills at a steady rate up to a capacity, so a client that has been idle can burst up to the capacity at once and is then held to the refill rate.
How do you implement a sliding window rate limiter in Python?
Keep a dict mapping each client to a collections.deque of timestamps of allowed requests. On each call, pop timestamps that are at least W seconds old from the left, allow the request if fewer than N remain, and append the current time only when you allow it. Each timestamp is appended and popped once, so the cost is amortized O(1).
Why does a fixed window rate limiter allow twice the limit?
The counter resets at each window boundary. A client can send N requests at the very end of one window and N more at the start of the next, so 2N requests pass in a span much shorter than one window.
How do you rate limit across multiple servers?
Keep the counters in shared storage such as Redis and make the read and update atomic with a Lua script or a transaction. INCR with EXPIRE gives a fixed window, a sorted set gives a sliding log, and two fields per client give a token bucket. The cost is a network round trip per request.
Should a rate limiter use time.time() or time.monotonic()?
Use time.monotonic() for measuring intervals. time.time() follows the wall clock, which can jump forwards or backwards when the system clock is corrected, and that breaks window and refill calculations. In tests, pass timestamps in or inject a fake clock instead of sleeping.