Skip to content

fix: track pending connections to prevent MaxConns violations during DB recovery - #9

Open
Kasuki354 wants to merge 2 commits into
colmev080:mainfrom
Kasuki354:fix/connection-storms
Open

fix: track pending connections to prevent MaxConns violations during DB recovery#9
Kasuki354 wants to merge 2 commits into
colmev080:mainfrom
Kasuki354:fix/connection-storms

Conversation

@Kasuki354

Copy link
Copy Markdown

Summary

Fixes issue #3: Prevent Connection Storms and MaxConns Violations in pgxpool during DB Recovery

Root Cause

The original code decremented inFlightConns immediately after createNewConn returned, before the connection was added to p.conns. Under a concurrent burst:

  1. Multiple goroutines see len(conns) + inFlightConns < maxConns
  2. All increment inFlightConns and start dialing
  3. One succeeds, decrements inFlightConns, but hasn't added to conns yet
  4. Another goroutine sees the freed slot and starts dialing too
  5. Total concurrent dial attempts can temporarily exceed maxConns

Fix

  • Decrement inFlightConns only AFTER the connection is fully established AND added to p.conns
  • On error, decrement inFlightConns immediately to free the slot (prevents pool starvation)
  • This ensures len(conns) + inFlightConns never exceeds maxConns

Test

  • TestMaxConnsNotExceeded: 50 concurrent Acquire() calls with maxConns=5, monitors max observed concurrent connections, asserts never exceeds 5

/claim #3

…DB recovery

The race condition occurred because inFlightConns was decremented immediately
after createNewConn, before the connection was added to the pool. Under a
concurrent burst, multiple goroutines could observe available slots and
initiate dialing simultaneously, temporarily exceeding MaxConns.

Fix: decrement inFlightConns only after the connection is fully established
and added to the pool. On error, decrement immediately to free the slot.
This ensures len(conns) + inFlightConns never exceeds maxConns.

Resolves colmev080#3
@opirebot

opirebot Bot commented Aug 7, 2026

Copy link
Copy Markdown

😅 Unfortunately there are no rewards left to claim in this issue!

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.

1 participant