What you'll learn: By the end of this lesson you will be able to (1) place limiter checks in the right layers of a request path, (2) size and shard a Redis-backed limiter and handle one very hot client, (3) say what a limiter loses when its store fails over and decide fail open or fail closed per rule, (4) define the rejection contract and the rollout, and (5) reuse the published Spring lab to see the core decision run.
This is an educational reference design, not the verified internal architecture of any company.
A theatre sells a fixed number of standing tickets per hour to each ticket agency. With one box office, the clerk keeps a tally on a sheet and the rule is easy. Now the theatre opens twenty counters in three cities. If every counter keeps its own sheet, an agency can buy the whole allowance at each one. If every counter phones one central desk for every ticket, the desk becomes the queue. The design question is how much of the tally to share, how often, and what to do when the phone line is down.
A distributed rate limiter is that theatre. The algorithms (token bucket, windows) are covered in rate limiter algorithms in Java with Redis and the overview in rate limiting. This lesson is the system around them: the fleet, the shared store, the failure choices. It follows the template from the case studies overview.
The core idea
A distributed limiter is a shared counter service with an exact decision rule and an explicit answer for "what if the counter service is unavailable". The decision itself is a few lines. Almost everything else is a placement and failure question.
Three ideas carry the design:
- Layer it. A cheap local check in each gateway absorbs bursts and obvious abuse. A shared check decides the exact, fleet-wide limit.
- Make each global decision one atomic step on the store that owns the client's key, so two gateways cannot both take the last token.
- Treat the limiter as a soft dependency. It protects the backend; it must not take the API down with it. Every rule says how it behaves when the limiter cannot answer.
Requirements and scope
Functional:
- Limit requests per client (API key or authenticated principal), per route group and per tier (free, paid, partner).
- Limits are configurable at runtime without a deploy.
- A rejected caller gets
429withRetry-After, and enough information to back off sensibly. - Different rules for different endpoints, such as login attempts versus catalogue reads.
Out of scope: bot detection and abuse scoring, billing-grade metering (a limiter may be approximate, an invoice may not), and concurrency limits (covered with load shedding in load shedding and retry storms).
Non-functional (assumptions):
- Added latency on the request path: p99 under 3 ms in the same region.
- Enforcement is close to exact for a single client: a client should not exceed its limit by more than a small, stated margin.
- The limiter's availability must not cap the API's availability.
- State for idle clients must clean itself up.
Back-of-envelope estimate
All numbers are illustrative assumptions, not measurements.
| Quantity | Assumption | Result |
|---|---|---|
| Peak API traffic | 200,000 requests per second across the fleet | 200,000 per-client decisions per second |
| Unauthenticated traffic checked per IP | 10% of requests | 20,000 more decisions per second |
| Total decisions | about 220,000 per second at peak | |
| One store shard | assume 50,000 scripted decisions per second, to be measured | 220,000 / 50,000 = 4.4, so at least 5 shards |
| Headroom | run at about 60% of the measured ceiling | 220,000 / (50,000 x 0.6) = 7.3, so 8 primaries |
| Replicas | one per primary | 16 nodes |
| Active clients | 5 million in an hour, 2 rules each | 10 million keys |
| State per key | about 150 bytes including overhead (assumption) | about 1.5 GB in total, about 190 MB per shard |
| Gateway instances | 100 | about 2,000 requests per second each |
Two things follow. Throughput of decisions, not memory, sizes the store. And one very hot client matters: a partner sending 30,000 requests per second through a single key puts 60% of one shard's assumed ceiling on that shard alone, no matter how many shards exist.
API design
Two interfaces: the data-plane check that gateways call, and the control-plane rule API.
CHECK (library call or gRPC, internal)
check(ruleId, clientKey, cost = 1) -> { allowed, remaining, retryAfterMs, resetAfterMs }
PUT /v1/limit-rules/{ruleId} control plane, versioned
{ "dimension": "api-key", "algorithm": "token-bucket",
"capacity": 50, "refillPerSecond": 20,
"failMode": "open", "enforce": false }
Client-facing, a rejection looks like this:
HTTP/1.1 429 Too Many Requests
Retry-After: 3
Content-Type: application/problem+json
RFC 6585 defines 429 as the user having "sent too many requests in a given amount of time", says the response may carry Retry-After, says the specification does not define how the origin identifies the user or counts requests, and says a 429 must not be stored by a cache. The body belongs to the problem details error model.
An IETF Internet-Draft defines RateLimit-Policy, RateLimit and RateLimit-Partition header fields. At the time of writing it is a work in progress, and it says clients must not assume that a positive available quota guarantees further requests will be served. Treat such headers as hints.
In the check call, cost lets expensive endpoints take more than one token, retryAfterMs lets the gateway build an honest header, and the rule's enforce flag makes dark launch (observe but do not block) a first-class mode.
Data model
The store is a sharded in-memory key-value store (Redis in this design). One key per client per rule.
- Bucket state: a hash at
rl:{<clientKey>}:<ruleId>withtokens(in integer thousandths) andts(last update in milliseconds). Its timeout is the time to refill fully, because after that the state equals no state. - Rule table: the rules themselves live in a small configuration store and are pushed to gateways, never read from the limiter store on the hot path.
- Counters for observability: allowed, rejected and unchecked counts per rule, kept in the metrics system, not the limiter store.
The braces in the key are a hash tag. Redis Cluster maps a key to one of 16384 slots with CRC16(key) mod 16384, and when a key contains a non-empty {...} substring only that substring is hashed. Keys that share a tag land in the same slot, which is what lets one script touch a client's per-second and per-minute buckets together. The cluster specification says clients are free to use multi-key operations when keys share a slot through hash tags.
Figure 1. Rules, clients and bucket state. How to read this: rules are configuration, buckets are the only per-request state, and each bucket expires by itself.
High-level design
Figure 2. Gateways with a local bucket, a sharded global store, and a rule store. How to read this: each gateway first checks a local bucket, then asks the shard that owns the client's key; the rule store pushes configuration out and is never on the hot path. Gateway 2 forwards admitted requests too; its arrow is omitted to keep the picture clear.
The flow for one request:
- The gateway authenticates the caller and derives the client key (API key, or user id; an IP address only for unauthenticated routes, since many users can share one).
- It looks up the rule for this route and tier from its in-memory copy.
- Local check. A small token bucket in the gateway's memory rejects obvious floods without any network call.
- Global check. The gateway sends one script call to the shard that owns the key. The script refills, decides and writes in a single step.
- On
allowed, the request proceeds. On rejection, the gateway answers429withRetry-After.
Figure 3. A request through both layers. How to read this: the backend is only called after both checks pass, so rejected traffic costs it nothing.
Reference deployment topology
The limiter store is a Redis Cluster-style deployment: primaries own slot ranges, each with a replica in another availability zone. Gateways hold a cluster-aware client that caches the slot map and follows redirects.
Figure 4. Primaries own slot ranges and replicate asynchronously. How to read this: three primaries are drawn to keep the picture small; the estimate above calls for eight. The slot ranges are an even three-way split of the 16384 slots.
Deep dive 1: where to enforce, and in which layers
A limit can be enforced at the edge (CDN or WAF), at the API gateway, inside each service, or in a shared sidecar. The overview lesson compares these. This design chooses the gateway because it sees the authenticated client and the route, and keeps the services unaware of limits. See the API gateway pattern.
Within the gateway there are two stages. Envoy's documentation describes the same idea for its proxy: a global rate limit service is called over gRPC, and "local rate limiting can be used in conjunction with global rate limiting to reduce load on the global rate limit service", so the limit is "applied in two stages", with a local token bucket handling coarse bursts and the global limit handling fine-grained enforcement.
Why not only global? Every request would cost a network round trip to the store, and the store would see the full request rate including floods. Why not only local? With 100 gateway instances, a client behind a load balancer could in the worst case be admitted up to 100 times its limit if each instance applied the full limit independently. A local limit set to the client's full limit is only a flood guard; the global check is what keeps the limit true.
Deep dive 2: one atomic decision per request
The core mistake in a hand-rolled limiter is reading the state, deciding in application code and writing it back as separate commands. Two gateways can read the same one remaining token and both admit. The sibling lesson shows this and its fix in detail; the working definition is enough here: the refill, the decision and the write must be one indivisible step on the store that owns the key.
Redis states that it "guarantees the script's atomic execution" and that "while executing the script, all server activities are blocked during its entire runtime". That gives both the guarantee and the constraint: scripts must be short. The documentation also says every key a script touches must be passed as an input key argument, scripts must not build key names from data, and scripts "may need to be reloaded by the application at any time" because the script cache is volatile and can be cleared on restart or failover. A limiter client therefore calls by digest and loads the script when the server answers that it has no such script.
The decision reads the clock from the store, not from the gateway. Instances with skewed clocks would otherwise disagree about how many tokens have refilled. The scripting page states that with script effects replication, the default since Redis 5.0, commands such as TIME can be used freely in scripts.
Build it: reuse the published lab
This lesson has a lab, and it is the one that already exists for the sibling lesson: examples/spring-labs/labs/rate-limiter-redis-model (Spring Boot, MockMvc, no Docker, no real Redis). Duplicating it would add nothing, so this lesson uses it as evidence for two claims in the design. What it is: five limiters behind a Spring MVC interceptor, run against an in-memory model of about a dozen Redis commands where each command, and each script, runs under one Java monitor. What it is not: it has no network, no sharding, no replication and no Lua, so it cannot show anything about shards, hash tags or failover.
From the repository:
cd examples/spring-labs
./gradlew :labs:rate-limiter-redis-model:test
The test task ran 16 tests with no failures for this lesson, one of which compares the lab's report with examples/spring-labs/golden/rate-limiter-redis-model.txt. The first claim it supports: separate read, decide and write commands let a second request in, while one script does not.
Expected output, captured from a real run (Spring Boot 4.1.2, Java 25; the race scenario):
separate commands: request B ran between A's read and A's write
B admitted: true, A admitted: true (capacity was 1)
one script: A admitted: true, B admitted: false
32 threads at the same moment, capacity 10, one script: admitted 10, rejected 22
The second claim, about failure policy, is shown by the store-unreachable scenario: with fail open, three requests are all served and counted as served without a check; with fail closed, each gets a 503; both recover when the store returns.
Expected output, captured from a real run (the same run; the failure-policy scenario):
OPEN store down, 3 requests: 3 x 200
served by the controller: 3, served without a check: 3
store back, 3 requests: 2 x 200, 1 x 429
CLOSED store down, 3 requests: 3 x 503
served by the controller: 0, served without a check: 0
store back, 3 requests: 2 x 200, 1 x 429
Read the "served without a check" count as the metric to alert on in production. The lab has no real Redis, cluster, replication or network latency. Its README has a "Break it" experiment; restore the code and re-run the tests after trying it.
Deep dive 3: sharding, hash tags and the hot client
Sharding. The key space is split by slot, so each client's buckets live on one primary. Adding a shard moves slots, not the algorithm; see consistent hashing for the general idea of limiting movement, and hot partitions and resharding for the operational side. Redis Cluster's fixed 16384 slots are an alternative to a ring: ownership is a table of slots, not a position computed from the node set.
Multi-rule decisions. A client often has a per-second burst rule and a per-minute rule. If both must pass, check them in one script on one shard, which needs both keys in one slot. Hash tags do that, and the cost is that all of one client's keys share a shard, which is correct here because the client is the unit of load.
The hot client. One key is one shard's work, always. With the assumed ceiling of 50,000 decisions per second per shard, a partner at 30,000 per second uses 60% of its shard. Three options:
| Option | How it works | Cost |
|---|---|---|
| Sub-buckets | Split the key into N sub-keys, each with 1/N of the limit, and pick one at random per request | Approximate: a burst can hit one sub-bucket while the others are idle, so the client sees rejections before reaching its full limit |
| Token leases | A gateway takes a batch of tokens (a lease) from the central bucket and spends it locally | Tokens held by a crashed or idle gateway are stranded until the lease expires, and the overshoot is bounded by outstanding leases |
| Dedicated shard | Move the hot key to its own node | Operational complexity, but exact |
A worked example for leases, with illustrative numbers: a partner limit of 1,000 requests per second, 100 gateways, a lease of 20 tokens. In the worst case every gateway holds a full lease, so up to 100 x 20 = 2,000 tokens are outstanding, twice the one-second limit. A smaller lease, or a lease that scales with the client's recent rate, shrinks that margin at the price of more store calls. Whether that margin is acceptable is a product decision. Reach for leases or sub-buckets only when a measured hot key justifies them.
Deep dive 4: what the store loses, and fail open or closed
Replication is asynchronous. The Redis replication documentation says replication is asynchronous by default and that even with WAIT, "acknowledged writes can still be lost during a failover". The cluster specification likewise says that a write acknowledged by a primary can be lost if the primary fails before replicating it and a replica is promoted.
For a limiter this is tolerable, and it is worth saying why. The lost writes are recent bucket updates. After a failover some clients get back tokens they had spent, so for a short time the limiter is more permissive than exact. The error is bounded: no client can get more than a full bucket back, so the extra traffic is at most one burst capacity per affected client. A limiter is a protection mechanism, not a ledger. Do not pay synchronous replication latency on every request to avoid this; contrast the payment case in payments and double-entry ledgers, where the same loss would be a bug.
When the store is unreachable, each rule has a policy:
- Fail open: serve without a check. The API stays up, and protection disappears exactly when load may be high. Suitable for read-only catalogue traffic.
- Fail closed: refuse with
503. The backend stays protected and a limiter outage becomes an API outage. Suitable for login and other credential-guarding routes.
Stripe's engineering post on rate limiters recommends hooking limiters in so that "if there were bugs in the rate limiting code (or if Redis were to go down), requests wouldn't be affected", catching exceptions at all levels so that errors fail open, building in kill switches, and dark launching each limiter to watch the traffic it would block. It also treats 429 against 503 as a choice of which is more accurate. This design adopts those ideas as defaults, with fail closed as an explicit per-rule exception.
Figure 5. The decision with its failure branch. How to read this: the only path that skips the store check is the timeout branch, and it is counted. The 20 ms budget is an assumption, to be set from the latency target.
A timeout needs care. If the limiter's timeout is longer than the request's own budget, a slow store makes every request slow before failing open. Set the limiter timeout well below the end-to-end budget, and add a circuit breaker so that after repeated failures the gateway skips the call for a short period instead of waiting each time; see timeouts, retries, backoff and jitter and graceful degradation and fallbacks.
Deep dive 5: multiple regions
A single global counter across regions needs cross-region round trips on the request path, which breaks the latency goal. Cloudflare's post on counting describes the shape of one public answer: reporting all counters to a single central point is not realistic because "the latency is far too high", so they run an isolated counting system inside each point of presence, and increment jobs "are run asynchronously without slowing down the requests". That is a statement about their system, not a recipe for this one.
For this reference design the options are:
| Option | Behaviour | Cost |
|---|---|---|
| Per-region limits | Each region enforces its own share of the global limit | Traffic skew can leave one region's share exhausted while another sits idle |
| Regional shares, rebalanced | Shares follow recent traffic (for example 60, 30 and 10 percent of a 900 per second limit gives 540, 270 and 90) and are recomputed every few seconds | Needs a coordinator; shares lag behind sudden shifts |
| Global store, home region | All checks go to the client's home region | Cross-region latency for clients served elsewhere |
Choose per-region shares for most traffic, with a global store only for rules where exactness matters more than latency, such as login throttling.
Failure modes
| Failure | Effect | Mitigation |
|---|---|---|
| Shard primary fails over | Recent updates lost; some clients briefly get tokens back | Accept bounded over-admission; alert on failover; no synchronous replication |
| Store unreachable | Checks cannot complete | Per-rule fail open or closed, short timeout, circuit breaker, unchecked counter |
| Script cache cleared after restart | Calls by digest are refused until the script is loaded | Load and retry in the one client wrapper; do not treat as "store down" |
| Hot client saturates a shard | Latency rises for every client on that shard | Local stage, leases or sub-buckets, dedicated shard, per-key metrics |
| Bad rule pushed | Legitimate traffic rejected | Versioned rules, staged rollout, enforce flag, kill switch |
| Clock skew between gateways | Inconsistent refill | Take time from the store inside the script |
| Key without timeout | Memory grows with every client ever seen | Timeout set in the same script that writes the state |
Retry storm after a wave of 429s |
Clients hammer the limiter | Retry-After, jittered backoff in clients, limiter checks cheap enough to survive it |
Trade-offs worth stating
| Decision | Option A | Option B | How to choose |
|---|---|---|---|
| Placement | Gateway | In each service | Gateway for one policy point; services for per-resource limits only they know |
| Shared state | Central store per request | Local counters synced periodically | Central for accuracy; local plus sync when store load or latency dominates |
| Algorithm | Token bucket | Sliding window counter | Token bucket when bursts are acceptable; windows when the contract is "N per window" |
| Failure | Fail open | Fail closed | Open for reads, closed for credentials and money |
| Replication | Asynchronous | Synchronous or WAIT |
Asynchronous; the limiter tolerates small bounded loss |
| Hot key | Leases | Sub-buckets | Leases when exactness matters; sub-buckets when simplicity does |
Interview cheat sheet
| Step | What to say | Key numbers (illustrative) |
|---|---|---|
| Requirements | Per-client limits, per route, configurable, 429 with Retry-After | p99 added latency under 3 ms |
| Estimate | Decisions per second size the store, not memory | 220,000 per second, 8 primaries |
| API | check(rule, key, cost), rule API with an enforce flag |
Dark launch first |
| Data | One hash per client per rule, timeout equals time to refill | 10 million keys, 1.5 GB |
| Design | Local bucket, then one atomic script on the owning shard | Hash tags for multi-rule |
| Deep dives | Atomicity, hot key, failover loss, fail open or closed, regions | Leases: 100 x 20 = 2,000 outstanding |
| Failures | Store down, failover, bad rule, retry storm | Unchecked counter, kill switch |
| Trade-offs | Exactness against latency and store load | Per-rule policy |
In practice: operating the reference design
This is a realistic scenario, not a case history. It is a composite built from common production patterns and describes no specific company; every number is an illustrative assumption.
Assume a team of eight runs the limiter for an API platform on Kubernetes across three zones. Gateways call a cluster-aware Redis client, rules sit in a versioned configuration store, and metrics and alerts come from the usual stack.
SLOs and dashboards
| SLI | SLO (assumed) | Dashboard panels |
|---|---|---|
| Limiter added latency | p99 under 3 ms | Script latency per shard, client-side timeout rate |
| Unchecked requests | Under 0.01% of traffic | Fail-open counter per rule and per gateway |
| Decision correctness | No client admitted above 1.2 times its limit over a minute | Admitted per client against limit, sampled |
| Rejections | Tracked, no target | 429 rate per rule, per tier, per top clients |
| Store health | Replica lag within seconds | Replication offset gap, failovers, memory per shard |
Rollout of a new rule
Publish it with enforce: false and review the would-reject list with the owners of the heaviest clients. Then enforce for internal traffic, one partner and everyone, testing the kill switch before each step.
Runbook
| Symptom | Likely cause | First check | Mitigation |
|---|---|---|---|
| All requests slower by tens of milliseconds | Limiter timeout too long during a store problem | Client timeout settings, script latency | Lower the timeout, open the circuit breaker, fail open on safe rules |
| Unchecked counter rising | Store errors or a missing script after a failover | Error types behind the counter | Load the script, retry, check the failover |
| One shard hot | A single partner key | Per-key rates on the shard | Local stage, lease or dedicated shard |
| Sudden wave of 429s | Bad rule or client regression | Rule version history, top rejected clients | Roll back the rule, disable enforcement |
Decision record: store failure policy
| Field | Entry |
|---|---|
| Context | The limiter protects backends but sits on every request path. Its store can fail independently. |
| Decision | Fail open by default with an alert on the unchecked counter. Fail closed only for login, password reset and other credential routes. Rules carry the mode explicitly. |
| Consequences (good) | A store outage does not become an API outage. Protection for sensitive routes stays. |
| Consequences (bad) | During an outage heavy clients are not limited on open rules. Login routes become unavailable if the store is down. |
| Revisit when | An outage shows backends overloading during fail open, or login availability is judged more important than credential protection. |
The 2 a.m. failure
A zone loses connectivity to one shard primary. Gateways in that zone keep waiting on the shard for the full client timeout, which was left at the library default, longer than the API's own deadline. Every request through those gateways becomes slow before failing open, and upstream retries pile on. The first check is script latency and the client timeout rate per gateway; the mitigation is a short timeout with a circuit breaker so those gateways skip the store call. The lasting fix is a timeout set from the latency budget, tested by injecting latency into the store in a game day.
Architect's notes
- Name the margin. Say how far over its limit a client can get in the worst case, and write it in the API documentation.
- Keep the limiter out of the correctness path. Anything that must be exact, such as money or inventory, belongs in the database, not in a limiter.
- Observe before you block. Dark launch every new rule; the would-reject list is the cheapest test there is.
- Own one wrapper. Script loading, timeouts, the circuit breaker and the unchecked counter live in one library every gateway uses.
- Make clients part of the design. A limiter that rejects is only half a protocol; clients must back off. See load shedding and retry storms.
Common mistakes
- Read, decide, write as separate commands. Two gateways take the same token. Use one script per decision.
- One local limiter per instance set to the full limit. With many instances the real limit is a multiple of it. Use a global check for exactness.
- No policy for the store being down. The first outage decides it for you. Choose per rule, and count unchecked requests.
- A limiter timeout longer than the request budget. The limiter becomes the slowest dependency.
- Synchronous replication for limiter state. It adds latency to every request to protect data that tolerates small bounded loss.
- Keys with no timeout. Memory grows with every client ever seen.
Key takeaways
- A distributed limiter is a layered design: a local stage for floods, a global stage for the true limit.
- Each global decision is one atomic step on the shard that owns the key; this lesson's lab shows the difference on a model.
- Sizing follows decisions per second; a single hot client is one shard's problem and needs its own answer.
- The store replicates asynchronously, so a failover can briefly over-admit; that bounded error is acceptable for protection, not for accounting.
- Every rule says how it behaves when the limiter is unavailable, and the unchecked count is monitored.
- Roll out in observe mode first; keep a kill switch.
- Rejection is a contract:
429,Retry-After, and clients that back off with jitter.
Practice exercises
Exercise 1 - Starter (30 min): Redo the estimate with 500,000 requests per second, 20% of traffic checked per IP, and a shard ceiling of 40,000 decisions per second at 50% headroom. How many primaries?
Exercise 2 - Intermediate (2 hours): A client has a limit of 100 per second and 600 per minute, checked together. Write the key layout and the script outline so both limits are decided in one atomic step, and explain which part makes the keys land on one shard.
Exercise 3 - Advanced (half day): Design the lease protocol for a hot partner key: lease size, expiry, what a gateway does when its lease runs out, and what happens to unspent tokens when a gateway crashes. State the worst-case overshoot.
Related reading
- Rate limiter algorithms in Java with Redis - the algorithms, the Redis commands and the lab this lesson reuses.
- Rate limiting - the overview and where to enforce.
- Distributed caches, Redis and Memcached - the store these limiters run on.
- Redis data structures - the hash and sorted set shapes used for limiter state.
- Hot partitions and resharding - the operational side of a hot key.
- API gateway pattern - the usual enforcement point.
- Timeouts, retries, backoff and jitter - how clients should react to a limit.
The other side of this topic is the client: it reads 429 and Retry-After, waits at least that long with jitter, and stops retrying instead of hammering a limit.
Official documentation
- Redis, Scripting with Lua: atomic execution,
KEYSandARGV, script cache volatility. - Redis, Cluster specification: hash slots, hash tags, write safety.
- Redis, Replication: asynchronous replication and
WAIT. - IETF, RFC 6585: 429 Too Many Requests.
- IETF, RateLimit header fields draft: a work in progress.
- Envoy, Global rate limiting.
- Stripe, Scaling your API with rate limiters, and Cloudflare, Counting things, a lot of different things: two public write-ups of production limiters, each describing its own system.