node-postgres icon indicating copy to clipboard operation
node-postgres copied to clipboard

My node server can process only one request at a time?

Open johnwu5 opened this issue 10 years ago • 4 comments

Hi, I'm trying to test how the non-blocking works for node-postgres. Below is the the code from the example. I added a console.log('111') to the beginning of the handler, and add pg_sleep(5) to the 3rd query so Postgres will pause 5 seconds to respond. My understanding is when a request comes in, the server should print '111' to console immediately and connect to Postgres which will sleep for 5+ seconds, because IO is not blocking, the server should be able to process new requests while Postgres is sleeping. But seems this is not the case according to my test, when I send 2 requests to the server at the same time, it always print '111', '222', '333', '111', '222', '333'. Which indicates it process one request after the other is completed. What am I doing wrong here? Thanks in advance.

var http = require('http');
var pg = require('pg');

var conString = "postgres://postgres:@localhost/database";

var server = http.createServer(function(req, res) {
  console.log('111');

  // get a pg client from the connection pool
  pg.connect(conString, function(err, client, done) {

    var handleError = function(err) {
      // no error occurred, continue with the request
      if(!err) return false;

      // An error occurred, remove the client from the connection pool.
      // A truthy value passed to done will remove the connection from the pool
      // instead of simply returning it to be reused.
      // In this case, if we have successfully received a client (truthy)
      // then it will be removed from the pool.
      if(client){
        done(client);
      }
      res.writeHead(500, {'content-type': 'text/plain'});
      res.end('An error occurred');
      return true;
    };

    // handle an error from the connection
    if(handleError(err)) return;

    // record the visit
    client.query('INSERT INTO visit (date) VALUES ($1)', [new Date()], function(err, result) {
      console.log('222');

      // handle an error from the query
      if(handleError(err)) return;

      // get the total number of visits today (including the current visit)
      client.query('SELECT COUNT(date) AS count, pg_sleep(5) FROM visit', function(err, result) {
        console.log('333');

        // handle an error from the query
        if(handleError(err)) return;

        // return the client to the connection pool for other requests to reuse
        done();
        res.writeHead(200, {'content-type': 'text/plain'});
        res.end('You are visitor number ' + result.rows[0].count);
      });
    });
  });
})

server.listen(3000)

johnwu5 avatar Jan 10 '16 11:01 johnwu5

You are picking just one client from the pool, pick a new one for each query you want to happen simultaneously

Aconradty avatar Jan 19 '16 08:01 Aconradty

I think @Aconradty is incorrect here -- it looks to me like each request coming into the http server will get its own client from the pool.

I've tried playing around with your example code, and I have a modified version which I think proves the blocking behavior is coming from the http module, not pg. It seems the http module won't feed you another incoming request until after the previous one is fully handled (via res.end()) -- this is surprising to me. So, perhaps this issue should actually be raised on the node core http module?

Here is my counter-example:

var http = require('http');
var pg = require('pg');

var conString = "postgres://user:pass@localhost:5432/test_db";

var server = http.createServer(function(req, res) {
  if (req.url == '/favicon.ico') {
    res.writeHead(404);
    res.end('File not found.');
    return;
  }

  console.log('111');

  // get a pg client from the connection pool
  pg.connect(conString, function(err, client, done) {

    var handleError = function(err) {
      // no error occurred, continue with the request
      if(!err) return false;

      // An error occurred, remove the client from the connection pool.
      // A truthy value passed to done will remove the connection from the pool
      // instead of simply returning it to be reused.
      // In this case, if we have successfully received a client (truthy)
      // then it will be removed from the pool.
      if(client){
        done(client);
      }
      res.writeHead(500, {'content-type': 'text/plain'});
      res.end('An error occurred');
      return true;
    };

    // handle an error from the connection
    if(handleError(err)) return;

    // record the visit
    client.query('INSERT INTO visit (date) VALUES ($1)', [new Date()], function(err, result) {
      console.log('222');

      // handle an error from the query
      if(handleError(err)) return;

      // get the total number of visits today (including the current visit)
      client.query('SELECT COUNT(date) AS count, pg_sleep(5) FROM visit', function(err, result) {
        console.log('333');

        // handle an error from the query
        if(handleError(err)) return;

        // return the client to the connection pool for other requests to reuse
        done();

        console.log('444');
        setTimeout(function () {
          console.log('555');
          res.writeHead(200, {'content-type': 'text/plain'});
          res.end('You are visitor number ' + result.rows[0].count);
          setTimeout(function () {
            console.log('666');
          }, 5000);
        }, 5000);
      });
    });
  });
})

server.listen(3000);

Logs 111-555 all happen in order, and it is only 666 which can occur out of order -- the part that takes place after res.end().

I think this ticket can be closed, as there is no reason to suspect pg given my version of the snippet.

zacronos avatar Feb 09 '16 05:02 zacronos

Here's a better example, which proves that node-postgres is not the problem:

var http = require('http');
var pg = require('pg');

var conString = "postgres://user:pass@localhost:5432/test_db";

function doQueries(prefix, callback) {
  prefix = ''+prefix;

  // get a pg client from the connection pool
  pg.connect(conString, function(err, client, done) {

    var handleError = function(err) {
      // no error occurred, continue with the request
      if(!err) return false;

      // An error occurred, remove the client from the connection pool.
      // A truthy value passed to done will remove the connection from the pool
      // instead of simply returning it to be reused.
      // In this case, if we have successfully received a client (truthy)
      // then it will be removed from the pool.
      if(client){
        done(client);
        callback(err);
      }
      return true;
    };

    // handle an error from the connection
    if(handleError(err)) return;

    // record the visit
    client.query('INSERT INTO visit (date) VALUES ($1)', [new Date()], function(err, result) {
      console.log(prefix+'-222');

      // handle an error from the query
      if(handleError(err)) return;

      // get the total number of visits today (including the current visit)
      client.query('SELECT COUNT(date) AS count, pg_sleep(5) FROM visit', function(err, result) {
        console.log(prefix+'-333');

        // handle an error from the query
        if(handleError(err)) return;

        // return the client to the connection pool for other requests to reuse
        done();
        // finish doQueries
        callback(null, result);
      });
    });
  });
};

var server = http.createServer(function(req, res) {
  if (req.url == '/favicon.ico') {
    res.writeHead(404);
    res.end('File not found.');
    return;
  }

  console.log('111');

  var calls = 0;
  var finished = 0;
  var maxCount = 0;
  var finish = function(err, result) {
    if (finished > calls) return;
    if (err) {
      finished = Number.MAX_VALUE;
      res.writeHead(500, {'content-type': 'text/plain'});
      res.end('An error occurred');
      return;
    }

    finished++;

    maxCount = Math.max(result.rows[0].count, maxCount);

    if (finished === calls) {
      console.log('444');
      setTimeout(function () {
        console.log('555');
        res.writeHead(200, {'content-type': 'text/plain'});
        res.end('You are visitor number ' + maxCount);
        setTimeout(function () {
          console.log('666');
        }, 5000);
      }, 5000);
    }
  };

  doQueries(++calls, finish);
  doQueries(++calls, finish);
  doQueries(++calls, finish);
})

server.listen(3000);

It gets a little weird since it is no longer counting "visits" (it counts 3 visits per page hit), but it does prove that the queries happen in parallel, as the 222's happen in parallel, and then the 333's, rather than 222 then 333 each time. My example output:

111
1-222
3-222
2-222
1-333
3-333
2-333
444
555
666

zacronos avatar Feb 12 '16 16:02 zacronos

Thanks for the help.

johnwu5 avatar Feb 20 '16 10:02 johnwu5