question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Cached Mongodb connection - Global variable

See original GitHub issue

Hi 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.

image (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:closed
  • Created 5 years ago
  • Reactions:1
  • Comments:6

github_iconTop GitHub Comments

2reactions
yottachencommented, May 30, 2018

I used lodash-memoize to cache the function. This solved my problem. Here is my code example, if someone is interested.

// index.js

const containerId = Date.now().toString().slice(-6);

exports.handler = async (event) => {
    const generate = require('./generator.js');
    console.log(`ContainerId: ${containerId}`);
    generate('clientId1');
    generate('clientId2');
    generate('clientId1');
    generate('clientId2');
};


// generate.js
const memoize = require('./memoize');

const getClientSecret = (clientId) => {
    console.log('hello');
    return clientId;
};

const cachedSecret = memoize(getClientSecret);

const generate = (clientId) => {
    const cs = cachedSecret(clientId);
    console.log(cs);
    return cs;
};

module.exports = generate ;

//memoize.js is lodash-memoize source code. I just use the source code here. 

The result looks like this:

// First trigger lambda
ContainerId: 071040
hello
clientId1
hello
clientId2
clientId1
clientId2

// Second time to trigger lambda
ContainerId: 071040
clientId1
clientId2
clientId1
clientId2

What I found:

  • Lambda will run in same container if you run it continuously.
  • No need to use NodeJS global variable. Lodash-memoize will cache getClientSecret function.
1reaction
brettstackcommented, Apr 18, 2018

You should be fine. app.js will only be loaded once per Lambda container (or “cold start”)

Read more comments on GitHub >

github_iconTop 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 >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found