Skip to content

fix(ratelimiter): resolve data race in token bucket#17

Open
its-jojoo wants to merge 1 commit into
imlargo:mainfrom
its-jojoo:fix/rate-limiter-race-condition
Open

fix(ratelimiter): resolve data race in token bucket#17
its-jojoo wants to merge 1 commit into
imlargo:mainfrom
its-jojoo:fix/rate-limiter-race-condition

Conversation

@its-jojoo

@its-jojoo its-jojoo commented Feb 7, 2026

Copy link
Copy Markdown

Description

Fixes a data race in the token bucket rate limiter where multiple goroutines could concurrently write to entry.LastSeen without synchronization.

Problem

The Go race detector flagged concurrent writes in getEntry():

  • Multiple goroutines writing to the same memory location
  • No synchronization between writes
  • Cleanup goroutine reading while others write

Solution

  • Changed LastSeen from time.Time to int64 (Unix nanoseconds) for atomic operations
  • Used atomic.StoreInt64 for writes and atomic.LoadInt64 for reads
  • Improved getEntry() with RLock for better read performance
  • Added double-check pattern to prevent duplicate entries

Testing

  • ✅ Verified with go test -race - no data races detected
  • ✅ Tested with 50+ concurrent goroutines

Performance Impact

Neutral to positive - uses RLock for reads instead of full Lock

@its-jojoo
its-jojoo force-pushed the fix/rate-limiter-race-condition branch 2 times, most recently from fc5457a to a1925c4 Compare February 7, 2026 23:09
@its-jojoo

Copy link
Copy Markdown
Author
image

@its-jojoo
its-jojoo force-pushed the fix/rate-limiter-race-condition branch from a1925c4 to 3c8e92d Compare February 8, 2026 01:14
@its-jojoo
its-jojoo force-pushed the fix/rate-limiter-race-condition branch from 3c8e92d to d043200 Compare February 8, 2026 19:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant