Databases
Transactions
A group of statements run as one atomic unit that either fully commits or fully rolls back, protecting invariants like 'debit and credit move together'. Isolation levels, from Read Uncommitted up to Serializable, trade consistency against concurrency and expose anomalies such as dirty reads, phantoms and deadlocks. Keep transactions short to limit lock contention.
Purpose
A transaction groups several statements into one atomic unit: either all of them commit or none do. It exists to protect invariants that span multiple rows or tables — a transfer debits one account and credits another, or does neither.
When to Use It
Any multi-step change where a partial write would corrupt state: payments, order placement, inventory adjustment, anything with a ledger. Also the tool for read consistency — a report that must see one coherent snapshot of the data.
Trade-offs
Isolation levels — from Read Uncommitted up to Serializable — trade correctness against concurrency: stricter levels prevent anomalies (dirty reads, non-repeatable reads, phantoms) but hold more locks and abort more often. Long transactions amplify contention and deadlocks, so the discipline is keeping them short.
Implementation
Wrap the unit in BEGIN…COMMIT with rollback on error; know your database's default level (often Read Committed) and raise it only where an anomaly actually threatens the logic. Acquire locks in a consistent order to avoid deadlocks, retry on serialization failures, and never hold a transaction open across a network call or user think-time.