What is optimistic vs pessimistic locking in Rails?
Answer
Optimistic locking assumes conflicts are rare — multiple users can read the same record simultaneously. When saving, Rails checks a lock_version integer column; if another user already updated the record, it raises ActiveRecord::StaleObjectError, which you rescue and retry. Enable by adding a lock_version column. Pessimistic locking acquires a database-level lock preventing other transactions from reading or writing: User.lock.find(id) issues SELECT ... FOR UPDATE. Use pessimistic locking for financial transactions where stale reads are unacceptable. Use optimistic locking for high-read, low-conflict scenarios like CMS editing.
Previous
What is the difference between class methods and instance methods in ActiveRecord?
Next
What is ActiveRecord's STI vs polymorphic associations — when to use each?
More Ruby on Rails Questions
View all →- Advanced What is metaprogramming in Ruby/Rails and give examples?
- Advanced What is the difference between include, extend, and prepend in Ruby?
- Advanced How does Rails handle database connection pooling?
- Advanced What is Rack and how does Rails relate to it?
- Advanced What is query optimization with explain in Rails?