Update - Mongoose Performance Issue and Fix
After upgrading Mongoose from version 6.12.9 to 8.10.0, queries executed inside AWS Lambda using the Serverless Framework became four times slower. However, the same queries remained fast when executed outside the framework (e.g., locally, in a manually deployed Lambda, or using the native MongoDB driver).
Extensive debugging revealed that the issue was not caused by Mongoose itself but rather by how it was bundled inside the Lambda function when using esbuild. Moving Mongoose to an AWS Lambda Layer restored optimal query performance. The fix was to explicitly exclude mongoose and mongodb in the esbuild configuration (exclude: ["mongoose", "mongodb"]). This ensured that the Lambda function used the version from the Lambda Layer instead of bundling its own copy, which resolved the performance issue.
Possible Cause
My theory is that this might be due to dynamic imports within the Mongoose module, which were affected by esbuild's tree shaking when packaging the Lambda function. Could this be the case? If so, is there a way to overcome this so Mongoose doese not need to be moved to an AWS Lambda Layer?
Alternative Solutions Tried
Upgrading esbuild and serverless-esbuild and including mongoose and mongodb in the esbuild bundle did not resolve the issue:
"esbuild": "^0.24.2"
"serverless-esbuild": "^1.54.6"
So far now, if anyone is facing this issue, simply move Mongoose to an AWS Lambda Layer.
I will continue to update if Mongoose replies with a fix.