Next.js Discord

Discord Forum

Next.js and Mongo Atlas : an issue with connection limit

Vizsla posted this in #help-forum
Open in Discord
Hey guys,

My app is using mongoose on top of mongodb. Today, we got a spike with 100 users at the same time and I reached the 1500 connections limit of my Mongo Atlas instance (M10). Btw, on my homepage i've 7 different calls to the same serverless fn with different query params.

So far, i feel like anytime a request is made, a new connection is created and last for a couple of minutes.

I tried different approach even this one (, but nothing is making it better.

Does anyone is able to share its experience about this issue ?

Here is my mongoose config file and an example of how i'm using it in a simple request.

// mongoose.ts - Lib mongoose

import mongoose, { Mongoose } from "mongoose";

const MONGODB_URI = process.env.MONGODB_URI as string;

const options = {};

class Singleton {
  private static _instance: Singleton;
  private clientPromise: Promise<Mongoose>;
  private constructor() {
    this.clientPromise = mongoose.connect(MONGODB_URI).then((mongoose) => {
      console.log("Mongoose connection created");
      return mongoose;

  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;

// /api/live.ts - A simple example
import clientPromise from "@/database/mongoose";
import User from "@/models/User";
import type { NextApiRequest, NextApiResponse } from "next";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== "GET") {

  await clientPromise;

  const count = await User.find({ isLive: true }).count();


Thanks for your help!

4 Replies

do you host Next.js on serverless environment such as Vercel?
I tried to reduce as much as possible the number of requests sent to vercel since it feels like a new one is created for each requests, got another spike today and same thing happens. There was 8 requests sent to serverless function on my homepage yesterday, there is only two since this morning and still number of connections is going crazy. I really don't get it ^^
And i tried to even close manually the connection in my code after each requests but its seems that sometime, the connection is reused, it's very random and so it end up with errors