Skip to main content
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."
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.
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."
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.
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."
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)
Example Python usage with redis-py
Quick comparison: Fixed-minute counter vs Token bucket 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/.
  • 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/.
  • 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 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.

Watch Video