Skip to content

Lesson 9 of 13 · 22m

database/sql Is a Pool, Not a Connection

MaxOpenConns × replicas vs Postgres' max_connections=100, ErrNoRows to your sentinel, defer tx.Rollback(), and pgx vs database/sql.

The app was fine in staging and melted in production: pq: sorry, too many clients already. Postgres' max_connections defaults to 100, your service runs twelve replicas, and each one treated sql.DB like a connection. It isn't. *sql.DB is a pool — a handle that opens, reuses, and retires connections for you — and its defaults are sized for a demo, not a service.

The pool and its knobs

db, err := sql.Open("pgx", dsn) // pgx's stdlib driver
if err != nil {
	return fmt.Errorf("db: %w", err)
}

db.SetMaxOpenConns(25)                  // hard cap on simultaneous connections
db.SetMaxIdleConns(10)                  // how many stay warm between calls
db.SetConnMaxLifetime(10 * time.Minute) // recycle before middleboxes kill them
db.SetConnMaxIdleTime(5 * time.Minute)  // close connections nobody uses

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
	return fmt.Errorf("db: unreachable: %w", err) // fail at boot, not first request
}

The defaults: MaxOpenConns is unlimited, MaxIdleConns is 2, and connections live forever. Under burst, the pool opens connections faster than it retires them and Postgres starts refusing; under steady load the idle-of-2 default churns connections it should have kept warm. db.Stats() exposes OpenConnections, InUse, WaitCount, and WaitDuration — when WaitDuration climbs, your pool is the queue, and requests are timing out inside database/sql before a query ever runs.

Size deliberately: MaxOpenConns × replicas < max_connections, minus what your other tools need. Or put pgbouncer/RDS Proxy in front and cap the pool lower — pool-in-front-of-pool is a real architecture, not an accident.

The query layer

var u User
err := db.QueryRowContext(ctx,
	`SELECT id, email FROM users WHERE id = $1`, id).Scan(&u.ID, &u.Email)
if errors.Is(err, sql.ErrNoRows) {
	return nil, store.ErrNotFound // your sentinel from the errors lesson
}
if err != nil {
	return nil, fmt.Errorf("store: getUser %d: %w", id, err)
}

Two traps live here. sql.ErrNoRows comes only from QueryRow* — a Query that matches nothing just iterates zero times, no error — and it must be translated into your package's ErrNotFound at the boundary, or callers end up branching on a stdlib detail. And rows.Close() is mandatory on multi-row queries: an unclosed *Rows pins its connection until GC, which is the quiet way to exhaust a pool without ever seeing an error.

Transactions get the defer tx.Rollback() idiom — after a successful Commit() it returns sql.ErrTxDone, safe to ignore:

tx, err := db.BeginTx(ctx, nil)
if err != nil {
	return err
}
defer tx.Rollback()

if _, err := tx.ExecContext(ctx,
	`UPDATE accounts SET balance = balance - $1 WHERE id = $2`, amt, from); err != nil {
	return fmt.Errorf("debit: %w", err)
}
if _, err := tx.ExecContext(ctx,
	`UPDATE accounts SET balance = balance + $1 WHERE id = $2`, amt, to); err != nil {
	return fmt.Errorf("credit: %w", err)
}
return tx.Commit()

Everything in the tx runs on one pinned connection — that's the point. Need a dedicated connection outside a transaction (advisory locks, session settings)? db.Conn(ctx) checks one out until conn.Close().

Drivers

lib/pq is in maintenance mode; jackc/pgx is the live Postgres driver. Two interfaces: the database/sql adapter (pgx/v5/stdlib, registered as "pgx") for drop-in compatibility, or pgxpool — pgx's own pool — when you want Postgres-specific features (LISTEN/NOTIFY, COPY, custom types) that database/sql abstracts away. Pick deliberately: the adapter keeps portability, the native pool gives you the features.

NULLs deserve the same care: Scan cannot put NULL into a string. sql.NullString or a *string field handles it; forgetting this turns sparse columns into unsupported Scan errors that only appear on real data.

Field notes

  • Prepared statements via db.Prepare are per-connection under the hood — for hot repeated queries the drivers already cache; explicit prepares matter for complex statements.
  • SetConnMaxLifetime is your defense against NAT/load-balancer idle kills: recycle the conn before the middlebox hands you a dead socket.
  • pgxpool.Stat() answers the same "is the pool the queue" question on the native interface.

Try this

Stand up a sql.DB with MaxOpenConns untouched and MaxIdleConns at 2. Hammer it with 200 concurrent SELECT pg_sleep(0.1) while polling db.Stats(). Then set the knobs and rerun — watch WaitCount flatline and wait time collapse. The numbers are the whole argument.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.