RELIABILITY, SECURITY & CASE STUDIES · SUBTOPIC
Token Bucket vs. Sliding Window Algorithms
Compare burst-friendly Token Bucket against strict Leaky Bucket and accurate Sliding Window counters.
IntermediatePart of Rate Limiting & Throttling
Subtopics in Rate Limiting & Throttling (2)
In plain words
Token Bucket gives you a small jar of tokens refilling steadily - if you haven’t used any for a minute, you can spend a few in a quick burst. Sliding Window strictly checks the exact past 60 seconds so you can’t cheat at midnight boundaries.
Think of it like…
Arcade tokens refilling 1/second up to a jar of 10 (Token Bucket) vs. strict rolling 60-second punch card (Sliding Window).
Loading interactive diagram
Loading interactive exercise
Theory & how it works
Why Redis Lua scripts are essential
If Gateway 1 and Gateway 2 both read tokens = 1 from Redis at the same millisecond and both decrement to 0, both requests slip through (race condition). Putting the read-refill-decrement inside one Redis Lua script executes atomically on Redis’s single thread.
Key points & practical guide
Summary checklist
- Token Bucket = simple, allows controlled bursts
- Sliding Window Counter = prevents 2× boundary spike
- Run check+decrement atomically via Redis Lua; fail-open if Redis briefly blips (for non-security APIs)
When to use it
- Public APIs, login/OTP brute-force protection, multi-tenant SaaS fairness
Watch out for
- Naive Fixed Window counters allowing 2× quota across
:59and:00
Quick check
Loading quiz