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!