Created
May 23, 2020 20:56
-
-
Save viniciusjssouza/0138fbc9d0ddbf3b8739ef4aec232693 to your computer and use it in GitHub Desktop.
Keep-Alive connection experiment
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
| import { HttpsAgent } from 'agentkeepalive'; | |
| import Axios, { AxiosInstance } from 'axios'; | |
| import http from 'http'; | |
| const KEEP_ALIVE_TIMEOUT = 10_000; | |
| const keepAliveAgent = new HttpsAgent({ | |
| maxSockets: 100, | |
| keepAlive: true, | |
| maxFreeSockets: 10, | |
| timeout: KEEP_ALIVE_TIMEOUT, // active socket keepalive for 60 seconds | |
| freeSocketTimeout: KEEP_ALIVE_TIMEOUT, // free socket keepalive for 30 seconds | |
| }); | |
| export const KEEP_ALIVE_CONFIG = { | |
| timeout: KEEP_ALIVE_TIMEOUT, | |
| maxRedirects: 5, | |
| httpAgent: new http.Agent({ keepAlive: true }), | |
| httpsAgent: keepAliveAgent, | |
| }; | |
| function wait(millis): Promise<void> { | |
| return new Promise(resolve => setTimeout(() => resolve(), millis)); | |
| } | |
| async function performRequest(requestIndex: number, axios: AxiosInstance): Promise<void> { | |
| console.time(`${requestIndex}`); | |
| await axios.get('https://httpbin.org/get'); | |
| console.timeEnd(`${requestIndex}`); | |
| await wait(100); | |
| } | |
| async function runExperiment(axios: AxiosInstance): Promise<void> { | |
| for (let i = 1; i <= 5; i += 1) { | |
| // eslint-disable-next-line no-await-in-loop | |
| await performRequest(i, axios); | |
| } | |
| console.log(); | |
| await wait(KEEP_ALIVE_TIMEOUT); | |
| for (let i = 1; i <= 5; i += 1) { | |
| // eslint-disable-next-line no-await-in-loop | |
| await performRequest(i, axios); | |
| } | |
| } | |
| async function main() { | |
| const keepAliveAxios = Axios.create(KEEP_ALIVE_CONFIG); | |
| const regularAxios = Axios.create(); | |
| console.log('Testing WITHOUT Keep Alive'); | |
| await runExperiment(regularAxios); | |
| console.log('\n\nTesting WITH Keep Alive'); | |
| await runExperiment(keepAliveAxios); | |
| } | |
| main().then(() => console.log('Finished!')).catch(err => console.error(err)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment