muturgan
muturgan

Reputation: 505

Node.js only one worker works

This is my server enterpoint:

const numCPUs: number = require('os').cpus().length;
const PORT = process.env.PORT;

import server from './app';
import logger from './logger';

import Domain = require('domain');
import cluster = require('cluster');

if (cluster.isMaster) {
    logger.info(`Master ${process.pid} is running`);

    for (let i = 0; i < numCPUs; i++) {
        cluster.fork();
    }

    cluster.on('exit', (worker, code, signal) => {
        logger.info(`Worker ${worker.process.pid} died`);
        cluster.fork();
    });

  } else {
    const domain = Domain.create();
    domain.on('error', (error) => {
        logger.error(`Domain error in precess id:${ process.pid }`, error);
        ...
    });

    domain.run(() => {
        server.listen(PORT, () => {
            logger.info(`Express server id:${ process.pid } listening on port ${ PORT }`);
        });
    });
}

I made testing html page that sends testing request in 20 times (or as much as you need) to some handler. This is it's code:

app.route('/api/admin/getProjectFilters')
    .get( async (req: Request, res: Response) => {
        try {
            const filters: projectFiltersType = {...};
            // some actions

            logger.info(`project filters were sent to admin in precess id:${ process.pid }`);
            res.status(200).send(filters);

        } catch (error) {
            logger.error(`project filters sending to admin failed in precess id:${ process.pid }`, error);
            res.status(500).send(error);
        }
    }
);

Starting my server and looking to the console:

2018-10-10T08:04:50.754Z [info]: Master 9584 is running

2018-10-10T08:04:52.273Z [info]: Express server id:11592 listening on port 2222

2018-10-10T08:04:52.334Z [info]: Express server id:2828 listening on port 2222

2018-10-10T08:04:52.352Z [info]: Express server id:2580 listening on port 2222

2018-10-10T08:04:52.383Z [info]: Express server id:4540 listening on port 2222

2018-10-10T08:04:58.330Z [info]: project filters were sent to admin in precess id:4540

2018-10-10T08:04:58.377Z [info]: project filters were sent to admin in precess id:4540

2018-10-10T08:04:58.447Z [info]: project filters were sent to admin in precess id:4540

2018-10-10T08:04:58.491Z [info]: project filters were sent to admin in precess id:4540

2018-10-10T08:04:58.538Z [info]: project filters were sent to admin in precess id:4540

As you can see, I have some workers, but only one handling client's requests.

How can I force the node.js to use all workers?

Upvotes: 0

Views: 63

Answers (1)

muturgan
muturgan

Reputation: 505

The reason is keep-alive header.

Tried to start my test in two browsers in same time.
I see two different ids in console!

Upvotes: 1

Related Questions