MongoDB multiple connections and new Concurrency Mode

I’m building a platform that when it will be in Production, it will expect lot of users.

I’m building the platform with MongoDB as Database and looking at internet, I see a lot of users having problem with Vercel doing a lot of connections to MongoDB.

Now, I’m connecting to MongoDB using Mongoose, using this script:

import mongoose, { ConnectOptions, Mongoose } from 'mongoose'

declare global {
  // eslint-disable-next-line no-var
  var mongoose: any // This must be a `var` and not a `let / const`
}

let cached = global.mongoose

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null }
}

async function dbConnect(): Promise<Mongoose> {
  const MONGODB_URI = process.env.MONGODB_URI!

  if (!MONGODB_URI) {
    throw new Error('Please define the MONGODB_URI environment variable inside .env.local')
  }

  if (cached.conn) {
    return cached.conn
  }

  if (!cached.promise) {
    const opts: ConnectOptions = {
      bufferCommands: false,
      maxPoolSize: 10,
      minPoolSize: 1,
      serverSelectionTimeoutMS: 5000
    }

    cached.promise = mongoose.connect(MONGODB_URI, opts).then(() => mongoose)
  }
  try {
    cached.conn = await cached.promise
  } catch (e) {
    cached.promise = null
    throw e
  }

  return cached.conn
}

export default dbConnect


Now, in the production domain, if I do reload lot of times, I get a peak of 70 connections open in MongoDB Atlas.

My question is, how many instances do Vercel open to execute the same function that causes that many connections?

And… with Vercel’s new In-Function Concurrency, this connections should be less, or I’m missing something?

Thank you in advance!

I did a Load Test and unless I reach tr 500 connection limit error in MongoDB Atlas.

Could anyone help me with that?

Thanks in advance

Do anyone have a solution?

Anyone with a solution?

Hey, @suituxr!

Could you share a minimal reproducible example for us?

Thank you!

Not many people answer questions in this community.

In the example you have of how integrate mongoose, it happens:

If you do a Load Test, you will reach MongoDB Connection limit easily.

I supose it’s because of the Serverless environment? It generates a new connection for each instance created for running the endpoint.

It should be a way to persist the connection between the calls.

Thanks for the response :slight_smile: