Is there a good way to close mongo connections when a lambda container expires?

▼魔方 西西 提交于 2021-01-28 03:03:44

问题


I am using AWS-lambda handler to write a dynamoDB stream to mongoDB. I want to define the db connection outside of the handler so that the requests reuse the same connections, based on our expected throughput volume. The problem with the lambda containers will expire without disposing of the connections properly.

Does anybody know of any good solutions for this problem? Essentially boils down to "I want to use connection pools without maxing out the connection limit"


回答1:


When I faced with this problem, I've found out two solutions:

  1. "Best practice" - create/close MongoDB connection for each Lambda invocation. Good idea if you know that Lambdas will be invoked not so often => your Lambdas containers would shout down.
  2. Reuse connection pull - for me, it's normal when you know that you Lambda will invoked enough usually to keep (potentially) container warm. In this case you should set socketTimeoutMS option (mongoose) enough to keep it between Lambdas invocation. For me it's :
 { 
   reconnectTries: 30, 
   reconnectInterval: 500, 
   poolSize: 1, 
   socketTimeoutMS: 2000000, 
   keepAlive: true, 
 }

(connection will be closed automatically after timeout)

** FYI: Any warm-up may be not suitable for you, if you use DynamoDB streams as trigger for lambda.

** I've already asked similar question here: AWS Lambda (Node.js, v. 8.10) & Mongoose: MongoNetworkError connection to DB timed out



来源:https://stackoverflow.com/questions/56435634/is-there-a-good-way-to-close-mongo-connections-when-a-lambda-container-expires

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!