Fix: PG::TRDeadlockDetected (MAYBE-RAILS-CE) #1621
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The deadlock issue occurs during concurrent inserts into the transfers table due to the unique index on inflow/outflow transaction IDs. When multiple processes try to create transfers simultaneously, they can attempt to acquire locks on the same transaction IDs but in different orders, leading to a circular wait condition.
Key changes made to the
auto_match_for_account
method:Added consistent transaction ID ordering:
Modified the transaction ID assignment logic:
[t1_id, t2_id].sort
)Maintains existing business logic:
Added comprehensive test coverage:
The original intent of the code was to match transfers based on opposing amounts within a date range, but it didn't account for concurrent execution patterns. The updated version maintains this functionality while adding thread-safety through consistent lock ordering.
Tip
You can make revisions or ask questions of Revise.dev by using
/revise
in any comment or review!/revise Add a comment above the method to explain why we're making this change.
/revise Why did you choose to make this change specifically?