chester
chester

Reputation: 297

Oracle database connection is not released after it exceeds maximum idle time in Rails app

I have a Rails app using an Nginx HTTP server and a Unicorn app server. I'm getting the following error when the app server doesn't receive any requests for about 15min:

OCIError: ORA-02396: exceeded maximum idle time, please connect again

After a page refresh, the page loads fine.

I'm using rails 4.2.1, ruby-oci8 2.1.0, and active-record-oracle_enhanced-adapter 1.6.0.

I'm still relatively new to web development, but I'm thinking this error occurs when the oracle connection idles out but app server doesn't know that the connection is bad.

I've tried setting the reaping_frequency to every 15min, but that didn't fix the problem.

How can I manage the database connections and make sure that these idle connections are dropped? Can I set a timeout to drop database connections before oracle times out?

this is my config/unicorn.rb

app_dir = File.expand_path("../..", __FILE__)
shared_dir = "#{app_dir}/shared"
working_directory app_dir

worker_processes 2
preload_app true
timeout 15

listen "#{shared_dir}/sockets/unicorn.sock", :backlog => 64

stderr_path "#{shared_dir}/log/unicorn.stderr.log"
stdout_path "#{shared_dir}/log/unicorn.stderr.log"

pid "{shared_dir}/pids/unicorn.pid"

before_fork do |server,worker|
    if defined? ActiveRecord::Base
        ActiveRecord::Base.connection.disconnect!
    end
end

after_fork do |server,worker|
    if defined? ActiveRecord::Base
        ActiveRecord::Base.establish_connection
    end
end

Upvotes: 0

Views: 485

Answers (1)

chester
chester

Reputation: 297

Here is my fix, which isn't that great.

in the application controller:

before_action :refresh_connection

def refresh_connection
    puts Time.now.to_s + ' - refreshing connection'
    ActiveRecord::Base.connection.disconnect!

    if ActiveRecord::Base.establish_connection
        puts Time.now.to_s + ' - new connection established' 
    else
        puts Time.now.to_s + ' - new connection cannot be established'
    end
ebd

Upvotes: 1

Related Questions