In the existing code, I found a money transfer procedure that is not completed by a transaction, should I panic?

In the existing code I am working with, I found a money transfer procedure that is not completed by a transaction, this is completely unacceptable or okay because there are all the necessary sanity checks, Ie that the amount of money to transfer is greater than zero and an ORM level check that balance is greater than or equal to zero.

The reason I am actually so puzzled in the first place is because it comes from a reputable developer, and this is the kind of piece of code that sees something like this without any transactions in sight is strange:

self.balance   -= amount
save!

target.balance += amount
target.save!

      

0


a source to share


4 answers


If you do not see any code, then I will make an educated guess that the existing code is NOT acceptable. Even with a sanity check, if the logout from this account occurs between statements in the "transfer" procedure, you will have a race condition in your code, resulting in a transfer of non-existent funds. The likelihood of this occurrence is greater if, of course, there are many concurrent users.



+4


a source


A transactional approach to database operations approaches - among others - two kinds of problems:

  • it provides protection against concurrent access
  • it provides a rollback mechanism


I don't see how any check can replace these two ...

+2


a source


Let me show you why this is bad with some pseudocode.

Two money transfers:

#1: How much money does George have? $1500, that is fine.
#1: Send $1000 to Martha.
#1: Take $1000 from George.

#2: How much money does George have? $500, this is not enough.  Give up!
#2: Do not send $1000 to Martha.
#2: Do not take $1000 from George.

      

What's really going on:

#1: How much money does George have? $1500, that is fine.
#2: How much money does George have? $1500, that is fine.
#1: Send $1000 to Martha.
#2: Send $1000 to Martha.
#1: Take $1000 from George.
#2: Take $1000 from George.

      

George has successfully transferred money that he doesn't have!

The more traffic your database generates, the more likely such a collision is.

+2


a source


Of course, you should fix this as soon as possible. A transaction is a logical unit of work that can include any number of file or database operations. Only a transaction can guarantee that everything is okay or not, and eludes you to recover the log from an unexpected random state.

0


a source







All Articles