Ventana deslizante con conjuntos ordenados en Redis
Implemente un limitador distribuido y preciso de frecuencia mediante una ventana deslizante y conjuntos ordenados de Redis, con operaciones atómicas y caducidad automática de las entradas antiguas.
Ventana deslizante con conjuntos ordenados en Redis es una lección gratuita de API Rate Limiting & Scalability Patterns en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de API Rate Limiting & Scalability Patterns, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de API Rate Limiting & Scalability Patterns incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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.
Preguntas frecuentes
¿La lección «Ventana deslizante con conjuntos ordenados en Redis» es gratis?
Sí — el texto completo de «Ventana deslizante con conjuntos ordenados en Redis» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de API Rate Limiting & Scalability Patterns, actualiza a CoddyKit PRO. El curso de API Rate Limiting & Scalability Patterns incluye 4 lecciones en total.
¿Qué aprenderé en «Ventana deslizante con conjuntos ordenados en Redis»?
Implemente un limitador distribuido y preciso de frecuencia mediante una ventana deslizante y conjuntos ordenados de Redis, con operaciones atómicas y caducidad automática de las entradas antiguas. Practicas API Rate Limiting & Scalability Patterns con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar API Rate Limiting & Scalability Patterns?
No se requiere experiencia previa. API Rate Limiting & Scalability Patterns en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Ventana deslizante con conjuntos ordenados en Redis»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de API Rate Limiting & Scalability Patterns?
Sí. Cada lección de API Rate Limiting & Scalability Patterns incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Implementación de Sliding Window Log
- Estrategia Sliding Window Counter
- Comparación de algoritmos y compromisos
- Ventana deslizante con conjuntos ordenados en Redis