How can I check the connection of Mongoid
We wanted to implement a health check for our running Mongoid client that tells us whether the established connection is still alive. This is what we came up with:
Mongoid.default_client.database_names.present?
Basically it takes your current client and tries to query the databases on its connected server. If this server is down, you will run into a timeout, which you can catch.
My solution:
def check_mongoid_connection mongoid_config = File.read("#{Rails.root}/config/mongoid.yml") config = YAML.load(mongoid_config)[Rails.env].symbolize_keys host, db_name, user_name, password = config[:host], config[:database], config[:username], config[:password] port = config[:port] || Mongo::Connection::DEFAULT_PORT db_connection = Mongo::Connection.new(host, port).db(db_name) db_connection.authenticate(user_name, password) unless (user_name.nil? || password.nil?) db_connection.collection_names return { status: :ok } rescue Exception => e return { status: :error, data: { message: e.to_s } } end
snrlx's answer is great.
I use following in my puma config file, FYI:
before_fork do begin # load configuration Mongoid.load!(File.expand_path('../../mongoid.yml', __dir__), :development) fail('Default client db check failed, is db connective?') unless Mongoid.default_client.database_names.present? rescue => exception # raise runtime error fail("connect to database failed: #{exception.message}") endend
One thing to remind is the default server_selection_timeout
is 30 seconds, which is too long for db status check at least in development, you can modify this in your mongoid.yml.