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:

  1. Add a lock_version column to the table.
  2. Rails automatically manages the lock_version column.
  3. When updating a record, Rails checks the lock_version to ensure it matches the current version in the database.

Example:

  1. 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
    
  2. Model: Rails automatically handles optimistic locking if the lock_version column is present.
    class Article < ApplicationRecord
    end
    
  3. 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

Both mechanisms help ensure data consistency and prevent race conditions when multiple processes or users attempt to edit the same object simultaneously.