Connection pooling
*sql.DB is a connection pool. It opens, reuses, and closes driver connections for you. SetMaxOpenConns, SetMaxIdleConns, and SetConnMaxLifetime are the knobs. You do not open a new DB per request.
Detailed Explanation
A Postgres connection is expensive to start (TCP, auth, session). A pool keeps a few live and lends them to QueryContext. When the query finishes and Rows is closed, the connection returns to the pool. If you never close Rows, the connection never returns, and the pool starves.
The knobs. SetMaxOpenConns(n) caps simultaneous connections (0 is unlimited — do not leave that on a public service). SetMaxIdleConns keeps extras warm. SetConnMaxLifetime recycles connections so load balancers and server-side idle timeouts do not deliver a dead conn. SetConnMaxIdleTime (Go 1.15+) closes idle conns sooner than lifetime.
Sizing. Start from the database's max_connections divided by the number of app replicas, then leave headroom for migrations and humans. A pool of 100 from 20 pods is 2000 sessions. n workers in a pool should not each assume a dedicated conn.
Not a second pool on top without thought. An application worker pool of 200 plus MaxOpenConns(10) means 190 workers wait on the SQL pool. That is backpressure. Two *sql.DB values to the same DSN are two pools — usually a mistake.
What it costs. Too few conns serialize request latency. Too many conns overload the database. Idle conns use memory on both sides. Lifetime too long hits "conn closed by server"; too short thrashes auth. Log Stats() (InUse, Idle, WaitCount) when latency spikes.
Code Examples
package main
import (
"database/sql"
"time"
)
func tune(db *sql.DB) {
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(30 * time.Minute)
db.SetConnMaxIdleTime(5 * time.Minute)
}
func main() {}func stats(db *sql.DB) sql.DBStats {
return db.Stats()
}Common Gotchas
Leaked `Rows` or `Tx` exhausts `MaxOpenConns`
the next query blocks until `SetConnMaxLifetime` or process death.
`sql.Open` per request is a pool per request
one `DB` at startup.
`Ping` uses a connection
it is a good startup check and a bad per-request ritual.