Prevent Concurrency In Nodejs

↘锁芯ラ 提交于 2020-01-14 17:52:32

问题


I have built a Ecommerce Backend in Nodejs(Express), Lets say there a product and only 1 quantity is left and two users are trying to buy that product at the same time both are getting that product leaving minus value in the quantity section of my Mysql Db

How to get rid of this , Suggestions will be helpful

Thank you


回答1:


Database Transaction Isolation Levels

This can be accomplished in your database by leveraging guarantees from your specific DB (mysql).

The default isolation level for postgres/mysql allow for 2 concurrent reads to see the same data, and then have each one overwrite the other (on a write).

The postgres documentation provides an excellent example of this case:

Because of the above rule, it is possible for an updating command to see an inconsistent snapshot: it can see the effects of concurrent updating commands on the same rows it is trying to update, but it does not see effects of those commands on other rows in the database. This behavior makes Read Committed mode unsuitable for commands that involve complex search conditions; however, it is just right for simpler cases. For example, consider updating bank balances with transactions like:

BEGIN;
UPDATE accounts SET balance = balance + 100.00 WHERE acctnum = 12345;
UPDATE accounts SET balance = balance - 100.00 WHERE acctnum = 7534;
COMMIT;

If two such transactions concurrently try to change the balance of account 12345, we clearly want the second transaction to start with the updated version of the account's row. Because each command is affecting only a predetermined row, letting it see the updated version of the row does not create any troublesome inconsistency.

...

The partial transaction isolation provided by Read Committed mode is adequate for many applications, and this mode is fast and simple to use; however, it is not sufficient for all cases. Applications that do complex queries and updates might require a more rigorously consistent view of the database than Read Committed mode provides.



来源:https://stackoverflow.com/questions/59310302/prevent-concurrency-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!