Add Optimistic Locking

This guide shows you how to add optimistic locking to prevent concurrent updates from overwriting each other.

When to Use

Use optimistic locking when:

  • Multiple users might edit the same record simultaneously

  • Conflicts are rare but data integrity is important

  • You want to avoid database-level row locks

Prerequisites

Your table needs a version column:

schema.table :users do
  primary :id, Int64, auto_increment: true
  column :name, String
  lock_version :version  # Adds integer column with default 1
  timestamps
end
schema.users.create!

Or add to an existing table:

Enable Optimistic Locking

Include the module and configure the version column:

Handle Updates

Updates automatically check the version:

Handle Conflicts

When a conflict occurs, reload and retry:

Retry with Limit

Implement retry logic with a maximum attempts:

How It Works

  1. Record is loaded with current version (e.g., version 5)

  2. When updating, CQL generates: UPDATE users SET name = ?, version = 6 WHERE id = ? AND version = 5

  3. If another process updated first (version is now 6), the WHERE clause matches 0 rows

  4. CQL raises OptimisticLockError

  5. Your code handles by reloading and retrying

Combine with Soft Deletes

You can use both modules together:

Verify It Works

Best Practices

  1. Always reload after conflict - Get latest data before retrying

  2. Limit retries - Avoid infinite loops

  3. Inform users - In UIs, tell users the data changed

  4. Use for important data - Not every table needs locking

  5. Test conflict scenarios - Write tests that simulate concurrent updates

Last updated

Was this helpful?