Pessimistic locking in Rails


  • Locking::Pessimistic provides support for row-level locking
  • Start a transaction and lock at the same time by calling with_lock with a block
class JournalEntry < ApplicationRecord  

  def post!
    with_lock do
      return unless pending? and balanced?
      items.each { |i|! }
      self.posted_at = Time.current; self.posted!


Calling lock with a find query is all that is needed to use pessimistic locking in Rails.

Toy.lock.find_by(name: 'racecar')

The above code will lock the racecar Toy until the end of the transaction. Calling lock outside of a transaction will only lock the record for the single call.

Decent tutorial and code

  • 0 posts
  • 0 subtopics
  • almost 2 years ago by vince