> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Design an API Rate Limiter

> Designing a scalable per-user API rate limiter using token-bucket algorithm with Redis and atomic Lua scripts to enforce 100 requests per minute, avoiding fixed-minute counter pitfalls.

Let's design an API rate limiter for an application that must handle thousands of requests per second. The requirement: each user is allowed 100 API calls per minute.

![A dark-themed diagram labeled "API RATE LIMITER" showing a stick figure at a laptop sending requests down to a server box. A partially filled progress bar below the server reads "31 / 100."](https://mintcdn.com/kodekloud-c4ac6d9a/2h0o-_DtLcLu6HM7/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/System-Design/Design-an-API-Rate-Limiter/api-rate-limiter-progress-31-100.jpg?fit=max\&auto=format\&n=2h0o-_DtLcLu6HM7\&q=85\&s=5fa3eb0ea4b58df1323aca092adf0652)

Summary of the basic flow: a user sends requests to your servers; each request should be checked against a per-user rate policy and accepted or rejected (HTTP 429) accordingly.

Counter-based approach (simple, but flawed)
A common, straightforward implementation is to maintain a per-user counter keyed by the current minute: store (userID, count, minute). On each request, increment the counter; reject the request once it exceeds 100. This is easy to implement and can be OK for low-scale or internal systems.

![A dark-themed diagram titled "COUNTER" showing a user record: User ID "alan" with a count of API calls (100) and current minute 12:04. Below it is a labeled "INTERNAL" box with server icons suggesting backend infrastructure.](https://mintcdn.com/kodekloud-c4ac6d9a/2h0o-_DtLcLu6HM7/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/System-Design/Design-an-API-Rate-Limiter/counter-alan-api-count-internal.jpg?fit=max\&auto=format\&n=2h0o-_DtLcLu6HM7\&q=85\&s=b9a8bdb22afb59bc04d4cf30c5c58515)

Why the fixed-minute counter is problematic
Two realistic scenarios demonstrate surprising and undesirable behavior with a per-minute counter:

* Alan sends 100 requests in the first 2 seconds of the minute. The minute counter hits 100 and Alan is blocked for the remaining \~58 seconds, then can immediately send 100 more requests at the next minute boundary.
* John sends 100 requests in the last second of a minute. Once the minute flips, his counter resets and he can immediately send another 100 requests. Over a two-second window he effectively sent 200 requests.

This shows the core flaw: the counter watches the clock instead of observing the user’s actual rate of requests. Rate limiting should be user-centric and capacity-driven, not tied to minute boundaries.

![A dark presentation slide titled "Why This Solution Is Not Good" showing a stick-figure labeled "John" and a dashboard card that reads "Count of API Calls 100" with the time 12:05. To the right is a small bar chart highlighting two 100-count bars at the 12:04–12:05 boundary labeled "Next Minute."](https://mintcdn.com/kodekloud-c4ac6d9a/2h0o-_DtLcLu6HM7/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/System-Design/Design-an-API-Rate-Limiter/why-solution-not-good-api-100.jpg?fit=max\&auto=format\&n=2h0o-_DtLcLu6HM7\&q=85\&s=7f47a1200b4cda1d1c512f80f5add2db)

The recommended approach: Token Bucket (user-centric, predictable)
Use a token-bucket per user:

* Each user has a bucket with capacity = 100 tokens.
* Each request consumes 1 token.
* Tokens refill over time at a steady rate: 100 tokens per minute ≈ 1.6667 tokens/second (for examples you can approximate to 2 tokens/sec).
* If the bucket is empty, requests are rejected. If it’s full, the user can burst up to the capacity.

This algorithm allows controlled bursts up to the bucket size while enforcing a long-term average rate. Many providers use variants of this (Stripe, GitHub, cloud API gateways).

![A dark-themed diagram titled "TOKEN BUCKET" showing a large bucket graphic partially filled and marked "100" with an arrow from a stick-figure above. To the right are circular Stripe and GitHub icons with their labels.](https://mintcdn.com/kodekloud-c4ac6d9a/2h0o-_DtLcLu6HM7/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/System-Design/Design-an-API-Rate-Limiter/token-bucket-100-stripe-github.jpg?fit=max\&auto=format\&n=2h0o-_DtLcLu6HM7\&q=85\&s=825d9e69131f865e1c723284ecd3d9f0)

How token bucket behaves for the earlier examples

* Alan drains 100 tokens in 2 seconds. After that he is limited to the refill rate (≈1.67 tokens/sec) until the bucket recovers.
* John drains 100 tokens at the end of the minute and must wait for tokens to refill; he cannot exploit a clock boundary to immediately perform another large burst.

Where should buckets be stored?
At small scale you can keep bucket state in memory on a single server. In production, multiple app servers handle requests in parallel (e.g., 20+ instances). Two concurrent requests for the same user could land on different servers, so bucket state must be in a shared, low-latency store that supports atomic updates.

![A dark infographic titled "STORE THESE BUCKETS" with a stick-figure icon above a grid of 20 tiles, each showing a server and a yellow bucket icon. The bottom caption reads "20 different servers."](https://mintcdn.com/kodekloud-c4ac6d9a/2h0o-_DtLcLu6HM7/images/DevOps-Interview-Questions-and-Answers-Scenario-Based-Prep/System-Design/Design-an-API-Rate-Limiter/store-these-buckets-20-servers.jpg?fit=max\&auto=format\&n=2h0o-_DtLcLu6HM7\&q=85\&s=bf2b540dbce8dc1d469b9a8849063083)

Redis is a common choice for this shared store because of its low latency and rich command set. To prevent race conditions from concurrent requests, perform the read-modify-write update atomically. The recommended pattern is to run a Redis Lua script (EVAL) that:

* Reads the stored token count and last refill timestamp,
* Computes tokens to add based on elapsed time and refill rate,
* Checks if enough tokens exist for the current request,
* If allowed, subtracts tokens and updates the timestamp atomically,
* Returns an allow/deny result.

Atomic token-bucket Lua script (Redis EVAL)

```lua theme={null}
-- KEYS[1] = bucket key (e.g., "rate:user:123")
-- ARGV[1] = capacity (e.g., 100)
-- ARGV[2] = refill_per_second (e.g., 1.6667)
-- ARGV[3] = requested_tokens (usually 1)

local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_per_sec = tonumber(ARGV[2])
local requested = tonumber(ARGV[3])

-- Use Redis server time (seconds + microseconds) for high-resolution timing
local time_data = redis.call('TIME')            -- returns table: { seconds, microseconds }
local now = tonumber(time_data[1]) + tonumber(time_data[2]) / 1000000.0

local data = redis.call('HMGET', key, 'tokens', 'timestamp')
local tokens = tonumber(data[1])
if tokens == nil then
  tokens = capacity
end
local last_ts = tonumber(data[2]) or now

local elapsed = now - last_ts
local filled = elapsed * refill_per_sec
tokens = math.min(capacity, tokens + filled)

if tokens >= requested then
  tokens = tokens - requested
  redis.call('HSET', key, 'tokens', tostring(tokens), 'timestamp', tostring(now))
  return 1
else
  redis.call('HSET', key, 'tokens', tostring(tokens), 'timestamp', tostring(now))
  return 0
end
```

Example Python usage with redis-py

```python theme={null}
import redis

r = redis.Redis(host="redis-host", port=6379, db=0)

lua_script = """
-- (paste the Lua script here)
"""

sha = r.script_load(lua_script)

key = "rate:user:123"
capacity = 100
refill_per_sec = 100.0 / 60.0  # ~1.6667 tokens/sec
requested = 1

allowed = r.evalsha(sha, 1, key, capacity, refill_per_sec, requested)
if allowed == 1:
    # process request
    pass
else:
    # reject request (429 Too Many Requests)
    pass
```

Quick comparison: Fixed-minute counter vs Token bucket

| Approach | Behavior | Pros | Cons |
| - | - | - | - |
| Fixed-minute counter | Counts within clock-aligned minute windows | Simple to implement; low memory | Allows boundary spikes; unfair bursts; depends on clock boundaries |
| Token bucket | Per-user capacity + refill rate (e.g., 100 tokens, 1.6667/sec) | Predictable, user-centric, allows controlled bursts | Requires shared, consistent store and atomic updates (e.g., Redis + Lua) |

Operational considerations and tips

* Use Redis server time via `redis.call('TIME')` in the Lua script to avoid clock skew between application servers. See TIME: [https://redis.io/commands/time/](https://redis.io/commands/time/).
* Running the token-bucket logic in a Redis Lua script ensures the read-modify-write is atomic and avoids race conditions across multiple app servers.

- Refill granularity: you can use fractional tokens (floating-point) and refill continuously using elapsed-time calculation. This provides smoother behavior than integer-only refills.
- Hot keys & scaling: for very high scale or very hot users, use Redis Cluster or sharded key namespaces so a single Redis node doesn’t become a bottleneck. See Redis Cluster: [https://redis.io/docs/latest/cluster/](https://redis.io/docs/latest/cluster/).
- Geo-distribution and strict global limits: if you need strict global enforcement across geographic regions, expect additional latency. Consider hybrid designs: local leaky buckets for immediate throttling plus periodic global reconciliation for exact global quotas.
- Tune two parameters: bucket capacity (allowed burst) and refill rate (sustained throughput). These define how bursty or smooth the user experience is.

Atomic updates and low-latency lookups are critical. If you implement a token-bucket without atomicity, concurrent requests can overspend tokens and break the rate-limit guarantees. Always benchmark Redis latency and plan for hot-key mitigation and failover.

Related links and references

* Redis: [https://redis.io/](https://redis.io/)
* Redis EVAL / Lua scripting: [https://redis.io/commands/eval](https://redis.io/commands/eval)
* Redis TIME command: [https://redis.io/commands/time/](https://redis.io/commands/time/)
* Stripe rate limit design: [https://stripe.com/docs/rate-limits](https://stripe.com/docs/rate-limits)
* GitHub rate limiting overview: [https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting](https://docs.github.com/en/rest/overview/resources-in-the-rest-api#rate-limiting)
* Amazon API Gateway throttling: [https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html)

Conclusion
The token-bucket algorithm provides predictable, user-centric throttling that prevents minute-bound counter anomalies while permitting controlled bursts. Use a shared low-latency store (Redis) with atomic Lua scripts to implement the algorithm reliably at scale. Tune capacity and refill rate to match desired burstiness and sustained throughput for your users.

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/devops-interview-prep/module/ef53ec43-96e9-4d1b-8a6e-e6eb97b0d0dc/lesson/f18e1432-0a41-447b-ba95-3f12861d92c1)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.