Optimistic Offline Locks solves the problem by validating changes about to be comitted by one session don’t conflict with changes of another session.
Optimistic Offline Locks uses a version number for each object or record in a database table. The validation works by comparing the version number stored in the session data to the current version number in the record data. If the validation passes, then the object can be updated and the version number incremented.
Ruby on Rails
Ruby on Rails provides several mechanisms to handle the locking of objects to ensure data consistency and prevent race conditions when multiple processes or users attempt to edit the same object simultaneously. The two primary types of locking mechanisms in Rails are Optimistic Locking and Pessimistic Locking.
Optimistic Locking is a technique where each record has a version number that gets incremented every time the record is updated. When an update is attempted, Rails checks the version number to ensure that the record has not been modified by another process since it was last read.
How It Works:
- Add a
lock_version
column to the table. - Rails automatically manages the
lock_version
column. - When updating a record, Rails checks the
lock_version
to ensure it matches the current version in the database.
Example:
- Migration: Add a
lock_version
column to the table.class AddLockVersionToArticles < ActiveRecord::Migration[6.0] def change add_column :articles, :lock_version, :integer, default: 0, null: false end end
- Model: Rails automatically handles optimistic locking if the
lock_version
column is present.class Article < ApplicationRecord end
- Usage: When updating an article, Rails checks the
lock_version
.article = Article.find(1) article.title = "New Title" article.save
If another process has updated the article since it was last read, Rails raises an
ActiveRecord::StaleObjectError
.
Summary
- Optimistic Locking: Uses a
lock_version
column to detect conflicts and raise an error if a record has been modified by another process since it was last read. It is suitable for scenarios where conflicts are rare. - Pessimistic Locking: Locks a record for the duration of a transaction, preventing other processes from modifying it until the lock is released. It is suitable for scenarios where conflicts are likely and need to be prevented.
Both mechanisms help ensure data consistency and prevent race conditions when multiple processes or users attempt to edit the same object simultaneously.