How can I keep a HTTP connection alive if I am making the first request outside of the main fetch function in NodeJS?

1k Views Asked by At

I have the following fetch function which I use with the undici fetch library:

async function call() {
        return await fetch('http://127.0.0.1:3000/', {
            dispatcher: new Agent({
                keepAliveTimeout: 100000000,
                keepAliveMaxTimeout: 100000000
              }),
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
    
            body: JSON.stringify({
                'a': 2,
                'b': '0x',
                'data': `${Data}`,
                'limit': 100,
                'loops': 1,
                'value': '0'
                
            })
            
            
        }).then((response) => response.json())
        .then((responseData) => {
            //console.log(responseData);
            return responseData;
        })
        .catch(error => console.warn(error));
        
        
    }; 

I am running a highly time sensitive application and need to make a post request with sub 1ms latency . The api server is running on localhost .

After establishing there was a bottleneck due to the fact that each time I called the function it would establish a new TCP / HTTP connection, I started looking into keepalive and added the dispatcher arguments which seem to do the trick with undici fetch .

Since the first request is the one that opens the TCP connection, I created a separate function which is basically a mirror of the call function in order to establish the tcp connection before call() is called .

However, I am unable to keep the connection alive this way, and only when the txsend function gets called multiple times (after the first time) it seems to eliminate the overhead cost of establishing a new TCP connection .

How can I create a new TCP / HTTP connection before my call() function is used in order to avoid establishing a new one when I call my main function ?

0

There are 0 best solutions below