0

After referring to Node.js server with multiple concurrent requests, how does it work?

I still can't fathom how Node.js works with MongoDB in terms of concurrency.

For example, I have a API where user will checkout from the shopping cart. (e.g in the inventory there are 2 shoes available, and there are 3 users buying it at the same time. Expected result is the 3rd user will not be able to purchase it. But how does it know which user will not get the shoes?)

When the checkout button is pressed, I can use "transactions" in Mongodb to ensure that all process (e.g. charge the customer, update inventory reduce count by 1, add item to shipping for that user) will only write if all process are successful.

But what if there are 3 transactions happening at the same time? Or am I being too paranoid and this scenario won't happen in real life.

How can I simulate this using postman? or curl?

I would like to achieve something like what firebase is offeringwhen working with complex data that could be corrupted by concurrent modifications, such as incremental counters.

user1872384
  • 6,886
  • 11
  • 61
  • 103

1 Answers1

3

I tried something similar once using Postman. I was generating an ID for users registering into an app, which would auto increment. So, basically first user gets ID 1, second user gets ID 2 and so on. To generate an ID I was getting the largest ID from mongodb, increment it by 1 and assign it to the next user. Now, what would happen if 2 users register at the same time. I simultaneously registered 2 users using Postman and the result was just as I expected, they both got the same ID. Now, how do you prevent it? You can do so by using locks. You will have to use MongoDB lock for the collection, so only one user can access it at at a time.

Praveen Rewar
  • 952
  • 1
  • 7
  • 18