May we use cookies so Meta, Google, LinkedIn and ChatGPT see your visit and we learn which ads work? PrivacyMay we use cookies to see which pages help, and let Meta, Google, LinkedIn and ChatGPT see your visit, so we know which of our ads work? That way we spend less on ads that do not work. We do not sell your data, and the site works the same if you decline. You can change your answer at any time under Cookie settings at the foot of the page. Privacy policy
Loading...
System Design and AI Engineering, by Roni Das. 989 interactive lessons in two courses.: 770 in System Design and 219 in AI Engineering.
Start LearningSystem design interview guide
in this guide
7 parts open to everyone · 3 with a free account · 3 with the course
You can read 7 of 13 parts. A free account opens the deep dive; the course opens all of it.
Interviewers like this problem because it looks small enough to finish in 45 minutes yet it forces you through the full stack of distributed systems reasoning. A weak candidate names token bucket and stops. A strong candidate notices that as soon as there are two limiter processes sharing one counter, the naive get-then-set has a race, and they can explain how an atomic Redis operation or a Lua script fixes it. The problem tests whether you understand consistency versus latency (do you check the counter synchronously on the hot path or propagate counts asynchronously and accept some overshoot), whether you think about failure (what happens when Redis is unreachable), and whether you care about the client contract (429, Retry-After, limit and remaining headers). It rewards precise thinking about a component that is deceptively simple.
This page is the free part.
₹1,111 in India$35 everywhere elseonce, for the whole course
The System Design course covers the Rate Limiter design across a run of lessons, not one page. These 4 alone are about 70 minutes of step-by-step reading, every one with a quiz.
Always clarify these in the first 5 minutes of the interview. Do not start drawing boxes until both lists are agreed.
This guide is built on these 6 lessons. Each one teaches one piece of the Rate Limiter design above, step by step.
Lifetime access for ₹1,111 in India or $35 elsewhere. Interactive diagrams, quizzes, and 20 capstone projects to practise on.
This one question is not enough for the interview.
Each question has why it is asked, a full answer, what the interviewer listens for, the follow-ups, the common mistakes and a diagram (268 diagrams in all). A PDF you keep, junior to staff level.
Two courses by the author of this page:
770 lessons · 18 free to read
₹1,111 in India · $35 elsewhere, once
Get System DesignYou own this course
219 lessons · 10 free to read
₹1,333 in India · $35 elsewhere, once
Get Generative AI and Agentic AIYou own this course
Save your progress and get the interview checklist PDF
A rate limiter is one of the few components that touches every single request before your real work begins. At the scale of a payments API or an edge network, that means tens or hundreds of thousands of decisions per second, each of which has to finish in well under a millisecond or it becomes the bottleneck it was meant to prevent. Cloudflare has described analyzing 400 million requests from roughly 270,000 distinct sources when validating their rate limiting accuracy, which gives a sense of the volume a real limiter sees.
The job sounds trivial, count requests per key and reject once the count crosses a limit, but almost everything hard is hidden in that sentence. You have to decide what a key is (user, IP, API key, or a tuple of endpoint and user), where the check runs (client, gateway, or service), and which algorithm to use (fixed window, sliding window log, sliding window counter, leaky bucket, or token bucket), each with a different memory and burst profile. The moment you run more than one limiter node, the counter has to live in shared state, usually Redis, and the read-modify-write becomes a race condition that lets requests slip through unless you make it atomic with a Lua script or an atomic INCR. Then you decide what happens when the shared store is slow or down, fail open and let traffic through, or fail closed and reject. On top of that you owe the caller a clean contract: a 429 status, a Retry-After header, and headers that tell them how many calls remain. A good answer treats the algorithm as the easy part and spends its time on atomicity, propagation delay, burst handling, and the failure modes.
Where it shows up
Asked at Stripe, Cloudflare, Amazon, Google, Uber, and most companies that run a public API or an API gateway. It shows up both as a standalone design question and as a subcomponent inside larger designs like an API gateway, a payments system, or a public developer platform.
Spec sheetRate Limiter
worked through below, with the maths
The hard parts of this design are taught step by step in the System Design course: Token Bucket Algorithm, Leaky Bucket Algorithm and Sliding Window.
A bucket of tokens that refills at a steady rate, the most popular rate limiting algorithm in production.
Requests drip out at a constant rate, smooth traffic shaping for APIs and networks.
Rate limit with a moving time window, smoother than fixed windows and more accurate.
Protect your API from abuse and overload by controlling how many requests each consumer can make.
all part of
System Design Masterclass
770 lessons · about 290 hours · 18 free to read
₹1,111in India, by UPI
$35everywhere else, by card or PayPal
You own this course
Continue with Token Bucket Algorithmpay once,
yours for life
Live from the course bench
Real interview questions, live diagrams and measured lab results, pulled at random from the lessons. A new set every time you come back.
Show your math. Pulling numbers from thin air signals you have not thought about the load.
Peak request rate through the limiter
~200,000 requests/sec (estimate)
Assume a large public API serving 10 billion requests/day. 10e9 / 86,400 ~= 116,000 req/sec average. Peak is usually 1.5x to 2x average, so roughly 200,000 req/sec. Every one of these hits the limiter first. Derived, illustrative.
Redis operations per second
~200,000+ ops/sec (estimate)
With a synchronous check, each request is at least one atomic Redis operation (INCR or a Lua eval). At 200,000 req/sec that is 200,000+ Redis ops/sec, which a single Redis node can handle but sits close to the practical ceiling, motivating sharding by key. Derived.
Distinct rate limit keys tracked
~10-50 million keys (estimate)
If the API has 5 million active API keys and you also limit per user and per endpoint, the number of live counter keys can reach tens of millions. Each with a short TTL so expired keys evict automatically. Derived from assumed customer counts.
Memory per counter key
~50-100 bytes (estimate)
A fixed window counter is a small integer plus key overhead. A token bucket stores two values (tokens and last-refill timestamp) in a Redis hash. A sliding window log stores a timestamp per request and is far heavier, which is exactly why it is avoided at scale. Roughly 50-100 bytes for the counter forms.
Counter store memory footprint
~1-5 GB (estimate)
30 million live keys times ~100 bytes ~= 3 GB, comfortably in RAM for a small Redis cluster. Short TTLs keep this bounded because idle keys expire rather than accumulate. Derived from the key count and per-key size above.
Latency budget for the check
< 1 ms target (estimate)
The limiter runs before useful work, so its budget is a fraction of the total request latency. An in-memory Redis lookup on the same network is typically a few hundred microseconds, which fits. If the check ever exceeds a few milliseconds it becomes the dominant cost and defeats the purpose.
A request arrives at the edge and hits the rate limiting layer before it reaches application logic. That layer is usually middleware inside an API gateway or reverse proxy, or a thin library inside each service. The limiter first derives the key for this request from whatever dimension the rule cares about, for example the API key from the Authorization header, the client IP, or a composite of user plus endpoint. It looks up the current count or token state for that key. In a single-node deployment this state can live in local memory, but any real system runs many limiter processes behind a load balancer, so the state lives in a shared store, almost always Redis, reached over the local network. The critical detail is that the read of the current count and the write of the new count must happen as one atomic operation, either with INCR plus an EXPIRE issued only when INCR returns 1 or, for token bucket and sliding window logic, a Lua script that runs the whole read-compute-write cycle inside Redis in a single round trip. The script returns an allow or deny decision plus the remaining budget and a reset time. If the decision is allow, the request continues to the application and the limiter attaches headers describing the remaining quota. If the decision is deny, the limiter short-circuits and returns 429 with a Retry-After header, never touching the backend. If Redis is unreachable, the limiter applies its configured failure policy, typically fail open so a limiter outage does not take down the API, and it emits a metric so operators know accuracy is degraded.
In a real interview, sketch this on the whiteboard before diving into any single box.
Walk through each service. The interviewer wants to hear what each one owns, not just the names.
Holds the limits themselves: which key dimension, what threshold, over what window, for which plan tier or customer. This is read-mostly and can be cached aggressively in each limiter process, refreshed periodically so limits can change at runtime without a redeploy. Keeping rules out of code lets support raise a customer's limit without a release.
Turns a raw request into the identity the rule limits on. It reads the API key, resolves the authenticated user, or falls back to client IP, and it composes tuples like endpoint plus user when a rule needs them. Getting this wrong is a common bug: limiting on a proxy's IP instead of the real client IP lets a whole network share one bucket, or breaks everyone behind a NAT at once.
The shared, in-memory home for per-key counters or token state, chosen for microsecond reads and writes and built-in key expiry via TTL. Redis is where the atomicity is enforced through INCR or Lua scripts. It is sharded by key using consistent hashing so that a given key always lands on the same node and load spreads evenly across the cluster.
The logic that turns counter state into an allow or deny, implementing fixed window, sliding window counter, leaky bucket, or token bucket. In a distributed setup this logic runs inside Redis as a Lua script so the whole read-compute-write is atomic. It returns the verdict plus the numbers needed for the response headers.
Produces the caller-facing contract. On allow it adds headers reporting the limit, the remaining count, and the reset time so well-behaved clients can self-throttle. On deny it returns 429 with a Retry-After header telling the client how long to wait. A clear contract turns rate limiting from a mystery into something clients can integrate against.
The safety layer that decides what happens when the counter store is slow or down. It wraps every Redis call in a timeout and a try-catch, and on failure applies the configured policy, usually fail open, sometimes with a coarse local in-memory limiter as a degraded backstop. This is what keeps a Redis incident from becoming an API outage.
Emits counts of allowed and rejected requests broken down by key, rule, and reason, plus latency of the check itself and the health of the counter store. This lets operators see who is hitting limits, spot abuse, tune thresholds, and detect when the limiter has silently failed open and is no longer enforcing anything.
rate_limit_rules. Configuration, not hot-path counters. key_dimension is one of user, ip, api_key, or a composite. Read-mostly and cached in every limiter process. Changing a row changes…
Every table for Rate Limiter, its keys, and which store fits it and why.
Choosing the algorithm: fixed window, sliding window, leaky bucket, token bucket. Fixed window is the cheapest: one integer per key per time window, incremented atomically, expired by TTL. Its flaw is the boundary problem, a caller can send the full…
7 deep dives on the parts that break at scale, with 26 diagrams: Choosing the algorithm: fixed window, sliding window, leaky bucket, token bucket; Where the limiter sits: client, gateway, or service; Distributed counting with Redis and atomicity.
Token bucket versus fixed window counter. Token bucket allows controlled bursts and enforces a smooth long-run average, but its multi-step update is not atomic and needs a Lua script to be correct under…
6 decisions an interviewer expects you to defend, each with the alternative and why it loses here.
One customer's API key is so busy that its single counter key overloads one Redis shard. What do you do?
4 follow-up questions with model answers, the interview scorecard for this question, and a mock interview on Design Rate Limiter with the AI tutor.
Stripe published a detailed account of running rate limiters and load shedders on Redis, using a token bucket per user plus concurrent-request limiters, and stressing that the limiter must fail open so a bug or a Redis outage never takes down request handling. Cloudflare described building rate limiting for millions of domains using an approximation of the sliding window (current plus previous window counts, weighted by overlap), storing counters in Memcached fronted by Twemproxy that consistent-hashes keys across nodes, and validated the approximation against 400 million requests. Two different numbers came out of that and they are worth keeping apart: about 0.003% of requests got the wrong allow-or-block decision, while the rate ESTIMATE itself sat roughly 6% away from the true rate on average. The first is how often the answer is wrong; the second is how far the arithmetic is off. Figma wrote openly about token bucket's Redis operations not being atomic and the race that makes a limiter too lenient, and about deciding against introducing Lua to their codebase to fix it. Their public API documentation separately describes a leaky bucket. Those are two different sources about two different moments, so do not present the second as the outcome of the first, which is a mistake this page previously made. These are three independent, primary engineering accounts that map directly onto the algorithm, atomicity, and failure-policy decisions in this design.
If any of these topics are fuzzy, the interviewer will catch it. Each lesson is 15 to 60 minutes with diagrams, code, and a quiz.
Token Bucket Algorithm
intermediate / api design protocols
Leaky Bucket Algorithm
intermediate / api design protocols
Sliding Window
intermediate / api design protocols
Rate Limiting
intermediate / api design protocols
API Gateway
foundation / load balancing proxies
Time To Live (TTL)
foundation / caching strategies
Distributed Cache
foundation / caching strategies
interview readiness
Three questions from this guide. Answer them without scrolling up, the way you would have to in the room.
Pay by UPI, cards or netbanking through Razorpay. Pay by card or PayPal, in US dollars. Download at once from My packs.
NEWSystem Design Hands-On
Postgres Sharding: Complete Hands-On (PgBouncer + Citus). 2 h 36 min and 20 chapters: one PostgreSQL loaded until it breaks, then four shards behind a router you write, PgBouncer and Citus, with the 139-page slide deck. The first 15 minutes are free to watch.
Free PDF · 79 pages
25 real tech interview questions, answered in full
Five from each of our AI, GenAI, Inference, Maths for ML and Forward Deployed packs. Each with a diagram and a model answer. Free by email.
free tool
Check these numbers yourself
Put in your own guesses for Rate Limiter and see requests per second, storage, bandwidth and servers, with every sum written out.
Open the Capacity EstimatorIt is really nice and good Please join the course