슬라이딩 윈도우 로그 구현
슬라이딩 윈도우 로그 알고리즘의 정밀도와 개별 요청 타임스탬프를 추적할 때 필요한 저장 공간을 이해합니다.
슬라이딩 윈도우 로그 구현은(는) CoddyKit의 무료 API Rate Limiting & Scalability Patterns 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 API Rate Limiting & Scalability Patterns 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. API Rate Limiting & Scalability Patterns 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
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:
- It records the current time and adds it to the list of request timestamps.
- 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 fromT - 60 secondstoT. - 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!
자주 묻는 질문
“슬라이딩 윈도우 로그 구현” 강의는 무료인가요?
네 — “슬라이딩 윈도우 로그 구현” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 API Rate Limiting & Scalability Patterns 강의 전체를 잠금 해제할 수 있습니다. API Rate Limiting & Scalability Patterns 강의에는 총 4개의 강의가 포함되어 있습니다.
“슬라이딩 윈도우 로그 구현”에서 뭘 배우나요?
슬라이딩 윈도우 로그 알고리즘의 정밀도와 개별 요청 타임스탬프를 추적할 때 필요한 저장 공간을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 API Rate Limiting & Scalability Patterns을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
API Rate Limiting & Scalability Patterns을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 API Rate Limiting & Scalability Patterns은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“슬라이딩 윈도우 로그 구현” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 API Rate Limiting & Scalability Patterns 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 API Rate Limiting & Scalability Patterns 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 슬라이딩 윈도우 로그 구현
- 슬라이딩 윈도우 카운터 전략
- 알고리즘 비교와 절충점
- Redis 정렬 집합을 활용한 슬라이딩 윈도