From 451d06bf3b80419ec6130c325242ebd95344402b Mon Sep 17 00:00:00 2001 From: bohdanstorozhuk Date: Mon, 31 Oct 2022 00:51:05 +0000 Subject: [PATCH 1/2] Fix return timestamp discrepancy between regular atomic limiter and int64 based one --- limiter_atomic_int64.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/limiter_atomic_int64.go b/limiter_atomic_int64.go index 38604ba..8f2e66c 100644 --- a/limiter_atomic_int64.go +++ b/limiter_atomic_int64.go @@ -82,6 +82,12 @@ func (t *atomicInt64Limiter) Take() time.Time { break } } - t.clock.Sleep(time.Duration(newTimeOfNextPermissionIssue - now)) - return time.Unix(0, newTimeOfNextPermissionIssue) + + sleepDuration := time.Duration(newTimeOfNextPermissionIssue - now) + if sleepDuration > 0 { + t.clock.Sleep(sleepDuration) + return time.Unix(0, newTimeOfNextPermissionIssue) + } + // return now if we don't sleep as atomicLimiter does + return time.Unix(0, now) } From 980cfa4169537219220e772cc8a7331ecb818046 Mon Sep 17 00:00:00 2001 From: bohdanstorozhuk Date: Mon, 31 Oct 2022 00:54:19 +0000 Subject: [PATCH 2/2] Make int64 based atomic limiter default --- ratelimit.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ratelimit.go b/ratelimit.go index 7370526..22b88ec 100644 --- a/ratelimit.go +++ b/ratelimit.go @@ -54,7 +54,7 @@ type config struct { // New returns a Limiter that will limit to the given RPS. func New(rate int, opts ...Option) Limiter { - return newAtomicBased(rate, opts...) + return newAtomicInt64Based(rate, opts...) } // buildConfig combines defaults with options.