Mongoose duplicate connections in a clustered express.js app

262 views Asked by At

I have added clustering to my express.js app, and I've specified 2 workers, in the app I connect to my db via mongoose, but when I run the app, my my mongoose connection (mongoose.connect) runs twice. I have tried putting it in the master cluster, but it won't work in the child cluster, is there any way I can make sure the db connects only once? I am using Throng module for this, and the rough code is below:

// Using this module for clustering
throng( { workers: 2, lifetime: Infinity, }, start);


// My express app code goes inside this function
function start() { 
  // Connecting via mongoose
  mongoose.connect('')

  // ....some other code here

 server.listen(port, () => { 
    var host = process.env.NODE_ENV == 'development' && 'localhost'; var port = process.env.NODE_ENV == 'development' && process.env.PORT;
    console.log(chalk.cyan(` app listening at http://${host}:${port}`));
 })
}

I can't figure out what to do, any help in this would be really appreciated, thanks!

1

There are 1 answers

0
Michael Hobbs On BEST ANSWER

Per: https://github.com/hunterloftis/throng#a-complex-example I've never worked with throng but based on the docs this should be close.

throng({master, worker, count: 4})

// This will only be called once
function master() {
  console.log('Started master')

  // Connecting via mongoose
  mongoose.connect('')

  // ....some other code here

  server.listen(port, () => {
    var host = process.env.NODE_ENV == 'development' && 'localhost';
    var port = process.env.NODE_ENV == 'development' && process.env.PORT;
    console.log(chalk.cyan(` app listening at http://${host}:${port}`));
  })
  process.on('beforeExit', () => {
    console.log('Master cleanup.')
  })
}

// This will be called four times
function worker(id, disconnect) {
  let exited = false

  console.log(`Started worker ${id}`)
  process.on('SIGTERM', shutdown)
  process.on('SIGINT', shutdown)

  async function shutdown() {
    if (exited) return
    exited = true

    disconnect()
  }
}