When a commit fails
If the connection drops while a COMMIT is on its way, your code can't know whether the database received it. The transaction may have committed even though you see an error.
ant.Attempts and ant.WithRetry don't retry this case. They retry only failures known to have rolled back, which ant.IsRetryable decides: deadlocks and serialization failures (see databases for what each database reports).
When Tx returns a commit error, its observers don't run. If the context ended before the commit, ant rolls back instead and returns the context's error together with the rollback's.
Make the work safe to repeat
Give each operation a client-chosen key and store it in the same transaction behind a unique constraint. A retry finds the key and returns the first result.
type Entry struct {
ID int64
Key string `ant:"unique"`
}
var Entries = ant.Fields[Entry]()
func transfer(ctx context.Context, tx *AppDB, key string) (*Entry, error) {
existing, err := tx.Entries.Where(ant.Eq(&Entries.Key, key)).First(ctx)
// SELECT ... FROM "entries" WHERE "entries"."key" = $1 LIMIT $2
if err == nil {
return existing, nil // it committed after all
}
entry := &Entry{Key: key}
// INSERT INTO "entries" ("key") VALUES ($1) RETURNING "id"
return entry, tx.Entries.Insert(ctx, entry)
}
First returns ant.ErrNotFound when the key is new. Any other error is a real failure, so check errors.Is(err, ant.ErrNotFound) before inserting.
Two concurrent retries can both miss the key. The unique constraint stops the second insert; ant.IsUniqueViolation(err) tells you to read the first one's result.
The ledger example does this for transfers, and the audit example does it with event IDs.
Check afterwards
Where a client key doesn't fit, reconnect and look for the result, using something the transaction wrote.
Call SaveChanges again
A failed SaveChanges always runs in a transaction, or a savepoint inside one. On failure nothing is saved, generated keys are cleared and the pending changes stay in the tracker, so you can call it again. After a lost commit, check first or the rows go in twice.