SoFunction
Updated on 2024-11-15

django to solve the order concurrency problem [Recommended].

concurrent processing

When more than one user initiates an order request for the same product at the same time, checking the inventory of the product first and then modifying the inventory of the product will cause a resource competition problem, resulting in an abnormal final result of the inventory.

Solution:

pessimistic lock

When querying a record, that is, let the database for the record lock, lock the record can not be operated by others, using a syntax similar to the following

select stock from tb_sku where id=1 for update;
.select_for_update().get(id=1)

Pessimistic locks are similar to the mutex locks we add when competing for resources in multiple threads, and are prone to deadlocks and are not used much.

Optimist Lock

Optimistic lock is not a real lock, but in the update time to determine whether the inventory at this time is the previous query out of the inventory, if the same, that no one modified, you can update the inventory, otherwise it means that other people have grabbed the resources, and no longer perform inventory updates. Similar to the following operation

update tb_sku set stock=2 where id=1 and stock=7;
(id=1, stock=7).update(stock=2)

task queue

Put the logic for placing orders into a task queue (such as celery), turn parallel into serial, and everyone queues up to place orders. For example, turn on Celery with only one process, and process one order at a time.

summarize

The above is a small introduction to django to solve the order concurrency problem, I hope to help you, if you have any questions please leave me a message, I will promptly reply to you. I would also like to thank you very much for your support of my website!
If you find this article helpful, please feel free to reprint it, and please note the source, thank you!