Implement rate limiting by cookie ID 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&lt;String, List&lt;Long&gt;&gt; cookieMap = new HashMap&lt;&gt;();

    private boolean isRateLimited(String cookieId) {
      long time = System.currentTimeMillis();
      long oldestTime = time - 60000;
      List&lt;Long&gt; timestamps = cookieMap.getOrDefault(cookieId, new LinkedList&lt;&gt;());
      timestamps.add(0, time);
      int count = 0;
      int tooOldIndex = -1;
      for (int i = 0; i &lt; timestamps.size(); i++) {
          if (timestamps.get(i) &gt;= oldestTime) {
              count++;
          } else {
              tooOldIndex = i;
              break;
          }
      }
      List&lt;Long&gt; newTimestamps = new LinkedList&lt;&gt;();
      // clean up timestamps older than the 60 second window
      for (int i = 0; i &lt; tooOldIndex; i++) {
          newTimestamps.add(timestamps.get(i));
      }
      cookieMap.put(cookieId, newTimestamps);
      if (count &gt;= MAX_REQUESTS) {
         return false;
      } else {
         return true;
      }
  }
}
Accessing elements of a linked list with .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  &gt;= 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).