Rate limiting: why, and the five algorithms

Why an API limits requests, how to choose a key, what a good 429 response looks like, and a full tour of the token bucket, fixed window counter, sliding window log, sliding window counter and leaky bucket, with their trade-offs.

Learning outcomes

  • Say what rate limiting protects against and what it does not.
  • Pick a limiting key (user, IP, API key) and justify it.
  • Explain the token bucket, with capacity, refill rate and lazy refill, step by step.
  • Explain the fixed window counter and show the 2x burst at a window boundary.
  • Explain the sliding window log and sliding window counter and what each costs in memory and accuracy.
  • Explain the leaky bucket and how it differs from the token bucket.
  • Choose an algorithm from a comparison of memory, accuracy, burstiness and cost.
  • Return 429 with Retry-After and X-RateLimit headers, and decide between failing open and failing closed.

Why a backend needs rate limiting

A food-delivery backend receives requests from mobile apps, restaurant dashboards, delivery-partner apps, internal services and sometimes automated clients. Most requests are legitimate, but the server cannot assume that every client will send requests at a reasonable rate.

Imagine a client repeatedly calling:

http
GET /v1/restaurants

A normal user might make this request a few times while browsing. A buggy mobile app might accidentally send it hundreds of times per minute. An automated script might send thousands of requests per second. All those requests consume server resources, even if they eventually return the same response.

Rate limiting controls how many requests a client can make during a defined period. A Rate limiting policy decides which requests are admitted and which are rejected.

For example, a policy might allow a client to make 60 requests per minute. Once the client reaches that limit, additional requests are rejected until capacity becomes available again.

Rate limiting protects a backend in several ways.

Abuse and accidental traffic

A client can intentionally send excessive traffic to consume resources or make an endpoint unavailable. It can also happen accidentally. A retry loop with no delay, a mobile app bug or a misconfigured integration can produce traffic that looks like an attack.

Rate limiting puts an upper bound on how much traffic a client can generate through a particular interface.

It is not a complete defence against malicious traffic. An attacker can distribute requests across many IP addresses or identities. Rate limiting is one layer of protection, not a substitute for a broader security strategy.

Noisy neighbours

A noisy neighbour is one client whose excessive usage affects other clients sharing the same infrastructure.

Suppose one restaurant dashboard repeatedly requests its order history. If every request competes for the same database connections and application capacity, other restaurants may experience slower responses.

Per-client limits help prevent one client from consuming a disproportionate share of shared resources.

Infrastructure cost

Requests are not free. They may trigger database queries, cache lookups, external API calls, image processing or other expensive operations.

An endpoint that generates a delivery estimate might call multiple internal services. An endpoint that sends an SMS might incur a direct provider charge.

A rate limit can protect these expensive operations from uncontrolled usage.

Cascading failure

A cascading failure occurs when one overloaded component causes other components to become overloaded too.

For example, excessive API traffic can exhaust database connections. Requests then wait longer, occupy more application resources and trigger retries. Those retries create even more traffic.

A rate limiter can reject excess requests before they enter the expensive part of the system. This does not guarantee that the system will remain healthy, but it reduces one source of overload.

What rate limiting does not do

Rate limiting is not authentication. Authentication establishes who a client is. Rate limiting controls how frequently that client can use a resource.

It is not a firewall either. A firewall controls network traffic according to network-level rules. An application rate limiter operates with information such as user identity, API key, IP address, route and request count.

A user who has passed authentication can still exceed a rate limit. An unauthenticated client can also be rate limited before authentication is complete.

Choosing what to limit

A rate limiter needs a key that identifies the traffic being counted. The key determines which requests share a limit.

Consider a policy that permits 60 requests per minute. The question is: 60 requests per minute from whom?

Common choices include:

  • User ID: All requests belonging to one authenticated user share a limit.
  • IP address: Requests from the same network address share a limit.
  • API key: Requests made with the same API credential share a limit.
  • Route: Requests to a particular endpoint share a limit.
  • User ID and route: Each user gets a separate limit for each endpoint.

For example, a restaurant listing endpoint might have a per-user limit, while an expensive order-placement endpoint might have a stricter per-user limit of its own.

A key can combine multiple values:

user:4821:GET:/v1/restaurants
api-key:partner-17:POST:/v1/orders
ip:203.0.113.10:POST:/v1/auth/login

The exact format is an implementation decision. The important point is that requests that should share a limit must produce the same key.

IP addresses and shared networks

IP-based limits are useful when the client is not authenticated. However, an IP address does not always identify one person or device.

Many users can share a public IP address because they are behind a Network Address Translation (NAT) gateway. This is common in offices, universities, homes and mobile networks.

If 200 people use the same public IP address, a strict per-IP limit can affect all of them. A single user might consume enough of the shared allowance to block everyone else.

The reverse problem also exists. A client can use different IP addresses and avoid a limit based on one address.

For authenticated requests, a user ID or API key is often a better primary identity. IP-based limits can still provide an additional layer of protection.

There is also a trust boundary around forwarded IP headers. Headers such as X-Forwarded-For can be supplied by clients. Your backend should trust them only when the request comes through a known proxy that is configured to set or sanitize them.

Request admission is not request processing

A rate limiter makes an admission decision. It does not process the request itself.

The decision is conceptually simple:

go
Allow(key string) bool

A true result means the request is permitted to continue. A false result means the request should be rejected.

The request still needs to pass through authentication, validation, business logic and any other relevant middleware. A successful admission does not guarantee that the operation will succeed.

Likewise, a rejected request should not reach the expensive handler.

This distinction matters because a limiter should run early enough to protect downstream resources, but it must have access to the identity used to construct its key.

The five algorithms

Different algorithms enforce limits in different ways. Some allow bursts, some smooth traffic, and some count requests in a precise time interval.

We will study five approaches:

  1. Token bucket
  2. Fixed window counter
  3. Sliding window log
  4. Sliding window counter
  5. Leaky bucket

No algorithm is universally best. The right choice depends on the traffic pattern, the resource being protected and the operational complexity you can accept.

1. Token bucket

The Token bucket algorithm is useful when clients should be allowed to make short bursts of requests but must stay within a sustainable average rate.

Imagine a bucket that holds tokens. Each admitted request consumes one token. Tokens are added back at a fixed rate, but the bucket cannot hold more than its capacity.

The algorithm has two configuration values:

  • Capacity: The maximum number of tokens the bucket can hold.
  • Refill rate: The number of tokens added per unit of time.

Suppose a bucket has a capacity of 5 tokens and refills at 1 token per second.

A request is admitted if at least one token is available. The request consumes one token. If the bucket is empty, the request is rejected.

Step by step

Assume the bucket starts full.

TimeEventTokens before requestTokens after request
0sInitial state55
0sRequest A54
0sRequest B43
0sRequest C32
0sRequest D21
0sRequest E10
0sRequest F0Rejected
1sRefill, then request G10
2sRefill, then request H10

The client can make five requests immediately because the bucket starts with five tokens. After that, it can sustain approximately one request per second.

The refill rate controls the long-term rate. Capacity controls how large a burst the client can make.

Lazy refill

A straightforward implementation might run a timer that adds tokens to every bucket at regular intervals. That is usually unnecessary.

Instead, a limiter can calculate how many tokens should have been added whenever a request arrives. This is called lazy refill.

The calculation is:

[ \text{elapsed} = \text{now} - \text{last refill time} ]

[ \text{new tokens} = \min(\text{capacity},\ \text{old tokens} + \text{elapsed seconds} \times \text{refill rate}) ]

After calculating the available tokens, the limiter updates the last refill time. If a request is admitted, it subtracts one token.

For example, suppose the bucket contains 2 tokens, its refill rate is 2 tokens per second, and 1.5 seconds have passed.

[ 2 + (1.5 \times 2) = 5 ]

If the capacity is 5, the bucket now contains 5 tokens. It cannot grow beyond capacity, even if the client has been idle for a long time.

Lazy refill avoids background work for buckets that receive no traffic. It also avoids maintaining a timer for every client.

Show a token bucket with capacity 5 and refill rate 1 token per second over time, including requests consuming tokens, one request rejected when empty, and the bucket level at every step.Show a token bucket with capacity 5 and refill rate 1 token per second over time, including requests consuming tokens, one request rejected when empty, and the bucket level at every step.

Advantages and limitations

Token bucket supports bursts while enforcing a sustainable average rate. It is useful for APIs where short bursts are normal, such as users quickly navigating between screens.

Its state is small: a token count and a last-refill timestamp per key. The main implementation challenge is ensuring that concurrent requests cannot consume the same token. That synchronization is covered in lesson 1.10.

2. Fixed window counter

The Fixed-window counter algorithm divides time into fixed intervals. Each interval has its own request counter.

Suppose the limit is 5 requests per 10 seconds. The windows might be:

  • 00:00 through 00:09
  • 00:10 through 00:19
  • 00:20 through 00:29

The exact boundary convention must be consistent. A common approach uses half-open intervals, where a window includes its start but excludes its end.

For a request at time (t), the window start can be calculated as:

[ \text{window start} = \left\lfloor \frac{t}{10} \right\rfloor \times 10 ]

The limiter maintains a count for the current window. If the count is below 5, it increments the count and admits the request. Otherwise, it rejects the request.

The boundary burst problem

Fixed windows are easy to understand, but they have an important weakness.

Imagine the limit is 5 requests per 10 seconds.

A client sends five requests at second 9. They belong to the window from second 0 to second 10.

At second 10, a new window begins. The counter resets. The client sends five more requests at second 11.

All ten requests are admitted, even though they arrived within two seconds.

TimeWindowRequests in windowResult
9s0 to 101 to 5All allowed
11s10 to 201 to 5All allowed

The configured limit is five requests per ten-second window, but the client can briefly send ten requests across a boundary.

This is the boundary burst problem. It is not an implementation bug. It is a consequence of resetting the counter at fixed boundaries.

Show a fixed-window limit of five requests per ten seconds with five requests at second 9 and five at second 11 all admitted, then show the same ten requests inside a sliding ten-second interval where the excess requests are rejected.Show a fixed-window limit of five requests per ten seconds with five requests at second 9 and five at second 11 all admitted, then show the same ten requests inside a sliding ten-second interval where the excess requests are rejected.

Advantages and limitations

A fixed window needs very little state: a counter and a window identifier. It is simple to implement and efficient to store in Redis.

Its main disadvantage is the boundary burst. It is a good choice when simplicity and low memory usage matter more than strict rolling-window accuracy.

The course implements a local fixed window and later a Redis-backed fixed window.

3. Sliding window log

The Sliding-window log algorithm tracks the timestamp of every admitted request.

Suppose the policy allows 5 requests in any rolling 10-second period.

When a new request arrives:

  1. Remove timestamps that are outside the current 10-second interval.
  2. Count the remaining timestamps.
  3. If fewer than 5 remain, record the new request and admit it.
  4. Otherwise, reject the request.

Unlike a fixed window, the interval moves with the current request.

For example, when a request arrives at second 11, the limiter checks the interval from second 1 through second 11. Requests at second 9 remain in the interval, even though the fixed window has changed.

This prevents the boundary burst. The limiter evaluates the actual rolling interval rather than a calendar-like bucket.

Accuracy and memory

The sliding window log is exact for the timestamps it records. It can answer how many requests occurred in the previous interval without estimating their distribution.

The cost is memory. If a client makes (n) requests during the window, the limiter stores (n) timestamps.

That means memory usage is (O(n)) per key. A high-volume client can create a large number of timestamp entries.

The algorithm also has more work to do on each request because it must remove expired timestamps and count the remaining ones. A suitable data structure can make these operations efficient, but the state is still proportional to the number of requests being tracked.

A Redis sorted set is one possible way to store timestamped entries. You will encounter sorted sets and their operations in the Redis material later in the course.

4. Sliding window counter

The Sliding-window counter algorithm estimates the number of requests in a rolling interval using two fixed-window counters.

It stores:

  • The count in the current window.
  • The count in the previous window.

It then calculates a weighted blend based on how far the current time has progressed through the current window.

Suppose the limit is 100 requests per minute. The current minute is 30 seconds old, meaning half of the current window has elapsed.

The previous window's requests are gradually discounted because older requests are less likely to fall inside the current rolling minute.

A common estimate is:

[ \text{estimated count} = \text{current count} + \text{previous count} \times (1 - \text{current window progress}) ]

Suppose:

  • Previous window count: 80
  • Current window count: 40
  • Current window progress: 0.5

Then:

[ 40 + (80 \times 0.5) = 80 ]

The estimated rolling count is 80. If the limit is 100, the request can be admitted.

Why it is approximate

The algorithm does not know exactly when each request in the previous window occurred. It assumes that those requests are distributed evenly across that window.

If most previous-window requests arrived at its very beginning, the estimate may count too many of them. If most arrived at its end, the estimate may count too few.

The result is an approximation, not an exact count.

Its advantage is predictable memory usage. It stores two counters per key, so memory is (O(1)) per key.

It is a useful compromise when a fixed window's boundary burst is undesirable but storing every request timestamp is too expensive.

5. Leaky bucket

The Leaky bucket algorithm models traffic as water entering a bucket with a small outlet. Water leaves at a constant rate.

In a request-processing system, the bucket represents a queue. Incoming requests are added to the queue, and the system processes queued requests at a steady rate.

For example, a queue might accept up to 10 pending requests and drain at 2 requests per second.

If requests arrive faster than the queue drains, the queue grows. If it reaches capacity, new requests are rejected.

Queue-based leaky bucket

The queue-based form smooths outgoing traffic. Even if many requests arrive together, they leave the queue at a controlled rate.

This is useful when a downstream service needs steady traffic rather than sudden bursts.

However, a queue introduces waiting time. A request may be admitted but not processed immediately. If the queue becomes long, the client may wait too long for a response.

A queue also needs a maximum size. An unbounded queue can turn overload into excessive memory usage and high latency rather than preventing it.

Meter-based leaky bucket

A meter variant does not necessarily queue requests for later processing. Instead, it measures incoming traffic against a steady allowance and rejects requests that exceed it.

This form is closer to an admission-control limiter. It can enforce a smooth rate without retaining a queue of pending work.

Leaky bucket versus token bucket

These algorithms are often confused because both regulate traffic over time.

A token bucket allows bursts up to its capacity. It then admits requests at the refill rate as tokens become available.

A queue-based leaky bucket smooths output. Requests wait in the queue and leave at a constant rate.

Choose token bucket when short bursts are acceptable and useful. Choose a queue-based leaky bucket when downstream work must be processed at a steady pace.

Comparing the five algorithms

AlgorithmMemory per keyAccuracyBurstinessImplementation difficultyBest use
Token bucketO(1)Enforces configured refill and capacity rulesAllows bounded burstsMediumGeneral API traffic with short bursts
Fixed window counterO(1)Exact within each fixed windowCan allow nearly 2x traffic at a boundaryLowSimple quotas and basic API limits
Sliding window logO(n) timestampsExact rolling-window countStrictly limited by the rolling intervalHighStrict limits where memory cost is acceptable
Sliding window counterO(1)Approximate rolling-window countReduces boundary burstsMediumHigh-volume APIs needing a practical compromise
Leaky bucketO(1) meter state, or queue-sized stateDepends on meter or queue implementationSmooths output in queue formMedium to highProtecting downstream systems from traffic spikes

The memory column describes state for one limiting key, not the total memory used by every client. A service with millions of distinct keys can still consume substantial memory even when each key uses only a constant amount.

Returning a useful HTTP response

When a client exceeds its limit, the standard HTTP status is 429 Too Many Requests.

The response should tell the client that it was rejected because of a rate limit, rather than making the client interpret an unrelated server error.

A useful response from the course API looks like this:

http
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 3

{"error":"rate_limited"}

The JSON body gives the client a machine-readable error. The Retry-After header tells it how long to wait before trying again.

The value can be a number of seconds or an HTTP date. A numeric value is straightforward for a client to interpret.

The value should be based on when capacity is expected to become available. It should not be an arbitrary constant if the limiter can calculate a more useful retry time.

Rate-limit headers

The API can also return X-RateLimit headers that describe the active limit and the client's remaining allowance.

Three commonly used headers are:

  • X-RateLimit-Limit: The configured request limit.
  • X-RateLimit-Remaining: The estimated number of requests still available.
  • X-RateLimit-Reset: The time when the current limit window resets, commonly represented as a Unix timestamp.

For example:

http
HTTP/1.1 200 OK
Content-Type: application/json
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 12
X-RateLimit-Reset: 1793613600

{"items":[]}

These headers are useful to clients that want to avoid sending requests they know will be rejected.

The exact meaning of the reset value depends on the algorithm. A fixed window has a clear window boundary. A token bucket refills continuously, so a single reset timestamp may be less informative. Document the semantics your API uses.

These X-RateLimit headers are application-level conventions. They are not a replacement for the standard HTTP status and Retry-After behavior.

Clients should not retry immediately

A client that receives a 429 should not immediately repeat the same request. Doing so can create a retry storm, where many clients keep adding load to an already busy service.

A well-behaved client should:

  1. Read and honour Retry-After when it is present.
  2. Wait before retrying.
  3. Use exponential backoff when repeated failures continue.
  4. Add random jitter to the delay so clients do not all retry at the same instant.
  5. Stop retrying after a reasonable number of attempts.

Jitter is a random variation added to a retry delay. It spreads retries over time and reduces the chance that many clients will hit the server together.

A rate limiter can reject requests correctly and still cause unnecessary load if clients ignore its response.

What happens when the limiter itself fails?

A rate limiter is another component that can fail. It may run out of memory, lose access to Redis, encounter a timeout or return an unexpected error.

The API must decide what to do when it cannot obtain a reliable admission decision.

There are two common policies.

Fail open

The fail open policy admits the request when the limiter is unavailable.

This prioritizes application availability. If Redis becomes unreachable, users can still place orders or browse restaurants rather than having every request rejected.

The downside is that the application temporarily loses the protection provided by the limiter. Excessive traffic may reach downstream services.

Fail open is often appropriate for ordinary read endpoints where denying all traffic would be worse than temporarily allowing extra traffic.

It must not be treated as a reason to ignore the failure. The service should record the problem, expose useful metrics and recover when the dependency becomes available.

Fail closed

The alternative is to reject requests when the limiter cannot make a decision.

This is called fail closed. It prioritizes enforcing the limit over application availability.

It may be appropriate for operations where allowing uncontrolled requests would create a serious cost, abuse or security risk.

For example, an endpoint that triggers an expensive third-party operation may need stricter protection than a restaurant listing endpoint.

Neither policy is always correct. Choose based on the consequences of admitting too much traffic versus rejecting legitimate traffic.

The Week 1 Redis implementation uses fail open with an in-memory fallback. It attempts to preserve some protection when Redis is unavailable, while allowing requests if the fallback cannot enforce the intended limit.

Why several API servers change the problem

So far, each algorithm has been described as if one process handles all requests.

That assumption breaks when an application runs on several servers.

Imagine two API instances behind a load balancer. Each instance has its own in-memory fixed-window counter. The limit is 5 requests per minute.

A client sends 5 requests to the first instance and 5 to the second. Each instance sees only 5 requests and admits them. The client has made 10 requests even though the intended limit was 5.

The problem is that the counters are local. They do not share state.

A distributed limiter needs shared state or another coordination strategy so that all API instances make decisions against a consistent limit.

In this course, Redis provides that shared state. The Redis lessons introduce atomic operations, expiry and transaction pipelines. Those topics make it possible for multiple API instances to coordinate their fixed-window counts.

Distributed rate limiting introduces additional concerns:

  • Network latency between the API and Redis.
  • Redis timeouts and connection failures.
  • Atomicity when multiple requests update the same key.
  • Key expiry and cleanup.
  • What happens when Redis is unavailable.
  • How much inconsistency the application can tolerate.

A local limiter is useful for learning the algorithms. It is not automatically a correct distributed limiter.

Choosing a limit from capacity

A limit should not be chosen only because a round number looks convenient.

Start with the resource being protected. Estimate how much work the endpoint performs and how much of that work the service can safely handle.

For example, a simple cached restaurant listing request may be much cheaper than an order-placement request that writes to MySQL and publishes an event.

Consider:

  • The expected number of legitimate users.
  • Normal request frequency for each user.
  • Short bursts caused by navigation or retries.
  • The cost of the endpoint.
  • Database and downstream service capacity.
  • The number of API instances.
  • The effect of NAT and shared client identities.
  • The latency users can reasonably tolerate.

A useful limit should allow normal user behavior while preventing one client from consuming an unreasonable share of capacity.

Measure actual traffic before tightening limits in production. Start with a defensible policy, observe rejections and latency, then adjust it based on evidence.

What this course implements

Week 1 focuses on two algorithms.

First, you implement a token bucket in exercise 1.11. This teaches capacity, refill rate, per-key state and request admission.

Next, you implement a fixed-window counter in exercise 1.14. This gives you a simpler algorithm with a different burst profile.

The HTTP exercises 1.18 and 1.19 connect admission decisions to the HTTP contract. You will return 429 responses, include a JSON error body and calculate Retry-After.

Exercise 1.22 moves the fixed-window counter to Redis. It introduces shared state across API instances and a fail-open policy when Redis is unavailable.

The remaining algorithms are optional extensions. Exercises 1.26 to 1.30 explore alternatives and improvements without being required to complete Week 1.

The next lesson covers the Go implementation details that these algorithms need: protecting shared state, handling elapsed time and injecting a clock so that behavior can be tested deterministically.

Knowledge assessment

Question 1 of 4

A user sends five requests immediately and then one request per second afterward. Which rate-limiting algorithm naturally supports this pattern, and what controls the initial burst?

Pick an answer, then say how sure you are.

Practical applications

  • Exercise 1.11: Implement a token bucket with capacity, refill rate and per-key admission decisions.
  • Exercise 1.14: Implement a fixed-window counter and observe its boundary behavior.
  • Exercise 1.18: Return a correct HTTP 429 response when a request is rejected.
  • Exercise 1.19: Calculate and return a useful Retry-After value.
  • Exercise 1.22: Implement a Redis-backed fixed window shared across API instances, with fail-open behavior.
  • Optional exercises 1.26 to 1.30: Explore alternative algorithms and extensions without blocking the required course path.

References

Everything above is explained on this page; these are where it comes from (Go 1.2x).

Finished Lesson 1.9?