Rails raises "PGError: Server unexpectedly terminated the connection" after some timeout

I have set up my Rails application as follows:

  • Rails: 3.0.5 (under Apache proxy), running on RHEL 5.6
  • Postgres: 8.4, running on Windows Server 2008 2 servers are on the same local network.

The problem is that after some downtime, when I make a new request to the Rails application, it causes the following error:

ActiveRecord::StatementInvalid (PGError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. 

From what I investigated, it seems that database connections are being deleted after some Postgres timeout. During this time, from Rails,

  • If I make a request to Rails (1st request), it will display a connection error as above
  • If I make another Rails request (second request), Rails seems to connect to Postgres again and function correctly.

This means that I will always experience the first connection error, and then again we will get all the normal work, which is very serious in my case, since I would like to provide an error response for my client.

I looked through the following questions and answers, but they do not seem to be suitable for my case:

Do you have any tips to make my application free of db connection errors? Thanks.

+6
source share
3 answers

We had this problem on Herek, a lot. As a hacker solution, here's what we did. Put the following in your ApplicationController:

 prepend_before_filter :confirm_connection def confirm_connection c = ActiveRecord::Base.connection begin c.select_all "SELECT 1" rescue ActiveRecord::StatementInvalid ActiveRecord::Base.logger.warn "Reconnecting to database" c.reconnect! end end 

Basically, it checks the connection on each controller. Scalability? Not really. But this fixed the problem for us.

+4
source

In database.yml, do you have the reconnect: true option to connect? eg:

 production: adapter: postgresql database: myapp username: deploy password: password reconnect: true 

I'm not sure about the specific error, but without this option you need to handle the class of expected db errors yourself.

+1
source

I encountered this error while continuing to live in the production process . I just opened my console and tried connecting PG db and it worked.

  RAILS_ENV=production rails c User.new 

and it worked after that.

hope this helps someone;)

0
source

Source: https://habr.com/ru/post/901086/


All Articles