PGXTransactions

PGXTransactions is a small Go library for running PostgreSQL transactions with
pgx that automatically retry on transient,
retryable failures such as deadlocks, serialization failures, and optimistic
concurrency conflicts.
Features
- Automatic retries for retryable database errors (deadlocks, unique-violation conflicts, and any other errors you classify as retryable).
- A separate
Preparer callback that runs inside the retry loop, but outside the transaction, and an Updater callback that runs inside it - making optimistic concurrency control easy to express.
- Exponential backoff with jitter and a configurable retry cap.
- Works against
*pgxpool.Pool or any type implementing the small PgxIface interface, so transactions are easy to mock in tests.
Installation
go get github.com/synaptor/pgxtransactions
Usage
Wrap your read-modify-write logic in a call to pgxtransactions.Transaction:
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/synaptor/pgxtransactions"
)
func dataUpdate(ctx context.Context, pool *pgxpool.Pool) error {
var data string
var version int
return pgxtransactions.Transaction(ctx, pool, pgxtransactions.TransactionOptions{
// Preparer runs outside the transaction to do any expensive work.
Preparer: func() error {
// Load the current state from the database.
err := pool.QueryRow(ctx, "SELECT data, version FROM tbl WHERE id=$1", id).Scan(&data, &version)
if err != nil {
return err
}
// Perform any expensive computations or API calls that shouldn't keep the transaction open.
// Prepare data for the Updater, e.g. new values to be stored in the database.
return nil
},
// Updater runs inside the transaction.
Updater: func(tx pgx.Tx) error {
// Perform the optimistic concurrency control update. If the row was modified by another transaction since we loaded it in Preparer, this will affect zero rows and we can treat it as a retryable conflict.
res, err := tx.Exec(ctx, "UPDATE tbl SET data=$1, version=version+1 WHERE id=$2 AND version=$3", data, id, version)
if err != nil {
return err
}
if res.RowsAffected() == 0 {
// No rows were updated, which means the version didn't match - i.e. the row was modified by another transaction.
return pgxtransactions.ErrConflict
}
return nil
},
})
}
On each retry, Transaction re-runs Preparer (to prepare again) and then Updater inside a fresh transaction. Preparer is optional. Updater is required.
Retrying unique constraint violations
By default, unique constraint violations are not retried. This behavior is needed when the caller updates a unique field to a fixed value, and failure to do so is not retryable.
However, if the caller is capable of resolving unique constraint violations (e.g. by generating a new value and retrying), they should be treated as retryable. To enable this, set the RetryUniqueViolations field to true.
Custom IsRetryable logic
By default, Transaction retries deadlocks, unique-violation conflicts and custom pgxtransactions.ErrConflict error.
To classify other errors as retryable, set the IsRetryable field of TransactionOptions to a function that returns true for those errors.
Custom MaxRetries
By default, Transaction retries up to 10 times. To change this, set the MaxRetries field of TransactionOptions to the desired maximum number of attempts (including the initial attempt).
License
MIT License