Transaction Retry with Rollback
Wrap database work in a transaction helper that rolls back on error and retries serialization conflicts with short backoff.
Code
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
)
var ErrConflict = errors.New("serialization conflict")
func WithTx(
ctx context.Context,
db *sql.DB,
attempts int,
work func(*sql.Tx) error,
) error {
if attempts < 1 {
attempts = 1
}
var last error
for attempt := 0; attempt < attempts; attempt++ {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
err = work(tx)
if err == nil {
if commitErr := tx.Commit(); commitErr == nil {
return nil
} else {
last = commitErr
}
} else {
_ = tx.Rollback()
last = err
}
if !errors.Is(last, ErrConflict) {
return last
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Duration(attempt+1) * 50 * time.Millisecond):
}
}
return fmt.Errorf("transaction failed after %d attempts: %w", attempts, last)
}
func transfer(ctx context.Context, db *sql.DB, from, to, amount int64) error {
return WithTx(ctx, db, 3, func(tx *sql.Tx) error {
result, err := tx.ExecContext(
ctx,
"UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ?",
amount, from, amount,
)
if err != nil {
return err
}
affected, err := result.RowsAffected()
if err != nil {
return err
}
if affected == 0 {
return errors.New("insufficient funds")
}
_, err = tx.ExecContext(
ctx,
"UPDATE accounts SET balance = balance + ? WHERE id = ?",
amount, to,
)
return err
})
}
func main() {
fmt.Println(transfer != nil, ErrConflict)
}
The route through the source
Transaction Retry with Rollback keeps everything in the functions WithTx, transfer and main.
Repetition is confined to for attempt := 0; attempt < attempts; attempt++ — the rest of the file is straight-line. The Go idiom runs throughout — 3 if err != nil checks, each handling the failure on the spot.
What to watch for
- The function reports failure by returning
error— callers branch on it before touching other results.
Applying it
Entry signature: func WithTx( ctx context.Context, db *sql.DB, attempts int, work func(*sql.Tx) error,
Statements that matter
return fmt.Errorf("transaction failed after %d attempts: %w", attempts, last)
return errors.New("insufficient funds")
return ctx.Err()
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Is there exception handling?
- Through `error` values, not panics — the snippet checks `err != nil` at 3 sites.
- How do you run Transaction Retry with Rollback?
- Run the file on its own; every call resolves against the standard surface it already imports.
Report a problem with this exampleOpens a pre-filled issue on GitHub.