Skip to content

Instantly share code, notes, and snippets.

@ukazap
Forked from ryanermita/rails_locking.md
Created September 27, 2018 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ukazap/7eb207251ebb6a92c1b67a766b0a36d1 to your computer and use it in GitHub Desktop.
Save ukazap/7eb207251ebb6a92c1b67a766b0a36d1 to your computer and use it in GitHub Desktop.
Optimistic and Pessimistic Locking in Rails

Optimistic Locking assumes that a database transaction conflict is very rare to happen. It uses a version number of the record to track the changes. It raise an error when other user tries to update the record while it is lock.

usage

Just add a lock_version column to the table you want to place the lock and Rails will automatically check this column before updating the record.

Pessimistic locking assumes that database transaction conflict is very likely to happen. It locks the record until the transaction is done. If the record is currently lock and the other user make a transaction, that second transaction will wait until the lock in first transaction is release.

usage

user = User.lock.find(1) #lock the record
user.name = 'ryan'
user.save! #release the lock

or you can also use with_lock method to select and lock the record.

user = User.find(1)
user.with_lock do #lock the record
  # you can run other code here.
  user.name = 'ryan'
  user.save!
end

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment