Design safe SQL transactions under concurrency

8 steps · about 5 h 15 min · Intermediate

  1. Define the transaction boundary (guide, PostgreSQL documentation, 35 min)

    Group reads and writes into one all-or-nothing unit that matches the business operation.

  2. Build an MVCC mental model (reference, PostgreSQL documentation, 40 min)

    Understand how snapshots let readers and writers overlap before reasoning about anomalies.

  3. Choose an isolation level (reference, PostgreSQL documentation, 45 min)

    Match allowed anomalies and retry requirements to the invariant the operation must preserve.

  4. Lock the necessary data (reference, PostgreSQL documentation, 45 min)

    Use row or table locks only where snapshot rules alone cannot coordinate competing changes.

  5. Enforce invariants with constraints (reference, PostgreSQL documentation, 40 min)

    Move uniqueness, reference and value rules into the database wherever they can be stated declaratively.

  6. Classify retryable failures (reference, PostgreSQL documentation, 30 min)

    Branch on stable SQLSTATE codes for serialization failures, deadlocks and constraint violations.

  7. Preserve application-level consistency (guide, PostgreSQL documentation, 40 min)

    Combine serializable transactions, locks and integrity checks according to the operation's threat model.

  8. 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.