2

I have a simple express server running on NodeJS and I want to perform database queries when receiving requests. My setup looks similar to this

var srv = require('express').createServer();
var db = new DbConnection(dsn);

srv.get('/', function (req, res) {
    var result = db.query(query);

    res.send(result);
});

srv.listen(80);

Will I have problems with concurrency ? What if two requests are being handled simultaneously and thus the querying is done simultaneously ?

I also thought about this approach

srv.get('/', function (req, res) {
    var db = new DbConnection(dsn);

    var result = db.query(query);

    res.send(result);
});

What do you thing is the best approach/practice to do this ?

Cristian Toma
  • 5,662
  • 2
  • 36
  • 43

1 Answers1

6

The key to node.js performance is to never block the thread.

var result = db.query(query);

is a big no no.

db.query(query, function(result) {
  res.send(result);
});

is the way queries for requests should be handled

connecting once should be fine, most databases have no issues with queues.

generalhenry
  • 17,227
  • 4
  • 48
  • 63
  • I understand that the strong point of NodeJS is its async behaviour. But I miss the point in which this behaviour will improve performance in a linear approach where no concurrency is implied (similar to mine). And I don't really see the point (and benefit) in your async approach in comparison with mine. And in fact the sync behaviour also has the benefit of linear exception propagation, which I leverage. – Cristian Toma Mar 29 '11 at 08:09
  • But thank you for your explanation of database concurrent access. I hope I won't stumble upon any problems in the future using a single connection. – Cristian Toma Mar 29 '11 at 08:21
  • 3
    @Christian Toma You are missing the point about node. The reason every IO is non-blocking and handled async is because it's just an event-loop, a single thread. If you make it synchronous like that you will not be able to handle another request before the db server returns, and your node server will just idle. It's the combination of an event-loop and non blocking IO that make node so fast. – Oscar Kilhed Mar 29 '11 at 21:59