SQL Transactions and Connection Pool Limits
Run atomic multi-statement SQL writes with db.BeginTx and defer tx.Rollback(), and bound connections with SetMaxOpenConns. After this, partial writes and exhausted DB pools stop happening.
Course content
Sign in to save your progress.
-
Interfaces and Standard Abstractions
-
Interfaces Are Satisfied Implicitly
-
Read and Stream With io.Reader and io.Writer
-
-
-
Context, Timeouts, and Cancellation
-
Use context.Context for Deadlines and Cancellation
-
Set Timeouts on HTTP Clients and Server Handlers
-
-
-
Goroutines, Channels, and Coordination
-
Run Concurrent Work Safely With sync.WaitGroup
-
Coordinate Pipelines and Timeouts With Channels and select
-
-
-
Structured Logging and Databases
-
Write Structured JSON Logs With log/slog
-
Query Relational Data Safely With database/sql
-
-
-
Middleware and Production-Ready Services
-
Wrap HTTP Handlers With Middleware
-
Build a Multi-Route Service With Graceful Shutdown
-
-
-
Generics, Transactions, Timers, and Test Doubles
-
Generics, Constraints, and slices/maps Packages
-
SQL Transactions and Connection Pool Limits
-
Timers, Tickers, and Avoiding time.After Leaks
-
Testing With Interface Fakes, t.TempDir, and testdata
-
-
Imagine an e-commerce checkout handler that runs two SQL statements straight on *sql.DB: first UPDATE inventory SET stock = stock - 1 WHERE sku = $1, then INSERT INTO orders (user_id, sku) VALUES ($1, $2). Because *sql.DB is a connection pool, those two statements can even execute on two separate database connections—and if the INSERT fails on a constraint or timeout, the customer has no order while inventory was already decremented permanently.
Wrapping multi-step writes in db.BeginTx with defer tx.Rollback() guarantees all-or-nothing atomicity, and tuning *sql.DB's connection pool prevents traffic bursts from exhausting your database server.
Skip ahead
If you already wrap multi-step SQL writes in db.BeginTx + defer tx.Rollback() and always configure SetMaxOpenConns, SetMaxIdleConns, and SetConnMaxLifetime, continue to "Timers, Tickers, and Avoiding time.After Leaks."
Experiment 1: Atomic inventory deduction + order creation
Notice two strict rules in placeOrder: defer tx.Rollback() sits right after checking db.BeginTx's error, and every SQL call uses tx.ExecContext—never db.ExecContext:
func placeOrder(ctx context.Context, db *sql.DB, userID int64, sku string) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer tx.Rollback()
res, err := tx.ExecContext(ctx,
"UPDATE inventory SET stock = stock - 1 WHERE sku = $1 AND stock > 0", sku)
if err != nil {
return fmt.Errorf("reserve stock: %w", err)
}
rows, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("rows affected: %w", err)
}
if rows == 0 {
return ErrOutOfStock
}
if _, err := tx.ExecContext(ctx,
"INSERT INTO orders (user_id, sku) VALUES ($1, $2)", userID, sku); err != nil {
return fmt.Errorf("insert order: %w", err)
}
return tx.Commit()
}
Experiment 2: Why defer tx.Rollback() is safe even when Commit() succeeds
Trace every exit path in placeOrder:
- If
stockis already0,placeOrderreturnsErrOutOfStockearly—anddefer tx.Rollback()rolls back immediately and releases the connection back to the pool. - If the
INSERT INTO ordersfails,tx.Rollback()undoes the inventory decrement too so stock counts stay accurate. - If everything succeeds and
tx.Commit()commits cleanly, the deferredtx.Rollback()sees the transaction is already done and returnssql.ErrTxDoneas a harmless no-op without touching the committed data.
fail_err=insufficient funds ok_err=<nil> committed=1 rolledBack=1
Experiment 3: Why mixing db.* inside a tx causes deadlocks
Suppose a helper called inside placeOrder accidentally receives *sql.DB instead of *sql.Tx and runs db.QueryRowContext(ctx, "SELECT stock FROM inventory WHERE sku = $1", sku). That call grabs a second connection from the pool outside the transaction. If your pool has only a few connections left—or if the row is locked by tx—both connections wait on each other and deadlock until the context times out!
Experiment 4: Bounding the *sql.DB connection pool
By default, *sql.DB has MaxOpenConns = 0 (unlimited) and MaxIdleConns = 2. Under load, Go keeps opening new TCP connections until PostgreSQL hits max_connections and rejects every app instance. Always configure three limits right after sql.Open:
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(10)
db.SetConnMaxLifetime(5 * time.Minute)
db.SetConnMaxIdleTime(2 * time.Minute)
Pick MaxOpenConns by dividing your database's connection limit across the maximum number of app replicas (for example, 4 pods × 25 conns = 100 max connections, safely below a 150-connection Postgres server).
Common mistakes
- Making outbound HTTP calls inside an open SQL transaction: Calling Stripe or SendGrid while holding a
txpins row locks and a pooled DB connection for seconds—blocking every other checkout. - Ignoring
tx.Commit()'s returned error: Deferred constraints and serialization conflicts fail at commit time; always returntx.Commit(). - Using
db.Begin()instead ofdb.BeginTx(ctx, nil): Ignores request cancellation and deadlines.
💡 Tip
Export db.Stats() metrics (OpenConnections, InUse, WaitCount, WaitDuration) to Prometheus or logs—a climbing WaitCount tells you immediately when your pool is undersized or a transaction is holding connections too long.
What happens if you skip this step
Without transactions, mid-flight failures leave orphan orders and negative inventory; without SetMaxOpenConns, a single slow query spike exhausts PostgreSQL's connection limit across your entire cluster.
Your service runs placeOrder with defer tx.Rollback() and succeeds, reaching return tx.Commit(). When the deferred tx.Rollback() executes right afterward, does it undo the committed order?
About
Run atomic multi-statement SQL writes with db.BeginTx and defer tx.Rollback(), and bound connections with SetMaxOpenConns. After this, partial writes and exhausted DB pools stop happening.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.