Last active
November 23, 2025 23:25
-
-
Save shrunyan/8d664f33c99f7bb304dd12282dad2464 to your computer and use it in GitHub Desktop.
Function to generate a total amount of requests over a specificed time period to simulate a natural traffic pattern
This file contains hidden or 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
| /** | |
| * Generates requests in batches over a specified time period | |
| * By varying the batch size randomly up to a max, it simulates more natural traffic | |
| * @name genRequests | |
| * @param {String} url The URL to send requests to | |
| * @param {Number} total Total number of requests to send | |
| * @param {Number} batchMax Max number of requests to send in parallel per batch | |
| * @param {Number} runTime Amount of time in millseconds to spread the requests over | |
| * @returns {Promise<Number>} Number of requests completed | |
| */ | |
| async function genRequests(url, total = 1, batchMax = 0, runTime = 0) { | |
| const resp = []; | |
| const errors = []; | |
| while (resp.length < total) { | |
| try { | |
| const batchSize = Math.floor(Math.random() * batchMax) + 1; | |
| const requests = Array.from({ length: batchSize }, () => fetch(url)); | |
| const responses = await Promise.all(requests); | |
| for (const res of responses) { | |
| if (!res.ok) { | |
| errors.push(res); | |
| } | |
| } | |
| resp.push(...responses); | |
| // Add a delay to make the loop last N milleseconds | |
| // Wait based on how much of the total 'share' this batch took | |
| // Formula: (BatchSize / TotalRequests) * TotalDesiredTimeInMs | |
| await new Promise((resolve) => | |
| setTimeout(resolve, (requests.length / total) * runTime) | |
| ); | |
| // NOTE: remove log if you do not want this function to be noisy | |
| console.log(`Submissions ${resp.length} of ${total}`); | |
| } catch (err) { | |
| console.error(err); | |
| // ensure errors do not exit the loop early | |
| continue; | |
| } | |
| } | |
| return [resp, errors]; | |
| } |
Author
Author
Note: This function could be improved to incorporate the logarithmic decline or could include a couple of algorithms in the function and an additional parameter could be added to allow selection of the desired pattern.
Author
Note: a negative exponential distribution is most likely what I want after initial viral burst of traffic.

Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simulating viral web traffic with a logarithmic decline would look something like the following.
Goal:

-- wikihow
Result: Needs more refinement.
