简体   繁体   English

在 Google Cloud Run 中运行 Node.js mongoose 应用程序时连接过多 MongoDB

[英]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.我正在运行一个 Node.js API 连接到 MongoDB Atlas 和 mongoose。Node.js API 在 Google Cloud Run 上运行。

I open one connection using mongoose我使用 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然后当 SINGINT 信号从 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!正如我在日志中看到的那样,它工作正常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.但是,即使 Cloud Run 实例永远不会超过 5 或 6,与数据库的连接数也会增加到 130。

Is there anything I am missing here?我在这里缺少什么吗?

I think I solved the mystery.我想我解开了这个谜。 According to mongoose documentation根据 mongoose 文档

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.我使用 Apollo graphql 服务器。 When you chain resolvers they are run as promises, and thus, mongoose could launch up to 100 connections for one single API call.当您链接解析器时,它们作为承诺运行,因此,mongoose 可以为一个 API 调用启动多达 100 个连接。 Which could happen if you query an array of ids to build your response object.如果您查询一组 ID 以构建您的响应 object,则可能会发生这种情况。

Why does this happen on Cloud Run and not in GKE.为什么这会发生在 Cloud Run 而不是 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.因为 Cloud Run 可以按需快速部署您的服务实例,而在 GKE 上您通常会限制 POD 的数量。 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.因此,为了响应 5 个 API 调用,Cloud Run 只需并行部署 5 个容器,从而扩展到最多 500 个 Mongo 连接,然后关闭实例。 With GKE this would not happen.使用 GKE,这不会发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM