跪拜 Guibai
← All articles
Go · Gin · Backend

Go's 'sql: waiting for connection' Pitfall: Why Raising MaxOpenConns Only Makes It Worse

By Sailing ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

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.

Summary

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.

Takeaways
— MaxOpenConns is a rate limiter, not a performance accelerator; increasing it beyond the MySQL instance's total connection quota can crash the database.
— Connection hold time can far exceed SQL execution time when rows are not closed or transactions are not committed.
— Calling downstream HTTP inside a rows loop or transaction holds the DB connection for the entire duration, causing pool exhaustion.
— Using `db.Query()` without a context prevents client cancellation from propagating, so connections stay occupied after clients disconnect.
— `db.Stats().WaitCount` rising while SQL is fast is the core signal for connection hold problems, not slow queries or CPU.
— A canceled context should make a query fail fast; a regression test can check that behavior.
— Set MaxOpenConns below the DB instance's total connection quota and reserve capacity for other services and background tasks.
Conclusions

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.

Concepts & terms
MaxOpenConns
The maximum number of simultaneously open connections in a database/sql pool. Treat it as a rate limiter, not a performance knob; exceeding the MySQL instance's total connection quota can crash the database.
Connection hold time
The duration a connection stays checked out from the pool, from borrowing to returning. It can be much longer than SQL execution time when rows are left open or transactions include external IO.
WaitCount
A counter in db.Stats() that increments each time a request must queue for a connection. A steadily rising WaitCount is the earliest sign of pool exhaustion, even when SQL execution is fast.
From the discussion
Featured comments
badhope

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?

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗