Transaction gom nhiều lệnh thành một khối "được ăn cả, ngã về không": commit thì ghi bền vững, rollback thì hủy sạch.
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT; -- hoặc ROLLBACK nếu lỗiVài cơ chế đáng biết:
- Savepoint: rollback một phần — SAVEPOINT sp1; ...; ROLLBACK TO sp1; — quay về điểm giữa mà không hủy toàn bộ.
- WAL (Write-Ahead Log): PostgreSQL ghi log trước khi áp thay đổi → đảm bảo bền vững và cho phép Point-in-Time Recovery.
- Deadlock: hai transaction chờ lock của nhau; DB tự phát hiện và hủy một bên (PostgreSQL trả lỗi 40P01) → app phải retry.
Điểm chốt thực dụng: giữ transaction càng ngắn càng tốt và không làm I/O bên trong (gọi HTTP, đọc file). Transaction kéo dài giữ lock lâu → chặn giao dịch khác, tăng độ trễ replica, và chặn vacuum gây phình bảng.
A transaction groups several statements into one all-or-nothing block: commit saves them durably, rollback discards everything.
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT; -- or ROLLBACK on errorA few mechanisms worth knowing:
- Savepoint: partial rollback — SAVEPOINT sp1; ...; ROLLBACK TO sp1; — returns to a mid-point without discarding everything.
- WAL (Write-Ahead Log): PostgreSQL logs before applying changes → ensures durability and enables Point-in-Time Recovery.
- Deadlock: two transactions wait on each other's locks; the DB detects it and kills one side (PostgreSQL returns error 40P01) → the app must retry.
Practical key point: keep transactions as short as possible and do no I/O inside them (HTTP calls, file reads). A long transaction holds locks for too long → blocks other transactions, increases replica lag, and blocks vacuum, causing table bloat.