DEV Community

Cover image for Understanding Optimistic Locking: Handling Conflicts in Concurrent Systems
Faiz Ahmad
Faiz Ahmad

Posted on

Understanding Optimistic Locking: Handling Conflicts in Concurrent Systems

In modern applications, where multiple users might try to access or update the same data simultaneously, ensuring data consistency while allowing concurrency is critical. One common way to manage this is through optimistic locking. This article will explain optimistic locking, walk through an example scenario, and explore when it’s appropriate to use and when it’s not.


What is Optimistic Locking?

Optimistic locking is a concurrency control mechanism used to manage simultaneous updates to the same data in a database. It assumes that conflicts are rare and allows multiple users to proceed with their operations without locking the data. At the time of committing the changes, optimistic locking checks if any conflict has occurred (i.e., if the data was modified by another user). If a conflict is detected, the transaction fails, and the user must retry.

Unlike pessimistic locking, which prevents conflicts by locking data during a transaction, optimistic locking allows changes to proceed concurrently but checks for conflicts only when changes are committed.

Use Case for Optimistic Locking

Optimistic locking is ideal in scenarios where conflicts are unlikely but must still be handled gracefully when they occur. This makes it useful in collaborative applications, such as:

  • Document editing systems (e.g., wikis or blog posts), where multiple users may edit the same document.
  • Shared shopping carts, where multiple users might add or update items simultaneously.
  • Content management systems (CMS), where users may update posts or entries without frequent overlapping changes.

Example Scenario: Conflict Detection with Optimistic Locking

Let’s explore how optimistic locking works in a database by simulating two users trying to update the same document simultaneously. We’ll use MySQL commands to illustrate this scenario.

Step 1: Initial Setup

Assume we have a documents table with a version number that tracks changes:

CREATE TABLE documents (
    id INT PRIMARY KEY AUTO_INCREMENT,
    title VARCHAR(255),
    content TEXT,
    version INT DEFAULT 1  -- Version number for optimistic locking
);
Enter fullscreen mode Exit fullscreen mode

We insert an initial document:

INSERT INTO documents (title, content) VALUES ('My First Document', 'This is the initial content.');
Enter fullscreen mode Exit fullscreen mode

Now, both users will attempt to modify the document simultaneously.

Step 2: Simulating Two Users Editing the Document

User A (First Transaction)
  1. Start a Transaction:
   START TRANSACTION;
Enter fullscreen mode Exit fullscreen mode
  1. Read the Document:
   SELECT title, content, version FROM documents WHERE id = 1;
Enter fullscreen mode Exit fullscreen mode

User A sees the content and the version of the document (version = 1).

  1. Update the Document:
   UPDATE documents
   SET content = 'This is User A’s updated content.', version = version + 1
   WHERE id = 1 AND version = 1;
Enter fullscreen mode Exit fullscreen mode

This update checks that the document’s version is still 1. If so, it updates the content and increments the version number.

  1. Commit the Transaction:
   COMMIT;
Enter fullscreen mode Exit fullscreen mode

Now, User A has successfully updated the content, and the version number of the document is incremented to 2.

User B (Second Transaction)
  1. Start a Transaction:
   START TRANSACTION;
Enter fullscreen mode Exit fullscreen mode
  1. Read the Document:
   SELECT title, content, version FROM documents WHERE id = 1;
Enter fullscreen mode Exit fullscreen mode

User B sees the same version (1), since User A has not yet committed.

  1. Attempt to Update the Document:
   UPDATE documents
   SET content = 'This is User B’s updated content.', version = version + 1
   WHERE id = 1 AND version = 1;
Enter fullscreen mode Exit fullscreen mode
  1. Commit the Transaction:
   COMMIT;
Enter fullscreen mode Exit fullscreen mode

Step 3: Conflict Detection

  • When User B tries to commit the update, the database checks the version of the document.
  • Since User A has already committed their changes and incremented the version number to 2, the condition WHERE version = 1 fails.
  • User B's transaction is not completed, and a conflict is detected.

In this case, User B can either retry the operation after reloading the updated data or handle the conflict by informing the user.


When Not to Use Optimistic Locking

While optimistic locking is great for collaborative environments with low chances of conflicts, there are scenarios where it’s not the best fit:

  1. High Contention Scenarios:
    In systems where multiple users frequently update the same data, conflicts might be too common, causing frequent transaction failures and retries. In such cases, pessimistic locking is a better fit because it prevents conflicts from happening at all by locking data upfront.

  2. Real-Time Systems:
    Applications like financial systems or high-frequency trading platforms, where data integrity and timing are critical, often use pessimistic locking or other concurrency controls to ensure consistency without waiting for conflicts to be detected.

  3. Latency-Sensitive Environments:
    In situations where retrying operations due to conflicts introduces unacceptable latency, optimistic locking might lead to a poor user experience. In these cases, pessimistic locking or other locking strategies might be more suitable.


Conclusion

Optimistic locking is a powerful mechanism for handling concurrent transactions, allowing multiple users to work on the same data without locking it, but still detecting conflicts when they occur. It’s especially useful in collaborative environments where the likelihood of conflicts is low, but it may not be ideal for high-contention systems where conflicts are frequent.

Have you used optimistic locking in your projects? What has your experience been? Share your thoughts in the comments below, and don’t forget to like, share, and provide your feedback on this article!

Top comments (0)