Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node PostgreSQL timeout a query by the client

I'm using Node package pg for postgres (here):

npm i pg

var pg = require('pg');

I'm querying a large cluster which is not owned by me, and under certain conditions may fail. Failure may be bad response which is easy to handle or endless query. Please note I can not introduce changes [config or otherwise] on the DB side.

Is there any way to set a timeout for query time? I'd like my client to give up after a set time, and return timeout error.

Couldn't find anything as such in the docs.

Thanks from ahead!

like image 309
Selfish Avatar asked Aug 09 '15 12:08

Selfish


People also ask

What is statement timeout in PostgreSQL?

The timeout is measured from the time a command arrives at the server until it is completed by the server. If multiple SQL statements appear in a single simple-Query message, the timeout is applied to each statement separately.

What is difference between pool and client postgres?

You have two options that you can connect to a PostgreSQL server with the node-postgres module. One of the options is to use a single client. The other method is to use a connection pool. However, if your application is using the database very frequently, the pool will be a better option than using a single client.

What is Pgclient?

PostgreSQL client is defined as connect to the database server using command, utility or third party tool. Basically we are using psql utility to connect the database server from OS interface, also we are using pg_admin tool to interact with database server using client interface.


2 Answers

You can setup statement_timeout in the client:

const { Client } = require('pg')

const client = new Client({
  statement_timeout: 10000
})

or in the pool:

const { Pool } = require('pg')

const pool = new Pool({
  statement_timeout: 10000
})
like image 109
Shiva127 Avatar answered Oct 10 '22 19:10

Shiva127


Best practice is using an init query, to set query timeout for the session.

    SET statement_timeout TO 15000; # x milliseconds or 0 (turns off limitation)

This takes an argument of the timeout in ms, and is applied for the session. Afterwards, when a query takes longer than the value specified, you will receive an error from the server. Note this is on user's request:

    ERROR:  Query (150) cancelled on user's request

Also note this actually cancels the query on the server side, reducing load.

like image 23
Selfish Avatar answered Oct 10 '22 18:10

Selfish