What you'll learn: By the end of this lesson you will be able to write the fixed window, sliding window log, sliding window counter, token bucket and leaky bucket limiters in terms of Redis commands, explain why a limiter built from separate read and write commands is wrong and what a Lua script changes, choose keys and timeouts so idle clients cost nothing, answer with
429andRetry-After, decide what happens when the limiter's store is down, and read the output of a Spring lab that models all of this in memory.
A ferry kiosk keeps a jar of tokens for each regular passenger. A token drops in every minute and the jar holds five. A passenger takes one token to board; with an empty jar they wait. Someone who skipped a week does not return to a hundred tokens, because the jar has a lid. The jar is the whole algorithm. The hard part is the kiosk: if two clerks look into the same jar at the same moment, both see one token, both hand out a ticket, and the jar is emptied once.
The overview, rate limiting, compares the algorithms. This lesson is the implementation on a shared store: the Redis commands, where atomicity matters, and what goes wrong at the edges. It assumes distributed caches, Redis and Memcached and API design. How clients should behave when limited is in timeouts, retries, backoff and jitter.
Verified with the Redis documentation (latest version, read on 2026-12-01), RFC 6585, RFC 9110, Spring Boot 4.1.2 and Eclipse Temurin 25.0.3, on 2026-12-01.
The core idea
A rate limiter is a small piece of state per client plus one decision per request, and on a shared store the decision must be one indivisible step. The algorithm, key and status code are detail around that.
Three illustrations run through the lesson: the minimal example is five limiters in a lab, run against an in-memory model of Redis; the realistic example is ShopStream's partner API; the failure example is a counter that never expires.
Five limiters in terms of Redis
Stripe's engineers describe running four kinds of limiter in production, implemented with Redis, with a token bucket that has "a centralized bucket host where you take tokens on each request". Redis plays that host here.
| Algorithm | Redis state per client | Commands in the decision | Edge behaviour |
|---|---|---|---|
| Fixed window counter | a counter per window | INCR, EXPIRE |
up to twice the limit across a window edge |
| Sliding window log | a sorted set of request times | ZREMRANGEBYSCORE, ZCARD, ZADD |
exact, one entry per admitted request |
| Sliding window counter | two counters | GET, INCR, EXPIRE |
approximate, constant memory |
| Token bucket | a hash: tokens and last-refill time | read, arithmetic, write, EXPIRE |
bursts up to capacity, smooth refill |
| Leaky bucket (meter) | a hash: level and last-drain time | read, arithmetic, write, EXPIRE |
the same decisions as the token bucket |
Figure 1. Many instances, one shared limiter state. How to read this: every instance asks the same store, so the limit holds across the fleet. The store is a new dependency on the request path.
Fixed window. One key per client per window, such as rl:fw:alice:12345. INCR creates a missing key at 0 and returns the new value, so the first request of a window gets 1; a timeout set then makes Redis delete the key when the window is over. This is the first of the two patterns on the Redis INCR page. Its cost is the edge: the lab sends 5 requests just before a window ends and 5 just after against a limit of 5 per 10 seconds, and the fixed window admits all 10.
Sliding window log. A sorted set per client, scored by request time in milliseconds. Each request removes members at or below now - window (the range is inclusive), counts the rest with ZCARD, and adds itself only if under the limit. Members are unique and ZADD on an existing member only changes its score, so each request needs a unique member such as a request id. Scores are floating point and hold integers exactly up to 2 to the power 53, so millisecond timestamps are safe.
Sliding window counter. Two fixed-window counters, the previous weighted by its overlap with the sliding window. Cloudflare's example, a limit of 50 a minute: 42 requests last minute and 18 this minute (started 15 seconds ago) give 42 * ((60-15)/60) + 18 = 49.5. It assumes the previous window was evenly spread; Cloudflare reports that on 400 million requests from 270,000 sources 0.003% were wrongly allowed or limited, with an average 6% difference between real and approximate rate.
Token bucket and leaky bucket. The bucket stores tokens and a last-refill time. A request refills for the elapsed time (capped at capacity), then takes a token if one is there. The leaky bucket as a meter holds a level that drains at a constant rate; with level equal to capacity minus tokens it is the same arithmetic, and the lab shows identical decisions on a fixed sequence and on 20 random ones. The queue form of the leaky bucket, which delays instead of rejecting, is not modelled.
Figure 2. A token bucket decision. How to read this: the whole chain is one decision. If anything runs between the read and the write, two requests can use the same token.
Why atomicity is the whole game
Each Redis command is atomic; a sequence of commands from the application is not. The token bucket is a read, arithmetic in Java and a write, and between the read and the write another request can read the same state.
Figure 3. The read-decide-write race. How to read this: both reads happen before either write. At thousands of requests a second this is not a rare coincidence.
The INCR page makes the same point. Its second rate limiter reads the counter, increments it, and sets the expiry only when the value is 1; the page calls this a race condition, because if the client performs INCR but not EXPIRE the key is leaked. Its fix is a Lua script sent with EVAL:
local current
current = redis.call("incr",KEYS[1])
if current == 1 then
redis.call("expire",KEYS[1],1)
end
The scripting page says Redis guarantees a script's atomic execution: all server activity is blocked while it runs. Three rules follow for a limiter script.
- Declare the keys. Every key a script touches must be passed as a key argument (
KEYS), other inputs inARGV, and key names must not be built from data. This also keeps a script valid in a cluster. - Keep it short. The server is blocked while it runs: a few commands, no loops over unbounded data.
- Expect the script cache to be lost. It is volatile and can vanish on restart or failover. Clients call
EVALSHAand load the script on aNOSCRIPTreply; most client libraries do this for you.
Time, keys and memory
Whose clock? Instances with skewed clocks disagree about which window a request belongs to. Reading the time from Redis inside the script removes that; the scripting page says that with effects replication, the default since Redis 5.0, commands such as TIME can be used freely in scripts.
Keys. One key per client per algorithm, such as rl:tb:alice, keyed by an authenticated principal or API key; an IP address is only a fallback, since many users can share one.
Memory. Without a timeout every client that ever called leaves a key behind. EXPIRE deletes the key after the timeout. INCR and HSET leave the timeout alone; SET and DEL clear it. For a token bucket the right timeout is the time to refill fully, because after that the state is the same as none.
Answering a rejected request
RFC 6585 defines 429 Too Many Requests as "the user has sent too many requests in a given amount of time", says the response should explain the condition and may include Retry-After, does not define how the server identifies the user or counts requests, and says a 429 must not be stored by a cache. RFC 9110 defines the header as Retry-After = HTTP-date / delay-seconds. A token bucket knows when the next token arrives and a log knows when its oldest entry leaves, so both can give an honest value; the lab rounds up to whole seconds, minimum 1.
Stripe's article treats 429 against 503 as a choice of which is more accurate: 429 blames one caller, 503 says the service cannot cope, the case in load shedding and retry storms. The response body belongs to the problem-details lesson, written separately.
In Spring MVC a HandlerInterceptor can be registered with InterceptorRegistry, with path patterns to include or exclude; the lab's interceptor asks the limiter in preHandle and returns false after writing the 429, so the controller is not called (a test checks that). The Spring documentation says interceptors are a poor security layer because of possible mismatches with annotated controller path matching, and recommends Spring Security or a servlet filter applied as early as possible. To limit abuse of unauthenticated routes, apply the check in a filter or at the API gateway.
When the store is down
A limiter on Redis adds a failure: what does a request do when the limiter cannot answer? Fail open serves it unchecked, keeping the API up and removing protection exactly when the system may be stressed. Fail closed refuses with 503, protecting the backend and turning a limiter outage into an API outage. A login endpoint may fail closed; a read-only catalogue may fail open.
Build it: five limiters on a model of Redis, behind Spring MVC
This is the minimal example. Goal: see each algorithm's decisions, the window-edge difference, the race, the counter that never expires and the two failure policies. What it is not: there is no Redis and no Docker. RedisModel is an in-memory model of about a dozen commands (INCR, EXPIRE, GET, SET, HGET, HSET, ZADD, ZREMRANGEBYSCORE, ZCARD, TIME, PTTL, EVAL). Each command is atomic because it runs under one Java monitor, and eval runs a Java function under that monitor as the model of a Lua script. It has no network, persistence, replication, cluster or Lua interpreter, so it says nothing about Redis latency, memory or failover. Time is a clock the test moves by hand, the client id comes from an X-Client-Id header standing in for authentication, and the controller runs behind MockMvc.
Setup. From the repository (Docker is not needed):
cd examples/spring-labs
./gradlew :labs:rate-limiter-redis-model:test
It runs 16 tests, one of which compares the report below with the golden file examples/spring-labs/golden/rate-limiter-redis-model.txt. The code is in examples/spring-labs/labs/rate-limiter-redis-model/. The token bucket is the whole decision inside one eval, in integer thousandths of a token:
return redis.eval(r -> {
long now = r.timeMillis();
String tokens = r.hget(key, "tokens");
String ts = r.hget(key, "ts");
BucketMath.State before = tokens == null
? new BucketMath.State(capacity * BucketMath.ONE, now)
: new BucketMath.State(Long.parseLong(tokens), Long.parseLong(ts));
BucketMath.Step step = BucketMath.take(before, now, capacity, refillPerSecond);
r.hset(key, "tokens", Long.toString(step.next().milliTokens()));
r.hset(key, "ts", Long.toString(now));
r.expire(key, BucketMath.secondsToFull(step.next().milliTokens(), capacity, refillPerSecond));
return step.allowed()
? Decision.admit(step.next().milliTokens() / BucketMath.ONE)
: Decision.reject(BucketMath.retryAfterMillis(step.next().milliTokens(), refillPerSecond));
});
The interceptor answers a rejection with 429 and Retry-After in whole seconds and does not call the controller.
Scenario 1: the window edge. The same ten requests (5 just before a 10-second window ends, 5 just after) through each algorithm; the last column is how many keys the store holds afterwards.
Expected output, captured from a real run (Spring Boot 4.1.2, Java 25, 2026-12-01):
== 2. The window edge: 5 requests at t+9.9 s and 5 more at t+10.1 s, limit 5 per 10 s
algorithm at 9.9 s at 10.1 s in 0.2 s keys
fixed window 5 5 10 2
sliding window log 5 0 5 1
sliding window counter 5 0 5 1
token bucket (5, 1/s) 5 0 5 1
leaky meter (5, 1/s) 5 0 5 1
Scenario 2: the race and the script. The race is a deterministic interleaving: request B is served between A's read and A's write. Then the same bucket as one script, and 32 threads against one script.
Expected output, captured from a real run (the same run):
== 4. Read, decide, write as separate commands, against one atomic script (capacity 1)
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
Scenario 3: the counter that never expires. INCR and EXPIRE as two commands, with a hook that stands for the process dying between them. In this algorithm a leaked counter that has reached the limit also blocks the client for ever.
Expected output, captured from a real run (the same run):
== 5. INCR and EXPIRE as two commands: the client dies in between (limit 3 per 60 s)
request 1: client crashed between INCR and EXPIRE
counter timeout (-1 means none): -1
request 2: admitted
request 3: admitted
request 4: rejected
request 5: rejected
one hour later: rejected, counter timeout: -1
INCR and EXPIRE in one script, same four requests, one hour later: admitted, keys in the store: 1 (the new request's)
Scenario 4: the store is down. With the policy fail open, three requests are all served and counted as unchecked; fail closed answers 503 each time. Both recover when the store returns.
Expected output, captured from a real run (the same run):
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
Break it. In FixedWindowLimiter.tryAcquire, delete the r.expire(...) call and its if: counters are never removed and GoldenRunTest fails on the key count. Restore the code and run the tests again.
Left out: a real Redis, a Lua script (the model runs Java), Redis Cluster, replication, persistence, network latency, the queue form of the leaky bucket, and per-route or per-tier limits.
Trade-offs
| Choice | Gain | Cost | Wrong when |
|---|---|---|---|
| Fixed window | One counter, trivial | Up to twice the limit at an edge | The target cannot take a double burst |
| Sliding window log | Exact | Memory grows with the limit | The limit is in the thousands per window |
| Sliding window counter | Small, close to exact | Assumes even spacing | You need a hard guarantee |
| Token bucket | Bursts allowed, smooth average | Two numbers per client and a script | Bursts must be forbidden |
| Script on the server | Atomic, one round trip | Logic lives in Redis; cache needs care | The team cannot test or version Lua |
| Fail open | API stays up | No protection in an outage | The limit guards credentials or money |
In practice: a partner API with a limit per partner
This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company, and every number is illustrative.
This is a realistic scenario, not a case history.
The situation
ShopStream offers a catalogue API to partner shops. One partner's nightly import requests every product page as fast as it can, and the catalogue slows down for everyone at 02:00.
Starting architecture
Figure 4. The limiter in front of the catalogue. How to read this: the gateway asks Redis for a decision before anything reaches the catalogue; rejected requests cost the service nothing.
Options considered
| Option | Behaviour | Risk |
|---|---|---|
| A. Ask the partner to slow down | No change on ShopStream's side | Nothing enforces it |
| B. Fixed window, 100 per second per partner | Cheap | A partner can send 200 across an edge |
| C. Token bucket per partner, burst 50, 20 per second | Bursts allowed, average bounded | A script and a state store to run |
The decision
Option C at the gateway, keyed by the partner's API key. Rejections are 429 with Retry-After, and importers are told to wait that long, with jitter. The read-only catalogue fails open if Redis is unreachable, with an alert on unchecked requests, because a total outage costs more than a slow night.
Rollout and verification
Start in log-only mode, counting what would have been rejected per partner; then enforce for the heaviest partner, then everyone. In production watch rejected requests per partner, unchecked requests (should be zero) and the latency the limiter adds.
The 2 a.m. failure
After a Redis failover the script cache is empty and clients calling EVALSHA get NOSCRIPT. One code path treated any error as "store down" and failed open, so for ten minutes the heavy partner was not limited. The checks are the unchecked-request counter and the error type behind it; the mitigation is to load the script and retry. The lasting fix is to handle NOSCRIPT explicitly in the one wrapper everything uses, and to alert when the fail-open counter rises.
Architect's notes
- Choose the algorithm by the edge behaviour you want: bursts, exactness or cheapness.
- One script per decision, all keys declared, time taken from the store.
- Decide fail open or closed per route, and measure unchecked requests.
Common mistakes
- Read, decide, write as separate commands. Two requests take the same token.
INCRwithout a guaranteedEXPIRE. A crash leaves a counter that never goes away.- A repeated member in the sorted set.
ZADDupdates its score instead of adding a request, so the count is too low. - One catch-all for limiter errors. A missing script, a timeout and an unreachable server need different handling.
Key takeaways
- On a shared store the decision is one atomic step: a Lua script, not a chain of commands.
- Each algorithm maps to a Redis shape: counters, a sorted set, or a hash with arithmetic.
- The token bucket and the leaky bucket meter decide alike; a fixed window can admit twice the limit at an edge.
- Give every key a timeout, answer with
429andRetry-After, and decide what happens when the limiter is down. - The lab models Redis in memory and shows the logic, not real Redis behaviour.
Practice exercises
Exercise 1 (30 min). For a limit of 100 a minute and a client that sends 100 requests at second 59 and 100 at second 61, count what each algorithm admits.
Exercise 2 (45 min). Run the lab. Make SlidingWindowLogLimiter use the same member for every request and explain what the count does.
Exercise 3 (1 hour). Write the token bucket as a Lua script from the Redis scripting and command pages, run it on a Redis you have, and compare its decisions with the lab's. This lesson ran no Lua.
Exercise 4 (1 hour). For ShopStream's login, catalogue read and checkout endpoints, choose fail open or closed and say what you would alert on.
Related reading
- Rate limiting: the overview, with where to enforce limits.
- Distributed caches, Redis and Memcached: the store these limiters run on.
- Load shedding and retry storms: the
503side. - API gateway pattern: the usual place to enforce 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, INCR: counters and the two rate limiter patterns.
- Redis, Scripting with Lua: atomic execution,
KEYSandARGV, the script cache. - Redis, EXPIRE and ZADD.
- IETF, RFC 6585: 429 Too Many Requests.
- Spring Framework, Interceptors.