3

I understand that nodejs is asynchronous, so under the covers there is a single thread that communicates with the operation system. The operating system manages when to wake up and send a signal to that thread about a response etc.

The issue is which I don't understand, how is concurrency handled if there is only 1 thread?

e.g. say in nodejs the server has an endpoint that saves large xml files

If you get 100 requests at the same time, won't it block since these calls are fairly heavy and it may take a long time to parse and save the xml file to the db?

loyalflow
  • 14,275
  • 27
  • 107
  • 168

1 Answers1

3

There is no concurrency in "your" code in Node.js. There are some threaded operations for file I/O, but everything else runs on a single thread. This means that if your request handlers take a long time to complete, then throughput will suffer accordingly.

In general, the "solution" to this is to write your code such that it doesn't do large amounts of processing at once. The standard libraries in Node make this easier for file i/o, since they manage a thread pool for you to make them asynchronous. For something like parsing a massive XML file, you'll have to find a library that exposes an event-driven interface, and hope/check that it actually implements the parsing in a way that occasionally yields control to the event loop. Luckily, there's npm, so you can probably find a half-dozen modules with varying levels of quality that do just that.

On the database I/O side, you're generally going to communicate with a remote database via socket I/O, so you get asynchronous operation "for free".

Mark Bessey
  • 19,598
  • 4
  • 47
  • 69