Senior
Two parallel transactions update the same row (debit and credit) — is there anything that needs to be done? The lost update problem.
sobes.tech AI
Answer from AI
The lost update problem occurs when two parallel transactions read the same row, modify it, and write it back, with one of the changes being lost.
To prevent this problem, proper transaction isolation and synchronization of updates must be ensured. The main approaches are:
-
Using locks (pessimistic locking):
- When reading a row, a lock is placed that prevents other transactions from modifying it until the current transaction is finished.
- For example,
SELECT ... FOR UPDATEin SQL.
-
Optimistic locking:
- A version or timestamp is added to the table.
- When updating, it checks that the version has not changed since reading.
- If it has changed, the transaction is rolled back or retried.
-
Proper transaction isolation level:
- The
SERIALIZABLElevel guarantees sequential execution of transactions but may reduce performance.
- The
-
Using atomic operations:
- For example, updating with SQL
UPDATE ... SET value = value + ?without prior reading.
- For example, updating with SQL
Example of optimistic locking:
// Assume there is a version field in the table
// Read the row with version
SELECT balance, version FROM accounts WHERE id = ?;
// When updating
UPDATE accounts SET balance = ?, version = version + 1 WHERE id = ? AND version = ?;
// If affected rows == 0, it means the version has changed — the operation should be retried
Thus, to avoid lost updates, either locking or optimistic version control mechanisms should be used.