SWEPrep
HomeBlogStart free
System DesignMedium• 9 min read• Updated 2026-11-24

Designing a Distributed Rate Limiter: Architecture and Traps

Rate limiters look trivial in single-threaded code. Put five API gateways behind a load balancer and suddenly your in-memory counter is useless. Centralize it in Redis, and high-concurrency race conditions start letting 200 requests through when the limit was 100. In this guide, I break down the exact patterns interviewers want to see, including Lua scripts and resilience fallbacks.

1. The 2-Millisecond Latency Budget and Headers

The rate limiter sits directly on the critical request path. If your backend service takes 40ms to respond, your rate limiter cannot add more than 2ms of overhead.

When a client exceeds their allowance, return HTTP 429 Too Many Requests immediately. Include these standard headers:

X-RateLimit-Limit: Total requests allowed in the current window.

X-RateLimit-Remaining: Number of remaining allowed requests.

Retry-After: Number of seconds the client must wait before making another call.

2. Choosing the Right Algorithm on the Whiteboard

Do not memorize five algorithms just to list them. Explain when to use which.

Token Bucket is the industry standard for general API rate limiting. A bucket holds up to N tokens and refills at a steady rate of R tokens per second. Requests consume one token. If empty, the request drops. It handles short bursts without penalty while strictly capping sustained load.

Leaky Bucket processes requests at a fixed FIFO rate. Bursts queue up in a buffer. Use this when downstream services require smooth, predictable throughput with zero spikes.

Fixed Window Counter counts requests within fixed time blocks (e.g. 12:00 to 12:01). It has a severe flaw: a user can send 100 requests at 12:00:59 and another 100 requests at 12:01:01, pushing 200 requests through in two seconds.

Sliding Window Counter calculates a weighted sum of the current and previous windows. It consumes minimal memory and smooths out boundary bursts within 0.05% error.

My Recommendation
Default to Token Bucket or Sliding Window Counter. They require minimal state and handle real-world bursty traffic cleanly.
Live Technical Interview Practice
Practice this topic on the interactive AI whiteboard

Do not just read the solution. Test your architecture under realistic interview pressure with an AI interviewer probing bottlenecks in real time.

Want to practice this in a real interview? Start free →

3. The Redis Concurrency Bug and the Lua Fix

Here is the exact trap interviewers watch for. A candidate writes code that fetches the current token count with Redis GET, checks if tokens > 0 in application code, and then decrements with DECR.

Under 10,000 requests per second, two concurrent threads read tokens = 1 at the same microsecond. Both pass the check. Both decrement. Your rate limit is violated.

You must execute the check and decrement atomically. Use a Redis Lua script. Redis executes Lua scripts as a single atomic transaction on its single-threaded event loop, preventing all interleaving.

local key = KEYS[1]
local limit = tonumber(ARGV[1])
local current = tonumber(redis.call('get', key) or "0")

if current + 1 > limit then
    return 0
else
    redis.call("INCRBY", key, 1)
    if current == 0 then
        redis.call("EXPIRE", key, tonumber(ARGV[2]))
    end
    return 1
end

4. Fail Open vs Fail Closed: The Architectural Dilemma

What happens when your Redis cluster encounters network packet loss or crashes?

If you fail closed, every API request returns an error. Your rate limiter just caused a total system outage. For standard product APIs, you must fail open: log the warning, alert on-call, and let traffic pass downstream.

The only exception is authentication and billing endpoints. On login routes, fail closed to prevent brute-force password spraying while your infrastructure recovers.

Interview Trap
Never say we will make Redis highly available so it never fails. Distributed systems fail. Interviewers want to know your blast radius policy when it does.

5. Multi-Tier Defenses: Edge to Service Mesh

Do not place the entire burden on one central Redis cluster.

Tier 1 (Edge): Cloudflare or AWS CloudFront rate limits volumetric DDoS attacks by IP address before traffic ever reaches your VPC.

Tier 2 (API Gateway): Envoy or Kong evaluates user and organization tier quotas against a Redis cluster.

Tier 3 (Service Mesh): Internal gRPC rate limiting protects fragile downstream microservices from runaway internal worker loops.

Key Architecture Decisions & Trade-offs

Decision AreaOptions EvaluatedRecommendation
Algorithm ChoiceToken Bucket vs Sliding Window LogToken Bucket. Sliding Window Log stores timestamps for every single call, exhausting RAM under high volume.
Atomicity StrategyApplication-level distributed lock vs Redis Lua scriptRedis Lua script. Distributed locks introduce heavy network round-trips and deadlock risks. Lua runs in memory.
Outage PolicyFail open vs Fail closedFail open for core API reads; fail closed for login and payment routes.

Frequently Asked Interview Follow-ups

How do you handle clock drift across server nodes?
Never use application server system time. Either pass timestamps generated by Redis using the TIME command, or rely on elapsed monotonic seconds for token refill calculations.
How do you prevent cache stampedes when rate limit keys expire?
Apply a small random jitter to key TTL values (e.g. 60 seconds plus or minus 5 seconds). This prevents millions of synchronized keys from expiring in the exact same millisecond.
What key structure should we use in Redis?
Use a namespaced string key such as rate:{user_id}:{endpoint_id}:{window_timestamp}. Keep keys short to save memory across millions of concurrent users.
Ready for the interview loop?

Test your design under real pressure

Simulate a full 45-minute technical session on SWEPrep. Diagram architecture on the canvas, justify your trade-offs, and receive instant rubric feedback.

Want to practice this in a real interview? Start free →

Keep practicing

View all guides →