Course contentsShow
← Databases & SQL
Lesson 1320 of 1,95312. Key-Value and Caching EnginesFree lesson

Transactions and Optimistic Locking

Use CAS operations to ensure data integrity during concurrent updates.

In this lesson, you will learn how to maintain data integrity in concurrent environments using Compare-And-Swap (CAS) operations, a cornerstone of optimistic locking.

The Problem: The Lost Update

When multiple clients read a value from a database or cache, modify it, and write it back, you risk a "lost update." If Client A reads a value, and then Client B reads the same value, Client A might save their change just before Client B overwrites it with their own calculation, effectively erasing Client A's contribution.

The Solution: Optimistic Locking with CAS

Optimistic locking assumes that conflicts are rare. Instead of locking the data and preventing others from accessing it (which hurts performance), we attach a version number or a timestamp to the data.

When you attempt to update the record, you include the version you originally read. The database checks: "Is the current version still the same as the one the client read?"

  1. If yes: The update succeeds, and the version is incremented.
  2. If no: The update fails because someone else modified the data in the interim.

Illustration: The CAS Workflow

Imagine a balance object in a distributed cache: {"value": 100, "version": 1}.

If two processes try to add 50 simultaneously:

  1. Process A reads the value (100) and version (1).
  2. Process B reads the same value (100) and version (1).
  3. Process A sends an update: SET balance=150, version=2 WHERE version=1. The cache sees the version matches, updates successfully, and now the state is {"value": 150, "version": 2}.
  4. Process B tries the same command: SET balance=150, version=2 WHERE version=1. The cache checks, sees the version is now 2, and rejects the request.

Process B must now fetch the latest data, re-apply its logic (adding 50 to 150 instead of 100), and try again. By using this "check-and-set" logic, we ensure no updates are silently overwritten, all without forcing threads to wait in a blocking queue.

Key Takeaway: Optimistic locking with CAS operations ensures atomicity by verifying the data version hasn't changed before committing, protecting your system from race conditions while keeping throughput high.