Transfer of money securely using transactions and durability in PostgreSQL.
I am building a system(like Phonepay/Gpay/Paytm).In that, users can store money,tranfer money,and view transactions where the system should not loose the money,should duplicate transactions and incorrect balances.
CREATING ACCOUNTS TABLE:
CREATE TABLE accounts (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
balance INT NOT NULL CHECK (balance >= 0),
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERTING DUMMY DATA:
INSERT INTO accounts (name, balance)
VALUES
('Alice', 1000),
('Bob', 500);
Now want to transfer between accounts(here,alice and bob) and commit the transaction,ensuring that the changes are made in databases.
In above statements,I have updated balance for alice to 800(1000-200) and bob to 700(500+200) then used commit command.After I restarted my system(assuming as a crash occured unexpectedly) then query to show my balances it shows the last updated value.
What happens here is the commited changes persist even after the restart.
CRASH HAPPENS BEFORE COMMIT:
When we begin to query and updates are done then suddenly unexpected crashes comes means the transaction is not saved,no money is transfered.Now alice will have balance=1000 and bob will have 500.Database will rollback automatically.This happen because we didn't use commit.
CRASH HAPPENS AFTER COMMIT:
When we begin to query,updates are done and we put the query commit,then suddenly unexpected crashes comes means the transaction is saved,money is transfered.Now alice will have balance=800 and bob will have 700.Database will be updated.This happen because we use commit.
HOW DATABASE ENSURES DURABILITY:
PostgreSQL uses WAL(Write Ahead Logging).It writes the changes that has been made to log file before saving the actual data.If crash happens,database reads the log and the data which is commited is restored successfully.
SUMMARY:
Comments
Post a Comment