0

I have a background with Java and I am relatively new to node. I am trying to understand node in relation to the fact that it is single threaded, but can still handle multiple requests at the same time. I have read about the single thread and the event loop, as well as the related stackoverflow questions, but I am still not sure I have understood it correctly, hence this question.

I have a simple http service that takes an id as an input. There can be multiple requests at almost the same time with the same id, and of course also other requests at almost the same time with other ids.

When the service is called, the following happens:

  1. Lookup id in DB (in a blocking manner, i.e. await)
  2. If the DB lookup did not find a result, insert id in DB

Let's say there are two requests at almost the same time, with the same id. My question is whether the following is possible:

  1. Request 1 makes the lookup in the DB -> no result
  2. Request 2 makes the lookup in the DB -> no result
  3. Request 1 inserts a new row
  4. Request 2 insert a new row

The blocking manner of the lookup makes me guess the answer is "no, that is not possible", but then I read that the blocking does not block the single thread. What makes me want to answer "yes, it is possible", is because I do not understand how several requests can be handled, if the above is not possible.

Thanks, -Louise

Lull
  • 365
  • 3
  • 14

1 Answers1

1

As far as I can determine the answer is "yes, that is possible". The "await" on the call to the DB ensures that the query has finished before we continue to the next line of code, but it does not block the thread. The thread continues with other tasks while awaiting the DB operation to finish, and those other tasks might be handling another request. This means that a race condition can happen between multiple requests.

Lull
  • 365
  • 3
  • 14