Chapter 18 / 24 · System Design

Rate limiting and abuse protection

An OTP endpoint, a script and an SMS bill: deciding how much each caller may ask for, keying limits on what attackers cannot vary, and counting across many machines.

This chapter lets you decide how much each caller may ask of Dabba, enforce that decision at the right layer, and keep enforcing it when the API runs on many machines. It also separates two jobs that are often confused: limiting a caller, and protecting the whole system when it is overloaded.

The situation that forces the question is the login screen. Dabba logs customers in with a one-time password sent by SMS. Each OTP costs Dabba a fraction of a rupee and lands on a real person’s phone. One Tuesday night a script calls POST /auth/otp for hundreds of thousands of phone numbers, a few hundred a second, from a few thousand IP addresses. By morning the SMS bill for the night is several times the monthly budget, thousands of people have received codes they did not request, and the SMS gateway has throttled Dabba’s account, which means real customers at breakfast cannot log in.

Nothing in the system was broken. Every request was well formed and every one did exactly what the code said. What was missing was a rule about how much is too much, written down before someone else decided it for us.

Start from what a request costs

A single limit for “the API” cannot be right, because Dabba’s endpoints cost very different amounts and attract very different abuse. The design starts by pricing them.

EndpointWhat one call costsAbuse it attractsWho should share a limit
POST /auth/otpmoney per SMS, a stranger’s phoneSMS pumping, harassment, account probingthe phone number; also device and IP
POST /auth/verifylittle, but guesses unlock accountsbrute-forcing 6-digit codesthe phone number’s pending OTP
GET /restaurants, menuscheap, mostly cachedcompetitors scraping pricesdevice or API client
POST /orderspayment call, restaurant loadfake orders, card testingthe account, and the payment instrument
Order tracking (SSE)an open connection, plus a status fetch on reconnectour own app reconnecting in a loopthe session

Two things fall out of the table. The key (who shares a bucket) differs per endpoint, and for the most expensive endpoint it is not the caller at all but the victim: the phone number receiving the SMS. And the most abused endpoints are not the busiest ones. Menu browsing is the bulk of Dabba’s traffic and needs only coarse limits. The OTP endpoint is a tiny fraction of the traffic and needs the most careful ones.

Brute force on verification deserves its own arithmetic. A 6-digit code has a million values. If an attacker may try 10 codes per minute against one phone number and the code lives for 5 minutes, they get 50 guesses, a 1 in 20,000 chance per code issued. If the verify endpoint has no limit and the attacker can try 1,000 a second, they will find the code in about eight minutes on average, which a 5-minute expiry only partly blocks. The right limit here is per pending code, not per minute: five wrong guesses and the code is burned, and a new one must be requested, which runs into the send limit.

A rate and a burst: the token bucket

Most limiters in production are some form of token bucket. Each key has a bucket holding at most b tokens. Tokens are added at a steady rate r. A request takes one token if there is one and is refused if there is not. The two numbers answer the two real questions: what long-run rate do we allow, and how large a burst do we forgive. A customer who opens the app and taps through five restaurants in three seconds is a burst, and that is normal. A script that does it every three seconds all night is a rate, and that is not.

refill r = 1 per 30 scapacity b = 5 tokenseach request spends one · none left → 429500 s60 s120 s180 s✕✕tokens over time · ticks = requests let through · ✕ = refusedbursts are allowed up to b; the long-run rate never exceeds r
Fig · A bucket of 5 refilling one token every 30 seconds. Five quick requests pass, the sixth is refused, and later requests pass as tokens trickle back

The implementation stores only two numbers per key: the token count and the time of the last update. There is no background process adding tokens. Each request computes how many tokens would have arrived since the last update, adds them up to the cap, and then spends.

def allow(key, now, rate, burst):
    tokens, last = store.get(key, default=(burst, now))
    tokens = min(burst, tokens + (now - last) * rate)
    if tokens < 1:
        store.put(key, (tokens, now))
        return False, (1 - tokens) / rate      # seconds until next token
    store.put(key, (tokens - 1, now))
    return True, 0

The second return value is not decoration. It is the honest Retry-After for a refused request, and it lets a well-written client wait exactly as long as it needs to.

Predict first

An older Dabba service uses a fixed window instead: “at most 10 requests per key per calendar minute”, with a counter that resets at :00. What is the most requests one key can make within any 2-second span?

Show the worked answer

Twenty. The client sends 10 requests at 20:00:59 and 10 more at 20:01:00. Each batch is within its own minute’s limit, and together they are twice the intended rate inside two seconds. For a coarse cap on browsing traffic that may not matter. For an OTP endpoint it means the limit is really 20, not 10, at the moment an attacker chooses.

The sliding-window variants fix this. A sliding log keeps the timestamp of every request in the last minute and counts them; it is exact and costs memory per request. A sliding window counter keeps this minute’s and last minute’s counts and estimates the rolling total as current + previous × (fraction of the previous window still inside the last 60 s); it is approximate, costs two numbers per key, and is accurate enough for almost every use. The token bucket avoids the boundary entirely, because it has no windows.

AlgorithmState per keyWhat it gets rightWhat it gets wrong
Fixed windowone countertrivial, cheap to explainallows 2× the limit across a boundary
Sliding loga timestamp per requestexactmemory grows with the limit; costly for high limits
Sliding window countertwo counterssmooth, cheap, close to exactan estimate; can be off when traffic is very uneven
Token bucketcount and timestampseparate knobs for rate and bursta full bucket allows a burst some endpoints should not

For Dabba’s OTP send we use small buckets with slow refill and a hard daily ceiling: per phone number, a burst of 3 and one new token every 10 minutes, plus no more than 10 per day. For menu browsing, per device, a generous burst of 60 and a rate of 5 a second. These numbers are not derived from first principles. They come from looking at what real customers do (the 99.9th percentile of honest users) and setting the limit comfortably above it, then watching how many honest users hit it.

Walk-through: the limit that did not stop the attack

After the Tuesday incident, Dabba adds a per-phone-number limit on OTP sends: three per 10 minutes. It works against the first script, which retried the same numbers. A week later the bill rises again. Walk through what the attacker changed.

The new traffic sends exactly one OTP per number, so no number ever reaches its limit. The numbers are not random. They fall in a few ranges, many outside India, that belong to carriers paying a share of termination fees to whoever generates traffic to them. This is SMS pumping (also called toll fraud): the attacker does not want the codes at all; they are paid per message that Dabba sends. A per-number limit cannot stop it, because every number is fresh. A per-IP limit fails too: the traffic comes through residential proxies, a few requests per IP.

The fix comes from asking what the attack needs rather than who sends it. It needs Dabba to send messages to many numbers in a few ranges. So the design adds limits keyed on the thing the attacker cannot vary cheaply. Dabba only operates in India, so OTPs to non-Indian numbers are refused outright. Sends are counted per number prefix (the first several digits), with alerts when a prefix suddenly sees far more sends than its history. A global ceiling on OTP sends per minute, set at a few times the busiest honest minute, acts as a circuit breaker on spend: when it trips, new OTP requests get a challenge (a CAPTCHA or app-attestation check) instead of an SMS. And the conversion rate is watched: honest OTPs are mostly verified within a minute, pumped ones almost never are.

Each of these has a cost. The country restriction blocks a customer visiting from abroad with a foreign SIM. The prefix alert produces false alarms when a new carrier range is legitimately popular. The global ceiling, when it trips, puts a challenge in front of honest users at the worst moment, so it is set high and treated as an alarm rather than a routine control. The general lesson is that a rate limit is keyed on an identity, and an attacker chooses which identities to present. The limits that hold are the ones keyed on something expensive for them to change.

A note on IP addresses in India in particular. Most mobile users sit behind carrier-grade NAT, where thousands of phones share a small pool of public IPv4 addresses. A per-IP limit tight enough to slow an attacker will block a neighbourhood of honest customers during dinner. Per-IP limits are still useful as a very coarse outer layer (no single address should send 500 requests a second), but they cannot be the main control. Devices, accounts and phone numbers are better keys, and IPv6 addresses, which are more often per device, help a little.

Enforce where the request is still cheap

A limit enforced after the work is done protects nothing. If the order service checks the limit after it has called the payment provider, the expensive part has already happened. The rule is to enforce each limit at the earliest point that has the information it needs.

That gives three layers in Dabba. At the edge (the CDN or a web application firewall), coarse per-IP limits and known-bad-client rules absorb floods before they reach any of our machines; the edge knows only the IP, headers and path, so that is all it can key on. At the API gateway, after the access token has been checked, per-account and per-device limits run; this is where most limits live, because the gateway knows who the caller is and has not yet spent anything. Inside the services, business limits run, the ones that need domain data: no more than three unpaid orders per account, no more than five cancellations a day, at most one refund request per order. These are not about request rates at all. They are invariants, and they belong next to the data they protect.

Counting across thirty API servers

Dabba’s API tier, from the first chapter, is 30 servers behind a load balancer. A customer’s requests land on different servers. If each server keeps its own buckets in memory, a limit of 5 per second per device becomes, in the worst case, 5 per second per server: 150 per second. In practice the load balancer spreads one client’s requests across several servers, not all 30, so the real error is smaller, but it is unpredictable.

The usual fix is a shared counter store, typically Redis, holding the buckets. The check and the spend must happen as one atomic operation. A gateway that reads the count, decides, and then writes back lets two machines both read “1 token left”, both allow, and both write 0. Redis makes the atomic version easy with a short script that runs the refill-and-spend logic server side, or with an atomic increment for window counters.

The shared store has costs we should state. Each request now waits for a network round trip to Redis, typically well under a millisecond inside one data centre, but not zero. In the dinner hour Dabba’s API handles about 4,200 requests a second and is designed for 10,000, plus 10,000 rider location updates a second, and each request checked against Redis is one Redis operation. That is comfortably within what a small Redis cluster handles, but it is a cluster to run, shard by key, and monitor. Rider location updates, which come from authenticated riders on a fixed 5-second schedule, are a reasonable place to skip the shared check and use a local, generous limit instead.

The harder question is what happens when Redis is unavailable. If the limiter fails closed, refusing all requests, a cache outage becomes a full outage. If it fails open, allowing everything, the OTP endpoint is unprotected exactly when something is already wrong. Dabba chooses per endpoint: browsing and order tracking fail open, falling back to each gateway’s local buckets; OTP sending falls back to strict local limits plus the global spend ceiling, which is tracked separately. A limiter is a dependency like any other, and the failure chapter’s rules about timeouts apply to it too: a 2 ms timeout on the limiter call, after which the fallback decides.

A middle path avoids the per-request round trip. Each gateway keeps local buckets and periodically (every few hundred milliseconds) reports its counts to the shared store and pulls back the global totals. Limits become approximately right within that sync interval. For a limit like “5 per second per device” that error is acceptable; for “10 OTPs per day per number” it is irrelevant, since the window is a day. Precision is a cost to buy where it pays.

Refuse in a way clients can obey

When a request is refused, the response is part of the API and will be depended on. Dabba returns 429 Too Many Requests with a Retry-After header taken from the limiter’s calculation, and on the endpoints partners use, headers stating the limit, what remains and when it resets. The point is to let a well-behaved client slow down before it is refused, not only after.

The most frequent abuser of an API is often its own client. Imagine a Dabba app release with a bug: when the order-tracking SSE connection drops, it reconnects and refetches the order immediately, with no delay. A small backend hiccup at 20:00 drops every open tracking screen, tens of thousands of them at dinner (about 88,000 orders are in flight at peak), and they all reconnect as fast as the network allows, over and over. The per-session limit on tracking turns that into a bounded load the backend can survive, and the 429 with Retry-After tells the app how to recover. The real fix is in the app (backoff with jitter, and honouring Retry-After), but app updates take weeks to reach most phones, and the server-side limit is what protects Dabba during those weeks.

One distinction to keep. A rate limit protects the system from one caller using more than its share. It does nothing when the total of everyone’s fair share exceeds capacity, as on a festival night when every customer is honestly ordering. That needs load shedding: refusing some work, chosen by priority, based on how loaded the system is rather than who is asking. Stripe’s engineering post in this chapter’s reading describes running both side by side. Dabba’s version appears in the failure chapter.

When a rate limit is the wrong tool

Do not rate limit traffic you must not drop. The payment provider’s webhook, telling Dabba a payment was captured, arrives in bursts at dinner. A limiter that refuses some of those calls causes paid orders to sit as unpaid until the provider retries, if it retries. Webhook endpoints need capacity and a queue behind them, not a limit in front.

Rate limits also do little against slow, distributed attacks. Credential stuffing across a million accounts at one attempt per account per day, from a million IPs, stays under every per-key limit. That is a detection problem (unusual success-to-failure ratios, device fingerprints, impossible travel) more than a limiting one. And limits that are tighter than honest peak behaviour create the outage they were meant to prevent: a festival evening when many customers retry a slow checkout is not abuse. Revisit limits after every large sale or festival using the real distribution of honest traffic, not the numbers chosen at launch.

Every limit in this chapter is keyed on an identity: an account, a device, a phone number. A limit keyed on an identity is only as good as our confidence in that identity. The next chapter, on security, is about establishing who is calling, and what each of Dabba’s three kinds of user may see and do once we know.