Skip to Content
Skip to content
Go Intermediate: Interfaces, Concurrency, and Services
Intermediate
Courses
Go Intermediate: Interfaces, Concurrency, and Services

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.

Course Home

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:

  1. If stock is already 0, placeOrder returns ErrOutOfStock early—and defer tx.Rollback() rolls back immediately and releases the connection back to the pool.
  2. If the INSERT INTO orders fails, tx.Rollback() undoes the inventory decrement too so stock counts stay accurate.
  3. If everything succeeds and tx.Commit() commits cleanly, the deferred tx.Rollback() sees the transaction is already done and returns sql.ErrTxDone as 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 tx pins 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 return tx.Commit().
  • Using db.Begin() instead of db.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
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.