Skip to content

fix: add circuit breaker to MongoDB logger to prevent repeated 10s connection delays - #105

Merged
SamXop123 merged 4 commits into
SamXop123:mainfrom
rishab11250:fix/circuit-breaker-mongodb
May 29, 2026
Merged

fix: add circuit breaker to MongoDB logger to prevent repeated 10s connection delays#105
SamXop123 merged 4 commits into
SamXop123:mainfrom
rishab11250:fix/circuit-breaker-mongodb

Conversation

@rishab11250

Copy link
Copy Markdown
Contributor

Description

connectToDatabase() in logger.js attempts a full MongoDB connection on every API request. If MongoDB is unreachable, each request waits 10 seconds (serverSelectionTimeoutMS) before failing — and the next request retries the same 10s delay.

The connectionAttempted variable was declared on line 4 but never read. This fix uses it as a circuit breaker: once the first connection attempt completes (success or failure), all subsequent requests skip connecting entirely.

Root Cause

After a failed connection:

  • connectingPromise is reset to null
  • mongoose.connection.readyState stays 0
  • Next request has no way to know a previous attempt was made → retries → 10s delay

Fix

  • Check connectionAttempted before attempting connection — if true and not connected, skip immediately
  • Set connectionAttempted = true in all exit paths: success, failure, and missing URI
  • On skip, log a single warning: "Skipping MongoDB connection (already attempted — see previous error)"

Behavior change

Scenario Before After
MongoDB down, request 1 10s delay, fails 10s delay, fails
MongoDB down, request 2 10s delay, fails ~0ms, skips
MongoDB down, request N 10s delay each time ~0ms, skips
MongoDB up, request 1 Connects (~2-3s) Connects (~2-3s)
MongoDB up, request 2 Reuses connection Reuses connection
MongoDB goes down mid-session Next request 10s delay Next request 10s delay

Testing

  • All 12 existing unit tests pass (npm run test:unit)

Closes #101

@vercel

vercel Bot commented May 28, 2026

Copy link
Copy Markdown

@rishab11250 is attempting to deploy a commit to the Dot_NotSam's projects Team on Vercel.

A member of the Team first needs to authorize it.

@SamXop123
SamXop123 merged commit 5779dca into SamXop123:main May 29, 2026
0 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: add circuit breaker to MongoDB logger to prevent 10s delays on every request

2 participants