Rate Limiting: Algorithms, Distributed Rate Limiting, and How It Differs from Load Shedding
System Design series · Part 6 Reliability (4 of 5)
- Redundancy, Failover, and Disaster Recovery: From Availability Numbers to Restore Drills
- Timeouts, Retries, Backoff, and Jitter: How Retries Save a System, and How They Bring It Down
- Circuit Breakers and Bulkheads: Keep One Broken Downstream from Taking Down the Whole System
- Rate Limiting: Algorithms, Distributed Rate Limiting, and How It Differs from Load Shedding
- Observability: Metrics, Logs, Traces, and SLOs, from 'It Seems Slow' to Finding the Cause
System Design series Part 6-4 | Previous: Circuit Breakers and Bulkheads | Next: Observability | Series map
Scenario and problem
The talk platform has run into a few problems lately:
- The moment sign-ups open for a popular talk, someone uses a script to send over a thousand sign-up requests a second. The seats are gone within 2 seconds, before real users have even loaded the page
- A partner’s system has a bug that keeps calling the query API in a loop, 5,000 requests a second, and it slows everyone down
- The login API receives tens of thousands of attempts a minute, with usernames and passwords taken from data leaked by other sites (credential stuffing)
- The SMS verification code API is called in huge volume, sending codes to premium-rate numbers abroad, and burns tens of thousands of NT dollars in SMS fees in one night
- The ticket botThe moment sign-ups open for a popular talk, someone uses a script to send over a thousand sign-up requests a second. The seats are gone within 2 seconds, before real users have even loaded the page.
- A partner's bugA partner's system has a bug that keeps calling the query API in a loop, 5,000 requests a second, and it slows everyone down.
- Credential stuffingThe login API receives tens of thousands of attempts a minute, with usernames and passwords taken from data leaked by other sites.
- The SMS bill burns upThe SMS verification code API is called in huge volume, the codes go to premium-rate numbers abroad, and tens of thousands of NT dollars in SMS fees burn up in one night.
The circuit breakers and bulkheads in the previous post protect “the downstream services I call”. This post protects the service itself: limit how many resources each caller can use up, so that one caller’s behavior does not affect anyone else.
The simplest approach and its limits
In the memory of each application server, keep a map of how many requests each user has sent this minute, and reject once the count goes over 100.
- With 4 servers each counting on their own, a user can actually send 400 requests (the “in-memory counter” problem from the stateless services post). Autoscale to 8 servers, and the limit quietly becomes 800
- “This minute” starts at the top of the minute, so a user can send 100 at 00:59 and another 100 at 01:00: 200 requests within 2 seconds
Core mechanism
Algorithms
Fixed window: one counter per time window (for example, per minute); reject once it goes over the limit.
- The simplest to implement: one Redis
INCRplus anEXPIREand you are done - The boundary problem: with a limit of 100 a minute, in the worst case 200 get through within 2 seconds
Sliding window log: record the timestamp of every request and count how many fall within the last 60 seconds.
- Exact, with no boundary problem
- Memory grows with the number of requests: 1 million users with a limit of 100 each need 1 million × 100 × 8 bytes = 800 MB for the timestamps alone
Sliding window counter: keep only two counters, “this minute” and “the previous minute”, and estimate from how much they overlap:
estimate = count this minute + count last minute × (fraction of last minute still inside the 60-second window)
At second 15 of this minute: this minute 40, last minute 80 → 40 + 80 × 45/60 = 100- Fixed memory, and the error is usually small, assuming the previous minute’s requests were spread evenly
Token bucket: the bucket holds at most C tokens and is refilled with R tokens a second. Each request takes one token, and when the bucket is empty, requests are rejected.
- Allows bursts: when the bucket is full, C requests can pass in a row, and after that they pass at R a second
- Each key needs only two values: the current number of tokens and the time of the last refill
- Different requests can cost different amounts: a normal query takes 1 token, a full-text search takes 5
Leaky bucket: requests enter a queue and flow out at a fixed rate. The output is very smooth, but requests have to wait in line, so it suits controlling the rate at which “I send to downstream services”, not a user-facing API.
| Algorithm | Bursts | Accuracy | State per key | Good for |
|---|---|---|---|---|
| Fixed window | Up to 2x at the boundary | Low | 1 counter | Rough quotas, such as a daily cap |
| Sliding window log | None | Exact | Grows with the number of requests | Very small limits, such as 5 password resets an hour |
| Sliding window counter | Very small | Approximate | 2 counters | General API rate limiting |
| Token bucket | Controlled (capacity C) | Exact | 2 values | API rate limiting that allows reasonable bursts, cost weighting |
| Leaky bucket | None, requests queue | Exact | A queue | Controlling the rate sent to downstream services |
What to use as the key
The rate limiting key decides “who” gets limited:
| Key | Pros | Problems |
|---|---|---|
| IP address | Works without logging in | Many users at a company, a school, or on a mobile network share one IP (carrier-grade NAT); attackers can rotate through many IPs; IPv6 lets anyone have a huge number of addresses |
| User ID | Maps exactly to a person | Only works after login |
| API key or tenant | Suits partners and paid plans | When a key leaks, the attacker spends someone else’s quota |
| Endpoint | Protects especially expensive APIs | Without telling callers apart, one person can use up everyone’s quota |
In practice you combine them: unauthenticated requests are limited by IP (by /64 prefix for IPv6), logged-in requests by user, partners by API key, and expensive endpoints get their own limit on top.
Distributed rate limiting
For several servers to share one count, the most common approach is to keep it in Redis:
- Reading, computing, and writing back must be atomic: with a
GETfollowed by aSET, two servers can both read “1 left” and both let their request through. Use a Lua script so the whole logic runs inside Redis in one go - Redis’s clock is the reference: every application server’s clock drifts a little, so the script uses Redis’s
TIME - One more Redis round trip per request: usually under 1 ms within the same availability zone, but Redis itself becomes a dependency of every request
- Hot keys: a global limit like “at most 10,000 requests a second for the whole API” has only one key, which lands on a single shard of Redis Cluster. You can split it into several sub-keys, or use an approximate local limit on each server
What to do when Redis fails depends on what the rate limit is for:
- Abuse prevention and security (login, SMS verification codes, password reset): reject requests (fail closed). Letting them through means an attacker only has to knock Redis over first to get unlimited attempts
- Fair sharing and capacity protection (general APIs): fall back to a conservative local limit on each server, instead of letting everything through or rejecting everything
429 and response headers
A rate-limited request gets 429 Too Many Requests, with Retry-After telling the client how long to wait before trying again (RFC 6585). A well-behaved client waits that long instead of retrying right away (the Timeouts and Retries post).
Should you tell clients how much quota they have left? Many APIs use non-standard headers such as X-RateLimit-Remaining. The IETF httpapi working group is defining standard RateLimit and RateLimit-Policy headers, and as of draft-11 in May 2026 they are still a draft. For partner APIs, publishing the quota helps partners pace their calls; for limits that prevent abuse, do not tell attackers how many tries they have left.
Rate limiting and load shedding
Both reject requests, but for different purposes:
| Rate limiting | Load shedding | |
|---|---|---|
| Based on | How much quota the caller has used | The server’s current load |
| Purpose | Fairness: one caller cannot affect the others | Self-protection: when total load goes over capacity, drop some of the requests |
| Normal times | Well-behaved callers are never rejected | Does not happen |
| Under overload | Everyone can be within their quota and the system can still be overloaded | Drops by priority |
Every user can be within their own quota while the total still goes over the system’s capacity, so rate limiting alone is not enough. Load shedding drops by priority: first drop the requests you can do without, such as recommendations and analytics, and keep sign-ups and payments. Base the decision on the number of concurrent requests, queue wait time, or latency, rather than on a slow-reacting metric such as CPU usage.
Flash sales: queue people instead of rejecting them
When sign-ups open for a popular talk, a flood of real users arrives in the same second. Return 429 to them and they keep refreshing the page, which only raises the load. A better approach is a virtual waiting room:
- Users first enter a waiting page and get a signed queue number that cannot be forged
- The system lets a fixed number of people a second into the sign-up page, at the rate the sign-up service can handle
- Add a human verification check (for example Cloudflare Turnstile) to filter out automated programs
Rate limiting protects the system; the waiting room protects the user experience and fairness.
Comparing options
| Where | How | Good for |
|---|---|---|
| CDN, WAF | Limit by IP, region, and request characteristics | Blocking large volumes of malicious traffic before it reaches the data center |
| API gateway | Limit by API key and plan tier | Quota management for public APIs |
| Application | Limit by user, business rules, and request cost | Limits that need to understand the business, such as “at most 3 sign-up attempts per person per talk” |
| Client calling external services | Control the rate at which you send | Staying within the quotas of SMS, email, and payment providers |
These places are not a choice of one; they are layers: the outer layers block obvious abuse, and the inner layers handle fairness for the business.
In Java
1. The token bucket Lua script
-- src/main/resources/ratelimit/token-bucket.lua
-- KEYS[1]: the bucket's key
-- ARGV[1]: capacity ARGV[2]: tokens refilled per second ARGV[3]: cost of this request
-- Returns 0 when allowed; greater than 0 when rejected, the value being the suggested wait in milliseconds
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local cost = tonumber(ARGV[3])
local time = redis.call('TIME')
local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
local bucket = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(bucket[1]) or capacity
local ts = tonumber(bucket[2]) or now
tokens = math.min(capacity, tokens + math.max(0, now - ts) * rate / 1000)
local wait = 0
if tokens >= cost then
tokens = tokens - cost
else
wait = math.ceil((cost - tokens) * 1000 / rate)
end
redis.call('HSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil(capacity * 1000 / rate) + 1000)
return wait- The whole script runs atomically inside Redis, so two servers can never read the same value at the same time
- Time comes from Redis’s
TIME, not from the application servers’ clocks. Since Redis 7, scripts are always replicated to replicas by their effects, so callingTIMEinside a script does not make the primary and its replicas diverge PEXPIREis set to “the time it takes to go from empty to full” plus one second: there is no reason to keep the key of a bucket that is already full, so idle users do not keep holding memory
2. Calling the script, and handling Redis failures
public record RateLimitPolicy(String name, int capacity, double refillPerSecond, boolean failClosed) {
}
@Component
public class RateLimiter {
private static final Logger log = LoggerFactory.getLogger(RateLimiter.class);
private final StringRedisTemplate redis;
private final RedisScript<Long> tokenBucket =
RedisScript.of(new ClassPathResource("ratelimit/token-bucket.lua"), Long.class);
private final Map<String, LocalTokenBucket> localFallbacks = new ConcurrentHashMap<>();
public RateLimiter(StringRedisTemplate redis) {
this.redis = redis;
}
/** Returns 0 when allowed; greater than 0 when rejected, the value being the suggested wait in milliseconds. */
public long tryAcquire(RateLimitPolicy policy, String subject, int cost) {
String key = "ratelimit:" + policy.name() + ":" + subject;
try {
Long wait = redis.execute(tokenBucket, List.of(key),
String.valueOf(policy.capacity()), String.valueOf(policy.refillPerSecond()), String.valueOf(cost));
return wait == null ? 0 : wait;
} catch (DataAccessException redisDown) {
log.warn("rate limiter unavailable, policy={}", policy.name());
if (policy.failClosed()) {
return 1_000; // Security-related limit: reject
}
// General limit: fall back to a conservative local limit (one bucket for the whole server, not per user)
LocalTokenBucket local = localFallbacks.computeIfAbsent(policy.name(),
name -> new LocalTokenBucket(policy.capacity(), policy.refillPerSecond()));
return local.tryAcquire(cost) ? 0 : 1_000;
}
}
}
final class LocalTokenBucket {
private final double capacity;
private final double refillPerNano;
private double tokens;
private long last = System.nanoTime();
LocalTokenBucket(double capacity, double refillPerSecond) {
this.capacity = capacity;
this.tokens = capacity;
this.refillPerNano = refillPerSecond / 1_000_000_000.0;
}
synchronized boolean tryAcquire(int cost) {
long now = System.nanoTime();
tokens = Math.min(capacity, tokens + (now - last) * refillPerNano);
last = now;
if (tokens < cost) {
return false;
}
tokens -= cost;
return true;
}
}The local fallback bucket uses the quota of “a single user”, but the whole server shares it, so it is very conservative: while Redis is down, the total traffic for this feature drops sharply, but the feature neither stops completely nor goes completely unprotected.
3. Applying it to the sign-up API
@Component
public class RegistrationRateLimitInterceptor implements HandlerInterceptor {
// At most 5 in a row per person, then 1 every 10 seconds
private static final RateLimitPolicy PER_MEMBER = new RateLimitPolicy("registration", 5, 0.1, false);
private final RateLimiter rateLimiter;
public RegistrationRateLimitInterceptor(RateLimiter rateLimiter) {
this.rateLimiter = rateLimiter;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
// Limit by user after login; unauthenticated requests are blocked by Spring Security and never get here
long waitMillis = rateLimiter.tryAcquire(PER_MEMBER, auth.getName(), 1);
if (waitMillis == 0) {
return true;
}
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
response.setHeader(HttpHeaders.RETRY_AFTER, String.valueOf((waitMillis + 999) / 1000));
return false;
}
}
@Configuration
public class RateLimitWebConfig implements WebMvcConfigurer {
private final RegistrationRateLimitInterceptor registrationLimit;
public RateLimitWebConfig(RegistrationRateLimitInterceptor registrationLimit) {
this.registrationLimit = registrationLimit;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(registrationLimit).addPathPatterns("/v1/registrations/**");
}
}- This limit is about fairness, not about stopping brute-force attacks, so
failClosedisfalse. The policies for login and SMS verification codes set it totrue - When you limit by IP, first make sure you have the real client IP, not
X-Forwarded-For, which the client can fill in itself (the Load Balancing post)
The code above is based on the official documentation for Spring Framework 7, Spring Data Redis, and Redis; it has not been compiled or run.
Pitfalls and gotchas
- Each server counts on its own: the real limit is the configured value times the number of servers, and it changes with autoscaling
- The fixed window boundary: a limit of 100, and 200 get through within 2 seconds
- Read, then write: without atomicity, concurrent requests all pass the check
- Using the application servers’ clocks: when the clocks disagree, tokens refill at different speeds on different servers
- No
Retry-After: clients do not know how long to wait, so they retry right away, and even more requests get rejected - Rate limiting without load shedding: everyone is within their quota, and the system is still overloaded
- Rate limiting your own traffic: health checks, internal batch jobs, and webhook callbacks get limited along with everything else. Give internal traffic a different policy or path
- Undocumented limits: partners do not know the limits until launch day, when they suddenly get a flood of 429s
- A hot key for a global limit: one Redis key takes every request, and its shard becomes the bottleneck
- No gradual rollout for limit changes: someone changes a limit from 1,000 to 100 by mistake, and everyone is blocked at once. Roll out rate limit changes in batches, just like code deploys
Security
- Limiting only by IP misses attackers and blocks the wrong people: attackers use botnets or proxy services to rotate through tens of thousands of IPs, and each IP stays within its quota; meanwhile, many real users behind the NAT of one school or carrier share a single IP and get blocked by mistake. Combine IP limits with the account, the device, and the IP prefix, and send suspicious traffic to human verification instead of blocking it outright
- A spoofed
X-Forwarded-For: trust this header directly, and an attacker can get around the limit by putting a different IP in each request. Trust the header only when it comes from known proxies - Credential stuffing: login has to limit failures per account, per IP, and across the whole site at the same time. Limit only per account, and attackers try each account just once or twice; limit only per IP, and attackers spread out across IPs
- Account lockout can be abused too: lock an account for 30 minutes after 5 failures, and an attacker only has to enter wrong passwords on purpose to keep the victim from logging in. Use gradually increasing delays and human verification instead of a hard lockout
- Cost attacks through SMS and email: the SMS verification code API is used to send huge volumes to premium-rate numbers (SMS pumping), and you pay the bill. Limit sends per phone number, per IP, and per country code, and set a total daily budget cap
- Limit the number of rate limiting keys too: if unauthenticated requests can decide the key (for example, when any ID in the request is used as the key), an attacker sends huge numbers of different IDs and fills up Redis’s memory. Key unauthenticated requests only by IP prefix, and give every key a TTL
- Security-related limits must fail closed: when Redis fails, the limits on login, verification codes, and password reset must reject requests, not let them through
- Do not leak details of your defenses: for limits that prevent abuse, such as on login, do not return the remaining count; whether an account exists should not change the rate limit response either, or the rate limit itself becomes a way to enumerate accounts
- Weight expensive requests: price GraphQL queries by complexity (the REST, gRPC, and GraphQL post), and make full-text search and exports take more tokens; otherwise attackers can exhaust your resources with a handful of requests
When to use it, and when not to
- Always do it: public APIs, login, verification codes, password reset, and any operation that incurs external cost (SMS, email, paid third-party APIs)
- Depends on the business: plan-tier quotas (1,000 calls a day on the free plan), a waiting room for flash sales
- Do not use rate limiting in place of capacity planning: when normal users get 429s under normal traffic, you are short of capacity, and that is not a rate limiting problem. Rate limiting stops anomalies and abuse; load shedding handles overload
References
- RFC 6585, “Additional HTTP Status Codes”, Section 4 “429 Too Many Requests”: https://www.rfc-editor.org/rfc/rfc6585#section-4
- IETF draft-ietf-httpapi-ratelimit-headers-11, “RateLimit header fields for HTTP”, May 2026: https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/
- Redis Documentation — Scripting with Lua (Script replication): https://redis.io/docs/latest/develop/programmability/eval-intro/
- Spring Data Redis Reference — Scripting: https://docs.spring.io/spring-data/redis/reference/redis/scripting.html
- AWS Builders’ Library — Fairness in multi-tenant systems: https://aws.amazon.com/builders-library/fairness-in-multi-tenant-systems/
- AWS Builders’ Library — Using load shedding to avoid overload: https://aws.amazon.com/builders-library/using-load-shedding-to-avoid-overload/
- OWASP — Credential Stuffing Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Credential_Stuffing_Prevention_Cheat_Sheet.html
- OWASP API Security Top 10 2023 — API4:2023 Unrestricted Resource Consumption: https://owasp.org/API-Security/editions/2023/en/0xa4-unrestricted-resource-consumption/
- Interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments