0

I'm trying to connect to a postgres database. If it takes more than 1/2 a second to connect(), I'd just like to timeout and assume it's unavailable. Unfortunately, if I change the config to an unreachable host/port, I'm seeing a hang time of about 15 seconds before I get an ETIMEDOUT. In the following code snippet example, I expect it to timeout 100% of the time because connecting to any database, no matter if it is reachable or not, is going to take longer than 1ms, specified in idleTimeoutMillis.

// npm install pg
var pg = require("pg");
var config = {
    "host": "myAWS-RDSinstance",
    "port": 5432,
    "database": "my_db",
    "user": "postgres",
    "password": "foobar",
    "idleTimeoutMillis": 1 // one millisecond = should timeout every time
};
var pool = new pg.Pool(config );
pool.connect(function(err, client, done){
    if(err) {
        return console.error('error fetching client from pool', err);
    }
    console.log("connected. attempting query.");

    client.query("SELECT COUNT(*) FROM my_table", function(err, result){
        done(); // release client to pool

        if(err) throw err;
        console.log(result.rows[0]);
    });
});

1 Answer 1

0

It turns out that you need to set the timeout for the pool's stream object, not the timeout of the pool itself. Below is code that will timeout and destroy the stream if it's open for more than half a second.

// npm install pg
var pg = require("pg");
var net = require("net");

var stream = new net.Stream();
stream.setTimeout(500, function(err, data){
    console.log("Reached timeout after half a second");
    stream.destroy();
});

var config = {
    "host": "myAWS-RDSinstance",
    "port": 5432,
    "database": "my_db",
    "user": "postgres",
    "password": "foobar",
    "stream": stream
};
var pool = new pg.Pool(config );
pool.connect(function(err, client, done){
    if(err) {
        return console.error('error fetching client from pool', err);
    }
    console.log("connected. attempting query.");

    client.query("SELECT COUNT(*) FROM my_table", function(err, result){
        done(); // release client to pool

        if(err) throw err;
        console.log(result.rows[0]);
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

I'm having issues with this solution. When a new client is created inside the pool it will try to use the same stream instance (since the config object is passed internally to pg.Client), failing with: "/usr/bin/nodejs[8673]: ../src/stream_base.h:233:void node::StreamBase::Consume(): Assertion `(consumed_) == (false)' failed."

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.