Netlify functions not retaining Singleton Database connections?

Netlify functions not retaining Singleton Database connections?

I am using:

  • MongoDB Driver
  • Node.js v12 and Express.js
  • serverless-http
    I am trying to use MongoDB Driver and I have created a DatabaseService singleton class. But I have noticed that the database connection is not being re-used.
    Do Netlify Functions allow Singleton classes?
    How can I reuse the MongoDB Client connection in a separate module?
    Any help would be greatly appreciated!

Hi @gitaalekhyapaul, welcome to the Community!

One thing to note is that each lambda function runs in its own separate ‘container’. So, if one function opens a connection to your DB, another function won’t be able to re-use that connection since it isn’t on the same ‘container’. Let me know if that makes sense. Otherwise, can you provide more context/details on what you are trying to do and we can go from there?

Thank you for replying @Dennis
I tried using this as my DatabaseService singleton. It is not working when I am calling it in the controllers:
I was not able to share any object data from different modules also.
For example, the following Database Service code in the Node runtime, but when compiled using netlify-lambda, the following code fails to work.

import * as MongoDB from "mongodb";
​
/**
 * Drives a database connection in a singleton.
 */
export class DatabaseService {
  public database: MongoDB.Db | null = null;
​
  private client: MongoDB.MongoClient = new MongoDB.MongoClient(
    process.env.DB_URL || "",
    { useUnifiedTopology: true }
  );
  private static instance: DatabaseService;
​
  constructor() {
    this.initialize();
  }
​
  /**
   * Initializes the database
   */
  private async initialize(): Promise<any> {
    try {
      const client = await this.client.connect();
      this.database = client.db(process.env.DB_NAME);
      console.log(
        `Established connection to database <${this.database.databaseName}>`
      );
    } catch (error) {
      console.log(
        `Failed to established connection to database <${process.env.DB_NAME}>`
      );
    }
  }
​
  /**
   * The static method that controls the access to the DatabaseService instance.
   */
  public static getInstance(): DatabaseService {
    if (!DatabaseService.instance) {
      DatabaseService.instance = new DatabaseService();
    }
​
    return DatabaseService.instance;
  }
}

We won’t be able to help debug your code so let’s focus back on what Dennis asked:

Are you trying to reuse a connection ACROSS FUNCTION INVOCATIONS? this could be two invocations of the same function, or two different functions. They all run in completely separate containers, and cannot share or reuse connections or local data (except the local read-only data that you might deploy with your function).