Skip to content

Core system concepts · Concept lesson

Transactions

Use transactional boundaries to preserve invariants across related state changes while understanding isolation, retries, and distributed limits.

Written for readers who already know the basics. If the words here are new to you, read The request lifecycle and Capacity estimation first.

Original educational architecture · Version 2026-11-12.1 · Examples use stated hypothetical assumptions, not a company's actual design.

What you will be able to explain

  • Explain atomicity and isolation in a database transaction.
  • Choose a transaction boundary that matches a business invariant.
  • Recognize retry, deadlock, and cross-system consistency limits.

How transactions work

A transaction groups operations that must preserve a set of data invariants. In a relational database, a transaction can read rows, validate conditions, make several updates, and commit them as one unit. Atomicity addresses partial database updates: either all included changes are committed or none are. Isolation describes what concurrent transactions can observe and which schedules are allowed; it is not synonymous with “everything is locked.” Durability depends on the database's configuration and failure model. Transactions are powerful within one transactional store, but an ordinary database transaction does not atomically include an external email provider, another database, or a remote API. Choose the smallest boundary that contains the invariant. A long transaction holds resources, increases conflicts, and can make recovery difficult. State the invariant first, then choose isolation and constraints that enforce it. Callers must also handle commit uncertainty if the connection fails around the acknowledgement.

A local transaction boundary
1. Begin

Start a bounded unit of database work.

2. Check invariant

Validate conditions against shared durable state.

3. Related changes

Apply all database updates within the transaction.

4. Commit or abort

Make all included changes durable or none.

5. External effect

Separate workflow; not part of this database commit.

  1. Begin → Check invariant: transaction scope
  2. Check invariant → Related changes: invariant permits operation
  3. Related changes → Commit or abort: atomic database result
  4. Commit or abort → External effect: durable intent can trigger later work

Worked example: transfer between accounts

A related correctness trap is write skew: two transactions can each read a valid snapshot and update different rows, yet together violate a cross-row rule. Imagine a service must keep at least one of two on-call contacts active. Transaction A reads that both contacts are active and deactivates the first; transaction B reads the same state and deactivates the second. Under snapshot-based isolation that permits this interleaving, neither write conflicts on the same row, and both can commit, leaving no active contact. A row lock on only the row each transaction changes may not protect the predicate across both contacts. Options include a database constraint that encodes the invariant, locking a shared parent row before checking, or serializable isolation with handling for serialization aborts. The exact guarantees depend on the database and isolation implementation; verify its primary documentation rather than assuming a level name is portable. If a serialization failure occurs, retry the whole database transaction with bounded attempts and no external side effects inside the retry loop. This is why transaction correctness starts from the invariant and anomaly model, not from using BEGIN and COMMIT alone.

Suppose account A has 80 currency units and account B has 25. A transfer of 30 should produce balances 50 and 55 while preserving the total of 105. Within one database transaction, read or conditionally update the source, require its available balance to be at least 30, subtract 30, add 30 to the destination, and write a transfer record. If the source update affects zero rows, reject for insufficient funds. If any later step fails before commit, roll back the database changes. Use integer minor units, such as cents, rather than binary floating-point currency: 30 dollars becomes 3,000 cents. The 3,000-cent amount remains the same unit across both account updates. The transaction should be short; do not call a payment network while holding database locks. If a client retries after a lost response, a transfer identifier and uniqueness constraint can return the prior transfer rather than move the funds again.

Isolation and workflow alternatives

Read committed, repeatable read, and serializable isolation provide different guarantees, with exact behavior varying by database. Constraints and conditional updates can enforce narrow invariants more simply than broad serializable transactions. Optimistic version checks detect stale updates and let the caller decide whether to retry. Pessimistic row locking is useful when conflicts are common and the critical section is brief. For a workflow spanning multiple services, a saga coordinates local transactions and compensating actions; compensation is a new business action, not a true rollback of an already observed external effect. An outbox records an event intent in the same local transaction as the state change, then a publisher delivers it later. These patterns trade immediate atomicity for explicit recovery and eventual completion. Choose based on the invariant, contention, and user contract; never claim that a message broker makes a cross-database commit atomic.

Failure and recovery

A transaction can abort because of a constraint, deadlock, serialization conflict, timeout, or process failure. The database can roll back its own uncommitted changes, but a client may lose contact after commit and before receiving confirmation. That leaves an ambiguous result, not a known rollback. Retry a complete transaction after a retryable serialization or deadlock abort, with a bounded policy and no external side effects inside the retry loop. Use a unique business operation key to deduplicate a repeated commit attempt when the domain allows it. If an external effect is required, persist intent transactionally, dispatch it separately, and make the recipient or consumer tolerate repeated delivery. Monitor transaction duration, abort rate, lock wait, and deadlocks. Recovery includes checking durable operation state and reconciling external effects; blindly replaying a transfer or charge can duplicate a real-world action.

When not to make a transaction larger

Do not wrap unrelated reads and writes in a single long transaction for convenience. A report that scans millions of records may hold snapshots or locks long enough to increase storage pressure and block useful work. Do not use a database transaction to pretend two independent stores share one commit boundary. Do not automatically choose the strongest isolation for every query; it can reduce concurrency without addressing a poorly defined invariant. If a task is naturally eventual, such as sending a welcome message after signup, store a durable intent and expose delivery state rather than keeping a user request open while an external provider responds. On the other hand, avoid splitting a genuinely atomic balance update into separate writes simply to improve throughput. Transaction scope is a business correctness decision constrained by store capabilities, not a performance switch.

Senior followups

Ask which anomalies the chosen isolation level permits and which database constraints independently protect the invariant. What is the maximum transaction duration, and which external calls or user waits occur inside it? How does the application identify a retryable abort versus a permanent business rejection? If commit acknowledgement is lost, can the operation be queried by a stable identifier? Does the retry repeat only database work, or could it send an email or charge a provider twice? For cross-service workflows, what is the state machine, who owns each step, how are compensations audited, and how are stuck operations resumed? Review lock ordering, indexes used by updates, and deadlock telemetry. Senior transaction design makes the atomic boundary, ambiguous states, and recovery procedures explicit instead of relying on the word ACID as a complete explanation.

Operational practice

Test important invariants with concurrent transactions and injected failures before and after commit. Use the actual database engine and isolation level; an in-memory substitute may not reproduce locking semantics. Keep transaction functions small, parameterized, and observable. Record duration and outcome categories, avoiding sensitive row data in logs. Set statement and transaction timeouts consistent with the caller's deadline. A deadlock alert should include enough safe identifiers to find the participants and query plans. For an outbox, monitor unpublished row age, retry count, and poison-event handling; an outbox that grows forever is not reliable delivery. Document whether a user can query a transaction result after a timeout. Recovery runbooks should prefer idempotent replay or audited compensation over direct edits to balances. After changing isolation or query patterns, validate contention and correctness together.

Terms in plain language

Atomicity
The transaction's changes commit together or are treated as not committed.
Isolation
The degree to which concurrent transactions are shielded from one another's intermediate effects.
Commit
The operation that makes a transaction's changes durable and visible according to the store's guarantees.
Serializable isolation
An isolation guarantee under which successful concurrent transactions behave as if run in some serial order.

Preparing practice controls…

Check your understanding

These checks explain concepts. They do not measure architecture seniority or update readiness.

1. What does a relational database transaction normally make atomic?
2. A database connection drops immediately after a commit request. What should the caller assume?

Design independently

A checkout operation reserves inventory, records an order, charges an external provider, and sends a confirmation email. Propose transaction boundaries and recovery behavior without claiming one atomic transaction spans all systems.

Hints, not a solution
  • Keep the local database transaction short.
  • Persist an intent for asynchronous external effects.
  • Distinguish compensation from rollback.

0 / 20,000 characters · Not saved

Your learning notes

Sign in to save

Marking a lesson read and reviewing an exercise are separate actions. Neither implies mastery. Saved work is account-owned; saves are explicit and do not queue offline.

References and boundaries

Primary documentation supports the mechanisms described. It does not certify these hypothetical architectures, prices or sizing assumptions. Review platform-specific behavior before implementation.

PostgreSQL Documentation: Transaction Isolation

Primary database documentation on isolation behavior and anomalies.

AWS Prescriptive Guidance: Transactional outbox pattern

Primary vendor guidance for atomically storing data and an event intent.

Back to curriculum