INDEPODENCY SITUATION
Let me explain duplicate transaction (same request multiple times)
First, we have accounts table
Alice = 1000
Bob = 500
since, now we try same transfer again and again.
First time transfer:
BEGIN;
UPDATE accounts
SET balance = balance - 200
WHERE name = 'Alice';
UPDATE accounts
SET balance = balance + 200
WHERE name = 'Bob';
COMMIT;
After first transfer:
Alice = 800
Bob = 700
since, 200 is transferred successfully.
Now we run the same transfer again (duplicate request).
BEGIN;
UPDATE accounts
SET balance = balance - 200
WHERE name = 'Alice';
UPDATE accounts
SET balance = balance + 200
WHERE name = 'Bob';
COMMIT;
After second time:
Alice = 600
Bob = 900
since, same operation is applied again.. so money is transferred again.
Final observation:
since, database does not know it is duplicate request
it will execute again and again
so duplicate transactions are allowed
Problem:
since, same request runs multiple times
money will be deducted multiple times
this leads to incorrect balance
THE FINAL THING IS:
since, database only ensures correctness of each transaction
but it does not prevent duplicate requests
so,
this should be handled in application level
like,
unique transaction id
checking if transaction already processed
because of this,
same request will not be applied again
no duplicate deduction
system remains correct
this is how real payment apps avoid duplicate transactions.
Comments
Post a Comment