N
N
Nikita Kornilov2020-10-28 22:53:22
Node.js
Nikita Kornilov, 2020-10-28 22:53:22

How to correctly implement the processing of simultaneous requests to the backend?

Hello! I use Node.js and the google-spreadsheet npm package as a backend for a Telegram bot that tracks the amount of products in stock and allows you to place an order for a certain amount of this product. All data is taken from Google Spreadsheet. When ordering, the bot checks the balance of products in the warehouse and, if the desired volume does not exceed the balance, forms an order.

The essence of the problem is that when two users place an order at the same time, between checking the balance and placing an order for one of the users, a second order can be formed. JavaScript works asynchronously, with non-blocking I/O, and this happens regularly. The script checks the available balance, the second order is formed, and after that the initial order is formed. This results in two orders for a total volume that exceeds the available balance.

Can you please tell me how to deal with this situation and how to avoid such confusion, while maintaining asynchrony and other advantages of using Node.js?

A similar situation occurs when working with files - if you read the file, change the received data and save it, and change the file with a third-party script in between these operations, then part of the data will be lost. The essence is the same.

I hope for your help. Thanks!)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-10-29
@Nikkorfed

You really touched on this serious problem.
there are two options
- either make locks at the database level, where bearded guys thought about such a problem and came up with different solutions (and you will need a normal database)
- or change the system so that there is no such problem at all - ensure that only one order is processed at a time , if your script works in a single instance, then you can suspend the processing of all other orders if one is already being processed. For example, start a queue, when an application arrives, put it in this queue, take and process one at a time from beginning to end, and when one order is completely completed and formed, take the next one, process it.
blocking some of your blocking over Google tables is a disastrous thing, you will reduce the probability, but not completely remove it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question