Configure connection pools
Configure connection pools
A pool reuses connections instead of opening one for every query. SetMaxOpenConns bounds open connections; SetMaxIdleConns bounds retained idle ones. SetConnMaxLifetime and SetConnMaxIdleTime limit reuse by age and idle duration. Derive limits from server capacity, replica count and measured wait statistics; zero maximum open means unlimited, not zero connections.
package main
import ( "context" "database/sql" "database/sql/driver" "errors" "fmt" "io" "time")
// fixtureDriver is a teaching double, not a SQL engine.type fixtureDriver struct{}type fixtureConn struct{ mode string }type fixtureTx struct{}type fixtureRows struct { values [][]driver.Value fail bool index int}
func (fixtureDriver) Open(name string) (driver.Conn, error) { if name == "offline" { return nil, errors.New("fixture offline") } return &fixtureConn{mode: name}, nil}func (c *fixtureConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("prepare not implemented in fixture")}func (c *fixtureConn) Close() error { return nil }func (c *fixtureConn) Begin() (driver.Tx, error) { return &fixtureTx{}, nil }func (c *fixtureConn) Ping(ctx context.Context) error { return ctx.Err() }func (t *fixtureTx) Commit() error { return nil }func (t *fixtureTx) Rollback() error { return nil }func (c *fixtureConn) QueryContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Rows, error) { if err := ctx.Err(); err != nil { return nil, err } switch q { case "SELECT name FROM books WHERE id = ?": if len(args) != 1 { return nil, errors.New("one argument required") } if args[0].Value == int64(7) { return &fixtureRows{values: [][]driver.Value{{"Go"}}}, nil } return &fixtureRows{}, nil case "SELECT name FROM books": return &fixtureRows{values: [][]driver.Value{{"Go"}, {nil}}, fail: c.mode == "broken"}, nil default: return nil, errors.New("unsupported fixture query") }}func (c *fixtureConn) ExecContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Result, error) { if err := ctx.Err(); err != nil { return nil, err } if q != "UPDATE books SET name = ? WHERE id = ?" || len(args) != 2 { return nil, errors.New("unsupported fixture update") } if args[1].Value == int64(7) { return driver.RowsAffected(1), nil } return driver.RowsAffected(0), nil}func (r *fixtureRows) Columns() []string { return []string{"name"} }func (r *fixtureRows) Close() error { return nil }func (r *fixtureRows) Next(dest []driver.Value) error { if r.index == len(r.values) { if r.fail { return errors.New("fixture stream interrupted") } return io.EOF } copy(dest, r.values[r.index]) r.index++ return nil}func must(err error) { if err != nil { panic(err) }}func openFixture(mode string) *sql.DB { db, err := sql.Open("bytemind-fixture", mode) must(err) return db}func init() { sql.Register("bytemind-fixture", fixtureDriver{}) }
func main() { db := openFixture("ready") defer db.Close() db.SetMaxOpenConns(2) db.SetMaxIdleConns(1) db.SetConnMaxLifetime(time.Minute) db.SetConnMaxIdleTime(10 * time.Second) must(db.Ping()) s := db.Stats() fmt.Println(s.MaxOpenConnections, s.Idle, s.InUse)}Stats is a snapshot; InUse and Idle change with concurrent operations. The chosen values are small lab values, not production recommendations. Idle connections may be cleaned up lazily. Monitor WaitCount and WaitDuration alongside query latency.
Expected output:
2 1 0Pool exhaustion and cancellation
package main
import ( "context" "database/sql" "database/sql/driver" "errors" "fmt" "io" "time")
// fixtureDriver is a teaching double, not a SQL engine.type fixtureDriver struct{}type fixtureConn struct{ mode string }type fixtureTx struct{}type fixtureRows struct { values [][]driver.Value fail bool index int}
func (fixtureDriver) Open(name string) (driver.Conn, error) { if name == "offline" { return nil, errors.New("fixture offline") } return &fixtureConn{mode: name}, nil}func (c *fixtureConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("prepare not implemented in fixture")}func (c *fixtureConn) Close() error { return nil }func (c *fixtureConn) Begin() (driver.Tx, error) { return &fixtureTx{}, nil }func (c *fixtureConn) Ping(ctx context.Context) error { return ctx.Err() }func (t *fixtureTx) Commit() error { return nil }func (t *fixtureTx) Rollback() error { return nil }func (c *fixtureConn) QueryContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Rows, error) { if err := ctx.Err(); err != nil { return nil, err } switch q { case "SELECT name FROM books WHERE id = ?": if len(args) != 1 { return nil, errors.New("one argument required") } if args[0].Value == int64(7) { return &fixtureRows{values: [][]driver.Value{{"Go"}}}, nil } return &fixtureRows{}, nil case "SELECT name FROM books": return &fixtureRows{values: [][]driver.Value{{"Go"}, {nil}}, fail: c.mode == "broken"}, nil default: return nil, errors.New("unsupported fixture query") }}func (c *fixtureConn) ExecContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Result, error) { if err := ctx.Err(); err != nil { return nil, err } if q != "UPDATE books SET name = ? WHERE id = ?" || len(args) != 2 { return nil, errors.New("unsupported fixture update") } if args[1].Value == int64(7) { return driver.RowsAffected(1), nil } return driver.RowsAffected(0), nil}func (r *fixtureRows) Columns() []string { return []string{"name"} }func (r *fixtureRows) Close() error { return nil }func (r *fixtureRows) Next(dest []driver.Value) error { if r.index == len(r.values) { if r.fail { return errors.New("fixture stream interrupted") } return io.EOF } copy(dest, r.values[r.index]) r.index++ return nil}func must(err error) { if err != nil { panic(err) }}func openFixture(mode string) *sql.DB { db, err := sql.Open("bytemind-fixture", mode) must(err) return db}func init() { sql.Register("bytemind-fixture", fixtureDriver{}) }
func main() { db := openFixture("ready") defer db.Close() db.SetMaxOpenConns(1) c, err := db.Conn(context.Background()) must(err) defer c.Close() ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) defer cancel() _, err = db.Conn(ctx) fmt.Println(errors.Is(err, context.DeadlineExceeded)) fmt.Println(db.Stats().WaitCount >= 1)}Holding the sole connection forces another acquisition to wait. The deadline bounds the wait without assuming a precise elapsed time. Close dedicated Conn and Rows promptly. A transaction that calls DB methods while holding the only connection can wait on itself; use Tx methods instead.
Expected output:
truetrueTry it locally
Set max open to 3 and max idle to 0; ping then print maximum and idle count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Database 03: Configure connection pools
Check the lesson objective before moving on.
What does max open = 0 mean?
What bounds waiting for a full pool?