I want to develop a simple in-memory web request rate limiting module, I am allowed to have 50 requests from each unique cookie ID every 60 seconds.
I am wondering if the following code is an optimal way of implementing such functionality:
class RateLimiter {
private static final int MAX_REQUESTS = 50;
private Map<String, List<Long>> cookieMap = new HashMap<>();
private boolean isRateLimited(String cookieId) {
long time = System.currentTimeMillis();
long oldestTime = time - 60000;
List<Long> timestamps = cookieMap.getOrDefault(cookieId, new LinkedList<>());
timestamps.add(0, time);
int count = 0;
int tooOldIndex = -1;
for (int i = 0; i < timestamps.size(); i++) {
if (timestamps.get(i) >= oldestTime) {
count++;
} else {
tooOldIndex = i;
break;
}
}
List<Long> newTimestamps = new LinkedList<>();
// clean up timestamps older than the 60 second window
for (int i = 0; i < tooOldIndex; i++) {
newTimestamps.add(timestamps.get(i));
}
cookieMap.put(cookieId, newTimestamps);
if (count >= MAX_REQUESTS) {
return false;
} else {
return true;
}
}
}
cookieId
will ever contain anything. It seems you always end up storing an empty list, and it cannot grow \$\endgroup\$LinkedList
? \$\endgroup\$