database/sql connection pool: no acquisition timeout when MaxOpenConns is saturated
0 reputation · 31 Mar 2025, 08:01 UTC
I'm designing a Go service (assuming Go 1.21+) that uses database/sql with SetMaxOpenConns to cap connections to PostgreSQL. Under burst load, once all pooled connections are checked out, additional calls to db.QueryContext or db.ExecContext appear to block waiting for a free slot, and the supplied context deadline does not seem to interrupt that wait — only the query execution itself.
My constraints: I cannot raise MaxOpenConns (database-side limit), and I want requests that wait too long for a connection to fail fast with a clear error rather than pile up as latency spikes. I am aware driver-level dial timeouts exist, but they cover establishing new connections, not waiting for a pooled slot.
- Is there any standard-library mechanism to bound the time spent waiting for a free pooled connection, or is wrapping calls in my own semaphore plus
context.WithTimeoutthe only option? - If a goroutine's context expires while it is blocked acquiring a connection, does the pool still hand it a connection later that then goes unused?
- What is the recommended way to observe pool-wait time separately from query time, given
db.Stats()offers limited detail?