API Rate Limiting & Scalability Patterns · Lezione

Rate limiting distribuito con Redis

Impari a condividere lo stato dei limiti di frequenza tra più istanze di gateway e servizi usando Redis, operazioni atomiche e script Lua per evitare race condition.

Lezione 4 di 413 passaggi

Rate limiting distribuito con Redis è una lezione API Rate Limiting & Scalability Patterns gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento API Rate Limiting & Scalability Patterns, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso API Rate Limiting & Scalability Patterns include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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
Gratis per iniziare

Impara API Rate Limiting & Scalability Patterns con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
12
Lezioni
48

Domande Frequenti

La lezione «Rate limiting distribuito con Redis» è gratuita?

Sì — il testo completo di «Rate limiting distribuito con Redis» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso API Rate Limiting & Scalability Patterns, passa a CoddyKit PRO. Il corso API Rate Limiting & Scalability Patterns include 4 lezioni in totale.

Cosa imparerò in «Rate limiting distribuito con Redis»?

Impari a condividere lo stato dei limiti di frequenza tra più istanze di gateway e servizi usando Redis, operazioni atomiche e script Lua per evitare race condition. Eserciti API Rate Limiting & Scalability Patterns con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare API Rate Limiting & Scalability Patterns?

Non è richiesta alcuna esperienza precedente. API Rate Limiting & Scalability Patterns su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Rate limiting distribuito con Redis»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione API Rate Limiting & Scalability Patterns?

Sì. Ogni lezione API Rate Limiting & Scalability Patterns include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Pattern di integrazione con API Gateway
  2. Rate limiting globale e per servizio
  3. Configurazione dinamica del rate limiting
  4. Rate limiting distribuito con Redis
← Torna a API Rate Limiting & Scalability Patterns