Vercel + MongoDB just killed my website

Connection handling is poor. I don’t even know what to do to fix this. I’m always at 400+ connections in flex tier no matter what configuration I use in Next.js. Tried singleton pattern in the starter template. Have you guys actually tested your examples at all? How do we supposed to keep the connections low in a serverless environment? Aren’t this supposed to be handled by your driver casually? If not, why do you even bother sharing starter templates, integrations with Vercel etc? Please guide me on how to fix this.

“mongodb”: “^6.2.0”,
“next”: 14.0.3

mongodb.ts

import { MongoClient } from 'mongodb';

const uri = process.env.MONGODB_URI as string; // your mongodb connection string
const options = {};

declare global {
  var _mongoClientPromise: Promise<MongoClient>;
}

class Singleton {
  private static _instance: Singleton;
  private client: MongoClient;
  private clientPromise: Promise<MongoClient>;
  private constructor() {
    this.client = new MongoClient(uri, options);
    this.clientPromise = this.client.connect();
    if (process.env.NODE_ENV === 'development') {
      // In development mode, use a global variable so that the value
      // is preserved across module reloads caused by HMR (Hot Module Replacement).
      global._mongoClientPromise = this.clientPromise;
    }
  }

  public static get instance() {
    if (!this._instance) {
      this._instance = new Singleton();
    }
    return this._instance.clientPromise;
  }
}
const clientPromise = Singleton.instance;

// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise;

Hey @Can_Uysal,

Vercel has some docs for Connection Pooling with Vercel Functions that call out using their attachDatabasePool helper as a way to improve client behavior. I can see in the starter template there’s a call to attachDatabasePool, but I don’t see it in the code you shared.

If you adapt your code per the starter template does it improve the behavior at all?