Cached Mongodb connection - Global variable
See original GitHub issueHi guys,
I’m using aws-serverless-express repository for a project, and I’m trying to optimize Mongodb connection when Lambda function is awakened.
Currently, for each call, my function create a new Mongodb connection (too bad…), and I found this solution: keep in global variable, the Mongodb connection.
(Full article: https://blog.cloudboost.io/i-wish-i-knew-how-to-use-mongodb-connection-in-aws-lambda-f91cd2694ae5)
But I don’t know how to do that with my current architecture code:
"use strict";
const awsServerlessExpress = require("aws-serverless-express");
const app = require("./app");
const binaryMimeTypes = [
"application/javascript",
"..."
];
const server = awsServerlessExpress.createServer(app, null, binaryMimeTypes);
exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context);
Currently my Mongodb connection is done in app.js
file. So each call reload app.js
file…
I’m looking for a solution to send my Mongodb variable to my file app and keep alive Mongodb connection while Lambda function is awakened.
Thanks for your help.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:6
Top Results From Across the Web
Cached Mongodb connection - Global variable · Issue #139
I'm using aws-serverless-express repository for a project, and I'm trying to optimize Mongodb connection when Lambda function is awakened.
Read more >How to cache or reuse MongoDB database connection in ...
I'm using a global variable cachedDb to store the database connection but each and every time I make a request it logs =====...
Read more >Huge amount of connections - MongoDB Atlas
Hello, I have a huge amount of connections not closing, I tried a lot of actions to make, but nothing changed, connections are...
Read more >Connection Pool Overview — MongoDB Manual
A connection pool is a cache of open, ready-to-use database connections ... Store your MongoClient instance in a place that is globally accessible...
Read more >How does the MongoDB Data API work from a high-level ...
It's the same thing for AWS Lambdas. You have to cache the connection in a global variable that is reused by all the...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I used lodash-memoize to cache the function. This solved my problem. Here is my code example, if someone is interested.
The result looks like this:
What I found:
getClientSecret
function.You should be fine.
app.js
will only be loaded once per Lambda container (or “cold start”)