Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
Handling errors and recoverying with node pg (postgres) client

I am using node module pg in my application and I want to make sure it can properly handle connection and query errors.

The first problem I have is I want to make sure it can properly recover when postgres is unavailable.

I found there is an error event so I can detect if there is a connection error.

import pg from 'pg'
let pgClient = null
async function postgresConnect() {
  pgClient = new pg.Client(process.env.CONNECTION_STRING)
  pgClient.connect()

  pgClient.on('error', async (e) => {
    console.log('Reconnecting')
    await sleep(5000)
    await postgresConnect()
  })
}

I don't like using a global here, and I want to set the sleep delay to do an small exponential backoff. I noticed "Reconnecting" fires twice immediately, then waits five seconds and I am not sure why it fired the first time without any waiting.

I also have to make sure the queries execute. I have something like this I was trying out.

async function getTimestamp() {
  try {
    const res = await pgClient.query(
      'select current_timestamp from current_timestamp;'
    )
    return res.rows[0].current_timestamp
  } catch (error) {
    console.log('Retrying Query')
    await sleep(1000)
    return getTimestamp()
  }
}

This seems to work, but I haven't tested it enough to make sure it will guarantee the query is executed or keep trying. I should look for specific errors and only loop forever on certain errors and fail on others. I need to do more research to find what errors are thrown. I also need to do a backoff on the delay here too.

It all "seems" to work, I don't want to fail victim to the Dunning-Kruger effect. I need to ensure this process can handle all sorts of situations and recover.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!