Build HTTP and database integrations

How to Commit or Roll Back a Go `database/sql` Transaction Safely

Use BeginTx, deferred rollback, and checked Commit errors to keep multi-step database work inside one Go transaction.

By Niko Minadze4 min read

Editorial illustration for How to Commit or Roll Back a Go `database/sql` Transaction Safely

When several database changes must succeed together, start a sql.Tx and run every change in that unit through the transaction. Return immediately when an operation fails. A nil error from tx.Commit() is the success boundary, not a successful update earlier in the function.

Start one transaction and keep the work on it

db.BeginTx(ctx, nil) returns the transaction. The nil options use the database's default transaction settings. Operations on that sql.Tx use a single connection; calling db.ExecContext midway through the function does not add that operation to the transaction. Keep transaction-scoped updates and queries on tx, and keep the transaction short because it holds a connection until it ends. The Go transaction documentation describes the begin, operate, and commit-or-rollback workflow.

Here is a focused example for an accounts table with an integer id and balance. It debits one account and credits another. The debit checks that enough balance exists, and both updates must affect exactly one row. The ? placeholders are illustrative: placeholder syntax varies by database driver, so adapt the SQL to the driver in use.

package accounts

import (
    "context"
    "database/sql"
    "errors"
    "fmt"
)

func Transfer(ctx context.Context, db *sql.DB, fromID, toID, amount int64) (err error) {
    if amount <= 0 || fromID == toID {
        return fmt.Errorf("transfer requires a positive amount and distinct accounts")
    }

    tx, beginErr := db.BeginTx(ctx, nil)
    if beginErr != nil {
        return fmt.Errorf("begin transfer: %w", beginErr)
    }

    committed := false
    defer func() {
        if committed {
            return
        }
        if rollbackErr := tx.Rollback(); rollbackErr != nil &&
            !errors.Is(rollbackErr, sql.ErrTxDone) {
            err = fmt.Errorf("rollback transfer: %v; original failure: %w", rollbackErr, err)
        }
    }()

    debit, execErr := tx.ExecContext(ctx,
        "UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?",
        amount, fromID, amount)
    if execErr != nil {
        return fmt.Errorf("debit account %d: %w", fromID, execErr)
    }
    n, rowsErr := debit.RowsAffected()
    if rowsErr != nil {
        return fmt.Errorf("check debit: %w", rowsErr)
    }
    if n != 1 {
        return fmt.Errorf("debit account %d: expected one updated row, got %d", fromID, n)
    }

    credit, execErr := tx.ExecContext(ctx,
        "UPDATE accounts SET balance = balance + ? WHERE id = ?",
        amount, toID)
    if execErr != nil {
        return fmt.Errorf("credit account %d: %w", toID, execErr)
    }
    n, rowsErr = credit.RowsAffected()
    if rowsErr != nil {
        return fmt.Errorf("check credit: %w", rowsErr)
    }
    if n != 1 {
        return fmt.Errorf("credit account %d: expected one updated row, got %d", toID, n)
    }

    if commitErr := tx.Commit(); commitErr != nil {
        return fmt.Errorf("commit transfer: %w", commitErr)
    }
    committed = true
    return nil
}

The example checks each call before proceeding. An error from the debit, including an unexpected affected-row count, returns before the credit runs. An error from the credit returns before Commit. RowsAffected is useful here because a statement can execute without updating the intended account; checking the result is separate from checking ExecContext's error.

The caller supplies ctx to both BeginTx and the updates. Context-taking database operations can carry a deadline or cancellation request. That is useful for bounding the work, but it does not replace checking each operation's error. For more on propagating cancellation outside the database call, see Using context.Context in Go: Cancellation, Timeouts, and Request-Scoped Values.

Make commit the success boundary

Do not report a transfer as successful just because both UPDATE calls returned without error. tx.Commit() can fail too. The Go transaction guide says that a nil commit error confirms the transaction's query results and applies its updates atomically. If commit fails, discard results obtained through that transaction rather than treating them as confirmed.

That is why the function returns nil only after Commit returns nil. The deferred function skips rollback on that path. On an earlier return, it attempts rollback. It also runs after a commit error, although the transaction may already be finished; sql.ErrTxDone is ignored in that cleanup path rather than reported as an additional failure.

Keep the operation error when rollback also fails

Rollback is a safety net, not a reason to replace the error that caused the return. The named return value lets the deferred function report a non-terminal rollback error alongside the original failure. The rollback error appears in the returned message; the original failure remains the error wrapped with %w. If rollback itself fails, that does not mean the transaction committed: the Go transaction guide says the Tx is no longer valid and has not been committed even when Rollback returns an error.

Finally, use BeginTx, Commit, and Rollback to manage this transaction. Do not issue SQL BEGIN or COMMIT statements alongside those methods. The database/sql guidance warns that mixing the two approaches can leave transaction state unpredictable, particularly in concurrent programs.

Comments

No comments yet.

Leave a comment

Your comment appears after approval. Plain text only; links stay as text. Line breaks and indentation are kept.

Up to 5,000 characters. No account or email needed.

All articles

Type at least two characters.

Press <kbd>Esc</kbd> to closeOpen the search page