juju / ratelimit

Efficient token-bucket-based rate limiter package.
Other
2.79k stars 312 forks source link

Does method ratelimit.go , Bucket.abjust has a bug ? #13

Closed stdpmk closed 7 years ago

stdpmk commented 8 years ago

I'm new in github. Found your package small and more understandable then others.

But little confused with tb.avail in Bucket.abjust:

tb.avail += (currentTick - tb.availTick) * tb.quantum

why used just currentTick , but not currentTick * tb.capacity.

For example, we have

t0----------------t1---------------t2 dt = t1-t0 = t2-t1 currentTick = int64(t2.Sub(t0) / dt) = 2. But in such interval [t0,t2] we must have 2 * tb.capacity tokens in the bucket, not just 2.

helinbo2015 commented 7 years ago

@stdpmk i'd like to have a comment about your doubt.

--> so calc tokens by currentTick and tb.availTick, you should multiply with tb.quantum

rogpeppe commented 7 years ago

@helinbo2015 is correct. The capacity is the maximum number of tokens that can be in the bucket at any one time; the quantum is the number of tokens that gets added on every tick. So in the interval [t0, t2] we'll have 2 (quantum (t2 - t1) / tickInterval) limited by the bucket's capacity.