Skip to content

Commit 80d8a65

Browse files
committed
Improves rate limiting accuracy
Rounds up the retry-after value to the next full second. Switches rate limiting refill strategy to interval based refill to allow more consistent rate limiting.
1 parent 98322d0 commit 80d8a65

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

src/main/java/com/dmware/api_onibusbh/infra/RateLimitingFilter.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
6161
long waitForRefill = probe.getNanosToWaitForRefill();
6262
long retryAfterSeconds = TimeUnit.NANOSECONDS.toSeconds(waitForRefill);
6363

64+
if (waitForRefill % TimeUnit.SECONDS.toNanos(1) != 0) {
65+
retryAfterSeconds++;
66+
}
67+
6468
handlerExceptionResolver.resolveException(request, response, null,
6569
new RateLimitExceededException(
6670
"Rate limit exceeded. Try again in " + retryAfterSeconds + " seconds.",
@@ -71,7 +75,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
7175

7276
private Bucket createNewBucket(String key) {
7377
return Bucket.builder()
74-
.addLimit(limit -> limit.capacity(capacity).refillGreedy(tokens, Duration.ofSeconds(durationSeconds)))
78+
.addLimit(limit -> limit.capacity(capacity).refillIntervally(tokens, Duration.ofSeconds(durationSeconds)))
7579
.build();
7680
}
7781
}

0 commit comments

Comments
 (0)