Database & SQL Engineering / TRANSACTIONS, MVCC & CONCURRENCY / SQL-019
Suggested study path · Step 8 of 10 · G2
Last Balance Race
Explore concept graphMateri
Masalah: dua withdrawal (80.00 dan 70.00) berebut saldo 100.00. Dua transaksi terpisah bisa melihat saldo lama yang sama dan sama-sama mengira debit aman.
Mulai: tulis hasil yang semestinya ketika 80.00 berhasil lebih dahulu: saldo tersisa 20.00, withdrawal 70.00 ditolak, hanya satu ledger record tersimpan.
Wallet W-01 = 100.00
/ \
Session A: -80 Session B: -70
BEGIN BEGIN
lock/update W-01 tries same row
| |
row lock held waits (Lock event)
| |
COMMIT resumes
| |
balance 20.00 WHERE >=70 false
| |
withdrawal W-FIRST UPDATE 0 / abort
\ /
independent SELECT
balance=20.00 | rows=1
Multi-account: both sessions lock A-01 then A-02Dua strategi PostgreSQL 16
| Strategi | Kapan menunggu | Aturan penerimaan |
|---|---|---|
SELECT ... FOR UPDATE |
Saat mengambil row lock sebelum membaca saldo | Baca saldo setelah lock, lalu jalankan debit terjaga |
UPDATE ... WHERE balance>=amount |
Saat conditional write bertabrakan dengan penulis lain | Sukses hanya jika tepat satu row berubah |
Keduanya diuji dengan dua koneksi psql serentak. CI mengamati pg_stat_activity.wait_event_type='Lock' dari sesi ketiga, bukan menganggap dua skrip yang berurutan sebagai pengujian race. Pada kasus multi-akun, kedua transaksi mengunci row dalam urutan account_id yang sama agar menghindari pola circular wait yang diuji.
Konsep 1 / 3
Coordinate two overlapping withdrawals against a single account using SELECT FOR UPDATE and one transaction per session.
A sequential test can pass while two customers both believe the last available balance is sufficient for their withdrawals.
Draw a wallet with balance 100.00 and predict the result of two withdrawals worth 80.00 plus 70.00.
Intuisi utama
Session A holds the wallet's row lock, session B waits. Once A commits, B's locking SELECT under READ COMMITTED sees the updated row, not the old assumed 100.00.
Begin with wallet W-01=100.00. Session A locks the row with SELECT ... FOR UPDATE, then session B tries to acquire the same lock for a 70.00 withdrawal while A plans to withdraw 80.00. A separate observer confirms B has wait_event_type='Lock' in pg_stat_activity. A commits its guarded 80.00 debit and withdrawal record. When B resumes, its SELECT FOR UPDATE returns 20.00 and the guarded 70.00 debit raises insufficient funds before any withdrawal record. Final persisted wallet balance=20.00; exactly one withdrawal row for 80.00. This proves the coordinated interleaving on real PostgreSQL 16, not all possible isolation or retry policies.
Contoh bertahap
Two customers try to withdraw 80.00 and 70.00 from a wallet with 100.00 available.
- In session A run BEGIN then SELECT balance FROM accounts WHERE account_id='W-01' FOR UPDATE.
Mengapa: Hold the wallet row lock until A commits or rolls back.
Hasil yang diharapkan: Session A reads 100.00 and owns the conflicting lock.
- In session B run a locking SELECT on the same row before A commits.
Mengapa: Force a real lock conflict rather than simulated parallelism.
Hasil yang diharapkan: Another connection sees B waiting on a PostgreSQL Lock event.
- Commit A's 80.00 guarded debit, then let B retry the 70.00 debit against the updated balance.
Mengapa: Only one withdrawal can satisfy the balance predicate.
Hasil yang diharapkan: B sees 20.00, rejects insufficient funds and inserts no ledger row.
Konsep 2 / 3
Use UPDATE ... WHERE balance >= amount with a checked affected-row count under concurrent READ COMMITTED writes.
Even with database row locking, a zero-row UPDATE does not raise an SQL error; ignoring it can record a withdrawal that never debited an account.
Find the WHERE balance>=80.00 predicate in the concurrency fixture before reading the rest of the test.
Intuisi utama
UPDATE obtains the row lock and, after a concurrent transaction commits, reevaluates the balance condition. A false condition yields UPDATE 0, which the application must interpret as insufficient funds.
On a fresh wallet with balance 100.00, session A executes a guarded UPDATE for 80.00 and holds the transaction open. Session B concurrently executes a guarded UPDATE for 70.00, blocking on A's row lock. After A inserts a withdrawal record and commits, B's WHERE balance>=70.00 is reevaluated against balance 20.00 and updates zero rows. The DO block checks ROW_COUNT and raises insufficient funds; its transaction rolls back. The CI fixture verifies an actual Lock wait and independently inspects the final row and withdrawal count. A CHECK(balance>=0) is defense in depth; it does not replace checking whether the withdrawal succeeded.
Contoh bertahap
A conditional debit statement returns UPDATE 0 after another transaction commits first.
- Session A begins and executes UPDATE accounts SET balance=balance-80.00 WHERE account_id='W-01' AND balance>=80.00.
Mengapa: A single guarded write checks and changes the same row.
Hasil yang diharapkan: Exactly one row is changed and A keeps its lock until COMMIT.
- Session B concurrently executes the same guarded pattern for 70.00.
Mengapa: It must wait for the row and reevaluate its balance predicate.
Hasil yang diharapkan: pg_stat_activity reports a Lock wait, followed by zero updated rows after A commits.
- Check ROW_COUNT in the same PL/pgSQL DO block and throw on anything other than one.
Mengapa: UPDATE 0 by itself is not SQL failure and must not be followed by a ledger INSERT.
Hasil yang diharapkan: A=success, B=insufficient funds; no B withdrawal record.
Konsep 3 / 3
Acquire the same pair of account row locks in ascending ID order for opposing transfers.
Transfers A→B and B→A can deadlock when each transaction acquires its source first and then waits on the other account.
Sketch two transactions with arrows A→B and B→A, then identify which account each tries to lock first.
Intuisi utama
Before writing either account, both sessions lock account IDs in the same ORDER BY sequence. This serializes the tested overlapping pair without a circular wait.
Fresh accounts A-01=100.00 and A-02=100.00 are shared by opposite transfers. Session A locks both rows with SELECT ... WHERE account_id IN (...) ORDER BY account_id FOR UPDATE. Session B attempts the same and a separate observer sees its Lock wait. A transfers 40.00 from A-01 to A-02 and commits. B resumes, transfers 30.00 from A-02 to A-01, and commits. Independent SELECT shows A-01=90.00, A-02=110.00, two transfer rows and total 200.00. Consistent lock order prevents the tested deadlock pattern; it is not a universal guarantee that all possible deadlocks are impossible.
Contoh bertahap
An A→B transfer and a B→A transfer need both account rows while running concurrently.
- For both transactions lock A-01 and A-02 with ORDER BY account_id FOR UPDATE before either UPDATE.
Mengapa: Every writer acquires shared rows in a consistent order.
Hasil yang diharapkan: A holds both locks while B waits on a real Lock event.
- Commit A→B 40.00, then let B execute B→A 30.00 using the same lock order.
Mengapa: Avoid a cycle where A holds one row and B holds the other.
Hasil yang diharapkan: Both transactions commit sequentially without a deadlock in this interleaving.
- Query accounts and transfer records in a third session.
Mengapa: Prove no partial writes or lost transferred value.
Hasil yang diharapkan: A-01=90.00, A-02=110.00, transfers=2, total=200.00.
Referensi resmi PostgreSQL 16
Sumber
Cross-domain connections
Curated relationships for this unit at G2. Proposed edges are suggestions, not prerequisites.
Dashed = proposed relationship; solid = reviewed connection. Only reviewed prerequisites constrain a learning path. Keyboard and text links remain available.