Optimistic locking for concurrent updates

1063
0

When multiple users can update the same record simultaneously, optimistic locking prevents lost updates by detecting conflicts. Rails provides built-in support via a lock_version integer column that increments on every update. If two users load the same record and both submit updates, the second update raises ActiveRecord::StaleObjectError because the lock_version has changed. This gives the application a chance to handle the conflict gracefully, perhaps by asking the user to review changes or merging updates. Optimistic locking works well for scenarios where conflicts are rare but the consequences of lost updates are serious. For high-contention scenarios, I switch to pessimistic locking with lock! to prevent concurrent access entirely.