Skip to content
This repository has been archived by the owner on Sep 13, 2022. It is now read-only.

Commit

Permalink
Fix leaky bucket bug
Browse files Browse the repository at this point in the history
  • Loading branch information
black-adder committed Mar 6, 2017
1 parent e3a0306 commit f4a5bf5
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 7 deletions.
9 changes: 5 additions & 4 deletions src/rate_limiter.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@
export default class RateLimiter {
_creditsPerSecond: number;
_balance: number;
_maxBalance: number;
_lastTick: number;

constructor(creditsPerSecond: number) {
constructor(creditsPerSecond: number, maxBalance: number) {
this._creditsPerSecond = creditsPerSecond;
this._balance = creditsPerSecond;
this._maxBalance = maxBalance;
this._lastTick = new Date().getTime();
}

Expand All @@ -36,10 +38,9 @@ export default class RateLimiter {
this._lastTick = currentTime;

this._balance += elapsedTime * this._creditsPerSecond;
if (this._balance > this._creditsPerSecond) {
this._balance = this._creditsPerSecond;
if (this._balance > this._maxBalance) {
this._balance = this._maxBalance;
}

if (this._balance >= itemCost) {
this._balance -= itemCost;
return true;
Expand Down
2 changes: 1 addition & 1 deletion src/samplers/ratelimiting_sampler.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export default class RateLimitingSampler {
}

this._maxTracesPerSecond = maxTracesPerSecond;
this._rateLimiter = new RateLimiter(maxTracesPerSecond);
this._rateLimiter = new RateLimiter(maxTracesPerSecond, 2.0);
}

name(): string {
Expand Down
4 changes: 2 additions & 2 deletions test/rate_limiter.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ describe ('leaky bucket ratelimiter should', () => {
it('block after threshold is met', () => {
let initialDate = new Date(2011,9,1).getTime();
let clock = sinon.useFakeTimers(initialDate);
let limiter = new RateLimiter(10);
let limiter = new RateLimiter(10, 10);
for (let i = 0; i < 10; i++) {
limiter.checkCredit(1);
}
Expand All @@ -43,7 +43,7 @@ describe ('leaky bucket ratelimiter should', () => {
let clock = sinon.useFakeTimers(initialDate);
let limit = 500;
let cost = 1 / limit;
let limiter = new RateLimiter(1);
let limiter = new RateLimiter(1, 1);
for (let i = 0; i < limit; i++) {
limiter.checkCredit(cost);
}
Expand Down

0 comments on commit f4a5bf5

Please sign in to comment.