In Software development, it's important to prevent an application from getting into an inconsistent state. Let's get into this by looking at an example,
Transferring of money, which involves deducting money from User A, and adding the money to User B.
Case 1:
What happens if the app crashes after deducting money from User A? This is an inconsistent state where User A sent the money and User B didn't receive the money.
Case 2:
What happens when User B also transfer money at the same time? There is a possibility that a transfer may override others. (race condition in a multi-threaded application). The balance of User B would be incorrect, which is also inconsistent.
This can be solved using Database Transactions, a sequence of operations that is considered a single unit of work. A Transactions provides ACID properties, which stands for
▶ Atomicity, all operations should succeed completely or fail i.e. If one operation fails, everything fails.
▶ Consistency, all the writes should be valid.
▶ Isolation, guarantees the correct execution of concurrent transactions, with isolation levels.
▶ Durability, If a transaction succeeds, it should persist even in case of system crashes.
The transaction's Atomicity property can solve case 1. The database locks can be used to prevent a single resource from being concurrently accessed by multiple threads/processes which will solve case 2.
Top comments (0)