Go's 'sql: waiting for connection' Pitfall: Why Raising MaxOpenConns Only Makes It Worse
Inflating MaxOpenConns can push a service past MySQL's total connection quota and crash the database, while the actual culprit is connection hold time. Shrinking the hold window and propagating context cancellation keep the pool from exhausting in the first place.
A production outage in a Go service showed `sql: waiting for connection` errors flooding despite DB CPU being low and SQL averaging 20ms. Bumping MaxOpenConns from 40 to 200 gave only temporary relief before the pool filled again. The article's key distinction: connection hold time is not the same as SQL execution time. A connection stays occupied until rows are closed or a transaction commits, so any downstream work inside those windows starves the pool.
Three common bad patterns are dissected: calling HTTP services while iterating over rows, performing external IO inside transactions, and using `db.Query()` instead of `QueryContext` so cancellation doesn't propagate. The fix is structural: repository layer only reads DB and immediately returns the connection; service layer orchestrates downstream calls after the connection is released. Pool parameters like MaxOpenConns should act as rate limiters, not performance knobs, and should stay below the MySQL instance's total connection quota.
Monitoring guidance points to `db.Stats().WaitCount` as the first indicator of queuing; rising WaitCount with fast SQL means connections are being held too long, not that the DB is slow. A simple regression test verifies that a canceled context makes the query fail fast instead of holding a connection.
A rising WaitCount with fast SQL points directly to hold time rather than capacity, because it tracks queue waits that slow query logs cannot reveal.
The three failure patterns share a root cause: mixing data access with downstream orchestration in the same function. Separating repository and service layers is the architectural fix.
Pool parameters in Go are consistently misread as throughput knobs; framing them as shared-resource quotas makes the failure mode of over-raising clear.
This article clearly separates the idea of a full connection pool from an insufficient number of connections. I fell into the same pit before, calling downstream services inside a rows loop, and later added two hard constraints: the Repository layer may only read from the database, no HTTP calls allowed; transactions contain only SQL, with all notifications and caching moved to after Commit. Also, rows.Err() and defer rows.Close() need to be handled together — only calling Close without checking iterator errors will still miss something. I'd like to ask: do you encode these constraints in static analysis now, or rely only on code review?