'DB Health Check in Rails
I am building an API to do a deep health check of my service.
Other than just doing a SomeTableWhichIsNeverEmpty.first == nil, is there a better way to check if my DB is up and available? Preferably, the solution would be sqlite3, postgres, and mysql compatible.
I'm on rails 3.
Solution 1:[1]
Take a look at https://github.com/blythedunham/health_monitor
Solution 2:[2]
11 years later, this post still sees some action so here's an update. I am now on Rails 7.
I create a dedicated table in the DB to which I can read and write to. Given that I wanted to make sure the db was writable, I didn't see any alternative. Since this is storing only timestamps, I felt the storage overhead was negligible. With an outside caller checking on regular intervals, it also gives a history of when we were available -- assuming the healthcheck service is operating normally, a gap in records would indicate a gap in availability.
class CreateDbStatusChecks < ActiveRecord::Migration[7.0]
def change
create_table :db_status_checks do |t|
t.timestamps
end
end
end
Then I create an empty model. My status check calls create and last in order to verify write and read access. Very simple.
def check_read
DBStatusCheck.last
rescue
false
end
def check_write
DBStatusCheck.create
rescue
false
end
Solution 3:[3]
You might want to check out newrelic. They do a pretty awesome job of monitoring rails and db health. It'd be hard to write something to compete and I think it's free for 1 or 2 rails apps.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | thekindofme |
| Solution 2 | John Hinnegan |
| Solution 3 | Upgradingdave |
