简体   繁体   中英

Real simple algorithm to calculate number of requests in the last minute

My service is calling an other service and this other service throttle me based on the number of request sent during a hole minutes (doesn't matter how much per second, as long as there is < x request in the last minute)

I would like to display a really really rough estimate to my user of how much request has been made during the last minute. It doesn't need to be accurate in anyway it is just a way for the user to see what roughly the numbers are

What would be the best, least memory demanding way of implementing such a counter ?

You could do something like:

  • maintain an int[] requestCount = new int[60]
  • for each request: requestCount[(System.currentTimeMillis() / 1000) % 60]++;
  • run a scheduled job every 1 second to reset the "stale" array position (61 seconds ago) back to 0
  • to get the number of requests over the past 60 seconds: IntStream.of(requestCount).sum();

Note:

  • this would not be thread safe. If you need thread safety you could use a final AtomicInteger[] array.
  • this is not robust to clock changes etc.

The footprint should be fairly small.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM