'Too much MongoDB connections when running Node.js mongoose app in Google Cloud Run

I am running a Node.js API connecting to MongoDB Atlas with mongoose. The Node.js API runs on Google Cloud Run.

I open one connection using mongoose

mongoose.connect(mongoUrl);
  const db = mongoose.connection;
  db.on("error", console.error.bind(console, "connection error:"));
  db.once("open", () => {
    console.info("Mongo Database connected");

And then gracefully close the connection to the database when SINGINT signal arrives from Google Cloud Run

process.on("SIGINT", () => gracefulShutdown(server));

and

const gracefulShutdown = async (apollo?: ApolloServer) => {
  await mongoose.connection.close();
  console.info(`MONGODB CONNECTION CLOSED!`);
  await apollo.stop();
  console.info(`APOLLO SERVER STOPPED!`);
  process.exit();
};

It is working right as I can see on the logs MONGODB CONNECTION CLOSED!

But, even if the Cloud Run instances never grow over 5 or 6, the number of connections to the DB rises up to 130.

Is there anything I am missing here?



Solution 1:[1]

I think I solved the mystery. According to mongoose documentation

maxPoolSize - The maximum number of sockets the MongoDB driver will keep open for this connection. By default, maxPoolSize is 100. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See Slow Trains in MongoDB and Node.js. You may want to decrease maxPoolSize if you are running into connection limits

I use Apollo graphql Server. When you chain resolvers they are run as promises, and thus, mongoose could launch up to 100 connections for one single API call. Which could happen if you query an array of ids to build your response object.

Why does this happen on Cloud Run and not in GKE. Because Cloud Run can deploy instances of your services on demand and very fast, while on GKE you have usually limited the number of PODs. Thus, for responding 5 API calls, Cloud Run could just deploy 5 containers in parallel, and thus, scale to up to 500 Mongo connections, and then just shut down de instances. With GKE this would not happen.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alberto Valero