2

Can you give a hint why is express handling one request at a time? I thought that it should be able to do multiple at once.

const express = require('express');
const app = express();
var count = 0;

app.get('/', (req, res) => {
    count++;
    if (count > 1) {
        console.log('concurrent!');
        debugger;
    }
    console.log(count);
    count--;
    res.send('Hello World!');
});

app.listen(1333, () => console.log('Example app listening on port 1333!'));

I'm never getting the case with the debugger no matter what. Tried to send multiple reqs with ab:

ab -n 100 -c 100 -m GET localhost:1333/

They are always waiting for each other...

Vans
  • 115
  • 1
  • 5
  • 3
    What do you exactly mean ? Your handler is 100% synchronous. The engine will only run one of them at a time. You'll have several handlers executed in "parallel" as soon as you have asynchronous operations (DB queries, file reading, etc.) – Denys Séguret Sep 14 '18 at 11:19
  • I'm firing 100 simultaneous requests to that handler and I was expecting that it would not wait for each response to finish before processing the next one). – Vans Sep 14 '18 at 11:22
  • This related QA might help you understand how concurrency is handled in node: https://stackoverflow.com/q/30638549/263525 – Denys Séguret Sep 14 '18 at 11:24
  • If you want count to grow, just do an async operation (like reading a file) in your get handler – Denys Séguret Sep 14 '18 at 11:26
  • And if do sync operation it will be blocked until it finishes. Actually sync operation blocks all handlers, not just the one in use but this is in the nature of Node. Just thought that Express handlers work async. – Vans Sep 14 '18 at 11:34

1 Answers1

3

Node "single thread", I mean the event loop of Node is single threaded, it as nothing to do with express. Only "IO" are managed asynchronously like DB queries, file read etc...

Here you have basic code without IO so each request are handled one by one and will finish on the order there were launched. If you had asynchrone call it would not be the case.

You can check this article for more detail : https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/

xrobert35
  • 2,488
  • 1
  • 16
  • 15