Limitación de frecuencia distribuida
Coordine los límites de solicitudes entre muchas instancias de la aplicación mediante contadores de Redis y scripts Lua atómicos para algoritmos de ventana fija, ventana deslizante y cubo de tokens.
Limitación de frecuencia distribuida es una lección gratuita de Redis Caching & Messaging (Pub/Sub, Streams) 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 Redis Caching & Messaging (Pub/Sub, Streams), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Redis Caching & Messaging (Pub/Sub, Streams) incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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.
Preguntas frecuentes
¿La lección «Limitación de frecuencia distribuida» es gratis?
Sí — el texto completo de «Limitación de frecuencia distribuida» 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 Redis Caching & Messaging (Pub/Sub, Streams), actualiza a CoddyKit PRO. El curso de Redis Caching & Messaging (Pub/Sub, Streams) incluye 4 lecciones en total.
¿Qué aprenderé en «Limitación de frecuencia distribuida»?
Coordine los límites de solicitudes entre muchas instancias de la aplicación mediante contadores de Redis y scripts Lua atómicos para algoritmos de ventana fija, ventana deslizante y cubo de tokens. Practicas Redis Caching & Messaging (Pub/Sub, Streams) 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 Redis Caching & Messaging (Pub/Sub, Streams)?
No se requiere experiencia previa. Redis Caching & Messaging (Pub/Sub, Streams) 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 «Limitación de frecuencia distribuida»?
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 Redis Caching & Messaging (Pub/Sub, Streams)?
Sí. Cada lección de Redis Caching & Messaging (Pub/Sub, Streams) 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
- Bloqueos distribuidos con Redis
- Patrones de elección de líder
- Redis como servicio de coordinación
- Limitación de frecuencia distribuida