views:

30

answers:

2

Hi!

In my Rails 2.3 app there is a possible situation when database is down, but app still should work. I.e. I need to disable part of my application when database is down. E.g., have some method like is_database_up? that will return true if database is up. For now, if database crushes, whole app will crush too. Is there any way to handle this situation?

P.S.: I'm actually asking "What to put inside is_database_up?". I.e. is there any way to catch ActiveRecord exceptions and tell ActiveRecord not to use any database? Or is there any way to understand that database is down during runtime by any ActiveRecord method. Something like this.

A: 

Well, the best way to deal with this is to make sure the application database never goes down. Maybe you do this by connecting to another database which slaves the one which can go up and down, so that if the master db goes down the slave continues and then updates/gets updated by the master once the master comes back. Then you are removed from the instability of the master db. That's a better solution.

But, to answer your question:

At the start of each request, you need to look at whether the database is up or down, and then react accordingly. Eg, if they try to do something that needs the db, then you need to redirect them somwehere else.

I would do this with a before_filter in ApplicationController, something like

before_filter :requires_database
...
protected
def requires_database
  redirect_to root_path unless database_is_up?
end

You can then ignore this filter in the pages (presumably a minority of the pages of the website) that don't need the db, with (eg)

#in home_controller
skip_before_filter :requires_database

You're then left with the problem of what happens if the db goes down halfway through a request. This is a pretty horrible situation to try and deal with, i'm not going to get into this right now. Basically avoid the possibility if you can.

Max Williams
Well, actually the question was - 'what is the content of database_is_up?', sorry if I wasn't clear. :) But your point is clear - make sure that database never goes down by relying to another 'slave' database. Thanks!
Yojik
cool, tick me for my wise advice then :)
Max Williams
A: 

You can use ActiveRecord::Base.connected?

mikezter