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.
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.
Skip ahead
Jump straight to BeginTx + defer tx.Rollback() or the connection pool settings table.
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 deferredtx.Rollback()sees the transaction is already closed and safely returnssql.ErrTxDonewithout 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.QueryContextinside atxfunction: Queries ondbbypasstx, grab a different pooled connection outside the transaction, and can deadlock waiting on row locks held bytx. - Leaving
MaxOpenConnsat default0: 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 returntx.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
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.