Next.js Discord

Discord Forum

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

Unanswered
Vizsla posted this in #help-forum
Open in Discord
Avatar
VizslaOP
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 (https://github.com/vercel/mongodb-starter/tree/main), 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") {
    res.status(404).end();
    return;
  }

  await clientPromise;

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

  res.status(200).json(count);
}


Thanks for your help!

4 Replies

Avatar
tafutada777
do you host Next.js on serverless environment such as Vercel?
Avatar
VizslaOP
Yes
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