Skip to Content
Skip to content
Run Safe SQL Transactions in Go With BeginTx and defer tx.Rollback
Intermediate
Tutorials

Run Safe SQL Transactions in Go With BeginTx and defer tx.Rollback

Wrap multi-step SQL writes in db.BeginTx with defer tx.Rollback() and bound database connections with SetMaxOpenConns. After this, partial writes and exhausted connection pools stop happening.

Updated 3 min read GoData and Formats

Running two SQL writes sequentially on *sql.DB—such as deducting product inventory and then inserting an order—gives you no atomicity. Worse, *sql.DB is a connection pool, so those two statements can even execute on two separate TCP connections. If the second statement fails on a constraint or timeout, the first write is already committed permanently.

Meanwhile, leaving *sql.DB's pool settings at their defaults (MaxOpenConns = 0, meaning unlimited) lets a slow query spike open hundreds of connections until PostgreSQL rejects every client with too many clients already.

Why defer tx.Rollback() right after BeginTx is safe

Putting defer tx.Rollback() on the line right after checking db.BeginTx's error handles every possible exit path cleanly:

  • If any query returns an error—or a panic unwinds the stack—tx.Rollback() aborts the transaction and releases locks and the connection back to the pool.
  • If everything succeeds and tx.Commit() runs at the end, the deferred tx.Rollback() sees the transaction is already closed and safely returns sql.ErrTxDone without undoing your commit.
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()
}

Bounding the *sql.DB connection pool

Method What it limits Recommended starting point
db.SetMaxOpenConns(n) Max active + idle connections to the DB 25 (keep sum across app pods under DB max)
db.SetMaxIdleConns(n) Warm idle connections kept ready in RAM 10–25 (avoid tiny defaults like 2 under steady load)
db.SetConnMaxLifetime(d) Max age before a connection is closed and recreated 5 * time.Minute (respects cloud DB failover and DNS rotation)

💡 Tip

Pass the request's ctx into db.BeginTx(ctx, nil) and every tx.ExecContext(ctx, ...). If the HTTP client cancels or times out mid-transaction, database/sql cancels and rolls back automatically.

Common mistakes

  • Calling db.QueryContext inside a tx function: Queries on db bypass tx, grab a different pooled connection outside the transaction, and can deadlock waiting on row locks held by tx.
  • Leaving MaxOpenConns at default 0: Unlimited connections let traffic spikes overwhelm the database server instead of queueing cleanly in Go.
  • Ignoring tx.Commit()'s error: Commit can fail on deferred constraints or serialization conflicts—always return tx.Commit().

⚠ Warning

Keep SQL transactions short. Never make external HTTP calls (like Stripe or email APIs) while holding an open SQL transaction—slow external calls pin database row locks and exhaust your connection pool.

What happens if you skip this

Without BeginTx + defer tx.Rollback(), partial failures corrupt multi-table state and early returns leak locked connections until the database times them out.

Related course: Go Intermediate.

About

Wrap multi-step SQL writes in db.BeginTx with defer tx.Rollback() and bound database connections with SetMaxOpenConns. After this, partial writes and exhausted connection pools stop happening.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
3 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.