DEV Community

Luckshvadhan B
Luckshvadhan B

Posted on

Atomicity

The problem
We are transferring money between two users
If something fails in between it can cause wrong balance or money loss
So both debit and credit must happen together or not happen at all

Initial Data
Alice has 1000
Bob has 500

Transaction Logic
Step 1
Start transaction
Step 2
Deduct amount from sender
Step 3
Add amount to receiver
Step 4
Commit transaction

If any step fails rollback everything

Normal Flow
Transfer 200 from Alice to Bob

After transaction
Alice balance becomes 800
Bob balance becomes 700

Both updates happen successfully

Error Case 1
Debit happens but credit fails
Transaction is not committed
Database rolls back

Final state

Alice still has 1000
Bob still has 500
No partial update happens

Error Case 2
Query fails after debit step
Transaction stops
Rollback is triggered

Final state

Alice balance is unchanged
Bob balance is unchanged

BECAUSE:
Database follows ACID properties
Transaction ensures all operations succeed together
If any step fails entire transaction is cancelled

There is no situation where
Alice loses money and Bob does not receive it
Either both balances update
Or nothing changes

If transactions are not used data inconsistency will happen
Improper handling can still cause issues in high concurrency systems
Transaction acts like a safety system
It guarantees consistency in money transfer
This is critical for systems like payment apps

Top comments (0)