Limitación de frecuencia distribuida con Redis
Aprenda a compartir el estado de los límites de frecuencia entre varias instancias de gateways y servicios mediante Redis, operaciones atómicas y scripts de Lua para evitar condiciones de carrera.
Limitación de frecuencia distribuida con 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.
The Multi-Instance Problem
When you run several gateway replicas, each one keeping its own in-memory counter means a client gets N x limit total — once per instance.
To enforce one global limit, every instance must read and update shared state.
Why Redis
Redis is the de facto choice for distributed rate limiting because it offers:
- Sub-millisecond in-memory reads and writes
- Atomic commands like
INCR - Built-in expiry for automatic window resets
- Lua scripting for multi-step atomic logic
A Naive Counter
The simplest fixed-window counter uses INCR plus EXPIRE:
The first request in a window creates the key and sets a TTL; later requests just increment.
INCR rate:user:42
-- if reply == 1 (first hit):
EXPIRE rate:user:42 60The Race Condition
Running INCR then EXPIRE as two separate calls has a bug: if the process crashes between them, the key has no TTL and the limit never resets.
The fix is to make the check-and-increment atomic.
Atomicity with Lua
Redis runs a Lua script as a single atomic unit. We can check the count, increment, and set expiry without interruption.
local c = redis.call('INCR', KEYS[1])
if c == 1 then
redis.call('EXPIRE', KEYS[1], ARGV[2])
end
if c > tonumber(ARGV[1]) then
return 0
end
return 1Calling the Script
From the gateway you invoke the script with EVAL, passing the key, the limit, and the window size.
A return of 1 means allow; 0 means reject with 429 Too Many Requests.
allowed = redis.eval(script, keys=['rate:user:42'], args=[100, 60])
if allowed == 0:
return Response(status=429)Sliding Window with Sorted Sets
For smoother limiting, store request timestamps in a sorted set. Remove old entries, count what remains, then add the new one.
ZREMRANGEBYSCORE rate:user:42 0 (now-window)
ZCARD rate:user:42
ZADD rate:user:42 now nowReturning Rate Limit Headers
Good gateways tell clients where they stand using standard headers:
X-RateLimit-LimitX-RateLimit-RemainingRetry-Afteron a429
The Lua script can return remaining count alongside the allow flag.
Handling Redis Failures
What if Redis is unreachable? Two strategies:
- Fail open — allow traffic; favors availability
- Fail closed — reject traffic; favors protection
Most APIs fail open with a local fallback limiter to avoid a full outage.
Reducing Latency
Every limit check is a network hop. Cut overhead by:
- Co-locating Redis near the gateway
- Using connection pooling
- Batching counters with a short local cache for very hot keys
Keying by Identity
The rate limit key defines what you are limiting. Common choices:
rate:ip:1.2.3.4for anonymous trafficrate:user:42for authenticated usersrate:apikey:abcfor API clients
Pick the most specific identity available so one abuser cannot exhaust a shared bucket.
Quick Check
Test your grasp of distributed limiting.
Recap
You learned to share rate limit state across instances:
- A shared Redis store gives one global limit
- Lua scripts make check-and-increment atomic
- Sorted sets enable sliding windows
- Decide fail open vs. closed for Redis outages
Preguntas frecuentes
¿La lección «Limitación de frecuencia distribuida con Redis» es gratis?
Sí — el texto completo de «Limitación de frecuencia distribuida con 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 «Limitación de frecuencia distribuida con Redis»?
Aprenda a compartir el estado de los límites de frecuencia entre varias instancias de gateways y servicios mediante Redis, operaciones atómicas y scripts de Lua para evitar condiciones de carrera. 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 «Limitación de frecuencia distribuida con 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
- Patrones de integración con API Gateway
- Limitación de tasa global frente a por servicio
- Configuración dinámica de límites de tasa
- Limitación de frecuencia distribuida con Redis