Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Node js, what happens if a new request arrives and event loop is already busy processing a request?

I have this file named index.js:

const express = require('express')
const app = express()
const port = 3000

app.get('/home', (req, res) => {
    res.send('Hello World!')
})

app.get('/route1', (req, res) => {
    var num = 0;
    for(var i=0; i<1000000; i++) {
        num = num+1;
        console.log(num);
    }
    res.send('This is Route1 '+ num)
})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

I first call the endpoint /route1 and then immediately the endpoint /home. The /route1 has for loop and takes some time to finish and then /home runs and finishes. My question is while app was busy processing /route1, how was the request to /home handled, given node js is single threaded?

like image 618
martinho Avatar asked Oct 24 '25 15:10

martinho


1 Answers

The incoming request will be queued in the nodejs event queue until nodejs gets a chance to process the next event (when your long running event handler is done).

Since nodejs is an event-driven system, it gets an event from the event queue, runs that event's callback until completion, then gets the next event, runs it to completion and so on. The internals of nodejs add things that are waiting to be run to the event queue so they are queued up ready for the next cycle of the event loop.

Depending upon the internals of how nodejs does networking, the incoming request might be queued in the OS for a bit and then later moved to the event queue until nodejs gets a chance to serve that event.

My question is while app was busy processing /route1, how was the request to /home handled, given node js is single threaded?

Keep in mind that node.js runs your Javascript as single threaded (though we do now have Worker Threads if you want), but it does use threads internally to manage things like file I/O and some other types of asynchronous operations. It does not need threads for networking, though. That is managed with actual asynchronous interfaces from the OS.

like image 90
jfriend00 Avatar answered Oct 27 '25 04:10

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!