How to design a rate limiter that survives an OTP attack
Why a counter in memory lets 9 requests through when the limit is 3, and the design that fixes it step by step: shared state, sliding windows, one atomic check, layered keys and a plan for when Redis fails.
12:03 video11 min read
- 3 architecture diagrams
- 1 sequence flow
- 1 API design
- 3 self-checks
9
codes sent when the limit was 3 (three servers)
60
codes through with 20 servers
1
atomic step that makes the check safe
1,000,000
possible six-digit codes to guess
On this page11 sectionsHLDLLDSenior depth
- Why a per-server counter fails as soon as there are two servers.
- Fixed window, sliding window and stacked windows, and when each fits.
- Why the check and the update must be one atomic operation.
- How to layer keys, place the limiter, and plan for Redis failing.
Chapters
- 0:00The attack (opens the video at this moment on YouTube)
- 0:57The counter that lies (opens the video at this moment on YouTube)
- 2:07One shared memory (opens the video at this moment on YouTube)
- 3:03Counting time: fixed vs sliding window (opens the video at this moment on YouTube)
- 4:40The race condition and the 429 (opens the video at this moment on YouTube)
- 6:19Who are you counting? (opens the video at this moment on YouTube)
- 7:57Where it lives: API gateway vs service (opens the video at this moment on YouTube)
- 8:42When Redis goes down (opens the video at this moment on YouTube)
- 10:01The attack that never hits a limit (opens the video at this moment on YouTube)
- 11:11Coordinating decisions (opens the video at this moment on YouTube)
Put a limit on it. That is the first thing anyone says when a login endpoint is under attack, and it sounds like a one-line fix. This post follows a hypothetical one-time-password (OTP) endpoint through the ways a simple limit fails, and the design that fixes each failure in turn. The scenario is illustrative: a company that texts six-digit login codes, where every request costs real money and buzzes a real phone.
The first version everyone writes is a map in memory: phone number in, count out, block above three per minute. On a laptop it is perfect. In production there is a load balancer and several copies of the app.
No server has a bug. Each counted correctly what it saw. With 20 servers, up to 60 codes get through, so every machine you add to handle traffic makes the limit weaker.
If every server needs the same answer, the count cannot live in any of them. Look at the data: a counter is a few bytes, written on every request, and worthless a minute later. You do not need a database that keeps things forever; you need something fast that forgets on purpose. That is a good fit for Redis: it keeps data in memory so a lookup is cheap enough to run before every login, it can increment a number in one command, and any key can carry a time to live.
The same nine requests now produce one, two, three, and a refusal from the fourth, whichever server it came through.
"Three per minute" sounds precise until you ask which minute.
A fixed window cuts time into one-minute buckets with one counter each. It is simple and cheap, and it has an edge:
window 1 (12:00:00 - 12:00:59) window 2 (12:01:00 - 12:01:59)
|..............................3 requests| 3 requests|.............|
12:00:59 12:01:00
six requests in about two seconds, and no rule was brokenA sliding window has no buckets. It asks how many requests arrived in the last 60 seconds, counted back from now, so there is no reset to time an attack around. In Redis, a sorted set per key does this: store each request with its timestamp, remove entries older than the window, count what is left, and add the new request only if there is room. The cost is memory, one entry per request. A popular compromise keeps two counters (this window and the last) and blends them into an estimate: slightly fuzzy, very cheap.
| Approach | Memory per key | Accuracy | Use when |
|---|---|---|---|
| Fixed window counter | One number | Allows up to double the limit at a boundary | Coarse limits where a burst is acceptable |
| Sliding window log | One entry per request | Exact | Small limits where abuse is expensive, such as OTP |
| Sliding window counter | Two numbers | Approximate | High-volume limits where memory matters |
For an OTP endpoint one window is not enough. Three per minute stops a burst; it does not stop a patient bot sending three every minute all day. So OTP limits usually stack windows on the same key: a short one for bursts and longer ones for the hour and the day.
Two servers can each follow the rules and still break them together. The steps are: read the count, compare it with the limit, write the new count.
Nothing errors. This is a race condition, and it lives in the gap between checking a value and acting on it. In normal traffic two requests for the same number almost never overlap. In an attack, overlap is all there is.
The fix is to make checking and writing a single step. For a fixed window, Redis can do this with an increment that returns the new total, so you never read first, but attach the expiry in the same atomic step: Redis's own documentation points out that an increment followed by a separate expire can leak a key that never expires if the client dies in between. For a sliding window, hand Redis a short Lua script. Redis runs a script start to finish before it touches anything else, so no other request can slip in between the steps.
-- KEYS[1] = the counter key, such as otp:{+15551234567}
-- ARGV[1] = window in milliseconds, ARGV[2] = limit, ARGV[3] = a unique id for this request
local t = redis.call('TIME')
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, now - tonumber(ARGV[1]))
if redis.call('ZCARD', KEYS[1]) < tonumber(ARGV[2]) then
redis.call('ZADD', KEYS[1], now, ARGV[3])
redis.call('PEXPIRE', KEYS[1], ARGV[1])
return 1
end
return 0It uses Redis's own clock so servers with skewed clocks cannot disagree about the window. A refused request stops right there, before a single message is paid for, and the client receives a 429 with a hint about when to retry.
- body
- { "phone": "+15551234567" }
- 200code sent
- 429too many requests; the Retry-After header says how many seconds to wait
A real app shows a countdown. A bot ignores it and keeps getting the same answer.
The key you count by decides which attackers you can even see.
| Key | Catches | Weakness |
|---|---|---|
| Phone number | Flooding one victim | A bot that sends one code each to 30,000 numbers never trips it |
| IP address | One machine hitting many numbers | Bots rotate addresses; a carrier or office puts thousands of people behind one IP |
| Device or session | A guest rotating numbers and addresses | Can be faked or cleared |
| Account | Logged-in abuse; expensive to fake in bulk, so its limit can be looser | Does not cover guests |
| Destination country | Spray attacks at expensive international numbers, where only the total looks wrong | Needs a global key (see below) |
No single key works, so check several. Two practical catches. In a Redis cluster, a script can only touch keys that live in the same hash slot, so each layer gets its own atomic check; a request may be counted by the phone layer and then blocked by the IP layer, and being slightly too strict during an attack is fine. Also, every request for a country hits one global key on one machine, which is a hot key. Split it into several small counters and add them up, or let each server count locally and flush to Redis every second or so: a little less exact, and nothing melts.
Stop bad traffic as early as you can, but only where you know enough to judge it.
The IP check needs only the connection, so it goes out front. The phone number check has to read the body and the account check has to know who is logged in, so those live next to the OTP service. Neither tier holds state, so adding gateway nodes or app servers does not change the math: twenty servers still mean three codes, not sixty.
The limiter now sits in front of every login, so it needs a failure plan of its own. There are two obvious moves. Fail open lets everything through: logins keep working and you are defenseless, possibly during the attack the limiter exists for. Fail closed blocks everything: nothing is abused and nobody logs in. Most endpoints fail open; a few minutes without limits beat an outage, and Stripe's engineering team recommends failing open when a limiter breaks. This endpoint is different, because every request let through is a message someone pays for.
So bring back the counter that failed in the first chapter: when Redis is unreachable, each server falls back to its own in-memory counter with a much tighter limit. It is no longer globally exact, but for a few minutes of outage a conservative local limit beats letting everything in. Two pieces make the switch clean: a short timeout on every Redis call so a slow Redis cannot stall every login, and a circuit breaker.
| Breaker state | Behaviour |
|---|---|
| Closed | Calls go to Redis as normal |
| Open | After enough failures, calls skip Redis and use the local fallback for a while |
| Half-open | One trial request checks whether Redis is back; success closes the breaker |
One bot gets past every limit above. It is patient, rotates addresses, sends one code per number, and stays under every threshold. Every layer checks its own key and sees nothing wrong. One ratio gives it away: codes sent against codes verified. A real person requests a code and types it in seconds later. A bot texting numbers it does not own never verifies anything. When sends keep climbing and verifications stay flat, that gap is a strong signal of abuse even with every limit green.
So the limiter cannot block quietly. Count every block by layer, country code and network; track sent against verified; alert on the gap; then act on the bad slice only by tightening one country code, challenging suspicious traffic, or blocking a hostile range at the gateway, while everyone else keeps logging in. The other side of the door needs a limit too: a six-digit code has a million possible values, so without a cap on wrong guesses per code a bot can simply keep guessing.
QuestionA limit of 3 per minute lets 9 requests through with three servers. Why, and what is the first fix?Reveal answer
Each server counts only what it saw, and the load balancer spreads the requests, so each allows 3. The first fix is to move the count to a shared store that every server consults.
QuestionWhy is "read the count, compare, write it back" unsafe even with a shared store?Reveal answer
Two requests can read the same value at the same moment, both see room, and both write, so the count ends above the limit. The check and the update must be a single atomic operation, such as an atomic increment or a Lua script.
QuestionThe OTP bot sends one code per number and stays under every limit. How do you catch it?Reveal answer
Compare codes sent with codes verified. Real users verify within seconds; a bot texting numbers it does not own never verifies. A growing gap between sends and verifications signals abuse even when every counter looks normal.
The rate limiting lesson covers token buckets and the algorithms in more depth, and you can break a distributed limiter yourself in the 3D rate limiter lab. The caching lesson explains hot keys, which also appear in the country counter above.
- Redis documentation, INCR (opens in a new tab): the rate limiter pattern, including why an increment and a separate expire can leak a key.
- Redis documentation, Redis rate limiter (opens in a new tab): fixed and sliding window approaches.
- Redis documentation, Redis cluster specification (opens in a new tab): hash slots and why multi-key operations need keys in one slot.
- Stripe engineering, Scaling your API with rate limiters (opens in a new tab): token buckets backed by Redis, and failing open.
Spot a mistake, or have a question?
Accuracy matters here. Tell me what looks wrong or unclear and I will fix it and credit you.