In this lesson, you will learn how to maintain data integrity in high-traffic document stores using Optimistic Concurrency Control (OCC) to prevent "lost updates."
The Conflict of Concurrent Writes
When multiple users try to update the same document simultaneously, a "race condition" can occur. Imagine two users are editing a shared inventory document. User A reads the document (version 1), then User B reads the same document (version 1). User A saves a change, updating the version to 2. If User B saves their change based on version 1, they will inadvertently overwrite User A's changes, effectively causing a "lost update."
Implementing Optimistic Concurrency Control (OCC)
Instead of locking the entire document and blocking other users, OCC assumes conflicts are rare. It allows multiple users to read the data, but it validates the state of the document at the exact moment of the write.
We typically use a version field within our JSON document. Every time an update occurs, we check if the version in the database matches the version we originally read.
The Logic in Action
Consider this update pattern:
- Read: Fetch the document:
{ "id": 101, "stock": 50, "version": 5 }. - Modify: Update the local application state:
stockbecomes 45. - Write: Perform a conditional update:
UPDATE inventory
SET stock = 45, version = 6
WHERE id = 101 AND version = 5;
If the database returns "0 rows affected," it means another process snuck in and changed the version to 6 (or higher) before your write reached the server. Your application now knows a conflict occurred, and you can decide how to resolve it—typically by re-reading the latest data and prompting the user to merge their changes.
By checking the version at the moment of the write, we avoid long-lived locks that would otherwise cripple performance in high-traffic, multi-tenant environments. This approach is highly efficient for read-heavy systems where write collisions are infrequent but must be handled reliably.
Key Takeaway: Optimistic Concurrency Control ensures data integrity by verifying that a document’s version has not changed since you last read it, allowing for safe updates without blocking other users.