diff --git a/internal/storage/ledger/balances.go b/internal/storage/ledger/balances.go index 4137739df1..5d6c569867 100644 --- a/internal/storage/ledger/balances.go +++ b/internal/storage/ledger/balances.go @@ -3,6 +3,7 @@ package ledger import ( "context" "math/big" + "slices" "strings" "github.com/formancehq/go-libs/v2/platform/postgres" @@ -49,6 +50,21 @@ func (store *Store) GetBalances(ctx context.Context, query ledgercontroller.Bala } } + // prevent deadlocks by sorting the accountsVolumes slice + slices.SortStableFunc(accountsVolumes, func(i, j AccountsVolumesWithLedger) int { + if i.Account < j.Account { + return -1 + } else if i.Account > j.Account { + return 1 + } else if i.Asset < j.Asset { + return -1 + } else if i.Asset > j.Asset { + return 1 + } else { + return 0 + } + }) + // Try to insert volumes using last move (to keep compat with previous version) or 0 values. // This way, if the account has a 0 balance at this point, it will be locked as any other accounts. // If the complete sql transaction fails, the account volumes will not be inserted.