0

I am creating a resp api with nodejs express and babael using escma6 my question is the following I have a module where I have the connection to the database and the configuration and another file called server where I create the server with express, but I am using the nodejs clusters, I see that when using the clusters and call the connection in the server file connects with each worker to the database, now my question is this would not generate a performance error so many connections in the database? taking into account that each time that a worker finishes it dies and another one is generated therefore also another connection to bd.

this is my server file

"use strict";
import 'dotenv/config';
import app from './app';
import cluster from 'node:cluster';
import { cpus } from 'node:os';
import process from 'node:process';
import { dbConexion } from "./db/db";

const port = process.env.PORT || 3000;
const numCPUs = cpus().length;


if (cluster.isPrimary) {
    console.log(` Primary ${process.pid} is running`);
  
    // Fork workers.
    for (let i = 0; i < numCPUs; i++) {
      cluster.fork();
    }
  
    cluster.on('exit', (worker, code, signal) => {
      console.log(`worker ${worker.process.pid} died`);
      cluster.fork();
    });

} else {
    // Workers can share any TCP connection
    // In this case it is an HTTP server
    app.listen(port, () => {
      console.log(` Worker ${process.pid} started`);
    });

    //db conexion 
    dbConexion();
}

import 'dotenv/config'
import { connect } from "mongoose";


export const dbConexion = async () =>{

  const MONGO_URI = process.env.DB_URI || "db";

  try{
    const db = await connect(
      MONGO_URI,
      {
        keepAlive:true,
        useNewUrlParser:true,
        useUnifiedTopology:true
      }
    );
  
    console.log('Db connected to ',db.connection.name);
  }catch(err){
    console.log('Db Connection failure:',err);
  }
}

enter image description here i would like to know if this is correct or it can generate problems later and how i could improve it pdta: no matter where i put the connection to the db in the server file it is still called 4 times

  • answered [here](https://stackoverflow.com/questions/41386483/nodejs-cluster-and-database-connection) – username_jj Jul 20 '22 at 06:55
  • and can u give me a example in code ? – Emanuel bass Jul 20 '22 at 14:18
  • 1
    `cluster.fork` creates a separate running instance of your application. Depending on what you're using for your database, it should be appropriate for each process to have their own connection. You just need to be aware of worker operations and either wrap them in a cluster.isPrimary or have a seprate app for that. – JonShipman Oct 25 '22 at 13:52

0 Answers0