0Pricing
API Rate Limiting & Scalability Patterns · Aula

Janela deslizante com conjuntos ordenados no Redis

Implemente um limitador distribuído preciso de requisições por janela deslizante usando conjuntos ordenados do Redis, com operações atômicas e expiração automática das entradas antigas.

Janela deslizante com conjuntos ordenados no 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.

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 1700000000123

Trimming 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:user123

Atomicity 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 0

Setting 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 120

Accuracy 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 with ZCARD.
  • 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.

Perguntas Frequentes

A aula “Janela deslizante com conjuntos ordenados no Redis” é grátis?

Sim — o texto completo de “Janela deslizante com conjuntos ordenados no 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 “Janela deslizante com conjuntos ordenados no Redis”?

Implemente um limitador distribuído preciso de requisições por janela deslizante usando conjuntos ordenados do Redis, com operações atômicas e expiração automática das entradas antigas. 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 “Janela deslizante com conjuntos ordenados no 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. Implementação do registro de janela deslizante
  2. Estratégia do contador de janela deslizante
  3. Comparação de algoritmos e compromissos
  4. Janela deslizante com conjuntos ordenados no Redis
← Voltar para API Rate Limiting & Scalability Patterns