Design safe SQL transactions under concurrency
8 steps · about 5 h 15 min · Intermediate
- Define the transaction boundary (guide, PostgreSQL documentation, 35 min)
Group reads and writes into one all-or-nothing unit that matches the business operation.
- Build an MVCC mental model (reference, PostgreSQL documentation, 40 min)
Understand how snapshots let readers and writers overlap before reasoning about anomalies.
- Choose an isolation level (reference, PostgreSQL documentation, 45 min)
Match allowed anomalies and retry requirements to the invariant the operation must preserve.
- Lock the necessary data (reference, PostgreSQL documentation, 45 min)
Use row or table locks only where snapshot rules alone cannot coordinate competing changes.
- Enforce invariants with constraints (reference, PostgreSQL documentation, 40 min)
Move uniqueness, reference and value rules into the database wherever they can be stated declaratively.
- Classify retryable failures (reference, PostgreSQL documentation, 30 min)
Branch on stable SQLSTATE codes for serialization failures, deadlocks and constraint violations.
- Preserve application-level consistency (guide, PostgreSQL documentation, 40 min)
Combine serializable transactions, locks and integrity checks according to the operation's threat model.
- Observe and test contention (reference, PostgreSQL documentation, 40 min)
Run competing sessions, inspect waiting locks and prove both the invariant and bounded retry path under collision.