Database connection pooling
suggest changeOpening a database connection is expensive. For a server database like PostgreSQL or MySQL, it means a TCP handshake, often TLS, authentication, and a new backend process or thread on the server. That can take several milliseconds, which is often longer than the query itself.
A connection pool keeps connections open and reuses them. A goroutine borrows a connection, runs a query and gives it back. The next query reuses it instead of dialing again.
In Go you rarely build a pool yourself. A *sql.DB from the standard database/sql package is a connection pool. This article explains how that pool behaves, how to configure it, how to watch it, and the mistakes that drain it. See SQL for the general database/sql API.
The examples use SQLite through the pure-Go modernc.org/sqlite driver, so they run without a database server (see SQLite). The pool code is in database/sql itself, so it works the same with the MySQL and PostgreSQL drivers.
go get modernc.org/sqlite
sql.DB is a pool, not a connection
sql.Open doesn't connect to anything. It validates its arguments and returns a *sql.DB with an empty pool. Connections are created lazily, the first time one is needed and no idle connection is available.
To see when the pool opens connections, the program below wraps the SQLite driver in a driver.Connector that prints a line for each new connection. sql.OpenDB creates a *sql.DB from a connector.
package main
import (
"context"
"database/sql"
"database/sql/driver"
"fmt"
"log"
"sync"
"sync/atomic"
"modernc.org/sqlite"
)
// connector wraps the SQLite driver and prints every new connection.
type connector struct {
dsn string
n atomic.Int64
}
func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
fmt.Println(" driver: opening connection", c.n.Add(1))
return (&sqlite.Driver{}).Open(c.dsn)
}
func (c *connector) Driver() driver.Driver { return &sqlite.Driver{} }
func printStats(label string, db *sql.DB) {
s := db.Stats()
fmt.Printf("%s: open=%d inUse=%d idle=%d maxIdleClosed=%d\n",
label, s.OpenConnections, s.InUse, s.Idle, s.MaxIdleClosed)
}
func main() {
db := sql.OpenDB(&connector{dsn: "file:pool.db"})
defer db.Close()
printStats("after OpenDB", db)
if err := db.Ping(); err != nil {
log.Fatal(err)
}
printStats("after Ping", db)
// Sequential queries reuse the same idle connection.
for range 3 {
var n int
if err := db.QueryRow("SELECT 1").Scan(&n); err != nil {
log.Fatal(err)
}
}
printStats("after 3 sequential queries", db)
// 5 goroutines each hold a connection at the same time.
var ready, done sync.WaitGroup
release := make(chan struct{})
for range 5 {
ready.Add(1)
done.Go(func() {
conn, err := db.Conn(context.Background())
if err != nil {
log.Fatal(err)
}
ready.Done()
<-release
conn.Close() // returns the connection to the pool
})
}
ready.Wait()
printStats("5 connections busy", db)
close(release)
done.Wait()
printStats("all returned", db)
}
after OpenDB: open=0 inUse=0 idle=0 maxIdleClosed=0
driver: opening connection 1
after Ping: open=1 inUse=0 idle=1 maxIdleClosed=0
after 3 sequential queries: open=1 inUse=0 idle=1 maxIdleClosed=0
driver: opening connection 2
driver: opening connection 3
driver: opening connection 4
driver: opening connection 5
5 connections busy: open=5 inUse=5 idle=0 maxIdleClosed=0
all returned: open=2 inUse=0 idle=2 maxIdleClosed=3
What happened:
OpenDBcreated no connections.Pingopened the first one.- Sequential queries reused that single connection. When a query finishes, its connection goes back to the idle list.
- 5 goroutines needing a connection at the same time made the pool open 4 more. By default there is no limit on open connections.
- When they were returned, the pool kept only 2 idle connections and closed the other 3 (
maxIdleClosed=3). The default idle limit is 2.
This is why you create one *sql.DB when the program starts and share it everywhere. It's safe for concurrent use by many goroutines. Opening a new *sql.DB per request creates a new pool each time and throws away the benefit of pooling.
// Bad: a new pool, and new connections, for every request.
func handler(w http.ResponseWriter, r *http.Request) {
db, _ := sql.Open("postgres", dsn)
defer db.Close()
// ...
}
// Good: one pool for the whole program.
type Server struct {
db *sql.DB
}
The four pool settings
*sql.DB has 4 methods that control the pool:
| Method | Default | What it does |
|---|---|---|
SetMaxOpenConns(n) |
0 (no limit) | Maximum number of connections, in use plus idle. When reached, callers wait for a connection to be returned. |
SetMaxIdleConns(n) |
2 | Maximum number of idle connections kept for reuse. Extra connections are closed when returned. |
SetConnMaxLifetime(d) |
0 (forever) | Close a connection once it's this old, measured from when it was opened. |
SetConnMaxIdleTime(d) |
0 (forever) | Close a connection that has been idle for this long. |
You can call them at any time, but it's usual to set them right after sql.Open. A few details:
- If
MaxIdleConnsis larger thanMaxOpenConns, it's reduced toMaxOpenConns. - A value
<= 0forSetMaxIdleConnsmeans no idle connections are kept: every connection is closed after use. That's almost never what you want. - Connections that are in use are never closed by the lifetime or idle time limits. They are checked when idle, and when taken out of the pool.
SetMaxOpenConns: limit and wait
With no limit, a traffic spike can open hundreds of connections and exceed the database server's limit (max_connections is 100 by default in PostgreSQL and 151 in MySQL). Then new connections fail with errors like "too many connections".
With a limit, a goroutine that needs a connection when all of them are busy waits until one is returned:
package main
import (
"context"
"database/sql"
"fmt"
"log"
"sync"
"time"
_ "modernc.org/sqlite"
)
func main() {
db, err := sql.Open("sqlite", "file:pool.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(2)
db.SetMaxIdleConns(2)
// 6 "requests", each keeps a connection busy for 100 ms.
start := time.Now()
var wg sync.WaitGroup
for i := range 6 {
wg.Go(func() {
conn, err := db.Conn(context.Background())
if err != nil {
log.Fatal(err)
}
defer conn.Close()
fmt.Printf("request %d got a connection after %3d ms\n",
i, time.Since(start).Round(50*time.Millisecond).Milliseconds())
time.Sleep(100 * time.Millisecond) // simulate a slow query
})
time.Sleep(time.Millisecond) // start them in order, for readable output
}
wg.Wait()
s := db.Stats()
fmt.Println("total time:", time.Since(start).Round(50*time.Millisecond))
fmt.Println("max open: ", s.MaxOpenConnections)
fmt.Println("open: ", s.OpenConnections)
fmt.Println("wait count:", s.WaitCount)
fmt.Println("waited: ", s.WaitDuration.Round(50*time.Millisecond))
}
request 0 got a connection after 0 ms
request 1 got a connection after 0 ms
request 2 got a connection after 100 ms
request 5 got a connection after 100 ms
request 3 got a connection after 200 ms
request 4 got a connection after 200 ms
total time: 300ms
max open: 2
open: 2
wait count: 4
waited: 600ms
Only 2 requests ran at a time. The other 4 waited, which Stats reports as WaitCount and WaitDuration. Waiting goroutines aren't served in arrival order: when a connection is returned, the pool hands it to a random waiter. Request 5 got a connection before requests 3 and 4, and the order changes from run to run.
Waiting isn't bad by itself. A short queue in Go is usually better than overloading the database with more concurrent queries than it has CPU cores. But if WaitDuration keeps growing, either queries are too slow or the limit is too low.
SetMaxIdleConns: avoid churn
With the default of 2 idle connections, a server that regularly runs 20 queries at once opens 18 new connections in each burst and closes them right after. That's the cost pooling is supposed to avoid. The MaxIdleClosed counter in Stats shows it happening.
Set MaxIdleConns close to, or equal to, MaxOpenConns. Idle connections cost some memory on both sides, which is cheap compared to reconnecting all the time.
SetConnMaxLifetime and SetConnMaxIdleTime: recycle connections
Long-lived connections cause trouble in practice:
- Load balancers, proxies and NAT gateways silently drop TCP connections that have been idle for a while. The next query on such a connection fails.
- MySQL closes connections idle for longer than
wait_timeout(8 hours by default). - After a database failover or DNS change, old connections keep pointing at the old server.
- A connection that lives forever never picks up rebalancing across database replicas.
SetConnMaxLifetime closes connections once they reach a certain age. SetConnMaxIdleTime closes connections that have been idle for a while, which also shrinks the pool after a burst.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"sync"
"time"
_ "modernc.org/sqlite"
)
// burst makes n connections busy at the same time, then returns them.
func burst(db *sql.DB, n int) {
var ready, done sync.WaitGroup
release := make(chan struct{})
for range n {
ready.Add(1)
done.Go(func() {
conn, err := db.Conn(context.Background())
if err != nil {
log.Fatal(err)
}
ready.Done()
<-release
conn.Close()
})
}
ready.Wait()
close(release)
done.Wait()
}
func show(label string, db *sql.DB) {
s := db.Stats()
fmt.Printf("%-22s open=%d idle=%d idleTimeClosed=%d lifetimeClosed=%d\n",
label, s.OpenConnections, s.Idle, s.MaxIdleTimeClosed, s.MaxLifetimeClosed)
}
func main() {
db, err := sql.Open("sqlite", "file:pool.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(10)
db.SetConnMaxIdleTime(500 * time.Millisecond)
db.SetConnMaxLifetime(2 * time.Second)
burst(db, 4)
show("after burst of 4:", db)
time.Sleep(1500 * time.Millisecond)
show("idle for 1.5 s:", db)
// A steady trickle of queries keeps one connection busy and never idle.
start := time.Now()
for time.Since(start) < 2500*time.Millisecond {
if _, err := db.Exec("SELECT 1"); err != nil {
log.Fatal(err)
}
time.Sleep(100 * time.Millisecond)
}
show("busy for 2.5 s:", db)
}
after burst of 4: open=4 idle=4 idleTimeClosed=0 lifetimeClosed=0
idle for 1.5 s: open=0 idle=0 idleTimeClosed=4 lifetimeClosed=0
busy for 2.5 s: open=1 idle=1 idleTimeClosed=4 lifetimeClosed=1
The 4 connections opened by the burst were closed after being idle for more than 500 ms. The connection used by the steady stream of queries was never idle long enough, but it was replaced when it reached its maximum age of 2 s.
Two things to know:
- A background goroutine checks idle connections at most once per second, so the limits aren't exact. Values in minutes are typical anyway.
- The pool reuses the most recently returned connection first. Under light load, the same few connections are reused and the rest stay idle long enough to be closed.
Choosing pool sizes
There is no single right number, but these are good starting points:
- Find the connection limit of your database server and divide it among all the processes that connect to it, leaving room for admin tools and migrations. If PostgreSQL allows 100 connections and you run 4 instances of your app,
MaxOpenConnsof 20 per instance is a reasonable ceiling. - More connections isn't faster. A database can only run as many queries at the same time as it has CPU cores and disk bandwidth. For a typical server, a few dozen active connections is enough, and extra connections mostly add contention.
- Set
MaxIdleConnsto the same value asMaxOpenConns, or a bit lower. - Set
ConnMaxLifetimeto a few minutes up to an hour, and shorter than any timeout of the network path or server. SetConnMaxIdleTimeto a few minutes. - For SQLite, the rules are different because only one connection can write at a time. A common setup is a separate write pool with
SetMaxOpenConns(1). See SQLite.
A helper that opens and configures the pool in one place:
func openDB(ctx context.Context, driverName, dsn string) (*sql.DB, error) {
db, err := sql.Open(driverName, dsn)
if err != nil {
return nil, err
}
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(25)
db.SetConnMaxLifetime(30 * time.Minute)
db.SetConnMaxIdleTime(5 * time.Minute)
// sql.Open doesn't connect. Fail fast at startup if the database is unreachable.
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
db.Close()
return nil, err
}
return db, nil
}
Leaking connections
A connection is in use from the moment a query starts until its result is fully consumed or closed. For db.Query that means until rows.Close() is called, or rows.Next() returns false. If you return early without closing rows, the connection never goes back to the pool.
With a limit on open connections, each leak takes one connection away for good, and eventually every query blocks:
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"time"
_ "modernc.org/sqlite"
)
const setup = `
DROP TABLE IF EXISTS users;
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO users (name) VALUES ('alice'), ('bob'), ('carol');`
// firstUser has a bug: it returns without closing rows.
func firstUser(db *sql.DB) (string, error) {
rows, err := db.Query("SELECT name FROM users ORDER BY id")
if err != nil {
return "", err
}
// BUG: missing defer rows.Close()
if rows.Next() {
var name string
err := rows.Scan(&name)
return name, err
}
return "", rows.Err()
}
func main() {
db, err := sql.Open("sqlite", "file:pool.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
if _, err := db.Exec(setup); err != nil {
log.Fatal(err)
}
db.SetMaxOpenConns(3)
for i := range 3 {
name, err := firstUser(db)
fmt.Printf("call %d: name=%q err=%v inUse=%d\n", i, name, err, db.Stats().InUse)
}
// The pool is now empty: every connection is held by a leaked *sql.Rows.
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
var count int
err = db.QueryRowContext(ctx, "SELECT count(*) FROM users").Scan(&count)
fmt.Println("error:", err)
fmt.Println("deadline exceeded:", errors.Is(err, context.DeadlineExceeded))
s := db.Stats()
fmt.Println("waited:", s.WaitDuration.Round(10*time.Millisecond), "wait count:", s.WaitCount)
}
call 0: name="alice" err=<nil> inUse=1
call 1: name="alice" err=<nil> inUse=2
call 2: name="alice" err=<nil> inUse=3
error: context deadline exceeded
deadline exceeded: true
waited: 200ms wait count: 1
Each call leaked one connection, as inUse shows. After 3 calls the pool was empty and the next query timed out waiting for a connection. Without a context deadline it would have blocked forever. With no MaxOpenConns limit the program wouldn't block. Instead it would open new connections until the database refused more.
The fix is to always close rows right after checking the error:
rows, err := db.Query("SELECT name FROM users ORDER BY id")
if err != nil {
return "", err
}
defer rows.Close()
The same applies to other things that hold a connection:
| Holds a connection | Released by |
|---|---|
*sql.Rows from Query |
rows.Close(), or rows.Next() returning false |
*sql.Row from QueryRow |
row.Scan(...). Always call Scan, even if you only check the error. |
*sql.Tx from Begin |
tx.Commit() or tx.Rollback(). Use defer tx.Rollback(); it does nothing after Commit. |
*sql.Conn from db.Conn |
conn.Close() |
Exec returns its connection to the pool before returning, so there's nothing to close.
Cancelling a query's context also releases its connection: database/sql closes the Rows when the context is done. That's one more reason to pass a context with a deadline to every query in a server, for example r.Context() in an HTTP handler.
Signs of a leak: InUse in Stats grows and never goes back down while the program is idle, and WaitCount climbs.
Pinning a connection with db.Conn
Because *sql.DB is a pool, consecutive calls like db.Exec can run on different connections. That's fine for normal queries, but not for anything stored in the session of a connection:
- temporary tables
- session variables (
SET search_pathin PostgreSQL,SET @xin MySQL, mostPRAGMAs in SQLite) - advisory locks taken with
pg_advisory_lockorGET_LOCK LAST_INSERT_ID()when called as a separate query
db.Conn takes one connection out of the pool and keeps it until you call Close:
package main
import (
"context"
"database/sql"
"fmt"
"log"
_ "modernc.org/sqlite"
)
func main() {
db, err := sql.Open("sqlite", "file:pool.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
ctx := context.Background()
// Wrong: each call may run on a different connection.
if _, err := db.Exec("CREATE TEMP TABLE scratch (v INTEGER)"); err != nil {
log.Fatal(err)
}
// Simulate another goroutine borrowing that connection right now.
other, err := db.Conn(ctx)
if err != nil {
log.Fatal(err)
}
_, err = db.Exec("INSERT INTO scratch VALUES (1)")
fmt.Println("insert:", err)
other.Close()
// Right: pin one connection with db.Conn for the whole sequence.
conn, err := db.Conn(ctx)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
steps := []string{
"CREATE TEMP TABLE work (v INTEGER)",
"INSERT INTO work VALUES (1), (2), (3)",
}
for _, q := range steps {
if _, err := conn.ExecContext(ctx, q); err != nil {
log.Fatal(err)
}
}
var sum int
err = conn.QueryRowContext(ctx, "SELECT sum(v) FROM work").Scan(&sum)
fmt.Println("sum on pinned connection:", sum, err)
}
insert: SQL logic error: no such table: scratch (1)
sum on pinned connection: 6 <nil>
The temporary table was created on one connection. While another goroutine was using that connection, db.Exec got a new one, which doesn't have the table. Using a *sql.Conn for the whole sequence guarantees every statement runs on the same connection.
A transaction (db.BeginTx) also runs all its statements on one connection, so use a transaction when the statements must also be atomic. For settings that every connection needs, don't use db.Conn. Set them when the connection is created: in the DSN, or in a custom driver.Connector like the one in the first example.
Hold a *sql.Conn for as short a time as possible. While you hold it, the pool has one connection less.
Monitoring the pool
db.Stats() returns a sql.DBStats snapshot:
| Field | Meaning |
|---|---|
MaxOpenConnections |
the SetMaxOpenConns limit |
OpenConnections |
connections open now, in use plus idle |
InUse |
connections currently borrowed |
Idle |
connections waiting in the pool |
WaitCount |
total number of times a caller had to wait for a connection |
WaitDuration |
total time callers spent waiting |
MaxIdleClosed |
connections closed because of SetMaxIdleConns |
MaxIdleTimeClosed |
connections closed because of SetConnMaxIdleTime |
MaxLifetimeClosed |
connections closed because of SetConnMaxLifetime |
The last 5 are counters that only grow since the pool was created. To see what happens over time, look at how they change between two snapshots. Export them to your metrics system, or at least log them periodically:
package main
import (
"context"
"database/sql"
"expvar"
"fmt"
"log"
"log/slog"
"os"
"time"
_ "modernc.org/sqlite"
)
// logPoolStats logs pool stats every interval until ctx is cancelled.
// WaitCount and WaitDuration are cumulative, so it logs the change since last time.
func logPoolStats(ctx context.Context, db *sql.DB, interval time.Duration) {
t := time.NewTicker(interval)
defer t.Stop()
var prev sql.DBStats
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
s := db.Stats()
slog.Info("db pool",
"open", s.OpenConnections,
"in_use", s.InUse,
"idle", s.Idle,
"waits", s.WaitCount-prev.WaitCount,
"waited", (s.WaitDuration - prev.WaitDuration).Round(time.Millisecond))
prev = s
}
}
func main() {
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{} // drop timestamps for stable output
}
return a
},
})))
db, err := sql.Open("sqlite", "file:pool.db")
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.SetMaxOpenConns(2)
// Expose stats as JSON at /debug/vars when the app serves HTTP.
expvar.Publish("db", expvar.Func(func() any { return db.Stats() }))
ctx, cancel := context.WithCancel(context.Background())
go logPoolStats(ctx, db, 100*time.Millisecond)
// Some load: 3 goroutines competing for 2 connections.
for range 3 {
go func() {
for ctx.Err() == nil {
conn, err := db.Conn(ctx)
if err != nil {
return
}
time.Sleep(20 * time.Millisecond)
conn.Close()
}
}()
}
time.Sleep(250 * time.Millisecond)
cancel()
time.Sleep(50 * time.Millisecond)
fmt.Println(expvar.Get("db").String())
}
level=INFO msg="db pool" open=2 in_use=2 idle=0 waits=9 waited=82ms
level=INFO msg="db pool" open=2 in_use=2 idle=0 waits=10 waited=102ms
{"MaxOpenConnections":2,"OpenConnections":2,"InUse":0,"Idle":2,"WaitCount":25,"WaitDuration":250155000,"MaxIdleClosed":0,"MaxIdleTimeClosed":0,"MaxLifetimeClosed":0}
(The numbers vary between runs.)
Each log line shows the waits during the last 100 ms. expvar.Publish registers the stats with the standard expvar package. If the program serves HTTP with http.DefaultServeMux, importing expvar also registers the /debug/vars handler, which returns them as JSON. If you use Prometheus, the client library has a collector for this: collectors.NewDBStatsCollector(db, "mydb") in github.com/prometheus/client_golang/prometheus/collectors.
How to read the numbers:
WaitCountandWaitDurationgrowing quickly: the pool is too small or queries are too slow. Check for slow queries before raising the limit.InUsestuck atMaxOpenConnectionswhile the program has no work: connections are leaking.MaxIdleClosedgrowing quickly:MaxIdleConnsis too low, and the pool keeps closing and reopening connections.OpenConnectionsclose to the server's connection limit: lowerMaxOpenConns, or put a pooler such as PgBouncer in front of PostgreSQL.
Bad connections and retries
When the network drops a connection, the driver returns driver.ErrBadConn for it. database/sql then discards that connection and retries the operation, first on another pooled connection and then on a new one. You usually don't see these errors. It only retries when it's safe, meaning the driver reported the failure before the statement was sent. It never retries in the middle of a transaction, because it can't know which statements already ran. A transaction that loses its connection returns an error, and your code has to decide whether to retry the whole transaction.
SetConnMaxLifetime and SetConnMaxIdleTime make such errors rarer by closing connections before something on the network path drops them.
pgxpool
If you use PostgreSQL with the native pgx API instead of database/sql, the pool is pgxpool.Pool. The ideas are the same, with different names: MaxConns, MinConns, MaxConnLifetime and MaxConnIdleTime in pgxpool.Config. Unlike database/sql, the default MaxConns is the larger of 4 and the number of CPUs, not unlimited. Configuration is shown in PostgreSQL.
Its equivalent of db.Stats() is pool.Stat():
s := pool.Stat()
slog.Info("pg pool",
"total", s.TotalConns(),
"acquired", s.AcquiredConns(),
"idle", s.IdleConns(),
"max", s.MaxConns(),
"empty_acquires", s.EmptyAcquireCount(), // had to wait for a connection
"acquire_wait", s.EmptyAcquireWaitTime(),
"canceled_acquires", s.CanceledAcquireCount())
Other Go clients pool connections the same way: a Redis client from go-redis and a MongoDB client each hold a pool too. Create one per process and share it. See Redis and MongoDB.
Summary
*sql.DBis a concurrency-safe connection pool. Create one at startup and share it, and don't open one per request.- Connections are opened lazily. Call
PingContextat startup to check the database is reachable. - By default the pool has no limit on open connections and keeps only 2 idle. Set
SetMaxOpenConnsandSetMaxIdleConnsexplicitly, usually to the same value. - Use
SetConnMaxLifetimeandSetConnMaxIdleTimeto recycle connections before the network or server drops them. - Always close
Rows, callScanon aRow, and finish everyTx, or connections leak and the pool runs dry. - Pass a context with a deadline to queries so waiting for a connection can't block forever.
- Use
db.Connor a transaction when statements depend on the same session. - Watch
db.Stats(): growingWaitCountmeans the pool is too small or queries too slow, andInUsethat never drops means a leak.