Skip to content

Commit

Permalink
fix(memstore): fix flaky rate-limiter test (#1948)
Browse files Browse the repository at this point in the history
  • Loading branch information
alextheimer authored Feb 7, 2025
1 parent 0764fa6 commit 8a3eae9
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 5 deletions.
9 changes: 5 additions & 4 deletions core/src/main/scala/filodb.core/RateLimiter.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import scala.concurrent.duration.Duration
* period has elapsed since the previous success.
*/
class RateLimiter(period: Duration) {
private var lastSuccessMillis = 0L;
private var lastSuccessNanos = 0L;

/**
* Returns true to indicate an attempt was "successful", else it was "failed".
Expand All @@ -20,9 +20,10 @@ class RateLimiter(period: Duration) {
* may be acceptable in some use-cases).
*/
def attempt(): Boolean = {
val nowMillis = System.currentTimeMillis()
if (nowMillis - lastSuccessMillis > period.toMillis) {
lastSuccessMillis = nowMillis
// Using nanoTime() because it is monotonic.
val nowNanos = System.nanoTime()
if (nowNanos - lastSuccessNanos > period.toNanos) {
lastSuccessNanos = nowNanos
return true
}
false
Expand Down
2 changes: 1 addition & 1 deletion core/src/test/scala/filodb.core/RateLimiterSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import scala.concurrent.duration.Duration

class RateLimiterSpec extends AnyFunSpec with Matchers {
it("should apply rate-limits accordingly") {
val rateLimiter = new RateLimiter(Duration(2, TimeUnit.SECONDS))
val rateLimiter = new RateLimiter(Duration(1, TimeUnit.SECONDS))

// First attempt should succeed.
rateLimiter.attempt() shouldEqual true
Expand Down

0 comments on commit 8a3eae9

Please sign in to comment.