Skip to main content
← CONCEPTS / SECURITY & IDENTITY
An end-to-end domain learning journey

Rate Limiting Algorithms, Token
Buckets & Redis Lua.

Rate limiting enforces caps on request or resource consumption per caller, tenant, or endpoint over time to protect downstream capacity, ensure fair multi-tenant sharing, and blunt abuse.
Start the journey7 sections· Last modified Nov 29, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If credentials or tokens are verified at the edge, Token Buckets & Redis Lua, pair an in-memory local limiter (token bucket) for sub-millisecond burst protection with a Redis Lua sliding-window or token-bucket store for global tenant quotas, and always return HTTP 429 with `Retry-After`.

TL;DR30-second simplified summary
▾

Core Mechanics: Rate limiting decouples incoming demand from system capacity by enforcing an admission budget keyed by tenant_id, api_key, or ip:route before expensive auth or database work runs.

Visual & Structural Flow: Depicts Two-Tier Local Token Bucket + Redis Lua Global Rate Limiter (API Client -> Gateway L1 Bucket -> Redis Lua (L2) -> Origin Service); Local Token-Lease Batching + Async Redis Sync (Client (500k RPS) -> Edge Gateway -> Regional Redis).

Trade-Offs & Production: Choose the algorithm based on memory per key, burst tolerance, and exactness. To eliminate cross-region RTT and Redis hot-key contention at 500,000 RPS, regional Envoy gateways enforce local in-memory Token Buckets and asynchronously batch-sync quota leases.

Failure Modes & Application: Explore distributed rate limiter architectures, token bucket designs, and retry-storm prevention.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
PRIME Core Invariants & Workload Constraints
Establish concrete scale, latency, memory, and concurrency bounds for Rate Limiting Algorithms, Token Buckets & Redis Lua before selecting data structures or storage components.
Failure Boundaries & Operational Trade-Offs
Identify hot-key skew, partial failures, resource leaks, and when simpler single-node or standard alternatives outperform complex designs.
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

What is Rate Limiting.

Why this matters: The mechanism: understand how Rate Limiting works from first principles.

Rate limiting decouples incoming demand from system capacity by enforcing an admission budget keyed by tenant_id, api_key, or ip:route before expensive auth or database work runs.

Token Bucket allows controlled bursts up to capacity BB while capping sustained rate at RR tokens/sec in O(1)O(1) memory. Leaky Bucket smooths bursts into a constant egress rate. Sliding Window Counter eliminates the 2x boundary-burst spike of Fixed Windows in O(1)O(1) space.

Hybrid Edge + Global Quota

Two-Tier Local Token Bucket + Redis Lua Global Rate Limiter

API Client429 + Retry-AfterGateway L1 BucketSub-ms burst shieldRedis Lua (L2)Atomic TIME + PEXPIREOrigin ServiceProtected capacity429 + Retry-AfterSub-ms burst shieldAtomic TIME + PEXPIRE

Hybrid local + Redis Lua rate limiting protects origin pools in <1 ms without a single point of failure.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why we need Rate Limiting (Race Conditions & Boundary Stampedes).

Why this matters: The problem: see what breaks without Rate Limiting under real concurrency or scale.

Think of Why we need Rate Limiting (Race Conditions & Boundary Stampedes) as the intuition layer for Rate Limiting Algorithms, Token Buckets & Redis Lua: The problem: see what breaks without Rate Limiting under real concurrency or scale.

Without rate limiting, a single buggy retry loop or scraper saturates DB pools and causes 503 outages for all tenants. Implementing it naively introduces two classic bugs: (1) separate Redis GET then INCR commands create read-modify-write race conditions that over-admit concurrent bursts; (2) Fixed Window Counters allow 2x quota (1,000 req at 12:00:59 + 1,000 req at 12:01:01).

Request & State Flow

Why we need Rate Limiting (Race Conditions & Boundary Stampedes)

API CallerAPI GatewayRedis Lua CounterUpstream Service1. Send API request + tenant key2. EVALSHA atomic token decrement3. Allow (tokens > 0) or 4294. Forward admitted request
Engineering Decision Framework
Problem
How to implement Rate Limiting Algorithms, Token Buckets & Redis Lua without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
If credentials or tokens are verified at the edge, token Buckets & Redis Lua, pair an in-memory local limiter (token bucket) for sub-millisecond burst protection with a Redis Lua sliding-window or token-bucket store for global tenant quotas, and always return HTTP 429 with Retry-After.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Rate Limiting Algorithms, Token Buckets & Redis Lua experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

Weighted Cost Budgets

Charge cost = 1 for GET /items/{id} and cost = 25 for POST /search/export against the same tenant bucket so heavy routes cannot starve cheap ones.

IETF RateLimit Headers + `429`

Always return 429 Too Many Requests (never 500/503) with Retry-After, RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where Rate Limiting applies (and where Healthchecks Must Bypass).

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of Where Rate Limiting applies (and where Healthchecks Must Bypass) as the intuition layer for Rate Limiting Algorithms, Token Buckets & Redis Lua: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Apply rate limits to public APIs, login/OTP endpoints, and expensive LLM/export routes; exempt internal healthchecks and metrics scrapes.

ChoiceWhat it buysWhat it costs
Good Candidate: Public APIs, Login/OTP & Multi-Tenant QuotasPrevents brute-force attacks, scraping, and noisy-neighbor DB pool exhaustion.Requires keying authenticated routes on `tenant_id`/`api_key_hash` rather than shared carrier NAT IPs.
Avoid: `/healthz`, Readiness & Prometheus Scrape PathsKeep probe endpoints unthrottled so Kubernetes never triggers false-positive pod restarts under load.Throttling `/healthz` turns a traffic spike into a cascading pod-eviction outage.
Avoid: Pure Downstream Slowness BottlenecksUse adaptive concurrency limits (Vegas/Gradient2) or backpressure when downstream latency degrades regardless of RPS.Static RPS limits cannot adapt when DB queries slow from 5 ms to 500 ms.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

How Atomic Token Buckets & Redis Lua are implemented.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Think of How Atomic Token Buckets & Redis Lua are implemented as the intuition layer for Rate Limiting Algorithms, Token Buckets & Redis Lua: Operational control: configure bounds, failure handling, and safe production defaults.

Use Redis TIME inside Lua scripts (avoiding gateway wall-clock skew), attach PEXPIRE TTLs to every key so one-off IPs never leak RAM, and deploy new limits in shadow/dry-run mode (enforce: false) before blocking traffic.

-- Atomic Redis Token Bucket (KEYS[1]=key, ARGV[1]=cap, ARGV[2]=rate_per_sec, ARGV[3]=cost)
local t = redis.call('TIME')
local now = tonumber(t[1]) + tonumber(t[2]) / 1000000
local data = redis.call('HMGET', KEYS[1], 'tokens', 'ts')
local tokens = tonumber(data[1]) or tonumber(ARGV[1])
local last = tonumber(data[2]) or now

tokens = math.min(tonumber(ARGV[1]), tokens + math.max(0, now - last) * tonumber(ARGV[2]))
local allowed = 0
if tokens >= tonumber(ARGV[3]) then
 tokens = tokens - tonumber(ARGV[3])
 allowed = 1
end
redis.call('HMSET', KEYS[1], 'tokens', tokens, 'ts', now)
redis.call('PEXPIRE', KEYS[1], math.ceil((tonumber(ARGV[1]) / tonumber(ARGV[2])) * 1000) + 1000)
return {allowed, math.floor(tokens)}
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives: Token Bucket vs. Sliding Window Log vs. Sliding Window Counter.

Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Think of Alternatives: Token Bucket vs. Sliding Window Log vs. Sliding Window Counter as the intuition layer for Rate Limiting Algorithms, Token Buckets & Redis Lua: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Choose the algorithm based on memory per key, burst tolerance, and exactness.

Design Trade-Off

Alternatives: Token Bucket vs. Sliding Window Log vs. Sliding Window Counter

Before · Naive Get-Then-Set
  • Race condition drops limits
  • Redis round-trip per check
  • Thundering retry storm
After · Atomic Lua + Local Burst
  • Single-RTT atomic Lua script
  • Retry-After jittered backoff
  • Per-tenant quota isolation
ChoiceWhat it buysWhat it costs
Token Bucket (Redis Hash / Local)$O(1)$ memory (2 numbers), allows controlled bursts up to $B$, zero boundary spikes.Requires atomic Lua script for distributed accuracy.
Sliding Window Counter$O(1)$ memory and smooths 2x fixed-window boundary spikes via weighted overlap.Approximate interpolation across the previous window.
Sliding Window Log (Redis `ZSET`)100% exact to the millisecond with zero boundary approximation.Stores $O(N)$ timestamps per key—explodes RAM for high-rate tenants.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Production example: Multi-Region Gateway with Token-Lease Batching.

Why this matters: Production architecture: see how the components compose end to end under real load.

Think of Production example: Multi-Region Gateway with Token-Lease Batching as the intuition layer for Rate Limiting Algorithms, Token Buckets & Redis Lua: Production architecture: see how the components compose end to end under real load.

To eliminate cross-region RTT and Redis hot-key contention at 500,000 RPS, regional Envoy gateways enforce local in-memory Token Buckets and asynchronously batch-sync quota leases (INCRBY 50) with a regional Redis/Valkey shard every 50–100 ms.

Hot-Key Mitigation

Local Token-Lease Batching + Async Redis Sync

Client (500k RPS)Edge GatewayRegional Redis1. Burst requests (sub-ms localcheck)2. Batch lease 50 tokens viaEVALSHA3. Bucket empty -> 429 +Retry-After

Batching 50-token leases cuts Redis QPS by 50x and keeps normal API checks at sub-millisecond local latency.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

Problems solved by Rate Limiting & System Design Deep Dives.

Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.

Think of Problems solved by Rate Limiting & System Design Deep Dives as the intuition layer for Rate Limiting Algorithms, Token Buckets & Redis Lua: Applied problems: connect these internals to concrete system design and debugging scenarios.

Explore distributed rate limiter architectures, token bucket designs, and retry-storm prevention.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 4
Score: 0/4

Why are separate Redis `GET` and `SET`/`INCR` commands unsafe for enforcing API rate limits across concurrent gateway pods?

Recommended Learning Flow