问题
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:
- "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.
- 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