Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add rate limiter class #1021

Merged
merged 4 commits into from
Apr 16, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 161 additions & 0 deletions dev/src/rate-limiter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*!
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as assert from 'assert';

import {Timestamp} from './timestamp';

/**
* A helper that uses the Token Bucket algorithm to rate limit the number of
* operations that can be made in a second.
*
* Before a given request containing a number of operations can proceed,
* RateLimiter determines doing so stays under the provided rate limits. It can
* also determine how much time is required before a request can be made.
*
* RateLimiter can also implement a gradually increasing rate limit. This is
* used to enforce the 500/50/5 rule
* (https://cloud.google.com/datastore/docs/best-practices#ramping_up_traffic).
*
* @private
*/
export class RateLimiter {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have to add some code to make tokens expire even if they are not used? I would suspect that if you issue 500 writes per second, then sit idle for a second, you can only issue 500 writes and not 1000.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Although we are not making tokens expire, we are already limiting the maximum number of tokens that can be accrued. When we refill the tokens, we call Math.min() on the capacity and the number of added tokens to prevent the scenario you mentioned above from happening.

I also added another test case to cover this as well.

// Number of tokens available. Each operation consumes one token.
availableTokens: number;

// When the token bucket was last refilled.
lastRefillTime = Timestamp.now();

/**
* @param initialCapacity Initial maximum number of operations per second.
* @param multiplier Rate by which to increase the capacity.
* @param multiplierMillis How often the capacity should increase in
* milliseconds.
* @param startTime Used for testing the limiter.
thebrianchen marked this conversation as resolved.
Show resolved Hide resolved
*/
constructor(
private readonly initialCapacity: number,
private readonly multiplier: number,
private readonly multiplierMillis: number,
private readonly startTime = Timestamp.now()
) {
this.availableTokens = initialCapacity;
this.lastRefillTime = startTime;
}

/**
* Tries to make the number of operations. Returns true if the request succeeded
* and false otherwise.
*
* @param currentTime Used for testing the limiter.
* @private
*/
tryMakeRequest(numOperations: number) {
return this._tryMakeRequest(numOperations, Timestamp.now());
}

/**
* Used in testing for different timestamps.
*
* @private
*/
// Visible for testing.
_tryMakeRequest(numOperations: number, currentTime: Timestamp): boolean {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you combine tryMakeRequest and _tryMakeRequest? You can assign a default value to currentTime (and name it something like requestTime to make it more suited for a public API).

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had that originally, but felt uncomfortable with the idea that you could break the limiter by passing in arbitrary timestamps far in the future. If someone specified a timestamp far in the future, the limiter would not refill any tokens until that time has been reached. It seems fragile to expose a parameter that would break the limiter, but if we're the only ones using the class, is it ok?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renamed to requestTimeMillis.

this.refillTokens(currentTime);
if (numOperations <= this.availableTokens) {
this.availableTokens -= numOperations;
return true;
}
return false;
}

/**
* Returns the number of ms needed to make a request with the provided number
* of operations. Returns 0 if the request can be made with the existing
* capacity. Returns -1 if the request is not possible with the current
* capacity.
*
* @private
*/
getNextRequestDelayMs(numOperations: number) {
return this._getNextRequestDelayMs(numOperations, Timestamp.now());
}

thebrianchen marked this conversation as resolved.
Show resolved Hide resolved
/**
* Used in testing for different timestamps.
*
* @private
*/
// Visible for testing.
_getNextRequestDelayMs(
numOperations: number,
currentTime: Timestamp
): number {
thebrianchen marked this conversation as resolved.
Show resolved Hide resolved
if (numOperations < this.availableTokens) {
return 0;
}

const capacity = this.calculateCapacity(currentTime, this.startTime);
if (capacity < numOperations) {
return -1;
}

const requiredTokens = numOperations - this.availableTokens;
return Math.ceil((requiredTokens * 1000) / capacity);
}

/**
* Refills the number of available tokens based on how much time has elapsed
* since the last time the tokens were refilled.
*
* @private
*/
private refillTokens(currentTime = Timestamp.now()): void {
if (currentTime.toMillis() > this.lastRefillTime.toMillis()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you used Date object or even just epoch milliseconds your code will be much more portable and can be used outside of the FIrestore client if need be.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switched to using Date and getTime().

const elapsedTime =
currentTime.toMillis() - this.lastRefillTime.toMillis();
const capacity = this.calculateCapacity(currentTime, this.startTime);
const tokensToAdd = Math.floor((elapsedTime * capacity) / 1000);
if (tokensToAdd > 0) {
this.availableTokens = Math.min(
capacity,
this.availableTokens + tokensToAdd
);
this.lastRefillTime = currentTime;
}
}
}

/**
* Calculates the maximum capacity based on the two provided timestamps.
*
* @private
*/
// Visible for testing.
calculateCapacity(currentTime: Timestamp, startTime: Timestamp): number {
thebrianchen marked this conversation as resolved.
Show resolved Hide resolved
assert(
currentTime.valueOf() >= startTime.valueOf(),
'startTime cannot be after currentTime'
);
const millisElapsed = currentTime.toMillis() - startTime.toMillis();
const operationsPerSecond = Math.floor(
Math.pow(
this.multiplier,
Math.floor(millisElapsed / this.multiplierMillis)
) * this.initialCapacity
);
return operationsPerSecond;
}
}
95 changes: 95 additions & 0 deletions dev/test/rate-limiter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import {expect} from 'chai';

import {Timestamp} from '../src';
import {RateLimiter} from '../src/rate-limiter';

describe('RateLimiter', () => {
let limiter: RateLimiter;

beforeEach(() => {
limiter = new RateLimiter(500, 1.5, 5 * 60 * 1000, new Timestamp(0, 0));
thebrianchen marked this conversation as resolved.
Show resolved Hide resolved
});

it('accepts and rejects requests based on capacity', () => {
expect(limiter._tryMakeRequest(250, new Timestamp(0, 0))).to.be.true;
expect(limiter._tryMakeRequest(250, new Timestamp(0, 0))).to.be.true;

// Once tokens have been used, further requests should fail.
expect(limiter._tryMakeRequest(1, new Timestamp(0, 0))).to.be.false;

// Tokens will only refill up to max capacity.
expect(limiter._tryMakeRequest(501, new Timestamp(1, 0))).to.be.false;
expect(limiter._tryMakeRequest(500, new Timestamp(1, 0))).to.be.true;

// Tokens will refill incrementally based on the number of ms elapsed.
expect(limiter._tryMakeRequest(251, new Timestamp(1, 500 * 1e6))).to.be
.false;
thebrianchen marked this conversation as resolved.
Show resolved Hide resolved
expect(limiter._tryMakeRequest(250, new Timestamp(1, 500 * 1e6))).to.be
.true;

// Scales with multiplier.
expect(limiter._tryMakeRequest(751, new Timestamp(5 * 60 - 1, 0))).to.be
.false;
expect(limiter._tryMakeRequest(751, new Timestamp(5 * 60, 0))).to.be.false;
expect(limiter._tryMakeRequest(750, new Timestamp(5 * 60, 0))).to.be.true;
});

it('calculates the number of ms needed to place the next request', () => {
// Should return 0 if there are enough tokens for the request to be made.
let timestamp = new Timestamp(0, 0);
expect(limiter._getNextRequestDelayMs(500, timestamp)).to.equal(0);

// Should factor in remaining tokens when calculating the time.
expect(limiter._tryMakeRequest(250, timestamp));
expect(limiter._getNextRequestDelayMs(500, timestamp)).to.equal(500);

// Once tokens have been used, should calculate time before next request.
timestamp = new Timestamp(1, 0);
expect(limiter._tryMakeRequest(500, timestamp)).to.be.true;
expect(limiter._getNextRequestDelayMs(100, timestamp)).to.equal(200);
expect(limiter._getNextRequestDelayMs(250, timestamp)).to.equal(500);
expect(limiter._getNextRequestDelayMs(500, timestamp)).to.equal(1000);
expect(limiter._getNextRequestDelayMs(501, timestamp)).to.equal(-1);

// Scales with multiplier.
timestamp = new Timestamp(5 * 60, 0);
expect(limiter._tryMakeRequest(750, timestamp)).to.be.true;
expect(limiter._getNextRequestDelayMs(250, timestamp)).to.equal(334);
expect(limiter._getNextRequestDelayMs(500, timestamp)).to.equal(667);
expect(limiter._getNextRequestDelayMs(750, timestamp)).to.equal(1000);
expect(limiter._getNextRequestDelayMs(751, timestamp)).to.equal(-1);
});

it('calculates the maximum number of operations correctly', async () => {
const currentTime = new Timestamp(0, 0);
expect(
limiter.calculateCapacity(new Timestamp(1, 0), currentTime)
).to.equal(500);
expect(
limiter.calculateCapacity(new Timestamp(5 * 60, 0), currentTime)
).to.equal(750);
expect(
limiter.calculateCapacity(new Timestamp(10 * 60, 0), currentTime)
).to.equal(1125);
expect(
limiter.calculateCapacity(new Timestamp(15 * 60, 0), currentTime)
).to.equal(1687);
expect(
limiter.calculateCapacity(new Timestamp(90 * 60, 0), currentTime)
).to.equal(738945);
});
});