Course contentsShow
← Databases & SQL
Lesson 1905 of 1,95318. Application Integration PatternsFree lesson

Optimistic Locking Implementation

Implement version-based concurrency control to prevent data corruption in high-concurrency read-modify-write cycles.

In this lesson, you will learn how to prevent the "lost update" problem in high-concurrency environments by implementing version-based concurrency control.

The Problem: Read-Modify-Write Conflicts

In a standard web application, a user reads a record, modifies it, and saves it back. If two users read the same record simultaneously, modify it, and attempt to save, the second user will inadvertently overwrite the changes made by the first. Pessimistic locking (locking the row) solves this, but it destroys performance in high-traffic systems. Optimistic Locking assumes conflicts are rare, checking for integrity only at the moment of the commit.

The Mechanism: Version Tracking

To implement this, we add a version column (an integer) to our database table. Every time a record is updated, we increment this version number.

When an application performs an update, it must include the version number it originally read in its WHERE clause:

-- Application logic:
-- 1. Read record: SELECT name, version FROM accounts WHERE id = 123; (Returns version 5)
-- 2. Modify: Change name to 'New Name'

-- 3. Update with version check:
UPDATE accounts 
SET name = 'New Name', version = version + 1 
WHERE id = 123 AND version = 5;

Why This Works

The database driver reports the number of rows affected by the UPDATE statement.

  • Success: If the query returns 1, the update was successful. No one else modified the record between your read and your write.
  • Failure: If the query returns 0, it means the version in the database is no longer 5. Someone else updated the record in the interim.

When the application detects 0 affected rows, it should catch the concurrency exception and handle it—typically by notifying the user or triggering an automatic retry. This approach keeps connections open for the shortest possible duration, as it avoids holding row-level locks while the application processes the business logic.

Key Takeaway: Optimistic locking uses a version column to ensure that an update only succeeds if the data has not been modified since it was last read, effectively preventing data corruption without the performance penalties of long-lived database locks.