See my jobs
Home/System design/Rate limiter

Design a rate limiter

Updated Nov 17, 2026

8 of 909 coded candidate reports (Jan 2025 to Nov 2026) mention a rate limiter, 4 of them in the last 90 days; 5 mention the hit-counter variant

A rate limiter caps how many requests a client can make in a time window and rejects the rest. The question looks small. The work is in choosing the algorithm, deciding where the counters live, and handling a counter store that goes down. In the reports we collected, half of the rate limiter questions asked for working code instead of a whiteboard design.

In short
  • The question is rare but recent: 8 of 909 candidate reports mention a rate limiter, and 4 of those 8 are from the last 90 days.
  • 4 of the 8 reports describe writing working code (a class, sometimes thread-safe), so practise the code as well as the diagram.
  • Know the five algorithms and pick one with a reason. Token bucket fits bursty APIs; a sliding window counter is cheap and close to exact.
  • The senior part is state. Local counters drift across servers; a central Redis adds a network hop and a failure point. Say which you pick and why.
  • Decide out loud what happens when the limiter itself fails: fail open or fail closed, per endpoint.

Who asks it and how often

We coded 909 first-hand candidate reports that list the questions asked, dated January 2025 to November 2026. 8 of them mention a rate limiter, either as a design or as code. 4 of those 8 are from the last 90 days, more recent activity than most named problems in our data. Separately, 5 reports mention the smaller hit-counter or logger-rate-limiter coding problem (1 in the last 90 days). One of them, an Amazon new-grad loop, is also among the 8.

Counting only reports that name a single company: Snowflake 2, Amazon 2, Cursor 1, OpenAI 1. One more came from a Microsoft SRE loop, where rate limiting came up while troubleshooting CPU saturation live [10].

CompanyReportsWhat candidates describe
Amazon2New-grad loop, Oct 2026: a rate limiter close to the hit-counter coding problem [1]. AWS loop, Oct 2026: a per-user throttle API [2].
Snowflake2A multi-threaded rate limiter where paid plans change the limits, Sep 2026 [3]. ML engineer onsite, Sep 2026: design and build a rate limiter with an AI tool, then explain the algorithm and trade-offs [4].
Cursor1Phone screen, Jan 2026: per-user limits behind an extensible rule interface [5]. A recruiter note for the same screen said AI tools were not allowed [6].
OpenAI1Full-stack loop, Aug 2026: design a streaming AI feature that included rate limiting and cost control [7].
Hit counter (smaller cousin)5Amazon, Uber, Cloudflare and Databricks one each. Examples: Uber SDE 2, May 2026 [8]; Databricks, paired with a key-value store, Jul 2026 [9].

This is thin data. Eight reports show the question is live in 2026. They are not enough to rank companies or predict your loop. Meta does not appear in these counts at all.

The useful signal is the format. One Snowflake candidate was told to expect LeetCode and ended up building a multi-threaded rate limiter instead [3]. Prepare a clean class you can write in 20 minutes, then the distributed version on top.

Clarifying questions to ask

Spend two or three minutes here. Each answer changes the design.

  • Who is limited? Per user, per API key, per IP, per tenant, or per endpoint. Often it is a mix: per key, with a tighter rule on expensive endpoints.
  • Why are we limiting? Abuse protection, fair sharing between tenants, or cost control (common for AI APIs). Abuse protection tolerates some error; billing quotas do not.
  • What are the rules? For example 100 requests per minute on the free plan and 1,000 on paid. Can rules change at runtime?
  • Are bursts allowed? If a client is idle for a minute, can it then send 50 requests at once?
  • How exact must it be? Is letting 105 through on a limit of 100 acceptable for a few seconds?
  • Where does it run? In an API gateway in front of many services, inside one service, or as a library?
  • What scale? How many clients, how many requests per second at peak, one region or several?
  • What does the client see? HTTP 429 with a Retry-After header, or a queue that delays the request?

Requirements

A reasonable set to write on the board after the questions above:

  • Functional: decide allow or reject for each request based on configurable rules; support per-key and per-endpoint rules; return remaining quota and reset time to the client; let operators change rules without a deploy.
  • Non-functional: add very little latency (a few milliseconds at most); stay correct when requests for one key hit many servers at once; keep working, or degrade in a known way, when the counter store is slow or down; handle the peak request rate with room to spare.

A back-of-envelope estimate, with assumed numbers: say 1 million active API keys and 50,000 requests per second at peak. A token bucket needs two numbers per key: tokens left and last refill time. With Redis key overhead that is roughly 100 bytes per key, so about 100 MB in total. Memory is fine. The request rate is the limit: one atomic script per request at 50,000 per second is close to what a single Redis node handles, so plan to shard by key.

Compare a sliding window log with a limit of 1,000 per hour: up to 1,000 timestamps of 8 bytes per key, so 8 KB per key and about 8 GB for 1 million keys. That number is why the log approach rarely wins at scale.

API

There are two interfaces: the internal check the gateway calls on every request, and what the client sees.

# Internal: called by the gateway or middleware on every request
allow(key: str, rule_id: str, cost: int = 1)
  -> { allowed: bool, remaining: int, reset_at: epoch_seconds }

# Admin: manage rules (stored in a config service, cached by limiters)
PUT /v1/rate-limit-rules/{rule_id}
  { "match": {"plan": "free", "endpoint": "/v1/search"},
    "limit": 100, "window_seconds": 60, "burst": 20 }

# Client-facing response when rejected
HTTP/1.1 429 Too Many Requests
Retry-After: 12
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1795392000

Passing a cost lets one call consume more than one unit. That matters for AI APIs where a long prompt should cost more than a short one.

High-level design

A request arrives at the API gateway (or a middleware layer in the service). The limiter builds a key from the request, such as free:key_123:/v1/search, looks up the matching rule in a local cache, and runs one atomic check-and-update against the counter store. If allowed, the request goes on to the backend. If not, the gateway returns 429 right away and the backend never sees it.

  • The limiter logic runs inside the gateway process or as a sidecar, so the check does not need an extra service hop.
  • A database or config service holds the rules. Each limiter node caches them and refreshes on change or every few seconds.
  • Counters usually live in Redis, sharded by key. Every key gets a TTL so idle clients do not fill memory.
  • Metrics count allowed and rejected requests per rule, so operators see who is being throttled before customers complain.

Deep dive 1: which algorithm

Interviewers expect you to know the main options and pick one with a reason. N is the request limit per window.

AlgorithmHow it worksMemory per keyBurstsAccuracyGood fit
Fixed window counterOne counter per key per window (e.g. per minute). Reset at the boundary.1 numberUp to 2N across a window boundaryRough at edgesSimple quotas where edge bursts do not matter
Sliding window logStore a timestamp per request; drop ones older than the window; count the rest.Up to N timestampsNone beyond NExactLow limits, low traffic, strict rules
Sliding window counterKeep current and previous window counts. Estimate = current + previous x (share of previous window still inside the sliding window).2 numbersSmallClose to exact (assumes even spread)General API limits at scale
Token bucketBucket holds up to B tokens and refills at R per second. Each request takes one token.2 numbersAllowed up to B, by designExact for its own definitionAPIs that should tolerate short bursts; per-request cost
Leaky bucketRequests enter a queue that drains at a fixed rate; overflow is dropped.QueueSmoothed outExact output rateShaping traffic to a fragile downstream

Token bucket is a safe default. It needs two numbers per key, handles bursts in a controlled way, and supports a cost per request. Explain the two settings in plain terms: capacity is the largest burst you accept, refill rate is the long-run average.

If the interviewer cares about a strict "no more than 100 in any 60 seconds" rule, move to the sliding window counter and say where it can be off: it assumes the previous window's requests were spread evenly.

Deep dive 2: where the counters live

This is where mid-level and senior answers split. A request for one key can land on any of many gateway servers, so the count has to be shared, or you accept an error.

OptionAccuracyAdded latencyIf it failsWhen to pick it
In-process memory on each serverEach server enforces its own copy, so the real limit is about N servers x limit (unless the load balancer routes each key to one server)NoneRestart loses counts; mostly harmlessOne server, or coarse protection only
Central RedisExact, if updates are atomicOne network round trip, often under a millisecond in the same zoneEvery check fails; you must choose fail open or fail closedThe default answer for most interviews
Redis sharded by keyExact per keySame as aboveOne shard down affects only its slice of keysHigh request rates; many keys
Local counts plus periodic syncApproximate; can overshoot for one sync intervalNone on the hot pathDegrades gently to local-only limitsVery high traffic, or one global limit across regions

The classic race: two servers read count = 99, both see room, both write 100, and 101 requests get through. The fix is to make check-and-update one atomic step inside the store. For a fixed window that is INCR followed by setting a TTL on first use. For a token bucket it is a short Lua script that reads tokens and timestamp, refills, decrements and writes back in one call, so no other client can run between those steps.

Clock skew is the next trap. If each app server passes its own clock into the refill math, skew between servers can create or destroy tokens. Use one time source, such as the Redis server time inside the script.

Across regions, either split the limit across regions (each region allows its share) or sync counts between regions asynchronously and accept a short overshoot. Say which one, and why the business can live with it.

The coding version

Since half the reports describe writing code, have a version you can type from memory. This one is a per-key token bucket, thread-safe, with an injectable clock so you can test it without sleeping.

import time
import threading


class TokenBucket:
    """Allows bursts up to `capacity`, refills at `rate` tokens per second."""

    def __init__(self, capacity: float, rate: float, clock=time.monotonic):
        self.capacity, self.rate, self.clock = capacity, rate, clock
        self.tokens = capacity
        self.updated = clock()
        self.lock = threading.Lock()

    def allow(self, cost: float = 1.0) -> bool:
        with self.lock:
            now = self.clock()
            elapsed = now - self.updated
            self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
            self.updated = now
            if self.tokens >= cost:
                self.tokens -= cost
                return True
            return False


class RateLimiter:
    """One bucket per key (user ID, API key, IP)."""

    def __init__(self, capacity: float, rate: float):
        self.capacity, self.rate = capacity, rate
        self.buckets: dict[str, TokenBucket] = {}
        self.lock = threading.Lock()

    def allow(self, key: str) -> bool:
        with self.lock:
            bucket = self.buckets.get(key)
            if bucket is None:
                bucket = self.buckets[key] = TokenBucket(self.capacity, self.rate)
        return bucket.allow()

Common follow-ups on this code: rules that differ per plan and change at runtime (look the rule up per call instead of fixing capacity in the constructor), an interface so new rule types plug in without editing the limiter, evicting idle buckets, and what changes when the dict becomes Redis.

Scaling and failure modes

ProblemWhat happensWhat to do
Counter store downEvery check errorsFail open for most read APIs (availability first). Fail closed for login, signup and paid quotas, where abuse or cost is the bigger risk. Fall back to a local in-memory limiter while the store recovers.
Counter store slowLatency added to every requestTight timeout (a few milliseconds), then the same fallback. Alert on limiter latency.
Hot key (one tenant sends huge traffic)One shard saturatesCache a local "denied until time T" for keys already over the limit, so repeated requests never reach Redis.
Retry stormsRejected clients retry at once and add loadSend Retry-After; document backoff with jitter for client SDKs.
Bad rule pushedEveryone gets blocked, or no one doesValidate rules, roll out in stages, keep the last good config cached.
Idle keys pile upMemory grows without boundTTL on every counter key.

What interviewers look for: mid vs senior

This is our guidance based on how these rounds usually go, not a published rubric from any company.

AreaMid-level answerSenior answer
ScopeCaptures the functional requirements and one clear ruleAsks why we limit (abuse, fairness, cost) and designs per-plan, per-endpoint rules from that
AlgorithmExplains and implements one algorithm correctlyCompares at least two, names the fixed-window edge burst, picks per use case
StatePuts counters in RedisExplains the race, the atomic script, sharding by key, and the local vs global trade-off
FailureMentions that Redis could failPicks fail open or closed per endpoint, sets timeouts, adds a fallback and reject metrics
Code (if asked)Working single-threaded classThread-safe, testable clock, extensible rule interface, notes what changes when it is distributed

Common mistakes

  • Jumping to Redis before asking who is limited and why.
  • Choosing fixed window without mentioning that it can let through twice the limit at a boundary.
  • Read-then-write counter updates with no atomicity, which leaks requests under concurrency.
  • Keeping counters in each server's memory and calling the limit global.
  • Never saying what happens when the counter store is down.
  • Forgetting TTLs, so memory grows with every client ever seen.
  • In the coding version: calling time.time() directly, which makes the class hard to test, and sharing one lock across all keys without saying why.

How to prepare

Write the class cold

Type a token bucket and a sliding window counter from memory in a plain editor, with tests that use a fake clock. Aim for under 20 minutes each.

Practise the trade-off table out loud

Explain the five algorithms in one minute, then say which you would pick for a public API, a login endpoint and an AI completions API.

Rehearse the failure answer

Have a one-sentence position on fail open vs fail closed, and a fallback, ready before the interviewer asks.

Prepare the AI-allowed version

If your loop allows AI tools, practise prompting for the class, then reviewing it for the race and the clock issue, as one Snowflake candidate had to do live [4].

Practise the rate limiter design

A mock interview that pushes on algorithm choice, shared state and what happens when the limiter fails.

Start free mock

FAQ

Token bucket or sliding window: which should I default to?

Token bucket is the safer default: two numbers per key, controlled bursts, and a natural way to charge more for expensive requests. Switch to a sliding window counter if the interviewer wants a strict cap over any rolling window.

Is the rate limiter asked as a coding question or a system design question?

Both. In our data, 4 of the 8 reports describe writing working code (Amazon, Snowflake twice, Cursor) [1][3][4][5]. Prepare a class first, then the distributed design.

Should the rate limiter be its own service?

Usually not on the hot path. Run the logic inside the gateway or as a sidecar and keep only the counters in a shared store. A separate service adds a network hop to every request.

Which companies ask it most?

The data is thin: Snowflake 2, Amazon 2, Cursor 1 and OpenAI 1 among single-company reports, plus 5 hit-counter reports from Amazon, Uber, Cloudflare and Databricks. Treat it as a question any backend loop can ask.

Can I use AI in this round?

It depends on the company. One Snowflake ML engineer onsite was explicitly AI-augmented [4], and Snowflake publishes guidance on when AI is allowed [11]. A Cursor recruiter note for its technical screen said AI tools were not allowed [6]. Ask your recruiter.

How do I test a rate limiter without sleeping in tests?

Inject the clock. Pass a function that returns the current time, then advance a fake time value in the test and check which calls are allowed.

Sources

  1. Candidate report · Reddit r/leetcode: Amazon SDE 1 in-person loop, fall 2026 (rate limiter, LRU-style store) · Oct 28, 2026
  2. Candidate report · PracHub: Amazon SWE (AWS), four rounds incl. per-user throttle API · Oct 2026
  3. Candidate report · Reddit r/leetcode thread; comment on a Snowflake multi-threaded rate limiter round · Sep 23, 2026
  4. Candidate report · PracHub: Snowflake ML engineer onsite with an AI-augmented rate limiter round · Sep 2026
  5. Candidate report · LeetCode Discuss: Cursor technical phone screen, multi-rule rate limiter · Jan 20, 2026
  6. Candidate report · LeetCode Discuss: Cursor technical screen, recruiter text says no AI tools · Jan 8, 2026
  7. Candidate report · PracHub: OpenAI full-stack engineer, streaming AI feature design · Aug 2026
  8. Candidate report · Reddit r/leetcode: Uber SDE 2 interview experience (hit-counter style problem) · May 27, 2026
  9. Candidate report · PracHub: Databricks SWE onsite (KV store + hit counter) · Jul 2026
  10. Candidate report · PracHub: Microsoft senior SRE, live CPU saturation troubleshooting · Jul 2026
  11. Official · Snowflake careers: AI cheat sheet, how and when to use AI in your interview · Jan 20, 2026

We quote briefly, never name posters, and correct errors on request: report an error.

Related