Skip to content

fix: pgxpool deadlock on context cancellation — release semaphore immediately - #5

Open
johneapen80 wants to merge 1 commit into
jaasielitaigq:mainfrom
johneapen80:fix/deadlock-context-cancellation-v2
Open

fix: pgxpool deadlock on context cancellation — release semaphore immediately#5
johneapen80 wants to merge 1 commit into
jaasielitaigq:mainfrom
johneapen80:fix/deadlock-context-cancellation-v2

Conversation

@johneapen80

Copy link
Copy Markdown

Fixes deadlock and goroutine leak in pgxpool.Acquire() on context cancellation.

Root cause: When context is cancelled after TryAcquire succeeds but before resource creation completes, the semaphore is held indefinitely — blocking all future acquires.

Fix: Added ctx.Done() check after TryAcquire succeeds. If context is cancelled, immediately release semaphore and return the context error. Also added ctx.Err() checks in retry loop after Destroy() calls for expired connections.

Test: TestPoolAcquireStressCancelContention — 30 goroutines × 10 attempts with 1-5ms timeouts against saturated pool (MaxSize=3). Verifies pool remains functional and stats are consistent after stress.

Closes #1

Fixes concurrent context cancellation + semaphore contention causing
pool to livelock. Two-part fix:

1. puddle/pool.go acquire(): check ctx.Done() after semaphore acquire
   to prevent goroutine leak when context is canceled between
   TryAcquire success and resource creation.

2. pgxpool/pool.go Acquire(): check ctx.Err() between retry iterations
   so a cancelled context terminates the retry loop immediately
   instead of cycling through all maxConns attempts.

Includes regression test TestPoolAcquireStressCancelContention that
exercises high-concurrency acquire with rapid context cancellation.
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 deadlock and inconsistent waiter queue state in pgxpool on Acquire context cancellation

2 participants