retry.go54 lines, 1.4 KB
| 1 | package postgres |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "math/rand/v2" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/jackc/pgx/v5/pgconn" |
| 11 | ) |
| 12 | |
| 13 | // MaxAttempts is how many times Retry runs a transaction before giving up. |
| 14 | const MaxAttempts = 5 |
| 15 | |
| 16 | // Retry runs fn, which must run one whole database transaction, and runs it |
| 17 | // again when Postgres aborted it with a serialization failure or a deadlock. |
| 18 | // Both mean nothing happened, so another attempt is safe, as long as fn has no |
| 19 | // side effects outside the transaction. It gives up after MaxAttempts. |
| 20 | func Retry(ctx context.Context, fn func() error) error { |
| 21 | backoff := 10 * time.Millisecond |
| 22 | for attempt := 1; ; attempt++ { |
| 23 | err := fn() |
| 24 | if err == nil || !retryable(err) { |
| 25 | return err |
| 26 | } |
| 27 | if attempt == MaxAttempts { |
| 28 | return fmt.Errorf("gave up after %d attempts: %w", attempt, err) |
| 29 | } |
| 30 | // Full jitter: wait a random time up to backoff, so transactions that |
| 31 | // just collided don't all come back at the same moment, and collide |
| 32 | // again. The ceiling doubles after every attempt. |
| 33 | select { |
| 34 | case <-time.After(rand.N(backoff)): |
| 35 | case <-ctx.Done(): |
| 36 | return err |
| 37 | } |
| 38 | backoff *= 2 |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | // retryable reports whether Postgres aborted a transaction only because it |
| 43 | // collided with a concurrent one. |
| 44 | func retryable(err error) bool { |
| 45 | pgErr, ok := errors.AsType[*pgconn.PgError](err) |
| 46 | if !ok { |
| 47 | return false |
| 48 | } |
| 49 | switch pgErr.Code { |
| 50 | case "40001", "40P01": // serialization_failure, deadlock_detected |
| 51 | return true |
| 52 | } |
| 53 | return false |
| 54 | } |