Peter Marklund

Peter Marklund's Home

Mon Jun 16 2008 06:23:49 GMT+0000 (Coordinated Universal Time)

Rails Optimistic Locking - Not Worth it for Me

When I upgraded to Rails 2.1 ActiveRecord partial updates were turned on, i.e. when you save a record only those attributes that have changed are saved to the database. In theory, if you have two almost simulateneous updates, and you have a validation rule across several columns, then those updates can render the database record in an invalid state. Of course, in practice, this is very unlikely to happen. Nevertheless, I decided to turn on optimistic locking to be on the safe side. It turned out optimistic locking caused more issues than it was worth. Suppose you have an Article model that has many instances of Chapter and also that the Article uses a counter cache. Then you can run into this issue:

article = Article.first

article.chapters.create(:name => "Summary")
# => UPDATE articles SET chapters_count = chapters_count + 1,
#    lock_version = lock_version + 1 WHERE id = XXX;

article.publish_date = 1.days.from_now
article.save
# => throws ActiveRecord::StaleObjectError

I like partial updates though since they make it less likely that simulteneous updates will clobber, since you are only writing to the db what has changed. It also makes SQL statements in the log file more readable.

I'm abandoning optimistic locking for now though.