APIs need protection from excessive traffic, whether it comes from accidental client loops, aggressive users, automated scripts, or sudden traffic spikes. Rate limiting controls how many requests a client can make within a defined period, helping preserve availability, performance, and fair resource usage. However, the algorithm behind a rate limiter determines how bursts, delays, and request rejection are handled. Token Bucket, Leaky Bucket, and Fixed Window are three widely used approaches, but they behave differently under real workloads. Choosing the right algorithm requires understanding traffic patterns, latency requirements, infrastructure design, and the experience you want legitimate users to receive.
What Is API Rate Limiting?
API rate limiting places a controlled boundary around request traffic. A server might allow a client to make 100 requests per minute, for example, and reject or delay requests that exceed that allowance. Limits can be applied by API key, authenticated user, IP address, tenant, endpoint, or another identity. Properly designed limits protect databases and application servers while also preventing one consumer from unfairly consuming shared capacity.
Rate limiting is not simply about blocking requests. A good implementation considers how traffic arrives and what happens when clients temporarily exceed the normal rate. Some systems should tolerate short bursts, while others need a steady request flow. The algorithm therefore affects throughput, latency, fairness, and how predictable the API feels to developers.
Token Bucket Algorithm
The Token Bucket algorithm represents permission to make requests as tokens stored in a bucket. Tokens are added at a fixed rate until the bucket reaches its maximum capacity. Each incoming request consumes one or more tokens, and a request can proceed when enough tokens are available. This allows unused capacity to accumulate temporarily and supports controlled bursts without permitting unlimited traffic.
For example, suppose an API adds 10 tokens per second and has a bucket capacity of 50. A client that has been idle can accumulate up to 50 tokens and potentially send a burst of requests immediately. After the burst, requests continue according to the token refill rate. This makes Token Bucket particularly useful for APIs where short bursts are legitimate but sustained traffic must remain controlled.
Advantages and Limitations
Token Bucket provides a practical balance between flexibility and protection. It works well for public APIs, authentication services, and applications where clients occasionally send batches of requests. The main consideration is choosing an appropriate refill rate and bucket capacity. A bucket that is too large can allow disruptive bursts, while one that is too small may reject legitimate short-term activity.
Leaky Bucket Algorithm
The Leaky Bucket algorithm focuses on controlling the rate at which requests leave the limiter. Incoming requests enter a queue or conceptual bucket, and processing occurs at a controlled rate. If the bucket becomes full, additional requests are rejected or handled according to the implementation. Unlike Token Bucket, the primary goal is maintaining a smoother output flow.
This behavior makes Leaky Bucket useful when downstream systems need predictable traffic. Imagine an API sending requests to a fragile third-party service that accepts only a steady number of calls. Rather than allowing a burst to reach that dependency, the limiter can queue requests and release them gradually. The trade-off is that queuing can increase latency, especially when traffic approaches or exceeds the configured processing rate.
Fixed Window Algorithm
Fixed Window is simpler than the other two algorithms. The system divides time into fixed intervals, such as one minute, and assigns each client a request counter for the current interval. If the configured limit is 100 requests per minute, requests 1 through 100 are accepted and subsequent requests are rejected until the next window begins. At the boundary, the counter resets.
The simplicity of Fixed Window makes it attractive for straightforward API protection. It is relatively easy to implement with counters in systems such as Redis and can be efficient at large scale. However, it has a boundary problem. A client could send 100 requests near the end of one window and another 100 immediately after the next window begins, creating a short burst of 200 requests despite a nominal limit of 100 per minute.
Token Bucket vs Leaky Bucket vs Fixed Window
The three algorithms differ mainly in how they handle bursts and timing. Token Bucket permits controlled bursts when tokens have accumulated, making it flexible for variable traffic. Leaky Bucket smooths traffic by processing requests at a controlled pace, which is useful when downstream capacity must remain stable. Fixed Window is the easiest to understand and implement, but its time boundaries can create uneven traffic patterns.
Which Algorithm Should You Choose?
Choose Token Bucket when your API needs to support occasional bursts while enforcing a sustainable average rate. Choose Leaky Bucket when smoothing traffic and protecting downstream services are more important than immediate request processing. Fixed Window works well for simple quotas where boundary bursts are acceptable or additional controls address that weakness. In larger systems, teams may also combine algorithms, such as using a broad quota alongside a short-term burst limiter.
Distributed Rate Limiting Considerations
Rate limiting becomes more complicated when an API runs across multiple servers. A local in-memory counter can produce inconsistent results because different requests may reach different application instances. Distributed deployments commonly use shared state so that all instances enforce the same policy. Atomic operations are important because concurrent requests can otherwise update counters incorrectly.
Developers should also return useful rate-limit information to clients. HTTP status 429 Too Many Requests is commonly used when a request exceeds the allowed limit. Response headers can communicate remaining capacity or retry timing where appropriate. Clear limits and predictable retry behavior help clients implement backoff instead of repeatedly sending requests that will continue to fail.
Conclusion
Token Bucket, Leaky Bucket, and Fixed Window each solve API traffic control in a different way. Token Bucket is flexible and supports controlled bursts, Leaky Bucket prioritizes smooth request flow, and Fixed Window offers simple, efficient enforcement with a known boundary limitation. The right choice depends on whether your priority is burst tolerance, traffic smoothing, implementation simplicity, or downstream protection. For production systems, also consider distributed state, atomicity, client retry behavior, and endpoint-specific limits. Rate limiting works best when it protects infrastructure without unnecessarily restricting legitimate traffic.
FAQs
What is the best rate limiting algorithm for an API?
There is no single best algorithm for every API. Token Bucket is a strong general-purpose option because it supports controlled bursts while maintaining a refill rate. Leaky Bucket is better when traffic needs smoothing, while Fixed Window is useful for simple quotas. The correct choice depends on workload patterns, infrastructure capacity, client behavior, and how strictly bursts should be controlled.
What is the difference between Token Bucket and Leaky Bucket?
Token Bucket controls request permission using tokens that accumulate over time, allowing limited bursts when capacity is available. Leaky Bucket focuses on releasing or processing requests at a controlled rate, producing smoother traffic. Token Bucket is generally more flexible for bursty clients, while Leaky Bucket is useful when downstream systems require predictable request flow and can tolerate some queuing.
Why is Fixed Window rate limiting problematic?
Fixed Window can create a burst at the boundary between two time intervals. For example, a client allowed 100 requests per minute could potentially send 100 requests just before a window ends and another 100 immediately after the next window starts. This produces 200 requests in a short period even though each individual window stayed within its configured limit.
Can rate limiting be implemented with Redis?
Yes, Redis is commonly used for distributed rate limiting because it provides fast shared state and atomic operations that can coordinate counters or token calculations across application instances. Implementations can support different algorithms depending on their data structures and commands. Careful design is still required for concurrency, expiration, clock behavior, failure handling, and avoiding inconsistent limits during infrastructure problems.
Should APIs return HTTP 429 when rate limits are exceeded?
Yes, HTTP 429 Too Many Requests is the standard status code for indicating that a client has exceeded a request limit. A useful response can also provide information about when the client should retry, where appropriate. Consistent responses allow SDKs and applications to implement exponential backoff or other retry strategies instead of repeatedly sending rejected requests.