V
V
vetsmen2019-08-28 17:18:45
JavaScript
vetsmen, 2019-08-28 17:18:45

What is the best way to organize a transaction?

There is an item in the cart, there is a method of checking for its presence in a third-party service. The validate method is called when trying to buy an item. If it was successful, the product is bought, if not, an error is displayed. The request takes about 10 seconds.
status: 1 - the item is in the cart
status: 2 - the item is being checked
status: 3 - the item is paid for
status: 4 - the item is not available in the third-party service
Problems:
1) Is it reasonable to use SQL transactions in this case? I start a transaction, get information about the product from the database, request its availability in a third-party service, update the product in the database, and only then do the commit. As I understand it, if someone else wants to buy an item, then he will not be able to do this, because the table is blocked for the duration of the transaction.
2) How can status: 2 be organized along with the transaction? After all, when the transaction starts, status: 1. When the transaction is completed, status: 3. How can I attach an intermediate status: 2 to this all?
The only solutions that come to mind are:
1. I start a transaction, get information about the product from the database, do checks, update status: 2 and make a commit.
2) I check the product for availability in a third-party service
3) If the response is successful / unsuccessful, I update the status of the product without a transaction status: 3/status: 1. Is the solution adequate?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2019-08-29
@vetsmen

I request its availability in a third-party service

Unreasonable. A third-party service may respond for a minute or two. All this time the transaction will hang in the database. This in itself is not bad, but it can lead to any consequences.
In principle, you need transactions only for atomicity, i.e. ensuring the consistent state of the database when changing several records at once. For example, to write off money from the account at the same time as changing the status to "paid". Table locks at creation time are bad. The "other user" request will just hang. Try to do it without transactions at all for a start, then look at the code to see what inconsistencies can occur. And then - according to the situation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question