Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
Set callbackWaitsForEmptyEventLoop in Nextjs API

I would like to set callbackWaitsForEmptyEventLoop to false in my Nextjs handler but it's signature is missing the context.

The goal is to properly configure nextjs, mongoDB, mongoose to avoid any performance issue when deployed on aws-lambda. I've been looking around and it looks like most option examples are outdated and doesn't apply to mongoose 6. Given that the connection are made inside aws-lambda and cached, is there still a need to close connections manually?

Current setup based on various recommendations:

// useDb options
export const useDbOptions = {
  useCache: true,
  noListener: true,
};

// Schema options
export const useSchemaOptions = {
  autoIndex: true,
  bufferCommands: false,
};

// Cached connection outside of handler
let conn: Promise<typeof mongoose> | null = null;

// Mongoose options
mongoose.connect(mongoDbUri, {
  bufferCommands: false,
})

Nextjs handler signature is missing context:

async function handler(req: NextApiRequest, res: NextApiResponse) {
  ...
}

Per recommendations from mongoose doc:

const mongoose = require('mongoose');

let conn = null;

const uri = 'YOUR CONNECTION STRING HERE';

exports.handler = async function(event, context) {
  // Make sure to add this so you can re-use `conn` between function calls.
  // See https://www.mongodb.com/blog/post/serverless-development-with-nodejs-aws-lambda-mongodb-atlas
  context.callbackWaitsForEmptyEventLoop = false;

  // Because `conn` is in the global scope, Lambda may retain it between
  // function calls thanks to `callbackWaitsForEmptyEventLoop`.
  // This means your Lambda function doesn't have to go through the
  // potentially expensive process of connecting to MongoDB every time.
  if (conn == null) {
    conn = mongoose.createConnection(uri, {
      // and tell the MongoDB driver to not wait more than 5 seconds
      // before erroring out if it isn't connected
      serverSelectionTimeoutMS: 5000
    });
    
    // `await`ing connection after assigning to the `conn` variable
    // to avoid multiple function calls creating new connections
    await conn;
    conn.model('Test', new mongoose.Schema({ name: String }));
  }

  const M = conn.model('Test');

  const doc = await M.findOne();
  console.log(doc);

  return doc;
};

Yet callbackWaitsForEmptyEventLoop isn't configured in their helper example:

'use strict';

const mongoose = require('mongoose');

let conn = null;

const uri = 'YOUR CONNECTION STRING HERE';

exports.connect = async function() {
  if (conn == null) {
    conn = mongoose.createConnection(uri, {
      serverSelectionTimeoutMS: 5000
    });
    
    // `await`ing connection after assigning to the `conn` variable
    // to avoid multiple function calls creating new connections
    await conn;
  }

  return conn;
};

Package versions:

"mongodb": "^4.3.0",
"mongoose": "^6.1.6",
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!