Designing an API Rate Limiter: Fixed Windows, Sliding Windows, and Token Buckets
An API can work perfectly under normal traffic and still fail when too many clients send requests at the same time. A public endpoint might receive thousands of requests in a short period, a client might accidentally enter a retry loop, or an automated script might consume resources far faster than expected. Even legitimate traffic can overwhelm an application when demand exceeds its capacity. Rate limiting provides a way to control that demand. Instead of allowing every request to proceed, an API rate limiter evaluates how frequently a client makes requests and decides whether the next request should be accepted or rejected. The decision can protect application resources, enforce usage policies, and help prevent one client from monopolizing shared capacity.
// TABLE OF CONTENTS+
An API can work perfectly under normal traffic and still fail when too many clients send requests at the same time. A public endpoint might receive thousands of requests in a short period, a client might accidentally enter a retry loop, or an automated script might consume resources far faster than expected. Even legitimate traffic can overwhelm an application when demand exceeds its capacity. Rate limiting provides a way to control that demand. Instead of allowing every request to proceed, an API rate limiter evaluates how frequently a client makes requests and decides whether the next request should be accepted or rejected. The decision can protect application resources, enforce usage policies, and help prevent one client from monopolizing shared capacity.
The difficult part is choosing how to count requests and where to store that information. A simple counter can enforce a basic quota, but it can also allow unexpected traffic bursts. A more sophisticated algorithm can smooth traffic, at the cost of additional state or computation. When an API runs on multiple servers, the design must also account for concurrent requests, shared storage, network failures, and the consistency of decisions across instances.
This article compares three widely used approaches: fixed windows, sliding windows, and token buckets. It develops small implementations and a deterministic simulation, then uses those examples to examine distributed enforcement, HTTP responses, operational failures, and the trade-offs involved in choosing an algorithm for a real API.
What Is an API Rate Limiter?
An API rate limiter is a component that restricts the number or frequency of requests a client can make according to a defined policy. A policy might permit 100 requests per minute, allow a burst of 20 requests, or limit a resource-intensive endpoint to five requests per second. The correct policy depends on the endpoint, client identity, business requirements, and available infrastructure.
A limiter typically identifies the caller, retrieves or calculates its current usage, evaluates the configured policy, updates the relevant state, and returns a decision. If the request is permitted, processing continues. Otherwise, the server rejects the request, commonly with HTTP status 429 Too Many Requests. The identity used for enforcement matters. Authenticated APIs can often use a user ID, API key, organization ID, or a combination of these. Unauthenticated endpoints may use an IP address, although shared networks, carrier-grade NAT, proxies, and changing addresses can make IP-based limits imperfect.
- Resource protection: Prevent excessive requests from exhausting CPU, memory, database connections, or downstream service capacity.
- Fairness: Stop a single client from consuming a disproportionate share of limited resources.
- Abuse resistance: Reduce the impact of automated request floods and accidental retry storms.
- Quota enforcement: Apply usage limits associated with API plans, tenants, or business rules.
- Cost control: Limit operations that trigger expensive computation or paid third-party calls.
Rate limiting is not a complete security mechanism. It cannot reliably distinguish every malicious request from legitimate traffic, and it does not replace authentication, authorization, input validation, or infrastructure-level denial-of-service protection. It is one layer in a broader defensive design.
Where Does Rate Limiting Fit in an API?
A rate limiter can run at an API gateway, reverse proxy, application middleware layer, or inside a particular service. An edge component can reject excessive traffic before it consumes application resources. Application-level enforcement, on the other hand, can use authenticated identities and endpoint-specific rules that an edge proxy may not understand.
A useful design separates the enforcement policy from the algorithm that implements it. The policy defines who is limited, which requests count, the permitted rate, and the burst allowance. The algorithm defines how the system tracks usage and determines whether a request is allowed. For example, two endpoints may both use token buckets but have different capacities and refill rates. Conversely, the same endpoint could use a fixed-window counter in a simple deployment and a Redis-backed sliding-window implementation when stronger enforcement is required.
Fixed Windows: Simple Counters With a Boundary Problem
A fixed-window limiter divides time into discrete intervals and counts requests within each interval. Suppose an API allows 100 requests per minute. Each client receives a counter for the current minute, and each accepted request increments that counter. Once the counter reaches 100, additional requests are rejected until the next window begins. A typical implementation identifies a window using the current timestamp divided by the window duration. For a 60-second window, timestamps from 12:00:00 through 12:00:59 belong to the same window, assuming boundaries are aligned to the Unix epoch. The next window begins at 12:01:00.
function getWindowId(nowMs, windowMs) {
return Math.floor(nowMs / windowMs);
}
const windowMs = 60_000;
console.log(getWindowId(12_000, windowMs));
console.log(getWindowId(72_000, windowMs));The window identifier is a number, not a formatted clock string. In a real implementation, it can be combined with the client identity to form a storage key such as rate-limit:user-42:window-29500000. A new identifier creates a logically separate counter, and old counters can expire when they are no longer needed.
How a Fixed Window Handles Traffic
Fixed windows are easy to reason about because every request belongs to exactly one interval. If the quota is 100 requests per minute, the limiter permits at most 100 requests inside any single window, assuming each counter update is enforced atomically. Memory usage is low because the system needs only a counter and its window identifier per active client and policy. However, the algorithm does not guarantee that no more than 100 requests arrive during every possible 60-second period. Its boundaries create a weakness known as the boundary burst problem.
Consider a client that sends 100 requests immediately before a window closes and another 100 immediately after the next window opens. Both groups fall within their respective windows, so both can be accepted. The client may therefore send 200 requests in a very short interval despite a configured limit of 100 per minute. This is not a counter bug. It is a consequence of the policy's definition: the limit applies independently to fixed, aligned intervals rather than to every rolling interval of 60 seconds.
Implementation Considerations
A fixed-window counter needs a safe increment operation and a reliable expiration policy. In a single-process application, a map can hold counters. In a distributed application, the counter usually belongs in shared storage or at a gateway that enforces the limit consistently. If the implementation increments a counter and sets its expiration as two independent operations, failures between those operations can create incorrect state. A counter might remain indefinitely if expiration is never configured. Under concurrent requests, separate read-modify-write operations can also lose increments unless the update is atomic.
- Advantages: Simple logic, low state requirements, inexpensive updates, and straightforward debugging.
- Disadvantages: Boundary bursts, coarse control over request distribution, and possible counter-key growth if expiration is mishandled.
- Suitable uses: Basic quotas, internal tools, low-complexity endpoints, and use cases where aligned-window bursts are acceptable.
Sliding Windows: Better Control Over Recent Traffic
A sliding-window limiter evaluates requests relative to the current time rather than relying exclusively on a permanently aligned interval. For a quota of 100 requests per minute, the decision considers activity during the previous 60 seconds. This reduces the boundary burst problem because requests from the preceding window remain relevant until they age out of the rolling interval. There are two common implementations: an exact sliding log and a sliding-window counter. They aim for similar outcomes but have different storage and accuracy characteristics.
Exact Sliding Logs
An exact sliding log records the timestamp of each request. When a new request arrives, the limiter removes timestamps that fall outside the rolling interval, counts the remaining entries, and permits the request only if the count is below the configured maximum. For a 60-second interval, a timestamp is relevant when it is within the previous 60 seconds according to the chosen boundary convention. A request exactly at the cutoff requires a consistent rule: for example, use the half-open interval (now - window, now] so the cutoff itself is excluded.
class SlidingLogLimiter {
constructor(limit, windowMs) {
this.limit = limit;
this.windowMs = windowMs;
this.requests = new Map();
}
allow(key, nowMs) {
const cutoff = nowMs - this.windowMs;
const timestamps = this.requests.get(key) ?? [];
const recent = timestamps.filter(
(timestamp) => timestamp > cutoff
);
if (recent.length >= this.limit) {
this.requests.set(key, recent);
return false;
}
recent.push(nowMs);
this.requests.set(key, recent);
return true;
}
}
const limiter = new SlidingLogLimiter(3, 60_000);
console.log(limiter.allow("user-42", 1_000)); // true
console.log(limiter.allow("user-42", 2_000)); // true
console.log(limiter.allow("user-42", 3_000)); // true
console.log(limiter.allow("user-42", 4_000)); // false
console.log(limiter.allow("user-42", 62_000)); // trueThis example deliberately accepts a timestamp at 62,000 milliseconds because the earliest request at 1,000 milliseconds is exactly at the cutoff and therefore excluded by the interval convention. The example also demonstrates why passing the current time into the limiter is useful: tests can reproduce boundary conditions without sleeping or depending on the machine clock. The implementation is educational rather than production-ready. It uses an in-memory map, retains empty client entries, and filters a client's entire timestamp list on every request. Under heavy traffic, those choices can create significant CPU and memory overhead. A production version would need bounded state, efficient pruning, concurrency control, and possibly a shared store.
Sliding-Window Counters
A sliding-window counter estimates the rolling request count using two adjacent fixed windows instead of storing every timestamp. It combines the current window's count with a weighted portion of the previous window's count. The intuition is straightforward: if 30 seconds of a 60-second window have elapsed, approximately half of the previous fixed window overlaps the current rolling interval. The algorithm weights the previous count by the fraction of that window that still overlaps the interval, then adds the current count.
function estimateSlidingCount({
previousCount,
currentCount,
elapsedMs,
windowMs,
}) {
const previousWeight = 1 - elapsedMs / windowMs;
return (
previousCount * previousWeight +
currentCount
);
}
console.log(
estimateSlidingCount({
previousCount: 80,
currentCount: 20,
elapsedMs: 30_000,
windowMs: 60_000,
})
); // 60The estimate is 60: the current window contributes 20 requests, while half of the previous window's 80 requests contributes an estimated 40. This is an approximation, not an exact reconstruction of the last 60 seconds. The formula assumes the previous window's traffic is distributed sufficiently evenly for its weighted contribution to be useful. If all 80 requests arrived at one edge of that window, the estimate could differ substantially from the true rolling count.
| Dimension | Exact sliding log | Sliding-window counter |
|---|---|---|
| Stored state | Request timestamps | A small number of counters |
| Accuracy | Exact for recorded timestamps and defined boundaries | Approximate |
| Memory | Grows with retained request volume | Typically constant per active key |
| Request cost | Pruning and counting stored timestamps | Constant-time arithmetic and counter updates |
| Concurrency | Requires atomic state changes | Requires atomic counter updates |
| Main trade-off | Precision versus storage and processing | Efficiency versus estimation error |
A sliding log is useful when the precise number of requests in a rolling interval matters enough to justify storing individual timestamps. A sliding-window counter is often more economical when approximate enforcement is sufficient. Neither approach eliminates the need for an atomic decision when multiple requests arrive concurrently.
- Advantages: Better control over recent traffic and fewer artificial bursts at fixed boundaries.
- Disadvantages: Exact logs can consume substantial memory; counter-based variants introduce approximation error.
- Suitable uses: Public APIs with rolling quotas, endpoints where recent usage matters, and systems needing a balance between accuracy and storage.
Token Buckets: Allow Bursts Without Unlimited Traffic
A token bucket models a limited supply of tokens that replenishes over time. Each permitted request consumes a token. When no tokens remain, the request is rejected or delayed until enough tokens become available. The bucket has two important parameters: its capacity and its refill rate. Capacity determines the maximum stored burst allowance. The refill rate determines how quickly that allowance is replenished. A bucket with capacity 20 and a refill rate of five tokens per second can accept a burst of up to 20 requests when full, then sustain approximately five requests per second over time, assuming each request consumes one token.
Unlike a fixed window, the token bucket does not reset every minute. It maintains a continuous balance. Unused capacity accumulates up to the maximum, so a quiet client can make a burst of requests later. Once the bucket is empty, requests are constrained by the refill rate instead of waiting for an arbitrary calendar boundary. This makes token buckets useful for APIs that need to support normal short bursts while controlling sustained traffic. The algorithm does not force requests to arrive at perfectly uniform intervals; it constrains the amount of traffic that can be admitted over time.
Implementing a Token Bucket
The implementation tracks the number of available tokens and the last time the bucket was updated. Before evaluating a request, it calculates how much time has passed and replenishes tokens proportionally. It then caps the balance at the configured capacity, preventing idle time from producing an unlimited future burst. Using a monotonic clock in a single process is preferable for elapsed-time calculations because wall-clock adjustments can move the system time backward or forward. When token state is shared across machines, the design needs a consistent time source or an explicit strategy for handling clock differences.
class TokenBucketLimiter {
constructor(capacity, refillPerSecond) {
this.capacity = capacity;
this.refillPerMs = refillPerSecond / 1000;
this.buckets = new Map();
}
allow(key, nowMs) {
const bucket = this.buckets.get(key) ?? {
tokens: this.capacity,
updatedAt: nowMs,
};
const elapsedMs = Math.max(
0,
nowMs - bucket.updatedAt
);
bucket.tokens = Math.min(
this.capacity,
bucket.tokens + elapsedMs * this.refillPerMs
);
bucket.updatedAt = Math.max(
bucket.updatedAt,
nowMs
);
if (bucket.tokens < 1) {
this.buckets.set(key, bucket);
return false;
}
bucket.tokens -= 1;
this.buckets.set(key, bucket);
return true;
}
}
const limiter = new TokenBucketLimiter(3, 1);
console.log(limiter.allow("user-42", 0)); // true
console.log(limiter.allow("user-42", 0)); // true
console.log(limiter.allow("user-42", 0)); // true
console.log(limiter.allow("user-42", 0)); // false
console.log(limiter.allow("user-42", 1000)); // trueThis example starts with a full bucket, so the first three requests are allowed. The fourth request is rejected because no tokens remain. After one second, one token is replenished, permitting another request. The map is local to one JavaScript process. It cannot enforce a shared quota across several application instances, and it has no expiration policy for inactive keys. A real deployment must address those limitations and ensure that reading the token balance, replenishing it, and consuming a token happen as one atomic operation.
Token Buckets and Leaky Buckets Are Not the Same
Token buckets and leaky buckets are related traffic-shaping techniques, but they are not interchangeable. A token bucket permits bursts up to its accumulated capacity and limits the long-term average through replenishment. A leaky-bucket traffic shaper typically processes queued traffic at a controlled rate, smoothing bursts before they reach the destination. Some leaky-bucket implementations are used as policing mechanisms rather than queues, so the exact behavior depends on the implementation. If an API should accept a short burst and then constrain sustained use, a token bucket is often a natural fit. If a downstream service needs a more regular stream of work, a queue-based shaping mechanism may be more appropriate.
- Advantages: Explicit burst control, continuous replenishment, and intuitive tuning of sustained throughput.
- Disadvantages: Requires per-key state and careful time calculations; shared state needs atomic updates.
- Suitable uses: Public APIs, workload admission control, client quotas with burst allowances, and traffic that should remain responsive without accepting unlimited bursts.
Which Rate-Limiting Algorithm Should You Choose?
There is no universally best rate-limiting algorithm. The correct choice depends on whether the system needs a simple quota, a precise rolling limit, or controlled bursts. Memory requirements, storage costs, traffic patterns, and the consequences of exceeding a limit also affect the decision.
| Dimension | Fixed window | Sliding window | Token bucket |
|---|---|---|---|
| Core state | Counter per window | Request log or weighted counters | Token balance and update time |
| Boundary bursts | Possible | Reduced or avoided | Controlled by bucket capacity |
| Rolling-window accuracy | No | Exact log: yes; counter: approximate | Not designed to enforce an exact rolling count |
| Memory | Low | Low for counters; potentially high for logs | Low per active key |
| Burst behavior | Can allow abrupt boundary bursts | Constrains recent request volume | Explicitly allows a configured burst |
| Implementation | Simplest | Moderate to complex | Moderate |
| Distributed enforcement | Requires shared atomic counter | Requires shared atomic state | Requires shared atomic token state |
| Best fit | Basic quotas | Rolling quotas | Sustained rate with burst tolerance |
Consider three requirements. A simple internal endpoint may allow 60 requests per minute and tolerate occasional boundary bursts; a fixed window may be sufficient. A billing API may need to enforce a strict rolling quota; an exact sliding log or another precise rolling-window design may be justified. A service that should support a burst of 20 requests and then sustain five requests per second may be better represented by a token bucket. The important distinction is that these algorithms implement different policies. Choosing a token bucket does not automatically guarantee a strict rolling-window maximum, and choosing a sliding-window counter does not automatically make the result exact.
A Small Simulation: Why Algorithm Choice Matters
A deterministic simulation helps compare algorithms without relying on external services or real traffic. The following example models requests at specific timestamps and compares a fixed-window counter with a token bucket. Both limiters use a quota of three requests per window or a bucket capacity of three tokens, with a refill rate of one token per second. The parameters are intentionally small so the differences are easy to inspect. They are not production recommendations.
class FixedWindowLimiter {
constructor(limit, windowMs) {
this.limit = limit;
this.windowMs = windowMs;
this.windows = new Map();
}
allow(key, nowMs) {
const windowId = Math.floor(nowMs / this.windowMs);
const current = this.windows.get(key);
if (!current || current.windowId !== windowId) {
this.windows.set(key, {
windowId,
count: 1,
});
return true;
}
if (current.count >= this.limit) {
return false;
}
current.count += 1;
return true;
}
}
const fixed = new FixedWindowLimiter(3, 1000);
const bucket = new TokenBucketLimiter(3, 1);
const arrivals = [
900, 950, 990, 1000, 1010, 1020, 2000,
];
for (const time of arrivals) {
console.log({
time,
fixedWindow: fixed.allow("client", time),
tokenBucket: bucket.allow("client", time),
});
}The first three requests arrive just before the fixed-window boundary at 1,000 milliseconds. The next three arrive just after it. The fixed-window limiter can accept three requests in the first interval and another three in the next interval, even though the requests are tightly clustered. The token bucket begins with three tokens, but its balance refills gradually; it cannot replenish three tokens merely because a window boundary has passed. The final request at 2,000 milliseconds illustrates another difference. The token bucket has accumulated additional tokens during the quiet interval, up to its capacity. A fixed-window counter, meanwhile, starts a new interval and resets its count.
This simulation is useful for exploring behavior, but it is not a benchmark. It measures neither throughput nor latency, and its in-memory data structures do not reproduce network delays, Redis contention, clock differences, or concurrency across application instances. The example also assumes requests are evaluated sequentially. Those limitations must be addressed before drawing conclusions about production performance.
- Change the arrival timestamps to test different traffic patterns.
- Increase the bucket capacity to see how burst tolerance changes.
- Increase the refill rate to examine sustained throughput.
- Add a sliding-window counter to compare approximate rolling enforcement.
- Run concurrent requests against a shared implementation to test whether the quota is actually enforced under contention.
Designing a Rate Limiter Across Multiple Servers
An in-memory limiter is adequate for a small single-process service, but it has a fundamental limitation in a horizontally scaled application. Each process has its own counters or token balances. If an API runs on four instances and each instance independently permits 100 requests per minute for the same client, the client may be able to make substantially more than 100 requests across the deployment. Load balancing does not solve this problem. It distributes requests among servers, but it does not automatically coordinate their state. To enforce a shared quota, the system needs a common state store, a centralized enforcement point, or a deliberate design that partitions quota among instances.
Why Atomicity Matters
Suppose a fixed-window counter contains 99 requests and the quota is 100. Two requests arrive simultaneously at different API instances. Both read 99, both decide that the limit has not been reached, and both increment the counter to 100 using separate writes. The system has admitted 101 requests even though the configured limit was 100. The same race can affect token buckets. Two instances may observe one remaining token and both consume it if the read, refill, and decrement steps are not coordinated. The result is an oversubscribed quota. The fix is to make the decision and state update an atomic operation. For simple counters, Redis commands such as INCR can provide atomic increments, but the complete policy still needs correct handling of expiration and the decision about whether an increment should be accepted. For more involved algorithms, a Redis Lua script or another transactional mechanism can evaluate and update state as a single server-side operation.
Using Redis as Shared State
Redis is a common option because it provides fast key-value operations and atomic commands that can support rate-limiting policies. A fixed-window implementation can store a counter under a key containing the client identity and window identifier, then expire that key after it is no longer needed. A token bucket can store its token balance and last-update timestamp, updating both atomically through a script. The details matter. If the counter is incremented successfully but its expiration is never set, old keys may accumulate. If the application sets the expiration on every request without considering the policy, it can accidentally turn a fixed window into a different, inactivity-based window. The expiration strategy must match the algorithm's intended semantics.
-- KEYS[1]: counter key for one client and one window
-- ARGV[1]: request limit
-- ARGV[2]: window duration in milliseconds
local current = redis.call("INCR", KEYS[1])
if current == 1 then
redis.call("PEXPIRE", KEYS[1], ARGV[2])
end
if current <= tonumber(ARGV[1]) then
return {1, current}
end
return {0, current}The script increments the counter and sets its expiration when the key is first created. Because Redis executes the script atomically, competing requests cannot interleave their counter updates with the script's decision. The returned first value indicates whether the request is within the quota, and the second value reports the counter. This compact example illustrates the core mechanism, not a complete production integration. The application must construct keys safely, validate policy configuration, handle Redis errors and timeouts, choose an appropriate key expiration, and ensure that rejected requests do not proceed. The counter is also incremented for rejected requests, so it can exceed the configured limit; that behavior is acceptable for this simple enforcement pattern because every subsequent request remains rejected until the window expires.
Redis itself becomes part of the critical request path. Network latency, connection pool exhaustion, failover, memory pressure, and storage unavailability can affect rate-limiter decisions. A deployment should monitor the limiter's latency and error rate separately from application performance, and it should test behavior during Redis outages rather than assuming the shared store is always available.
Returning the Right HTTP Response
When a request exceeds a rate limit, HTTP 429 Too Many Requests is the standard response status to communicate that the client has sent too many requests within a given period. The response should be predictable and documented. Clients need to know whether they should retry, how long they should wait, and whether the limit applies to an account, API key, endpoint, or another identity.
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 2
{
"error": "rate_limit_exceeded",
"message": "Too many requests. Try again later."
}The Retry-After header can tell the client how long to wait before retrying. It supports either a delay in seconds or an HTTP date. The example uses a two-second delay, which is illustrative rather than a value that should be hardcoded for every rejected request. A real limiter should calculate the delay from its policy and current state when it can do so reliably. Rate-limit response fields can also communicate the applicable limit, remaining quota, and reset information where appropriate. RFC 9333 defines standardized RateLimit fields for communicating rate-limit information. Implementations should follow the specification and avoid returning misleading reset times or treating an approximate quota as an exact guarantee.
Retry Behavior Is Part of the Design
A client that immediately retries every rejected request can make the situation worse. If many clients receive a rate-limit response at once and all retry at the same instant, they can create a synchronized burst when capacity becomes available. Clients should respect Retry-After when provided, use bounded retries, and consider exponential backoff with jitter when retrying transient failures. The server must also distinguish between rate limiting and other errors. A 429 response means the request exceeded a rate policy; a 503 Service Unavailable response may be more appropriate when the service itself cannot handle the request because of temporary capacity or dependency problems. These statuses should not be used interchangeably.
What Happens When the Rate Limiter Fails?
The choice of failure behavior is one of the most important production decisions. If Redis is unavailable, an application may be unable to determine whether a request is within its quota. The system must decide whether to allow the request, reject it, use a local fallback, or route enforcement through another component. There is no universal answer. The decision depends on the endpoint's cost, the sensitivity of the protected resource, and the consequences of an incorrect decision.
| Strategy | Behavior during state-store failure | Main trade-off |
|---|---|---|
| Fail open | Allow requests when the limiter cannot decide | Better availability, weaker protection |
| Fail closed | Reject requests when the limiter cannot decide | Stronger enforcement, possible disruption to legitimate users |
| Local fallback | Apply a temporary per-instance limit | Partial protection; aggregate quota can be exceeded |
| Degraded enforcement | Use a preallocated or conservative local budget | More complex coordination and budget management |
| Gateway enforcement | Rely on an independently available edge limiter where applicable | Depends on gateway coverage and its own failure behavior |
Fail-open behavior can be reasonable for a low-risk endpoint where rejecting all users during a Redis outage would be more harmful than temporarily allowing additional traffic. For expensive operations, sensitive resources, or costly downstream integrations, fail-closed or conservative fallback behavior may be preferable. A local fallback does not preserve a strict global limit automatically. If every instance independently allows 20 requests per second during an outage, the aggregate rate can rise with the number of instances. A fallback must be treated as a degraded policy, not as an equivalent replacement for shared enforcement.
Clock Skew, Expiration, and State Growth
Distributed rate limiters must handle time carefully. A fixed-window implementation needs a consistent definition of window boundaries. A token bucket needs elapsed-time calculations that do not accidentally create or destroy tokens because of clock adjustments. If different machines calculate windows independently, clock differences can cause requests near a boundary to be assigned to different windows. Using a shared store's time inside an atomic script can reduce inconsistencies for certain designs, but it does not remove every time-related problem. The implementation must still define its time precision, behavior after clock changes, and policy for requests that arrive late or concurrently.
State growth is another operational concern. A service with millions of client keys can accumulate large numbers of counters or token buckets. Expiration helps remove inactive state, but its duration must not be shorter than the policy requires. Very long expirations waste memory, while premature expiration can reset quotas or recreate full token buckets too early. Key design also matters. Use a consistent identity and policy namespace so separate users or endpoints do not accidentally share state. Avoid embedding secrets or unnecessary personal information directly in storage keys, and consider privacy implications when storing IP-derived identifiers.
- Measure rate-limiter decision latency, rejection rate, storage errors, and timeout frequency.
- Track active key counts, memory use, and expiration behavior.
- Test concurrent requests at the exact quota boundary.
- Test application behavior during storage failures and failover.
- Verify that client retries do not create unnecessary load.
- Review whether endpoint policies need different limits based on their resource costs.
Designing Limits That Are Fair and Difficult to Bypass
A correct algorithm can still enforce the wrong policy if the client identity is poorly chosen. Limiting only by IP address can penalize users behind shared networks, while limiting only by user ID may leave unauthenticated endpoints exposed to repeated requests from many identities. A practical design can combine several dimensions, such as an IP-based limit for login attempts, an API-key quota for authenticated traffic, and a global concurrency or throughput limit for an expensive downstream service.
The identity key should be derived from trusted information. If a service is behind a reverse proxy, the client IP should come from headers only when those headers are set or sanitized by trusted infrastructure. Accepting arbitrary client-supplied forwarding headers as authoritative can allow callers to manipulate their rate-limit identity. Limits should also account for the type of operation. A lightweight health check and a costly report-generation endpoint should not necessarily consume the same quota. Policies can vary by route, tenant, subscription tier, or resource class, provided those distinctions are explicit and tested.
Putting the Design Together
For a small application, begin with a clear policy and the simplest algorithm that meets its requirements. A fixed-window counter is often sufficient when a small amount of boundary bursting is acceptable. Use a sliding-window design when the system needs to constrain recent traffic more closely. Choose a token bucket when short bursts are useful but sustained throughput must remain bounded. As the application scales horizontally, move from process-local state to coordinated enforcement. A shared Redis store can provide atomic updates for counters and token balances, while a gateway can reject excess requests before they reach the application. The best choice depends on the deployment, latency budget, operational capabilities, and the accuracy required by the policy.
- Define the identity and scope of each limit.
- Specify the allowed request rate, window duration, or burst capacity.
- Choose the algorithm based on the required behavior rather than popularity.
- Implement the state transition atomically when concurrent requests share a quota.
- Set expiration and cleanup rules that match the policy.
- Return a consistent 429 response with useful retry information where possible.
- Define fail-open, fail-closed, or degraded behavior for dependency outages.
- Test boundary cases, concurrency, state growth, and failure recovery.
- Monitor latency, rejection rates, and storage health after deployment.
A rate limiter should be treated as an admission-control component, not merely a counter placed in middleware. Its job is to enforce an explicit traffic policy under normal conditions and behave predictably when requests arrive concurrently or dependencies fail. That requires aligning the algorithm, state model, infrastructure, and API contract.
Conclusion
Fixed windows offer simplicity and low state overhead but permit bursts around interval boundaries. Sliding windows provide better control over recent traffic, with exact logs trading memory for precision and counter-based variants trading some accuracy for efficiency. Token buckets allow controlled bursts while limiting sustained traffic through a configurable refill rate. In a distributed API, the hardest problems are often not the algorithm's basic mathematics. They are atomic enforcement across instances, consistent time handling, bounded state, storage failures, and a clear contract with API clients. Understanding these trade-offs makes it possible to choose a rate limiter that matches the workload rather than implementing a quota that only appears correct in a single-process demonstration.
OPEN
Thoughts on the article.