PGX Serialization Retry Transaction

Detect PostgreSQL serialization failures in pgx transactions and retry the whole unit with backoff, aborting only on hard errors.

GoData Integrity

Code

gosnippet
62 lines
package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgconn"
	"github.com/jackc/pgx/v5/pgxpool"
)

func isSerializationFailure(err error) bool {
	var pgErr *pgconn.PgError
	return errors.As(err, &pgErr) && pgErr.Code == "40001"
}

func runWithRetry(ctx context.Context, pool *pgxpool.Pool, attempts int) (int, error) {
	var balance int

	for attempt := 1; attempt <= attempts; attempt++ {
		err := pgx.BeginFunc(ctx, pool, func(tx pgx.Tx) error {
			row := tx.QueryRow(ctx,
				"select balance from accounts where id = 1 for update")
			if err := row.Scan(&balance); err != nil {
				return fmt.Errorf("lock read: %w", err)
			}

			if balance < 100 {
				return errors.New("insufficient funds")
			}

			_, err := tx.Exec(ctx,
				"update accounts set balance = balance - 100 where id = 1")
			return err
		})

		if err == nil {
			return balance - 100, nil
		}
		if isSerializationFailure(err) && attempt < attempts {
			time.Sleep(time.Duration(attempt*50) * time.Millisecond)
			continue // 序列化冲突:整块重放
		}
		return 0, err
	}
	return 0, errors.New("unreachable")
}

func main() {
	config, _ := pgxpool.ParseConfig("postgres://user:pass@localhost/app")
	pool, err := pgxpool.NewWithConfig(context.Background(), config)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer pool.Close()

	final, err := runWithRetry(context.Background(), pool, 4)
	fmt.Println("final balance:", final, "err:", err)
}

How it works

The snippet is organized around the functions isSerializationFailure, runWithRetry and main.

Iteration happens inside for attempt := 1; attempt <= attempts; attempt++ — everything outside it runs once. Every fallible call checks err != nil (2 sites), so an error is handled where it happens rather than bubbling invisibly. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

What to watch for

  • External dependency: github.com/jackc/pgx/v5, github.com/jackc/pgx/v5/pgconn and github.com/jackc/pgx/v5/pgxpool — install them before running the snippet.
  • Error values are returned, not thrown — every call site must inspect err before using the other return values.

Using it

Signature: func isSerializationFailure(err error) bool

The demo output is labeled (final balance:), so the printed lines read as a trace of the operations that ran.

Treat main as the orchestrator calling runWithRetry in a fixed order.

Key statements

return fmt.Errorf("lock read: %w", err)
return errors.As(err, &pgErr) && pgErr.Code == "40001"
return errors.New("insufficient funds")

Interactive Tools for This Topic

FAQ

How does the code signal failure?
No exceptions — `error` returns checked at 2 sites, and callers branch on `err` first.
Does this require external packages?
Yes — `github.com/jackc/pgx/v5`, `github.com/jackc/pgx/v5/pgconn` and `github.com/jackc/pgx/v5/pgxpool`. Add them to your project before running the snippet.