Fix MongoDB connection timeout on Vercel serverless#88
Merged
lnqminh3003 merged 2 commits intobackendfrom Mar 23, 2026
Merged
Conversation
Move DB connection middleware before route handlers in app.ts to ensure the connection is verified before any route handler fires. Extract shared connection logic into utils/db.ts with ping-based stale connection detection to handle Vercel freeze/thaw cycles that leave dead TCP sockets despite readyState showing connected. Tune connection options for serverless (bufferCommands: false, smaller pool, heartbeat).
Cast req.params.eventId to string in event controller to fix TS2345 where string | string[] was passed to functions expecting string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
src/utils/db.tswith ping-based stale connection detection. When Vercel freezes/thaws a serverless function, the MongoDB connection can appear connected (readyState === 1) but have a dead TCP socket. The newconnectDB()pings the DB to verify liveness and reconnects if stale.app.ts. Previously,api/index.tsregistered theconnectDBmiddleware after importingapp(which already had all routes mounted), so routes fired before the DB check ran. NowensureConnectionis registered on/apiinapp.tsbefore any route mounts.api/index.tsto just eagerly callconnectDB()at module load (for Vercel cold starts) and exportapp. All connection logic and middleware now lives inutils/db.tsandapp.ts.bufferCommands: false(fail fast instead of buffering for 10s),maxPoolSize: 5,heartbeatFrequencyMS: 10000.Problem
After ~3 days without redeployment, all DB operations fail with:
Redeploying temporarily fixes it. Root cause: Vercel freezes serverless functions between invocations, leaving stale MongoDB connections that pass the
readyStatecheck but can't actually send queries.Files changed
src/utils/db.tsconnectDB()with ping health check +ensureConnectionmiddlewaresrc/app.tsensureConnectionmiddleware before route handlersapi/index.tssrc/server.tsconnectDB()instead of directmongoose.connect()Test plan
GET /returnsHello(no DB middleware on non-API routes)POST /api/auth/loginqueries DB successfully (returns "Invalid credentials", not a timeout)GET /api/usersreturns full user list from MongoDB