ISOLATION

Let me explain concurrent transactions using accounts table

First, we have accounts table

Alice = 1000
Bob = 500

since, now we try to do multiple transactions at same time from same account.

Now we open 2 sessions (2 query windows).

In Session 1:

BEGIN;

UPDATE accounts
SET balance = balance - 800
WHERE name = 'Alice';

 not committing

since, we deducted 800 from Alice.. but not committed yet.. so change is not final.

Now in Session 2:

BEGIN;

SELECT * FROM accounts WHERE name = 'Alice';

since, we are checking balance in another session.

Result:

Alice = 1000

since, Session 2 cannot see uncommitted changes from Session 1.. so it still shows old value.

Now in Session 2 we try to deduct again:

UPDATE accounts
SET balance = balance - 500
WHERE name = 'Alice';

since, system will try to update same row.

Result:

it will wait (lock)

since, Session 1 is already using that row.. so Session 2 cannot update until Session 1 completes.

Now go back to Session 1 and do:

COMMIT;

since, now changes are saved.

Now Session 2 continues

and then updates based on latest value.

Final result:

Alice = 200 (after first) = then second update happens

since, database handles it properly using locking.

Now about isolation levels

Default (READ COMMITTED):

since, one transaction cannot see uncommitted data of another

so no dirty read happens

REPEATABLE READ:

since, once data is read.. it will not change inside that transaction

so no non-repeatable read

SERIALIZABLE:

since, transactions behave like one after another

so no conflicts and full safety

THE THING IS:

since, database uses isolation to prevent problems like

dirty read = reading uncommitted data
non-repeatable read = data changing inside same transaction
lost update = two updates overwriting each other

so,

Session 2 cannot see uncommitted data
and cannot update same row immediately

because of this,

balance will not become wrong
no duplicate deduction
system stays consistent

this is how payment apps handle multiple users at same time safely.

Comments

Popular posts from this blog

THE DELIVERY MAN

EC2 LAUNCHING

SORT A LINKED LIST USING MERGE SORT