mateos
mateos

Reputation: 1563

Should I have a new MongoDB connection per thread

When using the Node.js cluster library, should a connection to MongoDB be made in the master thread or in each child thread?

Firstly, can multiple threads use the same connection?

Secondly, would it be more performance-effective to use the same or separate connections

Upvotes: 1

Views: 1278

Answers (3)

Mark Stosberg
Mark Stosberg

Reputation: 13411

The question suggests that the cluster library uses threads, but it does not, it uses processes.

Each process MUST have its own connection. Connections cannot be shared across a process.

Upvotes: 1

Air One
Air One

Reputation: 326

In my experience, each child needs a connection, I use the following pattern in the app code for example

const cluster       = require('cluster');
const mongoose      = require('mongoose');
...

if (cluster.isMaster) { // Parent, only creates clusters
  global.processId = 'Master';
  for (let i = 0; i < 2; ++i) {
      cluster.fork();
  }
  ...
} else { // Child cluster
    // connect
    mongoose.connect('mongodb://localhost/myDB');
    ...
}

Upvotes: 1

Vishnu Kyatannawar
Vishnu Kyatannawar

Reputation: 373

Every process should have its own connection.

Don't mix sessions. Use connect-mongo for sessions.

Once client establishes session on one of the workers, it should not use any other instance for operations related to this client, this way you can cache clients on their respective server instances.

Upvotes: 0

Related Questions