Skip to content

Commit 4eb7a5d

Browse files
fix: race condition in concurrent request handling
Co-Authored-By: Wesley Willians <wesleywillians@gmail.com>
1 parent 3b6d1cb commit 4eb7a5d

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

ratelimiter/limiter.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,14 +86,19 @@ func (rl *RateLimiter) Allow(key string) (Response, error) {
8686
}, nil
8787
}
8888

89-
// Increment request count atomically
90-
count, err := rl.storage.IncrementRequests(key, time.Now())
89+
// Get current count first
90+
count, err := rl.storage.GetRequests(key)
9191
if err != nil {
9292
return Response{}, err
9393
}
9494

9595
// Allow requests until MaxRequests is reached
9696
if count < rl.opts.MaxRequests {
97+
// Increment only if we're under the limit
98+
count, err = rl.storage.IncrementRequests(key, time.Now())
99+
if err != nil {
100+
return Response{}, err
101+
}
97102
return Response{
98103
Allowed: true,
99104
RequestsLeft: rl.opts.MaxRequests - count,

0 commit comments

Comments
 (0)