snippetjavaModerate
Implement rate limiting by cookie ID
Viewed 0 times
ratecookielimitingimplement
Problem
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:
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> cookieMap = new HashMap<>();
private boolean isRateLimited(String cookieId) {
long time = System.currentTimeMillis();
long oldestTime = time - 60000;
List timestamps = cookieMap.getOrDefault(cookieId, new LinkedList<>());
timestamps.add(0, time);
int count = 0;
int tooOldIndex = -1;
for (int i = 0; i = oldestTime) {
count++;
} else {
tooOldIndex = i;
break;
}
}
List newTimestamps = new LinkedList<>();
// clean up timestamps older than the 60 second window
for (int i = 0; i = MAX_REQUESTS) {
return false;
} else {
return true;
}
}
}Solution
Accessing elements of a linked list with
If you need the element index, you can add a counting variable "manually" (declared before the loop, and increments in the loop body).
.get(i) is expensive, because it's an \$O(N)\$ operation compared to \$O(1)\$ of array backed structures. You should avoid doing this, and use an enhanced for-each loop instead, for example:for (Long currentTimeStamp : timestamps) {
if (currentTimeStamp >= oldestTime) {
newTimestamps.add(currentTimeStamp);
} else {
break;
}
}If you need the element index, you can add a counting variable "manually" (declared before the loop, and increments in the loop body).
Code Snippets
for (Long currentTimeStamp : timestamps) {
if (currentTimeStamp >= oldestTime) {
newTimestamps.add(currentTimeStamp);
} else {
break;
}
}Context
StackExchange Code Review Q#122378, answer score: 10
Revisions (0)
No revisions yet.