Fix stonk deadlock by adding missing select_for_update #2
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.
Rules
For my solution I set myself the following additional rules:
I set these rules because otherwise my preferred solution would be to use
bulk updates. But based on the context I doubt that this is what you want
to see here.
Solutions
Potential ways to solve the database deadlock:
Remove the atomic.
Every stonk gets updated in a seperate transaction.
Problem: This only works if we assume that stonks won't get deleted
and is a really dirty fix which could cause inconsistent states.
Update in the same order
Deadlocks only happen if two or multiple updates (locks) in transactions are
interleaving and therefore blocking each other.
If the updates are ordered and there is an overlap one transaction will
secure the row level lock first and because of the ordering
the rest of the data is unlocked. Resolving the problem in this case.
Problem: This only works if we assume that every transaction does ordered
updates.
Select for update
Tell the Database that we want to update the selected data.
This will (on query execution) create a row level lock for every
stonk we fetch. If there is already a lock held by another transaction
for a row the query blocks until the lock is released.
I prefer the
select for update
solution in this case because it most precisely shows theintent and doesn't rely on assumptions.