DEV Community

Christina Sharon S
Christina Sharon S

Posted on

Ensuring safety in ewallets using the concept of ATOMICITY

We use ewallets like gpay and phonepe everyday right and I have always wondered where the money goes when the server is down in the middle of a transaction.And that's where the concept of atomicity comes in.Atomicity means all or nothing.Either all the transactions are completed or everything is rolled back.

Creating a base 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
);
INSERT INTO accounts (name, balance) VALUES ('Christina', 1000), ('Sharon', 500);
Enter fullscreen mode Exit fullscreen mode

Correct Transaction

BEGIN;
UPDATE accounts SET balance = balance - 200 WHERE name = 'Christina';
UPDATE accounts SET balance = balance + 200 WHERE name = 'Sharon';
COMMIT;
Enter fullscreen mode Exit fullscreen mode

Result:
Christina = 800
Sharon = 700

Failure Test

BEGIN;
UPDATE accounts SET balance = balance - 200 WHERE name = 'Christina';
~Error occurs
UPDATE accounts SET balanc = balance + 200 WHERE name = 'Sharon';
COMMIT;
Enter fullscreen mode Exit fullscreen mode

What Happened?

The transaction failed.
Balances remain:
Christina = 1000
Sharon = 500

Top comments (0)