A web application needs to apply several related changes in one operation. For example, transferring $100 from Account A to Account B must debit one row and credit another. Or bulk-importing 10,000 rows from a CSV: should each row be a separate transaction, or should all rows be inserted in one big transaction?
How large should each transaction be? What operations must be bundled together to ensure correctness, and what is the performance impact? The trade-offs are between atomicity (doing all or nothing) and latency/resource usage (transactions can hold locks and consume log space). The examples use PostgreSQL. First choose the correctness boundary; tune its size only where the product permits partial progress.
Simple transactions and ACID guarantees
A transaction groups the database changes that must commit together.
A transaction in SQL begins (e.g. BEGIN), executes one or more statements, and then ends with COMMIT or ROLLBACK. ACID properties apply:
Atomicity: All statements in the transaction either succeed together, or none take effect. A classic example is a funds transfer:
The application checks the returned rows before proceeding. Insufficient funds makes the guarded debit update zero rows; that is not automatically a SQL error. The application must roll back and stop. A missing destination also rolls back the debit. If either statement raises an error, roll back the transaction.