DEV Community

Jonah Blessy
Jonah Blessy

Posted on

Atomicity

Design a transaction to transfer money from one account to another (atomic operation)

BEGIN;

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

UPDATE accounts 
SET balance = balance + 200 
WHERE name = 'Bob';

COMMIT;
Enter fullscreen mode Exit fullscreen mode

Both debit and credit are grouped inside one transaction so they act as a single unit. This ensures money is not lost between steps.


Check balances before and after successful transaction

SELECT * FROM accounts;
Enter fullscreen mode Exit fullscreen mode

First check initial state to know starting balances. After commit, verify both accounts reflect the correct updated values.


Introduce failure after debit (simulate error before credit)

BEGIN;

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

-- simulate failure
SELECT 1/0;

UPDATE accounts 
SET balance = balance + 200 
WHERE name = 'Bob';

COMMIT;
Enter fullscreen mode Exit fullscreen mode

An error is triggered after deducting money. This helps check whether the system allows partial updates or not.


Observe rollback behavior after failure

SELECT * FROM accounts;
Enter fullscreen mode Exit fullscreen mode

After failure, the transaction should not commit. The deducted amount should not persist if rollback works correctly.


Explicit rollback after error

BEGIN;

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

ROLLBACK;
Enter fullscreen mode Exit fullscreen mode

Rollback cancels everything inside the transaction. Even completed queries inside the block are undone.


Simulate failure in credit step

BEGIN;

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

UPDATE accounts 
SET balance = balance + 200 
WHERE name = 'sdkifhiasufha'; 

COMMIT;
Enter fullscreen mode Exit fullscreen mode

Second query fails logically. This checks whether system prevents inconsistent state.


Verify no partial update after failed credit

SELECT * FROM accounts;
Enter fullscreen mode Exit fullscreen mode

Balances should remain unchanged if transaction fails. Sender’s balance should not be reduced alone.


Safe version with validation

BEGIN;

UPDATE accounts 
SET balance = balance - 200 
WHERE name = 'Alice' AND balance >= 200;

UPDATE accounts 
SET balance = balance + 200 
WHERE name = 'Bob';

COMMIT;
Enter fullscreen mode Exit fullscreen mode

Added condition to avoid negative balance. Helps ensure business rule is enforced before transfer completes.


Final verification of consistency

SELECT * FROM accounts;
Enter fullscreen mode Exit fullscreen mode

Final check confirms either both updates happened or none. Ensures system maintains atomicity and consistency.

Top comments (0)