Rate limiting distribuito
Coordini i limiti delle richieste tra numerose istanze dell'app usando contatori Redis e script Lua atomici per gli algoritmi fixed-window, sliding-window e token-bucket.
Rate limiting distribuito è una lezione Redis Caching & Messaging (Pub/Sub, Streams) gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Redis Caching & Messaging (Pub/Sub, Streams), e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Redis Caching & Messaging (Pub/Sub, Streams) include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Local Limits Do Not Scale
An in-memory rate limiter only counts requests on one server. With many app instances behind a load balancer, you need a shared view of usage. Redis, being central and atomic, is the natural coordination point.
Fixed Window Counter
The simplest algorithm: a counter per time window. INCR the key; set a TTL equal to the window on first increment. Reject when the count exceeds the limit.
INCR rl:user:42:1716900000
EXPIRE rl:user:42:1716900000 60The Race Condition
Doing INCR then EXPIRE as two commands risks a key without a TTL if the client dies in between. An atomic Lua script fixes this by running both as one operation.
local c = redis.call('INCR', KEYS[1])
if c == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
return cWhy Atomicity Matters
Across many instances, concurrent requests could otherwise read and write counters in interleaved order. Lua scripts run atomically on the server, so the entire check-and-increment happens with no interleaving.
Fixed Window Burst Problem
Fixed windows allow bursts at the boundary: a client can send a full window's worth at the end of one window and again at the start of the next, doubling the effective rate.
Sliding Window Log
A sorted set of request timestamps gives a precise sliding window. Drop old entries, count what remains, and add the new request, all in one script.
ZREMRANGEBYSCORE rl:user:42 0 (now-window)
ZCARD rl:user:42
ZADD rl:user:42 now nowToken Bucket
The token bucket allows controlled bursts. Tokens refill at a fixed rate up to a cap; each request consumes one. Store tokens and last-refill time in a hash and update atomically with Lua.
HSET rl:tb:user:42 tokens 10 ts 1716900000Refill Logic
On each request, compute elapsed time, add elapsed * rate tokens (capped at the bucket size), then allow the request if at least one token remains. The Lua script keeps this consistent across instances.
Choosing an Algorithm
Fixed window: cheapest, allows boundary bursts. Sliding log: precise but more memory. Token bucket: smooth with controlled bursts, great for APIs.
Returning Useful Headers
Tell clients about their limits: return remaining requests and reset time so well-behaved clients can self-throttle.
# X-RateLimit-Remaining: 7
# X-RateLimit-Reset: 1716900060Resilience Note
Decide a fallback if Redis is unreachable: fail open (allow traffic) for availability, or fail closed (deny) for protection. The right choice depends on whether the limit guards cost or correctness.
Quick Check
Test your understanding of distributed rate limiting.
Recap
You built distributed rate limiting on Redis: fixed-window counters, atomic Lua to avoid TTL leaks and races, sliding-window logs with sorted sets, and token buckets for smooth bursts. Centralizing the counters makes limits consistent across all app instances; choose your fail-open vs fail-closed fallback deliberately.
Domande Frequenti
La lezione «Rate limiting distribuito» è gratuita?
Sì — il testo completo di «Rate limiting distribuito» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Redis Caching & Messaging (Pub/Sub, Streams), passa a CoddyKit PRO. Il corso Redis Caching & Messaging (Pub/Sub, Streams) include 4 lezioni in totale.
Cosa imparerò in «Rate limiting distribuito»?
Coordini i limiti delle richieste tra numerose istanze dell'app usando contatori Redis e script Lua atomici per gli algoritmi fixed-window, sliding-window e token-bucket. Eserciti Redis Caching & Messaging (Pub/Sub, Streams) con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Redis Caching & Messaging (Pub/Sub, Streams)?
Non è richiesta alcuna esperienza precedente. Redis Caching & Messaging (Pub/Sub, Streams) su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Rate limiting distribuito»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Redis Caching & Messaging (Pub/Sub, Streams)?
Sì. Ogni lezione Redis Caching & Messaging (Pub/Sub, Streams) include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Lock distribuiti con Redis
- Pattern di elezione del leader
- Redis come servizio di coordinamento
- Rate limiting distribuito