Stage 3 · Build
Databases & Persistence
Transactions
Use BEGIN, COMMIT, ROLLBACK, isolation levels, SELECT FOR UPDATE, and retryable conflicts.
Why Transactions
Transactions ensure that a group of operations either all succeed or all fail. Without transactions, partial failures leave your data in inconsistent states. A payment might deduct money without creating an order, or an order might be created without inventory being reserved.
Basic Transactions
Error Handling
Transaction error handling is critical. If any operation fails, the transaction must be rolled back. The defer tx.Rollback() pattern handles this automatically. But you must still check Commit errors.
Isolation Levels
Isolation levels control how transactions see each other's changes. Higher isolation prevents more anomalies but reduces concurrency. Choose the minimum isolation level that correctness requires.
| Level | Anomalies Prevented | Use Case |
|---|---|---|
| Read Uncommitted | None | Almost never |
| Read Committed | Dirty reads | Default for most databases |
| Repeatable Read | Non-repeatable reads | Financial calculations |
| Serializable | All anomalies | Critical consistency required |
Pessimistic Locking
SELECT FOR UPDATE locks rows so other transactions cannot modify them until your transaction completes. Use this when you read-then-write and need to prevent concurrent modifications.
Retryable Conflicts
Serializable transactions can fail with serialization errors when two transactions try to modify the same data concurrently. The correct response is to retry the entire transaction.
Long-running transactions hold locks and block other transactions. Do all non-database work (HTTP calls, file I/O) outside the transaction. Only begin the transaction when you are ready to write.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.