<p>I have multiple applications that run using Node.js and pg (node-postgres).</p>
<p>The issue i have is that every app is getting the error &quot;Connection terminated unexpectedly&quot; every hour. Here is the error :</p>
<pre><code>&gt; node ./dist/app.js

App Started
events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: Connection terminated unexpectedly
    at Connection.con.once (/app/node_modules/pg/lib/client.js:255:9)
    at Object.onceWrapper (events.js:286:20)
    at Connection.emit (events.js:198:13)
    at Socket.&lt;anonymous&gt; (/app/node_modules/pg/lib/connection.js:139:10)
    at Socket.emit (events.js:203:15)
    at endReadableNT (_stream_readable.js:1145:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
    at connectedErrorHandler (/app/node_modules/pg/lib/client.js:202:10)
    at Connection.con.once (/app/node_modules/pg/lib/client.js:272:9)
    at Object.onceWrapper (events.js:286:20)
    [... lines matching original stack trace ...]
    at process._tickCallback (internal/process/next_tick.js:63:19)
</code></pre>
<p>Here is how i connect my Client to the database :</p>
<p>Database.ts:</p>
<pre><code>import { Client, QueryResult } from 'pg';

export default class DatabaseModule {

    private client: Client;

    constructor() {
        this.client = new Client({
            connectionString: process.env.DATABASE_URL
        });
    }

    public init(): Promise&lt;any&gt; {
        return this.client.connect();
    }
}
</code></pre>
<p>app.ts:</p>
<pre><code>Promise.all([
    express.init(),
    database.init()
])
.then(() =&gt; {
    console.log(&quot;App Started&quot;);
    [load routes...];
})
.catch((error) =&gt; {
    console.error(error);
    process.exit(1);
});
</code></pre>
<p>All works fine on local but not on production.</p>
<p>On production we are running every app as micro services in Google Kubernetes Engine. Is there any config in K8s that may cause this connection loss every hour ? (even if the Client is idle or not idle, this error happens)</p>
<pre><code>NAME                                                    READY   STATUS    RESTARTS   AGE
my-service-57c9f99767-wnm47                             2/2     Running   96         4d
</code></pre>
<p>As you can see, my app has 96 restarts: 4 days * 24 hours = 96 =&gt; error every hour that crashs the pod.</p>
<p>We are using a postgreSQL server hosted by Google Cloud SQL, and every app in K8s has an access to it with a local address.</p>
<p>EDIT:</p>
<p>I just found this in the Google Cloud SQL documentation :
<code>WebSockets are always available to your application without any additional setup. Once a WebSockets connection is established, it will time out after one hour.</code></p>
<p>So the error was generated from the usage of pg.Client with a persistent connection to the SQL server. I will try to use pg.Pool().
Here is the explanation of why i should use pool instead of client : <a href="https://stackoverflow.com/a/48751665/12052533">https://stackoverflow.com/a/48751665/12052533</a></p>

<p>I found the problem :</p>
<p>In the Google Cloud SQL documentation : <code>WebSockets are always available to your application without any additional setup. Once a WebSockets connection is established, it will time out after one hour.</code></p>
<p>The error was generated by the usage of pg.Client() because i had a persistent connection into my database which is a bad practice. A client shall connect to the database then end its connection after it finished executing a query.</p>
<p>I will use pg.Pool() as it will generate clients and it is better for multiple requests.
After the generation of a client i juste have to release all my clients.</p>
<p>I removed the database.init() and modified the database.query() function like the following :</p>
<pre class="lang-js prettyprint-override"><code>     public query(command: string, args?: Array&lt;any&gt;): Promise&lt;QueryResult&gt; {
        if (args === undefined)
            args = [];
        return this.pool.connect()
            .then((client: Client) =&gt; {
                return this.queryClient(client, command, args)
            })
            .then((result: QueryResult) =&gt; {
                return result;
            })
            .catch((error) =&gt; {
                throw error;
            });
    }

     private queryClient(client: Client, command: string, args?: Array&lt;any&gt;): Promise&lt;QueryResult&gt; {
        return client.query(command, args)
            .then((result: QueryResult) =&gt; {
                client.release();
                return result;
            }).catch((error) =&gt; {
                client.release();
                throw error;
            })
    }
</code></pre>
