Skip to content

Instantly share code, notes, and snippets.

@technicool
Last active October 27, 2021 18:21
Show Gist options
  • Save technicool/0a8a3fce5c6ca790e63b069b0364d4f8 to your computer and use it in GitHub Desktop.
Save technicool/0a8a3fce5c6ca790e63b069b0364d4f8 to your computer and use it in GitHub Desktop.
Rate limiting only using a single scalar value per user/actor

You can use this by importing the function into the console (or your app)

> x = rateLimit(a, {rps: 1, grace: 2}); a = x[1]; x
[ true, 1635358774575 ]
> x = rateLimit(a, {rps: 1, grace: 2}); a = x[1]; x
[ false, 1635358774575 ]
> x = rateLimit(a, {rps: 1, grace: 2}); a = x[1]; x
[ false, 1635358774575 ]
> x = rateLimit(a, {rps: 1, grace: 2}); a = x[1]; x
[ true, 1635358775575 ]
> x = rateLimit(a, {rps: 1, grace: 2}); a = x[1]; x
[ false, 1635358775575 ]
> x = rateLimit(a, {rps: 1, grace: 2}); a = x[1]; x
[ false, 1635358775575 ]
> x = rateLimit(a, {rps: 1, grace: 2}); a = x[1]; x
[ false, 1635358775575 ]
> x = rateLimit(a, {rps: 1, grace: 2}); a = x[1]; x
[ true, 1635358776575 ]
> x = rateLimit(a, {rps: 1, grace: 2}); a = x[1]; x
[ false, 1635358776575 ]
/**
* @param {int} oldValue is the old ratelimiter value, or null
* @param {config} has `rps` for the number of requests per second. `grace` is how many requests to allow bursting.
* @returns {[success, int]} Boolean for successful request or false to limit. Also, new value for the ratelimiter to cache.
*/
export function rateLimit(oldValue, config) {
const now = (new Date()).getTime(); // milliseconds of current time. Important that this is accurate!
const reqMs = 1000 / config.rps; // equivelant request millisecond counter.
if (oldValue != null && oldValue > now) {
if (oldValue > now + (reqMs * config.grace)) {
// Too many requests beyond burst grace
return [false, oldValue];
} else {
// In grace, increment and allow the request
return [true, (oldValue + reqMs)];
}
}
// Haven't had a request in a while
return [true, (now + reqMs)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment