API Rate Limiting & Scalability Patterns · Aula

Escolha do algoritmo adequado de limitação

Compare os principais algoritmos de limitação de requisições — janela fixa, janela deslizante, balde de tokens e balde furado — e aprenda quando cada um se adapta ao seu perfil de tráfego e às suas metas de equidade.

Aula 4 de 413 etapas

Escolha do algoritmo adequado de limitação é 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.

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 2x the limit around the window edge
def allow(counter, limit):
    if counter['count'] >= limit:
        return False
    counter['count'] += 1
    return True

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

Sliding 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 < limit

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

Leaky 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 60

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

Grátis para começar

Aprenda API Rate Limiting & Scalability Patterns com um tutor de IA — grátis

Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.

Cursos
12
Aulas
48

Perguntas Frequentes

A aula “Escolha do algoritmo adequado de limitação” é grátis?

Sim — o texto completo de “Escolha do algoritmo adequado de limitação” é 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 “Escolha do algoritmo adequado de limitação”?

Compare os principais algoritmos de limitação de requisições — janela fixa, janela deslizante, balde de tokens e balde furado — e aprenda quando cada um se adapta ao seu perfil de tráfego e às suas m… 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 “Escolha do algoritmo adequado de limitação”?

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. Limitação de tráfego versus limitação de taxa
  2. Políticas de picos e períodos de tolerância
  3. Limites no cliente versus no servidor
  4. Escolha do algoritmo adequado de limitação
← Voltar para API Rate Limiting & Scalability Patterns