Sliding window con sorted set in Redis
Implementi un rate limiter distribuito a sliding window accurato usando gli sorted set di Redis, con operazioni atomiche e scadenza automatica delle vecchie voci.
Sliding window con sorted set in Redis è una lezione API Rate Limiting & Scalability Patterns 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 API Rate Limiting & Scalability Patterns, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso API Rate Limiting & Scalability Patterns include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
From Theory to Production
You understand the sliding window log and counter conceptually. Now build one that works across many servers using Redis sorted sets, the most common production technique for accurate distributed rate limiting.
Why Sorted Sets
A Redis sorted set (ZSET) stores members ranked by a numeric score. By using the request timestamp as the score, we get an ordered log of recent requests we can trim and count efficiently.
One Key Per Client
Each client gets a key like rl:user123. Every incoming request adds a member to that client's sorted set, scored by the current timestamp in milliseconds.
ZADD rl:user123 1700000000123 1700000000123Trimming the Window
Before counting, remove entries older than the window. If the window is 60 seconds, delete everything with a score below now - 60000. This keeps only the requests inside the current sliding window.
ZREMRANGEBYSCORE rl:user123 0 (now-60000)Counting Requests
After trimming, the cardinality of the set is the number of requests in the window. Compare it against the limit to allow or deny.
ZCARD rl:user123Atomicity Matters
Doing trim, add, and count as separate commands creates a race condition under concurrency. Wrap them in a single Lua script so Redis executes them atomically per client.
The Lua Script
A Lua script run with EVAL performs all steps in one atomic operation, returning whether the request is allowed. No two requests can interleave mid-check.
redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, ARGV[1])
local count = redis.call('ZCARD', KEYS[1])
if count < tonumber(ARGV[3]) then
redis.call('ZADD', KEYS[1], ARGV[2], ARGV[2])
return 1
end
return 0Setting Expiry
Always set a TTL on the key (a bit longer than the window) so abandoned clients do not leak memory. Idle keys expire automatically.
EXPIRE rl:user123 120Accuracy vs Memory
This approach is highly accurate because it tracks every request timestamp, but memory grows with request volume per window. For very high-traffic clients, the sliding window counter approximation uses far less memory.
Handling Many Nodes
Because all API nodes talk to the same Redis, the limit is enforced globally regardless of which node handles a request. Use a Redis cluster or replica setup for availability, mindful that replication lag can slightly relax limits.
Failure Modes
Decide what happens if Redis is unreachable: fail open (allow traffic, risk overload) or fail closed (block traffic, risk outage). Most public APIs fail open with a local fallback limiter.
Quick Check
Test your understanding of the Redis sliding window.
Recap
You built a distributed sliding window:
- Store request timestamps in a Redis sorted set, one key per client.
- Trim old entries with
ZREMRANGEBYSCORE, count withZCARD. - Wrap trim/count/add in a Lua script for atomicity.
- Set a TTL to free memory, and decide fail-open vs fail-closed for Redis outages.
Impara API Rate Limiting & Scalability Patterns con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 12
- Lezioni
- 48
Domande Frequenti
La lezione «Sliding window con sorted set in Redis» è gratuita?
Sì — il testo completo di «Sliding window con sorted set in Redis» è 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 API Rate Limiting & Scalability Patterns, passa a CoddyKit PRO. Il corso API Rate Limiting & Scalability Patterns include 4 lezioni in totale.
Cosa imparerò in «Sliding window con sorted set in Redis»?
Implementi un rate limiter distribuito a sliding window accurato usando gli sorted set di Redis, con operazioni atomiche e scadenza automatica delle vecchie voci. Eserciti API Rate Limiting & Scalability Patterns 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 API Rate Limiting & Scalability Patterns?
Non è richiesta alcuna esperienza precedente. API Rate Limiting & Scalability Patterns 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 «Sliding window con sorted set in Redis»?
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 API Rate Limiting & Scalability Patterns?
Sì. Ogni lezione API Rate Limiting & Scalability Patterns 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
- Implementazione dello Sliding Window Log
- Strategia dello Sliding Window Counter
- Confronto tra algoritmi e compromessi
- Sliding window con sorted set in Redis