What causes ActiveRecord breaking Postgres connection after forking?
Asked Answered
M

1

6

I have a Rake task in a Rails 4.2 project that uses fork. My problem is that after the forked process has finished (i.e. after Process.wait) I get the following Postgres error when I try to access the database again:

PG::ConnectionBad: PQconsumeInput() server closed the connection unexpectedly

At first I suspected ActiveRecord to automatically close the connection once the forked process finishes. But after reading the code of AR's connection_pool.rb it seems that forked processes should use their own connections:

A connection was established in an ancestor process that must have subsequently forked. We can't reuse the connection, but we can copy the specification and establish a new connection with it.

(from ActiveRecord::ConnectionAdapters::ConnectionHandler#pool_for_owner)

Nevertheless, forking renders the connection useless.

I tried to prevent the forked process from accessing the database at all and verified that the old connections cannot be reused with the following code after forking:

ActiveRecord::Base.default_connection_handler = nil
ActiveRecord::Base.connection_handler = nil

Any suggestions on how to solve this?

Mascarenas answered 11/1, 2015 at 22:47 Comment(1)
maybe the answer here helps? #13090375Neigh
R
1

After the child processes finish their work you can re-establish a connection to the DB with ActiveRecord::Base.establish_connection. Afterwards your Rake process should be able to access the DB as usual.

Rathskeller answered 9/3, 2016 at 18:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.