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.Prepareare per-connection under the hood — for hot repeated queries the drivers already cache; explicit prepares matter for complex statements. SetConnMaxLifetimeis 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?
Keep reading
Related articles from the SudoSecurity blog.
What is Go? The Language Google Built for Production Engineering
Go is a statically typed, compiled language built at Google in 2009. It compiles to a single binary with no runtime dependency, starts in milliseconds, and handles concurrency through goroutines and channels. Docker, Kubernetes, and Terraform are all written in Go. Here is why.
Go Lang 1.19: Refines Generics and Memory Model
Go 1.19, the latest version of Google’s Go (Golang) programming language, has reached production availability. The update improves recently added generics and debuts an enhanced memory model. With Go Language version 1.19, released August 2, generics development focused on addressing subtle…
One Slow Call, Three Runtimes: How PHP-FPM, Python ASGI and Node Fall Over When a Dependency Takes 200 ms
I put the same 200 ms wait behind PHP-FPM, FastAPI on uvicorn and a plain Node server, then hit each one with 50 concurrent requests. Handled correctly, the async runtimes served 205-211 req/s against FPM's 19.6. One blocking call in the wrong place took both of them down to 4.98, slower than...
Free-Threaded Python, Measured: Threads Finally Scale, and Your Unlocked Counter Finally Breaks
Python 3.14 made the no-GIL build officially supported, and 3.15 kept going. I ran the same CPU-bound job on standard and free-threaded builds of both: threads went from slower-than-serial to 1.9x faster, and a counter that never lost an update under the GIL lost 70% of them without it.