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...

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.) Commented Sep 14, 2018 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). Commented Sep 14, 2018 at 11:22
  • This related QA might help you understand how concurrency is handled in node: stackoverflow.com/q/30638549/263525 Commented Sep 14, 2018 at 11:24
  • If you want count to grow, just do an async operation (like reading a file) in your get handler Commented Sep 14, 2018 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. Commented Sep 14, 2018 at 11:34

1 Answer 1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.