Atomic Write operations prevent Lost Updates


Last Updated on Feb 18, 2021

Many databases provide support for atomic update operations, which eliminate the need for read-modify-write cycles. But your code should be concise enough to be expressable in terms of those operations. It is not always possible to express code in terms of these atomic operations. But when the answer is yes, performing atomic update operations may be the best solution around to prevent Lost Updates.

Atomic operations are usually implemented through Cursor Stability - by exclusively locking an object when it is read so that no other transaction can read it until the update has been applied. Another option is to simply force all updates through a single thread.

An example of an atomic operation is:

UPDATE users
SET failed_attempts = failed_attempts + 1
WHERE id='29384';

Support for such operations is not limited to relational databases. MongoDB provides atomic operations for making local modifications to a part of a JSON document. Redis provides atomic operations for modifying data structures such as priority queues.

Note that Read-Modify-Write cycles can be introduced by ORMs accidentally under the hood, leading to subtle bugs that are difficult to find by testing. It is essential to be aware of this possibility and work around it when using ORM frameworks.


© 2022 Ambitious Systems. All Rights Reserved.