Forward Deployed EngineeringSoftware EngineeringDistributed Systems

Explain how rate limiting works, fixed window, sliding window, token bucket. When does each break?

Question 28 of 73 · Updated

On this page

Interview-ready answer#

Rate limiting controls how much work a client, tenant or service can initiate over time. It protects shared capacity, prevents noisy-neighbor behavior, limits abuse and helps enforce downstream quotas.

A fixed window counts requests in discrete time intervals, such as 100 requests per minute. It is cheap and simple, but can admit almost twice the nominal limit around a window boundary. An exact sliding window tracks accepted requests within the immediately preceding interval, eliminating that boundary loophole at the cost of storing timestamps. A sliding-window counter approximates that behavior using adjacent time buckets and is cheaper, but its estimate can be wrong when traffic is uneven. A token bucket refills at a specified rate up to a maximum capacity. Each admitted request consumes tokens. It permits controlled bursts while bounding long-run throughput.

For production, I choose the algorithm based on the actual business contract: strict rolling quota, inexpensive calendar-based quota, or burst-tolerant average throughput. I enforce limits atomically in a shared state store when multiple application instances must share a quota, define failure and retry behavior, and combine rate limits with concurrency limits, deadlines and backpressure. A limit of 100 requests per second does not protect a service from 100 expensive requests that all take minutes to finish.

1. What exactly is being limited?#

Before choosing an algorithm, clarify the policy.

DimensionExample
SubjectAuthenticated tenant, user, API key, service or trusted IP
ResourceSearch endpoint, payment API, LLM inference or upload
UnitRequests, bytes, tokens, estimated work or credits
LimitMaximum admitted work per interval
Burst toleranceHow much short-term excess traffic is acceptable
ActionReject, delay in a bounded queue, or degrade safely

A gateway normally evaluates an admission policy before invoking expensive downstream work. An admitted request is not necessarily successful: the policy must explicitly state whether it counts attempted, admitted or completed operations. Counting only successful requests may leave expensive failures unbounded.

For an AI deployment, I may enforce independent requests-per-minute, tokens-per-minute and in-flight inference limits. Treat the token bucket's abstract credits as separate from an LLM tokenizer's tokens unless the policy explicitly assigns credits based on token consumption.

2. Fixed window#

Divide time into non-overlapping intervals of width W. Each interval has a counter initialized to zero. Admit a request if the counter is less than L and atomically increment it; otherwise reject until the next window.

For a trusted timestamp t, the window identifier is floor(t / W).

Suppose L = 100 and W = 60 seconds. Requests in [0, 60) use one counter and requests in [60, 120) use another.

Boundary problem#

Imagine 100 requests at t = 59.9 seconds followed by 100 requests at t = 60.1 seconds. Both groups satisfy their respective fixed-window quotas, so the server may admit 200 requests within 0.2 seconds.

The algorithm has not violated its own definition. The problem is using a calendar-aligned quota when the requirement is a strict limit over any rolling minute.

Loading diagram…

Advantages: O(1) state per active subject and interval, constant-time counter operations, straightforward resets and understandable quota reporting.

Where it breaks: boundary bursts, incorrect time synchronization between instances, non-atomic updates, and situations where the requirement is a rolling rather than a fixed quota.

A fixed window is reasonable for inexpensive, calendar-aligned business quotas when boundary traffic is acceptable. It is not automatically appropriate for protecting a fragile downstream service.

3. Sliding window#

Exact sliding log#

Maintain the timestamps of admitted requests. At time t, remove entries at or before t − W, count the remaining entries, and admit only if fewer than L remain.

This article uses the interval (t − W, t], including the current instant and excluding the left boundary. For a limit of two requests per ten seconds, two admissions at t = 9 mean requests at t = 10 must be rejected; the admissions expire at t = 19.

An ordered deque works for nondecreasing timestamps in a single-process implementation. In a distributed store, a sorted set with unique member identifiers can represent events with equal timestamps. Pruning, counting and admission must be atomic.

Advantages: Enforces the exact stated rolling quota; handles fixed-window boundary spikes correctly.

Where it breaks: Per-event state scales with admitted traffic, and a large expiry batch can make one operation expensive. Distributed sorted-set operations may become a bottleneck for high-volume tenants. Clock anomalies, duplicate timestamp identifiers and race conditions can invalidate correctness.

For a log containing only admitted requests, the number of active timestamps per subject is bounded by L. That still becomes expensive for large L or millions of active subjects.

Approximate sliding-window counter#

Store counts for the current and previous fixed windows. Estimate the rolling count by weighting the previous count by the portion of that window still overlapping the requested interval.

estimated = current_count + previous_count × (1 − elapsed / W)

For W = 60 seconds, 15 seconds into the current window, the previous window contributes 75% of its count. If its count is 80 and the current count is 30, the estimate is 30 + 60 = 90 before considering a new request.

This assumes the previous window's traffic is approximately uniform. If the 80 requests were concentrated entirely inside or outside the overlap, the true contribution could be very different. Approximation can both undercount and overcount.

Where it breaks: strict rolling-window guarantees, highly bursty traffic and requirements that cannot tolerate false admissions or unnecessary rejections.

This is a useful middle ground for large-scale approximate quotas. Do not market it as an exact sliding log.

4. Token bucket#

Define capacity B and refill rate r credits per second. Start with at most B credits. At each admission check, calculate the credits accumulated since the previous update:

LaTeX

If enough credits exist for the operation's cost c, subtract c and admit. Otherwise reject or wait under a separately defined bounded-queue policy.

For B = 5 and r = 2 tokens per second, a full bucket permits five unit-cost requests immediately. After that burst, roughly one unit-cost request becomes available every half-second if there is no other traffic.

TimeActionTokens remaining
0 sAdmit five requests0
0 sSixth request rejected0
0.5 sRefill one; admit one0
1.5 sRefill two; admit one1

Over an interval of duration T, total admitted cost is at most B + rT under ideal continuous-time accounting and a valid initial bucket. The long-term average approaches r, but the burst term remains.

Loading diagram…

Advantages: constant-size state, natural weighted costs and controlled burst allowance.

Where it breaks: strict rolling count requirements, a capacity larger than the backend can safely absorb, clock jumps, resetting buckets to full on premature expiry, and non-atomic refill/debit. An operation whose cost exceeds capacity cannot ever be admitted unless the policy is changed.

A token bucket does not make requests execute at evenly spaced times. If smoothing is required, consider a scheduler or bounded leaky-bucket-style queue. Queuing trades rejection for latency and must have deadlines and a finite capacity.

5. Algorithm comparison#

ApproachState per active keyTypical operation costBurst behaviorBest use
Fixed windowCounter and window identityO(1)Boundary burst up to roughly 2LCalendar-aligned quota
Exact sliding logUp to L admitted timestampsAmortized O(1) with local deque; distributed index costs varyAt most L in every defined rolling intervalStrict rolling quota
Approximate sliding counterTwo counters and time metadataO(1)Estimated rolling quotaScalable approximate enforcement
Token bucketBalance and last refillO(1)Controlled burst up to capacityProtecting burst-tolerant throughput

An exact sliding log can remove O(L) expired timestamps in one check, though each locally stored timestamp is removed at most once. A Redis sorted-set implementation has different complexity from a deque; deleting M expired entries from a sorted set can involve O(log N + M) work, with separate indexed insertion cost.

All state bounds are per active key, not the entire service. Expiration and limits on key cardinality are operational requirements.

6. Tested Python reference implementations#

These are single-process, unit-cost, admitted-request limiters. They assume positive integer limits and time widths, nonnegative nondecreasing integer timestamps, and serialized calls. For the token bucket, capacity and refill are positive integer credits, refill is credits per time tick, and now starts no earlier than the constructor timestamp. For finer-grained rates, use fixed-point units or suitably validated numeric arithmetic and a sufficiently fine time unit.

They deliberately accept time as an argument so boundary behavior is deterministic and testable. Production local implementations should obtain elapsed time from a monotonic clock and serialize state changes.

PYTHON
from collections import deque class FixedWindow: def __init__(self, limit, width): if limit <= 0 or width <= 0: raise ValueError('positive limit and width required') self.limit, self.width = limit, width self.window, self.used = None, 0 def allow(self, now): window = now // self.width if window != self.window: self.window, self.used = window, 0 if self.used >= self.limit: return False self.used += 1 return True class SlidingLog: def __init__(self, limit, width): if limit <= 0 or width <= 0: raise ValueError('positive limit and width required') self.limit, self.width = limit, width self.accepted = deque() def allow(self, now): while self.accepted and self.accepted[0] <= now - self.width: self.accepted.popleft() if len(self.accepted) >= self.limit: return False self.accepted.append(now) return True class TokenBucket: def __init__(self, capacity, refill, now=0): if capacity <= 0 or refill <= 0: raise ValueError('positive capacity and refill required') self.capacity, self.refill = capacity, refill self.tokens, self.last = capacity, now def allow(self, now): self.tokens = min(self.capacity, self.tokens + (now-self.last)*self.refill) self.last = now if self.tokens < 1: return False self.tokens -= 1 return True

Example boundary checks:

PYTHON
fixed = FixedWindow(2, 10) sliding = SlidingLog(2, 10) bucket = TokenBucket(2, 1) assert [fixed.allow(t) for t in [9,9,10,10]] == [True,True,True,True] assert [sliding.allow(t) for t in [9,9,10,10]] == [True,True,False,False] assert [bucket.allow(t) for t in [0,0,0,1,1]] == [True,True,False,True,False]

The fixed-window implementation resets when the bucket identity changes. The sliding log retains only admissions inside the rolling interval. The token bucket advances its refill timestamp even when the request is rejected, so later checks cannot double-count elapsed refill.

Local verification: Executed the exact three classes in Python 3.13.5. All 81,090 scenarios passed. The harness exhaustively enumerated nondecreasing sequences of zero through six arrivals at integer timestamps 0 through 7. It compared fixed-window and sliding-log decisions with independent accepted-history counters for limits 1–3 and widths 1, 2 and 4, and token-bucket decisions and balances with an independent per-tick refill simulator for capacities 1–3 and refill rates 1–3. Six invalid-constructor cases and three explicit boundary/burst cases also passed. These are sequential synthetic tests, not real Redis, concurrency, distributed-clock or load tests.

7. Distributed rate limiting with Redis#

If ten gateway instances each enforce a local limit of 100 requests per minute independently, a tenant could receive up to 1,000 admissions across them. A shared limiter, or a coordinated quota-allocation scheme, is needed for a shared limit.

Loading diagram…

A check-then-increment across separate uncoordinated calls is unsafe: two requests can read the same counter and both pass. Use a bounded Redis script or an appropriate transactional compare-and-update mechanism to make the entire read, decision and mutation indivisible with respect to other clients on the same primary.

Illustrative Redis Lua fixed-window script#

The gateway derives a key from the trusted subject, policy version and aligned window identifier. Pass a validated positive integer limit and a TTL in milliseconds at least as long as the remaining lifetime of that window (for example, twice the window width). Use a consistent trusted time basis across gateways. The script assumes the key contains only a valid counter controlled by the limiter.

LUA
local limit = tonumber(ARGV[1]) local ttl_ms = tonumber(ARGV[2]) local value = redis.call('GET', KEYS[1]) if not value then redis.call('SET', KEYS[1], '1', 'PX', ttl_ms) return {1, limit - 1} end local used = tonumber(value) if used >= limit then return {0, 0} end used = redis.call('INCR', KEYS[1]) return {1, limit - used}

Return values represent admission and remaining credits in the selected fixed window. The expiry removes old keys; the window identifier, rather than expiry timing alone, defines the reset. A script that sets a fresh full quota on a missing key is safe only if state has not been prematurely evicted or lost. Use appropriate memory and persistence policies and explicitly handle failover.

Redis example status: illustrative and manually reviewed, not executed against Redis in this environment. Validate arguments and key ownership, script behavior, expiry, failover and concurrent admissions against the actual Redis/client versions before deployment.

For a sliding log, atomically remove expired entries from a sorted set, count, and insert a unique event member only if allowed. For a token bucket, atomically read balance and refill timestamp, compute elapsed time, cap refill, debit when possible and store the updated state. Store a bucket until its balance would naturally be full before allowing expiry to reset it. Avoid unsafe floating-point drift for strict accounting; use appropriate integer credit units and guard against backwards time.

Redis scripting provides atomic isolation on the executing server, not automatic rollback of earlier writes if a script encounters a later error. Keep scripts short and validate inputs before mutations. In Redis Cluster, multi-key atomic scripts require keys in the same hash slot. A global limit and per-tenant limit may not naturally be colocated. Define how multi-quota reservations, rollback, partial charging and retries work rather than assuming independent calls are atomic together.

8. Scale, availability and fairness#

  • Hot keys: a global limiter can serialize enormous traffic on one primary. Shard naturally by trusted tenant or resource where independent quotas permit it. Global exact limits still require coordination.
  • Regional latency: synchronous remote quota checks add latency to every request. Allocate conservative regional sub-budgets or leases when bounded overshoot and temporary underutilization are acceptable. Strict globally shared limits under partitions require a deliberate availability trade-off.
  • Failover: asynchronous replication or primary loss may lose recent quota updates. Atomicity on one primary is not a guarantee of durable globally exact accounting.
  • Store outage: decide fail-open or fail-closed per endpoint. Protect expensive inference, financial operations and security-sensitive workflows with conservative local caps or fail-closed behavior when appropriate. Distinguish service unavailability from a known quota rejection.
  • Retries: an admission response can be lost after debiting a quota. If exactly-once charging is a requirement, associate a bounded, durable request identity with the admission outcome and define replay retention. Do not blindly retry an uncertain debit.
  • Fairness: enforce hierarchical budgets for shared capacity, tenants and expensive routes. Derive identity from authenticated claims and trusted gateway metadata; never trust an arbitrary user-provided tenant ID or forwarded IP header.
  • Cardinality: control attacker-generated keys and expiration. Do not let an unlimited number of distinct unauthenticated identities exhaust the limiter's memory.

A rate limiter bounds admission, not outstanding work. Pair it with per-tenant and global concurrency limits, timeouts, queue bounds, circuit breakers and downstream capacity monitoring.

9. HTTP and customer-facing behavior#

A known client quota violation commonly returns HTTP 429 Too Many Requests. When a defensible retry time is available, include Retry-After using a supported HTTP date or delay in seconds. Round a positive computed delay upward when providing integer seconds. For a fixed window, the next window boundary gives a retry estimate; for a sliding log, the oldest blocking admitted event's expiry may be relevant; for a token bucket, time until sufficient refill can be computed from the deficit and rate.

Retry guidance is not a reservation: another request may consume the newly available quota first. Clients should use bounded backoff and jitter rather than synchronized immediate retries. An unavailable limiter or overloaded service may warrant a different response, such as 503, according to the API contract.

Make quota errors actionable and avoid exposing other tenants' usage or sensitive keys. Document units, policy scope, reset semantics, and whether rejected attempts are counted.

10. Practical FDE deployment#

Imagine an enterprise customer using a document-analysis API with several users sharing an expensive inference backend. They require a strict rolling per-tenant request quota, a burst-tolerant shared compute budget and protection against long-running jobs.

I would use exact rolling enforcement where the strict contractual quota requires it, a weighted token bucket for estimated compute consumption, and a concurrency guard around inference. A separate fixed-window budget might be suitable for a billing-aligned daily quota if its boundary behavior is acceptable. I would measure actual resource use and reconcile estimated credits under a documented policy, rather than claiming request count predicts model cost.

Before launch, I would agree on burst tolerance, retry behavior, scope, capacity, failure policy and acceptable false-rejection or overshoot bounds. I would load-test uneven traffic and distributed failures and inspect both the accepted-request history and downstream health.

This is a hypothetical design, not a measured customer deployment.

11. Evaluation and production monitoring#

Track accepted and rejected requests, reason codes, quota-store latency, error rates, hot keys, memory, refill balance distributions, queue depth, concurrent work and backend tail latency. Measure quota violations against an independent event history and report rejected legitimate work separately.

Test exact window boundaries, same-timestamp events, fractional refill if used, idle refill caps, simultaneous debit attempts, clock rollback, Redis restart/failover, stale policy configuration, key eviction, retry after ambiguous admission, regional isolation and abusive key creation. Test the actual multi-limit admission contract under concurrency. Roll out initially in shadow mode where appropriate, compare decisions against observed capacity, then enforce with explicit customer-approved thresholds and rollback controls.

Likely interviewer follow-ups#

Which algorithm would you choose by default? Token bucket for controlled bursts and average throughput, unless the business requires an exact rolling or calendar-aligned quota.

Can a sliding-window counter guarantee no more than L requests in every rolling interval? Not the two-bucket weighted approximation. Use an exact log or another design with proven conservative guarantees when exactness matters.

Why use a Lua script rather than GET and INCR? It prevents concurrent clients from interleaving the check and update on the same Redis primary.

Does Redis solve global consistency during failover? No. Define the consistency and durability guarantees of the deployed topology and account for lost state and partitions.

Can rate limiting prevent an overload by itself? No. Bursts, expensive operations and long-lived work can overwhelm a service even under a request-rate limit. Bound concurrent work and queueing as well.

What matters most to an FDE? Translate the customer requirement into measurable admission semantics, then verify actual behavior at boundaries, under concurrency and during failures.

Related questions

Explore other topics:AI AgentsAI System DesignLarge Language Models