-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: Rate limiter
TokenBucket::auto_replenish()
#### Change Fixes bug in `TokenBucket::auto_replenish`. This change also yields a slight performance increase (from ~28ns to ~26ns). #### Reason When a TokenBucket gets empty, the implementation sets a timer of 100ms for replenishing it. The bucket replenishing function calculates the new tokens to add to the budget using the following formula: ``` let tokens = (time_delta * self.processed_capacity) / self.processed_refill_time; ``` However, this formula can return 0 depending of the values of `self.processed_capacity` and `self.processed_refill_time`. For a TokenBucket of size total capacity and `complete_refill_time_ns` refill period in nanoseconds, the above values are calculated as follows: ``` // Get the greatest common factor between `size` and `complete_refill_time_ns`. let common_factor = gcd(size, complete_refill_time_ns); let processed_capacity: u64 = size / common_factor; let processed_refill_time: u64 = complete_refill_time_ns / common_factor; ``` So, for example if `size == 1` and `complete_refill_time_ns == 1_000_000_000` (equivalent to 1 token per second) the replenishing tokens will be: ``` let tokens = (100_000_000 * 1) / 1_000_000_000; // which gives 0 in integer division ``` As a result, the bucket will never get replenished. Signed-off-by: Jonathan Woollett-Light <jcawl@amazon.co.uk>
- Loading branch information
1 parent
6900349
commit 40bb276
Showing
1 changed file
with
9 additions
and
66 deletions.
There are no files selected for viewing
This file contains 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