0Pricing
Redis Caching & Messaging (Pub/Sub, Streams) · Aula

Limitação de taxa distribuída

Coordene limites de solicitações entre várias instâncias do aplicativo usando contadores do Redis e scripts Lua atômicos para algoritmos de janela fixa, janela deslizante e balde de tokens.

Limitação de taxa distribuída é uma aula grátis de Redis Caching & Messaging (Pub/Sub, Streams) 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 Redis Caching & Messaging (Pub/Sub, Streams), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Redis Caching & Messaging (Pub/Sub, Streams) inclui 4 aulas no total.

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

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

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

Token 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 1716900000

Refill 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: 1716900060

Resilience 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.

Perguntas Frequentes

A aula “Limitação de taxa distribuída” é grátis?

Sim — o texto completo de “Limitação de taxa distribuída” é 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 Redis Caching & Messaging (Pub/Sub, Streams), atualize para CoddyKit PRO. O curso de Redis Caching & Messaging (Pub/Sub, Streams) inclui 4 aulas no total.

O que vou aprender em “Limitação de taxa distribuída”?

Coordene limites de solicitações entre várias instâncias do aplicativo usando contadores do Redis e scripts Lua atômicos para algoritmos de janela fixa, janela deslizante e balde de tokens. Você pratica Redis Caching & Messaging (Pub/Sub, Streams) 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 Redis Caching & Messaging (Pub/Sub, Streams)?

Nenhuma experiência prévia é necessária. Redis Caching & Messaging (Pub/Sub, Streams) 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 de taxa distribuída”?

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 Redis Caching & Messaging (Pub/Sub, Streams)?

Sim. Cada aula de Redis Caching & Messaging (Pub/Sub, Streams) 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. Bloqueios distribuídos com Redis
  2. Padrões de eleição de líder
  3. Redis como serviço de coordenação
  4. Limitação de taxa distribuída
← Voltar para Redis Caching & Messaging (Pub/Sub, Streams)