Scegliere l'algoritmo giusto per il rate limiting
Confronti i principali algoritmi di rate limiting — fixed window, sliding window, token bucket e leaky bucket — e impari quando ciascuno sia adatto al profilo del traffico e agli obiettivi di equità.
Scegliere l'algoritmo giusto per il rate limiting è 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.
Why the Algorithm Matters
A rate limit policy is only as good as the algorithm that enforces it. The same limit of 100 requests/minute behaves very differently depending on how you count.
In this lesson we compare four classic approaches and learn how to pick one based on your fairness, burst, and accuracy needs.
Fixed Window Counter
The simplest approach: count requests in a fixed time window (for example each calendar minute) and reset the counter at the boundary.
- Pros: trivial to implement, low memory
- Cons: allows a burst of
2xthe limit around the window edge
def allow(counter, limit):
if counter['count'] >= limit:
return False
counter['count'] += 1
return TrueThe Boundary Burst Problem
With a fixed window, a client can send limit requests at 00:59 and another limit at 01:00. That is double the intended rate in a one-second span.
Sliding window algorithms exist to smooth out exactly this spike.
Sliding Window Log
Store a timestamp for every request. To decide, drop timestamps older than the window and count what remains.
- Pros: exact, no boundary burst
- Cons: memory grows with request volume
def allow(log, now, window, limit):
cutoff = now - window
log[:] = [t for t in log if t > cutoff]
if len(log) >= limit:
return False
log.append(now)
return TrueSliding Window Counter
A hybrid: keep the current and previous fixed-window counts, then estimate the rate using a weighted overlap.
It approximates the sliding log with far less memory, which is why API gateways and CDNs favor it.
weighted = prev_count * overlap + curr_count
allowed = weighted < limitToken Bucket
A bucket holds tokens up to a capacity. Tokens refill at a steady rate; each request spends one token. Empty bucket means reject.
- Allows controlled bursts up to the bucket capacity
- Smooths the long-term average to the refill rate
def allow(bucket, now, rate, capacity):
elapsed = now - bucket['ts']
bucket['tokens'] = min(capacity, bucket['tokens'] + elapsed * rate)
bucket['ts'] = now
if bucket['tokens'] < 1:
return False
bucket['tokens'] -= 1
return TrueLeaky Bucket
Requests enter a queue that leaks at a constant rate. If the queue overflows, requests are dropped.
Unlike the token bucket, the leaky bucket enforces a steady output rate — ideal when a downstream service cannot handle spikes.
Token vs. Leaky Bucket
- Token bucket lets traffic burst up to capacity, then throttles — good for user-facing APIs that should feel responsive.
- Leaky bucket forces a smooth, constant flow — good for protecting fragile backends.
Memory and Accuracy Trade-offs
Pick based on constraints:
- Lowest memory: fixed window
- Highest accuracy: sliding window log
- Best balance: sliding window counter
- Burst-friendly: token bucket
Distributed Considerations
Across many servers, each node cannot keep its own counter or you multiply the real limit. Use a shared store like Redis with atomic operations so the count is global.
Token bucket and sliding window counter both map cleanly to Redis primitives.
-- Redis atomic counter with expiry
INCR rate:user:42
EXPIRE rate:user:42 60A Decision Checklist
Ask:
- Do I need to allow short bursts? → token bucket
- Must downstream see a steady rate? → leaky bucket
- Is exactness critical for billing? → sliding window log
- Do I want simple and cheap? → fixed or sliding window counter
Quick Check
Test your understanding of algorithm selection.
Recap
You compared four rate limiting algorithms:
- Fixed window — cheap but allows edge bursts
- Sliding window — accurate, smooths boundaries
- Token bucket — burst-friendly, averages out
- Leaky bucket — constant output rate
Choose based on burst tolerance, accuracy, and memory budget.
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 «Scegliere l'algoritmo giusto per il rate limiting» è gratuita?
Sì — il testo completo di «Scegliere l'algoritmo giusto per il rate limiting» è 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 «Scegliere l'algoritmo giusto per il rate limiting»?
Confronti i principali algoritmi di rate limiting — fixed window, sliding window, token bucket e leaky bucket — e impari quando ciascuno sia adatto al profilo del traffico e agli obiettivi di equità. 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 «Scegliere l'algoritmo giusto per il rate limiting»?
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
- Differenze tra throttling e rate limiting
- Policy per i picchi e i periodi di tolleranza
- Limiti lato client e lato server
- Scegliere l'algoritmo giusto per il rate limiting