Skip to content

Instantly share code, notes, and snippets.

@celsowhite
Created March 1, 2022 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celsowhite/fd4db692a9c34ea04cdf7194ee07d942 to your computer and use it in GitHub Desktop.
Save celsowhite/fd4db692a9c34ea04cdf7194ee07d942 to your computer and use it in GitHub Desktop.
Simulate a leaky bucket to understand how many calls and requests can be made in a certain amount of time without going beyond capacity.
let callCount = 0;
let bucketCount = 0;
// Bucket Settings
const bucketCapacity = 8;
const leakRate = 2;
const leakTime = 1000;
// Call Settings
const callAmount = 5;
const timePerCall = 2000;
const requestsPerCall = 4;
// Bucket Interval - Controls how full the bucket is and leaks a certain amount per second.
const bucketInterval = setInterval(() => {
console.log(`Bucket Count: ${bucketCount} Call Count: ${callCount}`);
if (bucketCount > 0) {
bucketCount -= leakRate;
}
if (bucketCount >= bucketCapacity) {
console.error("Bucket is full.");
}
if (callCount === callAmount) {
clearInterval(bucketInterval);
clearInterval(callInterval);
res.status(200).send();
}
}, leakTime);
// Call Interval - Controls the amount of requests filling the bucket in a given time.
const callInterval = setInterval(() => {
callCount += 1;
bucketCount += requestsPerCall;
}, timePerCall);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment