fix!: isolate token buckets per key and manage limiter lifecycle - #4
Merged
Conversation
Previously every key shared a single underlying rate.Limiter, so all keys drained one token bucket and per-key limiting did not actually work. GetOrAdd now builds an independent Limiter per key via a factory. Also: - Make key creation atomic with LoadOrStore (fixes a TOCTOU race that could create duplicate limiters for the same key). - Replace the per-key sleeping cleanup goroutine with a single background sweeper that evicts genuinely idle keys (idle timer refreshed on every access) and add Close() to stop it. - Make Storage[K, V] and BucketLimiter[K] generic for type safety. - Add NewRateLimiterFunc helper and WithClock/WithSweepInterval options. - Rewrite tests: per-key isolation regression test, deterministic eviction via an injected clock, concurrency and storage tests, and benchmarks (100% statement coverage, race-clean). - Examples: IPv6-safe client IP via net.SplitHostPort, accurate Retry-After and RateLimit-* response headers, and Close() usage. - Add docs/TOKEN_BUCKET.md and rewrite README. BREAKING CHANGE: NewBucketLimiter now takes a func() Limiter factory instead of a Limiter instance; Storage and BucketLimiter are generic and NewInMemoryStorage requires type parameters; BucketLimiter no longer implements Limiter (call GetOrAdd(key) to obtain one); Remove no longer returns an error.
Add docs/MIGRATION.md with before/after mappings for every breaking change (factory-based NewBucketLimiter, generic storage, Close(), the manager no longer being a Limiter, Remove's dropped error, custom Storage) plus the behavioral changes, and link it from the README.
…s/ratelimiter into fix/per-key-limiter-isolation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR fixes a critical correctness bug and modernizes the library.
The headline bug: every key shared a single underlying
rate.Limiter, so all keys drained one token bucket — the core promise of per-key rate limiting did not actually hold. A new regression test (TestBucketLimiter_PerKeyIsolation) fails on the old code and passes now.What changed
Correctness
GetOrAddnow builds an independentLimiterper key via afunc() Limiterfactory. One key exhausting its budget no longer affects others.LoadOrStore, fixing a TOCTOU race that could create duplicate limiters for the same key.Close()to stop it.API / best practices (Go 1.25)
Storage[K, V]andBucketLimiter[K]are now generic for type safety.NewRateLimiterFunc(limit, burst)helper andWithClock/WithSweepIntervaloptions.StoragegainedLoadOrStoreandRange.Examples & headers
net.SplitHostPort(IPv6-safe client IP).Retry-After(from the reservation delay) andRateLimit-Limit/Remaining/Resetheaders (IETF draft names + legacyX-RateLimit-*).examples/keyis a minimal demo of per-key isolation and refill over time.Docs & tests
docs/TOKEN_BUCKET.md: a thorough explanation of the token bucket algorithm, choosinglimit/burst,AllowvsWaitvsReserve, eviction, HTTP headers, algorithm comparison, and single-process vs distributed scope.README.mdand added package-leveldoc.go.Waittest), concurrency, storage, and benchmarks.Verification
go test -race ./...— passing, 100% statement coverage.go vet ./...,gofmt— clean.RateLimit-*headers → 429 withRetry-After: 1).NewBucketLimitertakes afunc() Limiterfactory instead of aLimiterinstance.StorageandBucketLimiterare generic;NewInMemoryStoragerequires type parameters (NewInMemoryStorage[string, ratelimiter.Limiter]()).BucketLimiterno longer implementsLimiter— callGetOrAdd(key)to obtain one.Removeno longer returns anerror.Scope note
This library limits within a single process. Global cross-instance limiting needs a distributed algorithm and remains out of scope;
Storageis for custom in-process stores.🤖 Generated with Claude Code