Add rate limiting code

This commit is contained in:
Ashish Pratap Singh
2024-07-16 19:53:11 -07:00
parent 494b04b1b4
commit 5a9bf86980
10 changed files with 356 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
package implementations.java.rate_limiting;
import java.time.Instant;
import java.util.LinkedList;
import java.util.Queue;
public class SlidingWindowLog {
private final long windowSizeInSeconds; // Size of the sliding window in seconds
private final long maxRequestsPerWindow; // Maximum number of requests allowed in the window
private final Queue<Long> requestLog; // Log of request timestamps
public SlidingWindowLog(long windowSizeInSeconds, long maxRequestsPerWindow) {
this.windowSizeInSeconds = windowSizeInSeconds;
this.maxRequestsPerWindow = maxRequestsPerWindow;
this.requestLog = new LinkedList<>();
}
public synchronized boolean allowRequest() {
long now = Instant.now().getEpochSecond();
long windowStart = now - windowSizeInSeconds;
// Remove timestamps that are outside of the current window
while (!requestLog.isEmpty() && requestLog.peek() <= windowStart) {
requestLog.poll();
}
if (requestLog.size() < maxRequestsPerWindow) {
requestLog.offer(now); // Log this request
return true; // Allow the request
}
return false; // We've exceeded the limit for this window, deny the request
}
}