You can absolutely end up with the same timestamp on 2 concurrent calls. But not because NodeJS or your server served the request in parallel, but rather because a millisecond is a long enough time that your server could process many requests in the same millisecond.
Multi-threaded vs. Concurrent
You have correctly identified a subtle but important distinction between concurrency and multi-threading. In a multi-threaded environment, two different operations can truly take place at the same time on 2 different cores of a CPU. In a concurrent but single-threaded environment, things do happen sequentially, hopefully in a non-blocking manner, and really fast!
Javascript is a single threaded environment. And yes, it has an event loop where it queues tasks and processes them one at a time. NodeJS (and Web APIs in case of browser Javascript apps) offer certain async functions, such as fs.writeFile
or fetch
, which the runtime in collaboration with the OS may perform in the same or different thread/core, and then orchestrate returning results back to your application via callbacks and Promises.
In case of your example, your handler (the part starting from (req, res) => { ... }
) consists of sync calls only. So, yes, various calls to this handler will run sequentially, one after another. And, while no two runs of this handler will ever truly happen at the same time, but they will happen really fast and you will likely have cases where you'll get the same millisecond value from the Date object. If you had a higher resolution timestamp available (maybe nano seconds) or if your handler took longer to run (for example, you ran a for
loop a billion iterations), then you'll be able to observe the sequential behavior more clearly.
Avoid blocking (sync) calls in single-threaded applications
This is the exact reason why you are advised against performing any synchronous IO operation (e.g. fs.writeFileSync
, etc.) in a NodeJS web server, because while one request is performing a blocking IO operation, all other requests are waiting, queued on the event loop.
Really good video about Javascript event loop; this should illuminate some topics: https://www.youtube.com/watch?v=8aGhZQkoFbQ