Skip to content

fix: prevent MongoDB connection leak by reusing cached client connection#77

Open
ayuxsh009 wants to merge 1 commit into
seetadev:mainfrom
ayuxsh009:fix/mongodb-connection-leak
Open

fix: prevent MongoDB connection leak by reusing cached client connection#77
ayuxsh009 wants to merge 1 commit into
seetadev:mainfrom
ayuxsh009:fix/mongodb-connection-leak

Conversation

@ayuxsh009

Copy link
Copy Markdown

Description

This PR fixes a MongoDB connection leak in src/app/api/cohort/route.ts by replacing repeated client.connect() calls with a shared cached MongoDB client connection.

Previously, every incoming request attempted to establish a new MongoDB connection without properly closing it, which could eventually exhaust the MongoDB connection pool and degrade application performance.

Fixes #76


Changes

  • Fix
  • Added src/lib/mongodb.ts singleton connection manager
  • Replaced per-request client.connect() calls with shared clientPromise
  • Added development-safe global caching for HMR hot reloads
  • Optimized production connection reuse per serverless instance
  • Updated API route logic in src/app/api/cohort/route.ts

📷 Screenshots / Demo (if applicable)

N/A — backend connection lifecycle fix.


Additional Notes

Problem

The previous implementation created a new MongoDB connection on every request:

await client.connect();

without ever closing or reusing the connection.

This could lead to:

  • MongoDB connection pool exhaustion
  • Increased memory/resource usage
  • Performance degradation under load
  • Connection timeout issues

Solution

This PR introduces a centralized MongoDB connection utility using a singleton clientPromise pattern:

  • Ensures only one active connection per process/runtime
  • Prevents duplicate connections during development hot reloads
  • Improves scalability and resource efficiency

Files Changed

  • src/lib/mongodb.ts (new)
  • src/app/api/cohort/route.ts (modified)

Checklist

  • I have tested this code
  • I have added necessary documentation
  • I have linked relevant issue(s)
  • I followed the code style of the project
  • I reviewed my own code

@vercel

vercel Bot commented May 9, 2026

Copy link
Copy Markdown

@ayuxsh009 is attempting to deploy a commit to the SEETA's projects Team on Vercel.

A member of the Team first needs to authorize it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: prevent MongoDB connection leak by reusing cached client connection

1 participant