Home > Back-end >  Two express js app runs on different threads?
Two express js app runs on different threads?

Time:03-21

I have two express apps running on a different port, as we know express runs on a single thread, so do they assign themselves different cores?

Cluster module replicates the express app making them use different core.

But suppose if I take two or more apps and connect them does that means that I have almost created a cluster module?

CodePudding user response:

Two express apps running in the same nodejs process will share the one thread that nodejs uses to run your Javascript. They will also share the same event queue. So, if a request arrives at about the same time for each express app, then one will run first and then the other will get a chance to run. They will not run in parallel on different cores.

The cluster module actually starts up additional nodejs processes and then routes incoming connections to the clustered processes. In that case, you have completely separate processes that run independently from one another and can use separate cores.

Two express apps running in the same nodejs app will not provide the same type of multi-core concurrency that clustering will.

I have two express apps running on a different port, as we know express runs on a single thread, so do they assign themselves different cores?

No. Nodejs will have one thread that services both Express apps.

But suppose if I take two or more apps and connect them does that means that I have almost created a cluster module?

No. Two or more Express apps in the same nodejs process does not create the equivalent of clustering. In fact, it doesn't give you any advantage at all over just having the same number of requests all be served by one Express app in your nodejs process.


If you want two Express apps to each have access to their own CPU core, then you should either put each Express app in its own nodejs process. Then, the OS can allocate a separate core to each nodejs process.

Also, keep in mind that the app itself doesn't choose a core. The OS looks at which threads in which processes are waiting to run and assigns a core. That assignment may even be dynamic (changing which core it uses over time). While an OS will prefer to use the same core for a given process over time (because of the possibility of better caching), it isn't forced to only ever use the same core.

CPU core management and assignment is managed by the OS based on demand from competing processes.

  • Related