10

i have a simple application linked up to a postgres database. it reads about 30 rows of data when you load up the application. but every now an then it wont load and when i look at my server i have the error Error: connection terminated.

usually if i load it up several times in a short space of time.

does anyone know why this might be happening? am i working it too hard?

the code is below:

    function getDB(callback){
        console.log('inside getDB')
        Client.connect(function(err){
            if(err){
                return console.log('connection error', err)
            }
            Client.query('SELECT * FROM gallery', function(err, result){
                if(err){
                    return console.log('error receiving data', err)
                } else{
                callback(null, result.rows)
                }
                Client.end()
            })

        })
    }

2 Answers 2

15

I ran into the same "Error: Connection terminated" error on a Node method that was inserting rows into a Postgres database. Here's how I was able to fix it.

The console error was not very helpful, so I looked at the Postgres logs. (using a Mac)

$ tail -10 /usr/local/var/log/postgres.log 
2019-02-24 10:06:38.920 CST [58520] LOG:  could not receive data from client: Connection reset by peer
2019-02-24 10:06:38.921 CST [58520] LOG:  unexpected EOF on client connection with an open transaction

This means that the client somehow dropped the connection before the server could finish. In my case, I did not call my asynchronous methods correctly so the client finished before the database statement could be executed and client dropped the DB connection. I used the async/await style Node methods and I forgot to call my async method with await, which caused the error.

Be sure to follow one of these examples for Postgres queries in Node.

Sign up to request clarification or add additional context in comments.

Comments

5

It looks like you're using node-postgres. You should consider using its connection pooling. From the documentation:

"Generally you will access the PostgreSQL server through a pool of clients. A client takes a non-trivial amount of time to establish a new connection. A client also consumes a non-trivial amount of resources on the PostgreSQL server - not something you want to do on every http request. Good news: node-postgres ships with built in client pooling."

There is a lot going on when creating a new connection and you should look to avoid it when possible. Taking advantage of pooling could help in your situation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.