0Pricing
API Rate Limiting & Scalability Patterns · Aula

Implementação do registro de janela deslizante

Compreenda o algoritmo do registro de janela deslizante, sua precisão e as implicações de armazenamento do acompanhamento dos carimbos de data e hora de cada solicitação.

Implementação do registro de janela deslizante é uma aula grátis de API Rate Limiting & Scalability Patterns no CoddyKit. Esta é a aula 1 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.

Intro to Sliding Window Log

Welcome to the Sliding Window Log algorithm! This method offers a highly precise way to enforce API rate limits.

Unlike simpler methods, it keeps a detailed record of each request, allowing for very accurate control over traffic.

The Timestamp Log Core

The core idea of the Sliding Window Log is to store the exact timestamp of every request made by a client.

  • Imagine a list or array.
  • Each time a request is made, its current time (e.g., in milliseconds) is added to this list.
  • This log allows us to precisely track activity over any given period.

Logging New Requests

When a new request arrives, the algorithm performs two main steps:

  1. It records the current time and adds it to the list of request timestamps.
  2. It then cleans up old timestamps that are no longer relevant to the current 'sliding' window.

This ensures the log only contains recent, active requests.

Checking the Sliding Window

To determine if a new request should be allowed, the algorithm calculates a sliding window.

  • For a 60-second limit, if the current time is T, the window covers requests from T - 60 seconds to T.
  • It counts how many timestamps in the log fall within this calculated window.
  • If the count is below the allowed limit, the request is permitted.

Visualizing Window Movement

Think of the window as a continuous period that 'slides' forward with each new request.

If your limit is 3 requests per 5 seconds:

  • At t=0, window is [-5s, 0s].
  • At t=2s, window is [-3s, 2s].
  • At t=6s, window is [1s, 6s].

Only timestamps within the current sliding window are counted.

Limiter Class Setup

Let's set up a basic Java class for our Sliding Window Log rate limiter. We'll use an ArrayList to store the request timestamps.

Try running this to see the initial setup:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class SlidingWindowLogRateLimiter {
    private final List<Long> requestTimestamps;
    private final long windowSizeMillis; // e.g., 60_000 for 60 seconds
    private final int maxRequests;

    public SlidingWindowLogRateLimiter(long windowSize, TimeUnit unit, int maxRequests) {
        this.requestTimestamps = new ArrayList<>();
        this.windowSizeMillis = unit.toMillis(windowSize);
        this.maxRequests = maxRequests;
    }

    // The allowRequest() method will be added next!
    public static void main(String[] args) {
        System.out.println("Rate Limiter setup complete!");
    }
}

Implementing allowRequest()

Now, let's implement the core logic for the allowRequest() method. This method will remove old timestamps and check if the current request can be allowed.

Run the code to see a simple test of the rate limiter in action!

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class SlidingWindowLogRateLimiter {
    private final List<Long> requestTimestamps;
    private final long windowSizeMillis;
    private final int maxRequests;

    public SlidingWindowLogRateLimiter(long windowSize, TimeUnit unit, int maxRequests) {
        this.requestTimestamps = new ArrayList<>();
        this.windowSizeMillis = unit.toMillis(windowSize);
        this.maxRequests = maxRequests;
    }

    public synchronized boolean allowRequest() {
        long currentTime = System.currentTimeMillis();
        long windowStartTime = currentTime - windowSizeMillis;

        // Remove timestamps older than the current window
        requestTimestamps.removeIf(timestamp -> timestamp <= windowStartTime);

        // Check if adding a new request would exceed the limit
        if (requestTimestamps.size() < maxRequests) {
            requestTimestamps.add(currentTime);
            return true;
        }
        return false;
    }

    public static void main(String[] args) throws InterruptedException {
        // Example: 3 requests allowed per 5 seconds
        SlidingWindowLogRateLimiter limiter =
            new SlidingWindowLogRateLimiter(5, TimeUnit.SECONDS, 3);

        System.out.println("Testing 5s, 3 requests limit:");
        for (int i = 0; i < 5; i++) {
            boolean allowed = limiter.allowRequest();
            System.out.println("Request " + (i + 1) + ": " + (allowed ? "Allowed" : "Blocked"));
            if (i == 2) Thread.sleep(1000); // Small delay to simulate real traffic
        }
        // Wait for the window to pass to allow more requests
        System.out.println("Waiting 5 seconds for window reset...");
        Thread.sleep(5000);
        System.out.println("Request after window reset: " + (limiter.allowRequest() ? "Allowed" : "Blocked"));
    }
}

Key Advantage: High Precision

The biggest strength of the Sliding Window Log algorithm is its high precision.

  • Because it records every individual timestamp, it can accurately calculate the number of requests within any dynamic window.
  • This eliminates the 'burstiness' problem seen in Fixed Window Counters, where a sudden spike at the window's edge could bypass limits.

The Memory & Performance Challenge

While precise, the Sliding Window Log has significant drawbacks, especially for high-volume APIs:

  • Memory Usage: Storing every timestamp for millions of requests can consume a lot of memory.
  • Performance: Operations like adding new timestamps and removing old ones (especially with large lists) can become slow, impacting performance.

This makes it less suitable for extremely high-throughput systems unless optimized.

Check Your Understanding

Consider the Sliding Window Log algorithm. Which of the following statements are true about its characteristics?

Recap: Sliding Window Log

In this lesson, we explored the Sliding Window Log algorithm:

  • It tracks every request by its exact timestamp.
  • It offers high precision, avoiding the 'burst' issue of fixed windows.
  • Its main drawbacks are high memory usage and potential performance bottlenecks for very large request logs.

Next, we'll look at the Sliding Window Counter, which aims to improve on these drawbacks!

Perguntas Frequentes

A aula “Implementação do registro de janela deslizante” é grátis?

Sim — o texto completo de “Implementação do registro de janela deslizante” é 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 “Implementação do registro de janela deslizante”?

Compreenda o algoritmo do registro de janela deslizante, sua precisão e as implicações de armazenamento do acompanhamento dos carimbos de data e hora de cada solicitação. 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 1 de 4.

Quanto tempo leva a aula “Implementação do registro de janela deslizante”?

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