0Pricing
API Rate Limiting & Scalability Patterns · Aula

Limitação distribuída de requisições com Redis

Aprenda a compartilhar o estado dos limites de requisições entre várias instâncias de gateway e serviço usando Redis, operações atômicas e scripts Lua para evitar condições de corrida.

Limitação distribuída de requisições com Redis é uma aula grátis de API Rate Limiting & Scalability Patterns no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de API Rate Limiting & Scalability Patterns, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de API Rate Limiting & Scalability Patterns inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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 60

The 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 1

Calling 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 now

Returning Rate Limit Headers

Good gateways tell clients where they stand using standard headers:

  • X-RateLimit-Limit
  • X-RateLimit-Remaining
  • Retry-After on a 429

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.4 for anonymous traffic
  • rate:user:42 for authenticated users
  • rate:apikey:abc for 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

Perguntas Frequentes

A aula “Limitação distribuída de requisições com Redis” é grátis?

Sim — o texto completo de “Limitação distribuída de requisições com Redis” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de API Rate Limiting & Scalability Patterns, atualize para CoddyKit PRO. O curso de API Rate Limiting & Scalability Patterns inclui 4 aulas no total.

O que vou aprender em “Limitação distribuída de requisições com Redis”?

Aprenda a compartilhar o estado dos limites de requisições entre várias instâncias de gateway e serviço usando Redis, operações atômicas e scripts Lua para evitar condições de corrida. Você pratica API Rate Limiting & Scalability Patterns com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar API Rate Limiting & Scalability Patterns?

Nenhuma experiência prévia é necessária. API Rate Limiting & Scalability Patterns no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Limitação distribuída de requisições com Redis”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de API Rate Limiting & Scalability Patterns?

Sim. Cada aula de API Rate Limiting & Scalability Patterns inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Padrões de integração com gateways de API
  2. Limitação de taxa global versus por serviço
  3. Configuração dinâmica de limites de taxa
  4. Limitação distribuída de requisições com Redis
← Voltar para API Rate Limiting & Scalability Patterns