Skip to main content

Retries

ant.Attempts and ant.WithRetry rerun a transaction that the database cancelled in a collision.

Retry one transaction​

ant.Attempts reruns a transaction that lost a serialization conflict or a deadlock. The number is the total number of runs, and ant waits a little longer between runs. An ordinary error is never retried.

func transfer(ctx context.Context, db *BankDB, from, to string, amount int64) error {
return db.Tx(
ctx,
func(tx *BankDB) error {
// A tracker of its own, so every attempt reads the rows afresh.
tx = ant.Session(tx, ant.WithTracking(true))

source, err := tx.Accounts.Where(ant.Eq(&Accounts.Owner, from)).Single(ctx)
if err != nil {
return err
}

target, err := tx.Accounts.Where(ant.Eq(&Accounts.Owner, to)).Single(ctx)
if err != nil {
return err
}

source.Balance -= amount
target.Balance += amount

return tx.SaveChanges(ctx)
},
ant.Isolation(sql.LevelSerializable),
ant.Attempts(3),
)
}

If another transfer commits between the reads and the writes, the first run is cancelled at its first UPDATE and the second reads the new balances:

-- run 1
SELECT ... FROM "accounts" WHERE "accounts"."owner" = $1 LIMIT $2
SELECT ... FROM "accounts" WHERE "accounts"."owner" = $1 LIMIT $2
SAVEPOINT ant_sp_1
UPDATE "accounts" SET "balance" = $1, "updated_at" = $2, "version" = $3 WHERE "accounts"."id" = $4 AND "accounts"."version" = $5
-- ERROR: could not serialize access due to concurrent update (SQLSTATE 40001)
ROLLBACK TO SAVEPOINT ant_sp_1
-- run 2
SELECT ... FROM "accounts" WHERE "accounts"."owner" = $1 LIMIT $2
SELECT ... FROM "accounts" WHERE "accounts"."owner" = $1 LIMIT $2
SAVEPOINT ant_sp_1
UPDATE "accounts" SET ... WHERE "accounts"."id" = $4 AND "accounts"."version" = $5
UPDATE "accounts" SET ... WHERE "accounts"."id" = $4 AND "accounts"."version" = $5
RELEASE SAVEPOINT ant_sp_1
What a rerun sees

Before a rerun, the tracker forgets what the failed run loaded or added, so the next run reads its rows afresh and inserts an added entity once. Entities tracked before the transaction stay, with any change the failed run made to them, so load what the function changes inside it.

The function runs from the top each time. If it changes an entity tracked before the transaction, a tracked read returns that same instance, edits included, so a function that changes source.Balance subtracts twice on the second run. A session inside the function, as above, gives each run a clean tracker of its own. Reading with NoTracking and writing with a bulk Update avoids the tracker altogether:

err := db.Tx(
ctx,
func(tx *AppDB) error {
user, err := tx.Users.NoTracking().Find(ctx, id)
if err != nil {
return err
}

_, err = tx.Users.Where(ant.Eq(&Users.ID, id)).Update(ctx, ant.Set(&Users.Age, user.Age+1))

return err
},
ant.Isolation(sql.LevelSerializable),
ant.Attempts(5),
)

What is retryable​

ant.IsRetryable reports whether an error is a deadlock or a serialization failure, on every database:

DatabaseRetryable errors
PostgreSQL40001 serialization failure, 40P01 deadlock
MySQL, MariaDBDeadlock (1213)
MariaDB 11.6 and laterError 1020, a row changed since the transaction's snapshot, which rolls the transaction back
SQL ServerDeadlock
SQLiteA busy database

ErrConcurrency from SaveChanges is not retryable: running the same function again with the same loaded values would fail the same way.

Retry every transaction​

ant.WithRetry applies to every Tx and SaveChanges of a context. ant.Attempts overrides it for one call; other options, such as ant.Isolation, keep it.

db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn, ant.WithRetry(ant.Retry{Attempts: 5}))

A SaveChanges outside a transaction retries its own transaction. Inside a Tx, the transaction decides, and SaveChanges runs once per attempt.

On MySQL, MariaDB and SQL Server a deadlock rolls back the whole transaction, not just the statement. ant then marks the transaction lost: later statements in it return ant.ErrTxDone, and Tx rolls it back and retries it if it may. When the context ends during a retry, the error joins the context's and the conflict that caused the retry.

Check by hand​

Use ant.IsRetryable to write your own loop for work that doesn't fit in a Tx closure.

err := db.SaveChanges(ctx)

if ant.IsRetryable(err) {
log.Println("worth another try")
}
The function may run twice

A retried function runs again from the top, so it shouldn't change anything outside the database. Send the email after the commit, or from an observer.

Commit failures aren't retried: the transaction may already have committed. See when a commit fails.