Backend Development

Transactions

Keep related database changes atomic and avoid mixing transactional and non-transactional work.

What you will learn

By the end of this lesson, you will be able to:

  • decide when several database operations require a transaction;
  • use BeginTx, deferred rollback, and commit correctly;
  • keep every transactional query on *sql.Tx;
  • reason about isolation and retryable conflicts;
  • avoid pretending a database transaction includes external side effects.

Mental model: one atomic database decision

A transaction groups database operations so they commit together or do not commit at all.

For example, transferring credits requires both account changes. Applying only one would violate the business invariant.

The standard pattern

func (r *Repository) Transfer(ctx context.Context, fromID, toID string, amount int64) error {
    tx, err := r.database.BeginTx(ctx, nil)
    if err != nil {
        return fmt.Errorf("begin transfer: %w", err)
    }
    defer tx.Rollback()

    if err := debit(ctx, tx, fromID, amount); err != nil {
        return err
    }
    if err := credit(ctx, tx, toID, amount); err != nil {
        return err
    }

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

The deferred rollback is safe after a successful commit; it returns sql.ErrTxDone, which is intentionally ignored. Its purpose is to roll back every early return.

Use only the transaction handle

Inside the transaction, every related query must use tx, not the original *sql.DB:

tx.ExecContext(ctx, query, args...)
tx.QueryRowContext(ctx, query, args...)

Calling db.QueryContext in the middle may use another connection outside the transaction, producing inconsistent state or blocking behaviour.

Accept a small query interface

Helpers can work with both a database and a transaction when their required methods match:

type Queryer interface {
    ExecContext(context.Context, string, ...any) (sql.Result, error)
    QueryRowContext(context.Context, string, ...any) *sql.Row
}

func debit(ctx context.Context, q Queryer, accountID string, amount int64) error {
    // Execute a bounded, parameterized update through q.
    return nil
}

Keep the interface local to the consumer and include only the operations it uses.

Isolation and locking

Concurrent transactions can observe or overwrite state depending on the database, query shape, and isolation level. sql.TxOptions can request an isolation level:

tx, err := database.BeginTx(ctx, &sql.TxOptions{
    Isolation: sql.LevelSerializable,
})

Drivers and databases differ in supported levels and exact behaviour. Read the database documentation and design queries and constraints for the invariant being protected.

Higher isolation may increase waiting or transaction aborts. It is not a substitute for understanding the access pattern.

Retrying conflicts

Some serialization failures or deadlocks may be safe to retry. Retry only when:

  • the database/driver error is positively classified as retryable;
  • the complete operation is safe to repeat;
  • attempts are bounded;
  • backoff respects context cancellation;
  • the final error preserves useful context.

Do not retry every error. Syntax errors, validation failures, and most constraint violations will not improve.

External side effects are not included

A database transaction cannot roll back an email, HTTP request, or message already sent to another system.

For reliable event publication, one common pattern writes both domain state and an outbox record in the same transaction. A separate worker later publishes the outbox entry and records progress with idempotent handling.

This pattern provides durable coordination; it does not create a magical transaction across unrelated systems.

Keep transactions short

Do not wait for user input, call slow remote APIs, or perform large unrelated computation while holding a transaction. Long transactions retain connections and locks, increasing contention.

Prepare external input first, transact only the required database work, commit, then perform post-commit behaviour designed for failure.

Common mistakes

  • Forgetting deferred rollback: an early return can leave resources tied up until cancellation or cleanup.
  • Using db during tx: work silently occurs outside the transaction.
  • Ignoring commit failure: a successful final statement does not prove the commit succeeded.
  • Calling an external API before commit: the API side effect remains when the database rolls back.
  • Retrying an operation containing non-idempotent side effects: duplicate work can occur.
  • Choosing serializable isolation without handling aborts: contention becomes unexplained failures.

Practice

Implement EnrollStudent so it checks course capacity, inserts an enrollment, and increments the enrolled count atomically. Prevent capacity from being exceeded under concurrent requests.

Summary

  • Transactions make a group of database operations commit or roll back together.
  • Defer rollback immediately after BeginTx and check commit errors.
  • Use the transaction handle for every related database operation.
  • Choose isolation and retries from concrete database behaviour.
  • Coordinate external side effects with explicit durable patterns such as an outbox.

Official reference: Executing transactions.

Ready to wrap up?

Mark this complete when you can explain the main idea and finish the practice task.

Copyright © 2026