Repository navigation
Description
What happens
Limiter.run closes the token channel when it returns (defer close(limiter.tokens) in ratelimit.go).
TakeContext waits on case <-limiter.tokens: and returns nil on any receive, so once Stop ends run, every Take already waiting returns at once, and every later Take returns without waiting.
AutoLimiter.Remove and AutoLimiter.Stop call Limiter.Stop, so removing a key releases its waiters the same way.
The release is not immediate.
With the bucket empty, run first waits for the next tick, then chooses at random between sending a token and reading the cancelled context, so the waiters go at the next tick or a later one.
Seen on v0.0.94, and ratelimit.go on main is the same today (2026-11-16).
Reproduction
package main
import (
"context"
"fmt"
"sync/atomic"
"time"
"github.com/projectdiscovery/ratelimit"
)
func main() {
// One token every 200 ms, so 3 s of waiting may hand out 15 tokens at most.
l := ratelimit.New(context.Background(), 1, 200*time.Millisecond)
l.Take()
var passed atomic.Int32
for range 100 {
go func() { l.Take(); passed.Add(1) }()
}
time.Sleep(50 * time.Millisecond)
l.Stop()
time.Sleep(3 * time.Second)
fmt.Println("waiters that passed within 3 s of Stop:", passed.Load(), "of 100")
start := time.Now()
for range 1000 {
l.Take()
}
fmt.Println("1000 more takes took", time.Since(start).Round(time.Millisecond))
}Output, three runs of three:
waiters that passed within 3 s of Stop: 100 of 100
1000 more takes took 0s
Why it matters
A caller that stops or removes a limiter while requests wait on it sends all of them together.
Changing a key's rate on an AutoLimiter takes a Remove and an Add, so each change of rate sends the key's whole queue in one burst.
A caller cannot tell a released take from a granted one, since Take returns nothing and AutoLimiter.Take returns nil.
What would fix it
TakeContext could tell a closed channel from a token (_, ok := <-limiter.tokens) and return an error such as ErrLimiterStopped when ok is false, with AutoLimiter.Take passing that error on.
Take has no result to carry it, so a stopped limiter would still let Take return; the callers that need to know would use TakeContext.
Activity