SkillSprout
Chapter 5 · Lesson 2
Intermediate
29 min read

Design an API Rate Limiter

Overview

A rate limiter decides, for every incoming request, one question: "has this caller already used their share?" If not, the request continues. If yes, it is rejected immediately with 429 Too Many Requests. It protects servers from overload, keeps one noisy customer from starving everyone else, blocks brute-force password guessing and keeps paid quotas honest. The idea fits in one sentence, but the interview is hard because the limiter sits in front of every request: it must add only a few milliseconds, it must be correct when 30 gateway machines check the same user at the same moment, and it must never become the thing that takes the whole API down. This lesson walks the full eight-step framework and ends with the trade-offs you should say out loud.

Detailed Notes

How to use this lesson

Treat this as a 45-minute interview. The numbers are assumptions you state out loud, not facts about a real company. The algorithms (token bucket, windows) were introduced in the rate-limiting lesson, so here we spend our time on the harder part: running them correctly across many machines, at very high speed.

Step 1: Clarify Requirements

Do not start with "I'd use a token bucket." Start by asking what is being limited and what should happen when the limit is hit. A good opening: "I'd like to agree on who we limit, how strict the limit must be, and where the limiter lives, before I pick an algorithm."

Functional requirements

  • Limit requests per caller. The caller (called the subject) can be a user ID, an API key, or an IP address for anonymous traffic.
  • Configurable rules: different limits per endpoint and per customer tier, for example free users get 100 requests per minute and paid users get 1,000.
  • Reject clearly: a limited request gets HTTP 429 with headers that tell the client how long to wait.
  • Rules can be changed by an operator without redeploying any server.
  • Allow bursts within reason: a client that was idle may send a short spike.

Extended requirements

Mention these and ask whether to include them.

  • Several rules at once per request (per user and per IP and a global limit for the endpoint).
  • Per-customer overrides: one big customer negotiated 10,000 requests per minute.
  • Cost-based limits: an expensive search call counts as 5 units, a simple read as 1.
  • Dashboards: who is being limited, and how often.

Non-functional requirements

  • Very low latency: the limiter adds at most 5 ms at p99 (99 of every 100 checks are faster). It runs on every request, so it is part of the latency of the whole API.
  • High availability: the limiter must not reduce the availability of the API. If the limiter breaks, traffic must still flow (we revisit this "fail open" decision in Step 7). Target 99.99% for the check path.
  • Accuracy: the limit is enforced within a small error, for example under 5% over-admission at the edges. We do not need bank-grade exactness, but we must not let a caller send 2x their quota.
  • Scalability: hundreds of thousands of checks per second, across tens of gateway servers and more than one region.
  • Memory efficiency: state for 100 million callers must fit in memory at reasonable cost.
  • Fairness: one caller exceeding their limit must not slow down anyone else.

Consistency decision. A limiter can tolerate approximate counts (letting 103 requests through a limit of 100 once in a while is fine), but it cannot tolerate being slow or being down. This is the opposite of a payments system. Saying this early shows you pick consistency per component, not per system.

Out of scope

Authentication itself, billing and invoicing based on usage, DDoS protection at the network level (that belongs to a CDN or network firewall, because by the time an application-level limiter sees a request, the connection and TLS cost has already been paid), and bot detection by behaviour. We mention them but do not build them.

Interview tip. Ask "client-side or server-side?" Client-side limiting is unreliable because a malicious client simply ignores it. Say you build the enforcement on the server side and mention that well-behaved client SDKs can also back off voluntarily.

Step 2: Estimate Scale

A limiter has no huge database, so the surprise in this estimate is what is large: it is the number of checks per second, not the number of bytes. Round every number so the arithmetic is easy to do aloud.

Assumptions to state

  • 100 million daily active users, each sending about 100 API requests per day.
  • Every request triggers one limiter check (we merge several rules into one call, see Step 6).
  • A day has about 100,000 seconds (the real value is 86,400; the error is small and the math is easy).
  • Peak traffic is 3x the average.
  • A Redis node, an in-memory key-value store, handles about 50,000 limiter checks per second. Plain reads and writes reach roughly 100,000 per second, but our check runs a small script, so we plan with half of that.
  • A gateway server handles about 10,000 requests per second.
  • 100 million distinct subjects (users, API keys, IPs) are active in any given hour, and each needs about 100 bytes of state.

Request load

text
100M users x 100 requests       = 10 billion requests per day
10B / 100,000 seconds           = 100,000 checks per second (average)
100,000 x 3 peak factor         = 300,000 checks per second (peak)

Counter store capacity

text
300,000 checks/s / 50,000 per Redis node = 6 nodes at full load
6 nodes x 2 headroom                     = 12 shards

We never run at 100%: a failover or a traffic spike would immediately overload us. Doubling gives 12 shards, each with a replica.

Rate Limiter: Estimate the Scale
Estimation

Request load

10Brequests / day
100M users × 100
100K/schecks, average
÷ 100,000 s
300K/schecks at peak
× 3 peak factor
50K/sper Redis node
given (script)
6nodes at full load
300K ÷ 50K
12shards
× 2 headroom

Counter memory

~10 GB

100M active subjects × 100 bytes (a window log would need 1.6 TB)

Memory is tiny: shard for speed, not size

Gateway servers

~30

300K peak requests/s ÷ 10K per server

A user hits many gateways: counters must be shared

Latency budget

5 ms p99

one Redis call ~0.5 ms, rule lookup in memory

Exactly one atomic round trip per check
Key point. Shard Redis for throughput, keep counters in a shared store, and allow exactly one round trip per check.

10 billion requests a day become 300,000 limiter checks per second at peak. Operations per second, not bytes, are the challenge.

Memory

text
100M active subjects x 100 bytes = 10 GB
10 GB / 12 shards                = under 1 GB per shard

Ten gigabytes is tiny. Counters have a TTL (time to live: the store deletes the key automatically), so idle callers disappear on their own. Memory is not the constraint; operations per second are. This is the "so what" for the whole design: we shard to get throughput, not capacity.

A comparison that makes the algorithm choice for us in Step 6. If we stored every request timestamp for a limit of 1,000 per minute (a sliding window log):

text
1,000 timestamps x 16 bytes   = 16 KB per subject
16 KB x 100M subjects         = 1.6 TB

Compare that with 10 GB for a token bucket. The log needs about 160x more memory, so we avoid it.

Bandwidth

text
300,000 checks/s x 200 bytes (request + reply) = 60 MB/s
60 MB/s / 12 shards                            = 5 MB/s per shard

Negligible. We skip bandwidth.

Gateway servers

text
300,000 peak requests/s / 10,000 per server = 30 gateway servers

This number drives the hardest problem. With 30 servers, a single user's requests land on different servers (the load balancer spreads them). If each server kept its own counter, each would see about 1/30 of that user's traffic, and a limit of 100 per minute would turn into up to 3,000. The counters must live in a shared store.

Latency budget

text
Total limiter budget (p99)     = 5 ms
One Redis call, same zone      = about 0.5 ms
Gateway rule lookup in memory  = under 0.1 ms

We can afford exactly one network round trip per request. Two sequential calls (read, then write) are expensive and also unsafe, as we will see in the race-condition discussion.

Interview tip. Finish every estimate with "so what": "operations per second dominate, so I shard for throughput", "30 gateways means local counters undercount, so I need a shared store", "the latency budget allows one round trip".

Step 3: Define the APIs

The limiter has three faces: what a client sees, what internal services call, and what operators manage.

What the client sees

The limiter is invisible when requests pass. We still add headers to every response so clients can pace themselves.

http
GET /v1/orders HTTP/1.1
Authorization: Bearer <token>

HTTP/1.1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 57
X-RateLimit-Reset: 23
  • X-RateLimit-Limit: the rule's limit for this window.
  • X-RateLimit-Remaining: how many calls are left.
  • X-RateLimit-Reset: seconds until the allowance is full again (some APIs send a timestamp instead; pick one and document it).

When the limit is exceeded:

http
HTTP/1.1 429 Too Many Requests
Retry-After: 12
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
Content-Type: application/json

{
  "error": "rate_limited",
  "message": "Rule 'orders-read-free' allows 100 requests per minute.",
  "retry_after_seconds": 12
}

429 Too Many Requests is the right code (not 403 and not 503), and Retry-After is the standard header that tells a client exactly how long to wait. Without it, clients guess and retry immediately, which makes the overload worse. A 503 is for "the server is unhealthy", a 429 is "you specifically used too much".

Internal check API

If other services (not only the gateway) need limiting, expose a check call. It must be fast, so use a lightweight protocol such as gRPC.

http
POST /v1/ratelimit/check
Content-Type: application/json

{
  "domain": "orders-api",
  "descriptors": [
    { "key": "user_id", "value": "42" },
    { "key": "ip", "value": "203.0.113.7" }
  ],
  "cost": 1
}
json
{
  "allowed": true,
  "limit": 100,
  "remaining": 57,
  "retry_after_ms": 0,
  "rule_id": "orders-read-free"
}

The internal call itself returns 200 OK even when the answer is "denied": the call worked, and allowed carries the decision. The gateway turns a denial into the client-facing 429. In our design the gateway runs the check as a library inside the process, saving a network hop; this API exists for everything else.

Design decision: cost. The optional cost field lets one request consume several units, which is how an expensive endpoint is limited more strictly than a cheap one.

Admin API for rules

http
PUT    /v1/rules/{rule_id}      # create or update (send If-Match: <version>)
GET    /v1/rules?domain=orders-api
DELETE /v1/rules/{rule_id}
  • 200 OK / 201 Created on success.
  • 400 Bad Request for an invalid rule (limit below 1, unknown algorithm).
  • 401 / 403 if the caller is not an authorized operator.
  • 404 Not Found if the rule does not exist.
  • 409 Conflict if If-Match does not equal the stored version (two operators edited at once). This is optimistic concurrency: you are allowed to write only if nobody changed the rule since you read it.

How the API shapes the architecture

The hot path is one call per request that returns a yes/no, with no search and no joins. That makes the counters a pure key-value, single-key problem, and it demands in-memory storage. The rule definitions, in contrast, change rarely and are read constantly, so they can be copied into every gateway's memory.

Step 4: Define the Data Model

We have two very different kinds of data. Rules are small, durable and rarely change. Counters are tiny, extremely hot and disposable (losing one only means a caller briefly gets a fresh allowance).

Fields and why each exists

Rule:

  • rule_id: primary key, readable (for example orders-read-free).
  • domain and endpoint_pattern: which API and path the rule applies to (/v1/orders/*).
  • subject_type: what we count by: user_id, api_key, ip or global.
  • tier: free, pro, internal. Lets one endpoint have different limits per customer plan.
  • algorithm: token_bucket or sliding_window_counter.
  • limit, window_sec: for example 100 per 60 seconds. For a token bucket the refill rate is limit / window_sec.
  • burst: bucket capacity (maximum instant spike). Can be larger than limit / window_sec.
  • fail_mode: open or closed: what to do if the counter store is unreachable.
  • version, updated_at: let gateways detect changes and let admins avoid overwriting each other.

Counter state (token bucket):

  • Key rl:{rule_id}:{subject} holding tokens (current tokens, a number) and ts (last refill time in milliseconds). Two small fields, about 100 bytes with the key.

Counter state (sliding window counter):

  • Key rl:{rule_id}:{subject}:{window_index} holding an integer count, where window_index = floor(now / window_sec). Each key expires after 2 windows.
The Data Model
Data model
rulesRules store (relational)
  • PKrule_idvarchar

    e.g. orders-read-free

  • IDXdomainvarchar

    which API; gateways load by domain

  • endpoint_patternvarchar

    e.g. /v1/orders/*

  • subject_typeuser_id | api_key | ip | global

    what we count by

  • tierfree | pro | internal
  • algorithmtoken_bucket | sliding_window_counter
  • limitint

    requests per window_sec

  • window_secint
  • burstint

    bucket capacity

  • fail_modeopen | closed

    behaviour if Redis is down

  • versionbigint

    bumped on every change; used for If-Match

A few thousand rows. Every gateway holds a full copy in memory.

rule_overridesRules store (relational)
  • PKsubjectvarchar

    user id or api key

  • FKrule_idvarchar
  • limitint

    replaces the rule limit

  • expires_attimestamp

    null = permanent

Per-customer exceptions without creating one rule per customer.

bucket:{rule}:{subject}Redis hash
  • PKkeystring

    hashed to pick the shard

  • tokensfloat

    current tokens

  • tsms

    last refill, from Redis TIME

~100 bytes. TTL = 2 × time to refill, so idle keys vanish.

win:{rule}:{subject}:{n}Redis integer
  • PKkeystring

    n = floor(now / window_sec)

  • countint

    requests in window n

Current and previous window are read. TTL = 2 windows.

  • rule_overrides.rule_idrules.rule_id· many to one
Key point. Rules are read often and written rarely. Counters are written on every request and may be lost safely.

Durable rules live in a small database. Counters live only in Redis and expire by themselves.

Why not store counters in the rules database?

A relational database doing a write per request (300,000 per second at peak) would collapse and add 10+ ms. Counters need an in-memory store with atomic operations and automatic expiry. A relational or key-value database is the right place for rules.

Which store for counters?

Reason from the access pattern: single-key read-modify-write, 300,000 per second, sub-millisecond, loss tolerated. Redis fits: in-memory, atomic operations, built-in TTL, scripting, replication and clustering. Memcached lacks scripts and atomic multi-step logic. A disk-based database is too slow. DynamoDB-style stores can work but cost more per operation and add latency. We pick Redis and say why.

Trade-off thinking. Memory-only counters are fast but volatile: a Redis crash can reset counts, giving callers a few extra requests. Persisting every increment would make the limiter slower than the thing it protects. For a limiter, "slightly generous after a crash" is the right failure.

Step 5: High-Level Design

The first decision is where the limiter runs.

  • In the client: unreliable, a malicious caller ignores it.
  • In each application server: works, but every service re-implements it, and the services that are being overloaded spend CPU rejecting traffic.
  • At the API gateway (the entry point that authenticates and routes every request): one place, rejects bad traffic before it reaches the services. Recommended.
  • As a separate limiter service: one more network hop per request (1-2 ms), but reusable by internal services. We offer it through the internal check API.

We run the limiter as a module inside each gateway server, talking directly to a shared Redis cluster.

Where the Limiter Lives
Architecture
Clientapp / browserAPI gatewaylimiter moduleLocal rulecachein gateway memoryRedis counters12 shardsRules storedurable sourceBackendservicesonly allowed calls1find ruleLua checkif allowedsync
Key point. Only the check touches the network, and it is a single call. Rules never wait on a database.

The limiter is a module in every gateway. It reads rules from local memory and counters from Redis.

Components and why each exists

  • API gateway with limiter module: finds the matching rule, builds the key, runs one atomic check, and either forwards the request or answers 429. The gateway fleet is stateless: no counters live in the servers, so any gateway can serve any user.
  • Local rule cache: a copy of all rules in each gateway's memory. Matching a request to a rule costs microseconds and no network.
  • Rules store: the durable source of truth for rules. Not on the hot path.
  • Redis counter cluster: holds the buckets and window counters, partitioned across 12 shards with a replica for each.
  • Backend services: receive only traffic that passed the check.
Allowed and Rejected Requests
Request flow
ClientGatewayRedis shardBackend1GET /v1/ordersrule: 100/min, key user:422EVALSHA token bucketone atomic call3allowed, remaining=574forward request5200 OK6200 + X-RateLimit-*7denied, retry_ms=12000later call, bucket empty8429 + Retry-After: 12backend never called

Messages 1 to 6 show an allowed request. Messages 7 and 8 show a later call from the same caller after the bucket is empty.

Request flow

  1. The client sends GET /v1/orders. The gateway authenticates it and finds user_id = 42.
  2. The gateway matches the request against its cached rules: tier free, rule orders-read-free, 100 per minute.
  3. It builds the key rl:orders-read-free:42 and runs the atomic check on the Redis shard owning that key.
  4. Redis answers allowed, remaining, and retry_after.
  5. If allowed, the gateway forwards the request and adds the X-RateLimit-* headers to the response.
  6. If denied, the gateway returns 429 with Retry-After and never touches the backend.

Step 6: Deep Dive

The interviewer will pick the correctness problem. We cover five topics: the algorithm, atomic counting, distributed enforcement, rules propagation, and multi-region.

6.1 Which algorithm: token bucket or sliding window counter?

There are four classic options, and you should be able to name why three of them lose in some situations.

  • Fixed window counter: count requests in each calendar minute. Simplest, but a caller can send 100 requests at 12:00:59 and 100 more at 12:01:00, which is 200 in two seconds while obeying "100 per minute". The boundary burst can reach 2x the limit.
  • Sliding window log: store every timestamp. Exact, but 1.6 TB of memory in our estimate.
  • Token bucket: a bucket holds up to burst tokens and refills at a steady rate. Each request removes one token. Allows controlled bursts, and uses two numbers per key.
  • Sliding window counter: keep the count for the current window and the previous window, and estimate the sliding total by weighting the previous window by how much of it still overlaps.
Token Bucket vs Sliding Window Counter
Comparison

Token bucket

2 numbers per key: tokens, last refill

  1. 1

    Load tokens and last refill time

    new key = full bucket

  2. 2

    Add elapsed time × rate

    capped at burst capacity

  3. 3

    Enough tokens? Remove the cost

    request is allowed

  4. 4

    Not enough? Reject

    wait = missing / rate

  • Allows controlled bursts
  • Exact Retry-After
  • ~100 bytes per key
  • Burst briefly exceeds average rate
  • Needs an atomic script

Best default for public APIs

Sliding window counter

2 counters per key: current, previous

  1. 1

    INCR the current window counter

    window = floor(now / size)

  2. 2

    Read the previous window count

    missing = 0

  3. 3

    prev × overlap + current

    e.g. 80 × 0.7 + 20 = 76

  4. 4

    Estimate above limit? Reject

    otherwise allow

  • Smooth, no boundary double burst
  • Very cheap, mostly INCR
  • Approximate (assumes even spread)
  • Retry-After is a rough guess

Best for strict quotas and login limits

Key point. Default to token bucket. Use the sliding window counter when the promise is 'N in any window' and bursts should be smoothed.

Both use a tiny amount of memory per caller. They differ in how they treat bursts and how exact they are.

The sliding window counter math. Limit 100 per minute. The previous minute had 80 requests, and we are 30% into the current minute with 20 requests so far:

text
overlap of previous window = 1 - 0.30         = 0.70
estimated requests         = 80 x 0.70 + 20   = 76
76 < 100, so the request is allowed

It smooths out the fixed-window boundary burst using only two integers. The cost is that it assumes previous-window requests were evenly spread, so it is an approximation. Published measurements of this technique show errors of only a few percent, which meets our "under 5%" requirement.

The token bucket math. Rate 100 per minute is 1.67 tokens per second; burst 20. A caller who was idle has 20 tokens and may send 20 requests instantly. After that, sustained traffic is limited to 1.67 per second. A caller with 0.4 tokens must wait (1 - 0.4) / 1.67 = 0.36 seconds, which becomes our Retry-After (rounded up to 1 second).

Our choice. Token bucket is the default: cheap, supports bursts (real clients are bursty, such as a page load firing 10 calls), and produces an exact wait time. Use sliding window counter for rules where the promise is "no more than N in any 60 seconds" and bursts must be smoothed, such as billing quotas and login attempts. Because algorithm is a field in the rule, both coexist.

Trade-off thinking. Token bucket allows a burst up to burst immediately, which protects users but lets a caller briefly send more than the average rate. Sliding window counter limits more evenly but is approximate and bursts less naturally. Pick by what the business promises, not by taste.

6.2 Counting atomically in Redis

The most common interview bug is this:

text
1. GET tokens          -> 1
2. (decide: allowed)
3. SET tokens = 0

Two gateways run step 1 at the same moment, both read 1, both allow, and both write 0. One token paid for two requests. This is a race condition: the result depends on the unlucky timing of two actors. With 30 gateways and a bursty caller it happens constantly.

The fix is to make read, decide, and write one indivisible step. Redis runs commands one at a time on a single thread, and a Lua script (a small program the server executes) runs as a single command: no other command can run in the middle of it.

Token bucket script:

text
-- KEYS[1] = rl:{rule}:{subject}
-- ARGV: rate (tokens per second), capacity (burst), cost
local rate     = tonumber(ARGV[1])
local capacity = tonumber(ARGV[2])
local cost     = tonumber(ARGV[3])

local t   = redis.call('TIME')
local now = t[1] * 1000 + math.floor(t[2] / 1000)    -- milliseconds

local data   = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(data[1])
local ts     = tonumber(data[2])
if tokens == nil then tokens = capacity; ts = now end

tokens = math.min(capacity, tokens + math.max(0, now - ts) * rate / 1000)

local allowed, retry_ms = 0, 0
if tokens >= cost then
  tokens = tokens - cost
  allowed = 1
else
  retry_ms = math.ceil((cost - tokens) * 1000 / rate)
end

redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity / rate * 1000) * 2)
return { allowed, math.floor(tokens), retry_ms }

Things worth pointing out aloud:

  • Time comes from Redis (TIME), not from the gateway. Thirty gateways have slightly different clocks, and clock skew of a few hundred milliseconds would corrupt refill math.
  • One round trip: the gateway sends the script once (loaded by hash, EVALSHA) and gets back the decision and the numbers for the headers.
  • The PEXPIRE deletes the key after twice the time a full refill takes, so idle callers cost no memory. A deleted key behaves exactly like a full bucket.
  • The script touches one key, so it works in a clustered Redis where each key belongs to exactly one shard.

The sliding window counter needs even less logic, because INCR is atomic by itself:

text
current  = INCR  rl:{rule}:{subject}:{window_index}
EXPIRE   that key to 2 x window_sec    (set when current == 1)
previous = GET   rl:{rule}:{subject}:{window_index - 1}   (0 if missing)
estimate = previous x (1 - elapsed_fraction) + current
if estimate > limit: deny (and DECR the key so rejected calls do not count)

Run both steps in a Lua script as well, so the count and the decision stay atomic. Cheaper trick: send the increment and the read in one pipeline (several commands in one network round trip).

Several rules per request. A request may match "per user" and "per IP" rules, living on different shards. Send the checks in parallel and combine the results; the request is allowed only if all pass. Order the cheaper, stricter rule first when possible. If one rule denies after another already consumed a token, we do not refund: the slight over-count is harmless and refunds add complexity.

6.3 Enforcing one limit across many gateways

Three designs, from simple to precise.

  • Local counters only: each gateway counts alone. No network cost, but a user spread over 30 gateways gets up to 30x the limit. Acceptable only for crude protection, for example limiting one gateway's total load.
  • Central counters (our default): every check is one Redis call on the shard owning hash(key). Exact (to within replication lag) at the price of one 0.5 ms round trip.
  • Local batching ("token leasing"): a gateway asks Redis for a block of, say, 10 tokens, and then spends them locally. Redis calls drop 10x, but a block taken by an idle gateway is stranded, so accuracy drops. Use it only for the hottest keys.
Sharded Redis Counters
Architecture
Shard 1Shard 2Shard 12Gateway fleet30 servers, hash keyPrimary 1slots 0-1365Replica 1other zonePrimary 2slots 1366-2730Replica 2other zonePrimary 12last slotsReplica 12other zoneasync copyasync copyasync copy
Key point. Hashing spreads many keys evenly, but one very hot key still lands on one shard. That is why hot keys get special handling.

hash(rule + subject) picks the shard. Each shard has an asynchronous replica in another zone.

Sharding the counters. Keys are placed by hash: the gateway computes hash(rl:orders-read-free:42) and sends the call to the owning shard. This is the consistent hashing idea from the partitioning lesson (Redis Cluster uses 16,384 hash slots spread over the nodes, which gives the same property: adding a shard moves only a fraction of keys). Subjects are many and random, so load spreads evenly across the 12 shards.

Replication. Each shard has a replica copying changes asynchronously. If the leader dies, the replica takes over. Asynchronous copying can lose the last few milliseconds of counter updates, so right after a failover some callers get a little extra allowance. We accept that, it is the right trade for speed.

Hot keys. Hashing balances many keys, not one huge key. If one API key sends 50,000 requests per second, that is an entire shard's capacity (50,000 checks per second) on a single key, so every other key on that shard slows down. Mitigations, from cheap to complex:

  1. Cache denials locally. When Redis says "denied, retry in 12 s", the gateway remembers the denial for min(retry_after, 1 second) and rejects the caller's next requests from memory. A caller who is already over the limit costs almost no Redis calls.
  2. Token leasing for that key (above), so 50,000 requests become 5,000 Redis calls.
  3. Split the key into N sub-counters (...#0 to ...#7), each with limit/8, with a gateway picking one at random. Accuracy drops a little, and load is spread over several shards.
  4. For abuse at this volume, block at the network edge (CDN or firewall) rather than the application.

6.4 Propagating rule changes

Rules must change without restarting servers, and the hot path must never wait for the rules store.

Propagating Rule Changes
Architecture
GatewaysOperatorPUT /v1/rulesRules storeversioned rowsChange feednotify + snapshotGateway Arule cache v42Gateway Brule cache v42Gateway Crule cache v42validatenew versionpushpushpush
Key point. Rules change in seconds and the hot path never waits for the rules store.

Push for speed, poll as a safety net. Gateways keep serving with their last good copy if the store is down.

  • Operators write rules through the admin API into a durable rules store (a small relational database or a strongly consistent configuration store such as etcd).
  • The write increments version and publishes a notification.
  • Every gateway keeps all rules in memory (a few thousand rules is a few megabytes). It subscribes to change notifications for speed, and also polls every 10 seconds as a safety net in case a notification is lost.
  • A gateway applies a new snapshot atomically (swap one pointer), so no request sees half of an update.
  • If the rules store is down, gateways keep using their last good copy. Rule reads never depend on rule storage being up.

The cost is propagation delay: for up to about 10 seconds, different gateways may use different limits. That is fine for a rate limit. Lowering a limit takes effect within seconds, and a bad rule can be rolled back with the same path. Validate rules before saving (limit above 0, known algorithm), and roll out sensitive changes to a small percentage of gateways first.

Interview tip. Candidates often say "update the database and the servers will see it." Name the mechanism (push plus poll), the delay you accept, and what happens when the store is unreachable.

6.5 Multiple regions

Users around the world hit gateways in the nearest region. A single global Redis would put 100+ ms on the hot path, so each region has its own Redis cluster and the check never leaves the region.

  • Most callers stay in one region (geo-based DNS keeps a user near the same data center), so enforcing the full limit regionally is already accurate.
  • For strict global limits, give each region a share of the quota (for example 60% and 40% based on recent traffic) and rebalance the shares every few seconds from a small coordinator. A caller who truly sprays traffic over regions can exceed the limit slightly during one rebalance interval.
  • Asynchronous sync of counters between regions is possible (regions exchange totals every second or so) and is simpler for a few big keys, but is only eventually consistent.

State the trade-off plainly: global exactness would cost a cross-region round trip on every request, which breaks the 5 ms budget. We choose low latency with a bounded error.

Step 7: Bottlenecks and Failure Handling

Bottlenecks

  • Redis throughput. Cause: checks per second exceeding 50,000 per shard. Mitigation: add shards (headroom of 2x is already planned), pipeline multi-rule checks, token leasing for hot keys.
  • Hot keys. Covered in 6.3: local denial cache, leasing, key splitting.
  • Gateway CPU. Rule matching on every request must be efficient: index rules by domain and the first path segments, not a linear scan.
  • Latency tail. Cause: one slow Redis shard delays every request that hashes there. Mitigation: a strict timeout on the check (for example 10 ms) so a slow limiter does not slow the API, and then apply the fail mode below.
  • Rule explosion. Per-customer overrides can multiply the rules. Store overrides separately and look them up by subject, instead of creating a rule per customer.

Failures: fail open or fail closed?

This is the question interviewers love. When the limiter cannot decide (Redis timeout, shard down), we choose between two behaviours:

  • Fail open: allow the request. The API stays available, but protection is temporarily off. A limiter outage must not become an API outage, so this is the default.
  • Fail closed: reject the request. Protection holds, but legitimate users see errors. Use it only for rules where an unlimited burst is more dangerous than downtime, such as login attempts (brute-force guessing), SMS or email sending (direct cost), and password reset. That is why fail_mode lives on the rule.

Practical handling:

  • A shard fails. Only the keys on that shard are affected (1/12 of subjects). The replica is promoted, typically within seconds; during that time, those subjects follow their rule's fail mode.
  • Fast failure detection. Use a circuit breaker (stop calling a failing dependency for a short time instead of waiting on timeouts). After several consecutive Redis failures, the gateway skips Redis for a few seconds and applies the fail mode immediately, saving 10 ms per request.
  • Fallback to local limits. While failing open, enforce a coarse local limit on each gateway (for example, a per-IP bucket held in memory). It is imprecise but stops runaway abuse during an outage.
  • Redis restarts empty. Counters reset, so callers get fresh allowances. Self-healing and acceptable.
  • Clock problems. Using TIME inside Redis avoids gateway skew; a replica promoted with a different clock causes only a small error.
  • A gateway fails. The load balancer removes it. No state is lost, because gateways are stateless.
  • A bad rule is deployed (limit of 0, matching everything). This is a real cause of outages. Defend with validation, staged rollout, a quick rollback, and a kill switch (a flag that disables limiting for a rule or a domain).

Monitoring

Track allowed versus denied counts per rule (a sudden spike in 429s is either an attack or a bad rule), p99 latency of the check, Redis shard CPU and operations per second, fail-open events, rule propagation lag (the difference between the newest rule version and the version each gateway holds), and the top denied subjects.

Interview tip. Do not answer "fail open or closed" with one word. Say: "open by default so the limiter never takes the API down, closed for login and costly operations, set per rule, with a local fallback limit during the outage."

Step 8: Final Design Walkthrough

Final Design
Architecture
RulesCountersClientGateway +limiter30 serversRule cachein memoryRules storepush + pollRedis shards12, Lua checkReplicasfailoverBackendservicesallowed trafficmatch ruleatomic checkallowedasync copysync

Solid arrows are synchronous. Dashed arrows are background or fallback paths.

Request flow

The client reaches a gateway. The gateway authenticates, matches the request to a rule from its local cache, and runs one atomic Lua check on the Redis shard that owns hash(rule + subject). Allowed requests are forwarded with X-RateLimit-* headers. Denied requests receive 429 with Retry-After and never reach the backend. If Redis is unreachable, the rule's fail mode decides.

Data flow

Rules live in the durable rules store and are copied to every gateway's memory. Counters live only in Redis (12 shards, each with an asynchronous replica), expire by TTL, and are never written to a database. Allow and deny events flow asynchronously to metrics.

Background processing

A rules publisher notifies gateways of changes, and gateways also poll as a safety net. A metrics pipeline aggregates allow and deny counts per rule for dashboards and alerts. An optional rebalancer adjusts regional quota shares for global limits.

Critical design decisions

  1. Enforce at the gateway, so rejected traffic never costs a backend any work.
  2. Shared counters in Redis, because 30 gateways must not each keep their own count.
  3. One Lua script per check, for atomic read-decide-write in one round trip.
  4. Token bucket by default, sliding window counter for strict quotas, selected per rule.
  5. Sharding for throughput (12 shards), since memory (10 GB) is not the constraint.
  6. Rules cached in gateway memory, updated by push plus poll, so the hot path never waits on rules storage.
  7. Fail open by default, closed for dangerous rules, so the limiter cannot become the outage.

If time remains, discuss multi-tenant fairness (a per-tenant cap above per-user caps), cost-based limits, adaptive limits that tighten when backends are slow (load shedding), and returning limits in the response so clients can self-throttle.

Common Interview Questions

Finished this lesson?

0 of 44 lessons done · 0% of the course