# Transaction isolation

## What it is

Transaction isolation determines which changes from concurrent transactions an
operation can see and which combinations of results a database will allow to
commit. A transaction can group several statements into one decision. For
example, a booking service can read available places, write a reservation, and
record the amount it expects to collect. Isolation governs what happens when
another transaction reads or changes the same information during that decision.

A database can use snapshots to give readers a consistent view while other
sessions write. PostgreSQL uses a new snapshot at the start of each ordinary
query under Read Committed, its default isolation level. A later query in the
same transaction can therefore see work committed after the earlier query began.
Under PostgreSQL's Repeatable Read, ordinary reads use a transaction snapshot
set when the first relevant statement runs. The transaction also sees its own
changes. PostgreSQL's Serializable level checks dependencies between concurrent
work and can reject a transaction when their combined result would be impossible
in any serial order. Several transactions can still run at once.

The labels describe guarantees, and implementation details matter when choosing
one. A snapshot explains what a query can see. Write conflicts, constraint
checks, and explicit locks add rules about the changes a transaction can make.
It helps to trace both halves. Ask which rows each statement reads, then ask
which later commits can invalidate the decision those rows support.

## Why it matters

Consider a team documenting the last place in a training session. Two workers
can each see one place available and each try to record a booking. An
application that performs a check followed by an unconditional write has left
time for another decision between its two statements. Committing each worker's
statements together still leaves a question about whether both decisions can
succeed. The invariant is that confirmed bookings fit within capacity. The data
model and the statements have to give the database enough information to protect
it.

Some invariants are local to a row. A conditional decrement can tie an inventory
write to the current quantity. Other invariants span records. Suppose a rota
requires at least one operator on duty. Two people can each use a snapshot that
shows the other person on duty, then each update a different record. Their
writes can avoid a direct row conflict even though the combined decision would
leave nobody on call. This is a case of write skew. A transaction-level snapshot
supplies repeatable observations but can still leave that combined decision
possible in systems that allow snapshot isolation without a serializability
check.

Choose isolation with the decisions in mind. An approximate dashboard that
refreshes in several independent panels can tolerate each panel seeing a recent
snapshot. A report that reconciles a ledger total against its component rows
needs those reads to describe the same point in time. A workflow that updates
several related records may need a documented serialization guarantee, a
database constraint or a shared lock that writers consistently use. The
consequences of an inconsistent result tell you which behaviour to test.

## What it looks like in practice

A useful test gives two independent database connections a predictable schedule.
Begin a transaction on the first connection and read a stock item. Commit a
change from the second connection. Then read the same item again on the first
connection. Record what each read returns and the exact moment each connection
commits. Run an additional case in which both connections are trying to reserve
the last item. An explicit wait in the test should correspond to a visible
event, such as a completed statement, so its result has meaning under a busy
test runner.

Engineer's
[limited-stock engineering note](/notes/selling-limited-stock-without-overselling/)
illustrates a simpler shape for the last-item decision. One conditional database
statement performs the decrement only while stock is available. In PostgreSQL
under Read Committed, when that update encounters a row already updated by
another transaction, it can wait for the first one to finish and re-evaluate its
condition against the updated row. An application can use the count of affected
rows to distinguish a successful change from a reservation that could not be
made. The note also calls out the cost of holding the database lock across a
network payment.

An illustrative review would test both the final balance and the decision
reported to each caller. It could then add a pair of operations that depend on
several rows and check which isolation level or constraint enforces that wider
rule. Separating the tests makes the evidence easier to interpret. A passing
last-item test establishes a particular invariant for that write path. A
multi-row scheduling rule needs its own case and an explicit explanation of what
makes concurrent decisions safe.

## Where it goes wrong

Applications sometimes retry only the final statement after a serialization
failure. The earlier reads can be the reason the database rejected the
transaction. Start a new transaction, repeat the decision against its new view,
and bound the number of attempts so busy clients leave room for other work.
Distinguish a serialization failure from a validation error and from a client
deadline. The application should report whether a decision was accepted,
rejected or still uncertain after a lost response.

External side effects need their own policy. A database rollback can discard a
reservation record. A message another system already received needs a separate
recovery path. For a retryable transaction, keep that external action outside
the retried decision and give it a stable identity that helps its consumer
handle duplicates. After a lost connection near commit, use a durable operation
identifier or a read-back procedure to establish whether the action was already
recorded.

Long-running views also have a cost. Reports that retain snapshots for a long
time can delay the removal of older row versions. Keep the time spent inside a
transaction visible, particularly when application code waits on the network or
a user interface. A test fixture should cover the configured isolation level
used by the application's production connection factory. Finding a driver
default in documentation is useful. Observing the actual connection setting and
the two-session result makes the decision easier to defend when the database or
client changes.

## Further reading

- [PostgreSQL transaction isolation](https://www.postgresql.org/docs/18/transaction-iso.html).
  Describes concurrent reads and writes at each supported level.
- [PostgreSQL SET TRANSACTION](https://www.postgresql.org/docs/18/sql-set-transaction.html).
  Documents when a connection assigns transaction characteristics.
- [PostgreSQL concurrency control](https://www.postgresql.org/docs/18/mvcc.html).
  Connects isolation to locks, consistency checks and application behaviour.

<https://engineer.company/glossary/transaction-isolation/>
