Transactions and Isolation

What ACID guarantees, which anomalies each isolation level allows, how locking works, and how sagas and the outbox replace distributed transactions.

16 minLesson 2 of 8
On this page
  1. Where transactions apply
  2. ACID
  3. Concurrency anomalies
  4. Isolation levels
  5. Preventing lost updates and write skew
  6. Deadlocks
  7. Transactions across services
  8. Why the default isolation level is not enough
  9. In the interview
  10. What to practise next

A transaction is a group of reads and writes that the database treats as one unit: either all of the writes take effect or none do, and concurrent transactions cannot see or disturb the half-finished work. It lets application code change several rows, such as debiting one account and crediting another, without handling crashes and concurrent users itself.

Without transactions, a crash between two writes leaves the data half-updated, and two requests that change the same row at once overwrite each other silently. A transaction cannot span services with separate databases, so those need the approaches at the end of this lesson.

Where transactions apply

A transaction covers one database. A request that changes data in two services involves two databases, and no single transaction spans both.Client to Order service; Order service to Orders database (one transaction); Order service to Payment service (API call); Payment service to Payments database (another transaction).ClientOrder serviceOrders databasePayment servicePaymentsdatabaseone transactionAPI callanother transaction
A transaction covers one database. A request that changes data in two services involves two databases, and no single transaction spans both.

ACID

ACID names the four guarantees that a transaction gives.

  • Atomicity means that all the writes in the transaction happen or none of them do, so a crash or rollback halfway leaves no partial work.
  • Consistency means that the transaction moves the data from one valid state to another. The database enforces only the rules you declare, such as UNIQUE and CHECK (stock >= 0), and the application handles the rest.
  • Isolation means that concurrent transactions do not interfere with each other. How strictly depends on the isolation level, which is the main subject of this lesson.
  • Durability means that once a commit is acknowledged, the data survives a crash, because the change is written to a log on disk first.

Concurrency anomalies

Each anomaly is a way in which concurrent transactions produce a result that no one-at-a-time ordering of them would produce.

Dirty read

A dirty read happens when a transaction reads data that another transaction has written but not yet committed. If the writer rolls back, the reader has acted on a value that never officially existed, such as a low-balance email sent because a payment job briefly set a balance of 20 before failing and restoring 100.

Non-repeatable read

A non-repeatable read happens when a transaction reads the same row twice and gets different values because another transaction committed a change in between. A report that reads a balance of 100 at the start and 60 at the end shows two numbers inside one transaction.

Phantom

A phantom is the same problem for a set of rows. A transaction counts the bookings for room 7 at 10:00 and gets 0, another transaction commits a booking for that slot, and a second count returns 1. Row locks cannot prevent this, because the new row did not exist yet.

Lost update

A lost update happens when two transactions read the same value, each computes a new value from it, and each writes its result, so the second write replaces the first. If two buyers of the last concert ticket both read remaining = 1 and both write remaining = 0, both sell the same ticket.

Write skew

Write skew happens when two transactions read the same rows, each decides that a rule holds, and each writes a different row, so that together they break the rule. If a team must keep one admin, and its only two admins each check that there are two and then demote themselves, the team ends up with none. The two writes go to different rows, so the database sees no write conflict between them and lets both commit.

Isolation levels

An isolation level tells the database which anomalies it must prevent. A stricter level prevents more but makes transactions wait or fail and need a retry, so use the weakest level that is safe for the operation.

Read committed

Under read committed, a query sees only committed data, as it was when that statement started. This removes dirty reads, but the other anomalies can still happen, because another transaction can commit between two of your statements. It is the default in many databases.

Repeatable read and snapshot isolation

Under snapshot isolation, a transaction sees a frozen view of the database as of its start, whatever others commit meanwhile. This prevents dirty reads, non-repeatable reads and, in most implementations, phantoms. It still allows write skew, because both transactions read consistent snapshots and write different rows. Whether it prevents lost updates depends on the database: some abort a transaction whose row changed after its snapshot, and others let the second write win. Many databases call this level "repeatable read".

Serializable

Serializable means the outcome is the same as if the transactions had run one after another, so no anomaly can occur, including write skew. Databases achieve it by running transactions one at a time, by two-phase locking, or by running on snapshots and aborting a transaction when a dangerous pattern of reads and writes appears. The cost is more waiting or aborts that the application must retry, so use it only for rules that span several rows and have no simpler fix.

LevelDirty readNon-repeatable readPhantomLost updateWrite skew
Read committedpreventedpossiblepossiblepossiblepossible
Snapshot (often called repeatable read)preventedpreventedusually preventeddepends on the databasepossible
Serializablepreventedpreventedpreventedpreventedprevented

Preventing lost updates and write skew

Raising the isolation level is one fix, and the techniques below are the others. They work at any level.

Atomic update

The simplest fix is to let the database read and write in one statement, so no other transaction can interfere in between. For the ticket example it is UPDATE tickets SET remaining = remaining - 1 WHERE id = 5 AND remaining > 0, and zero updated rows means sold out. It works whenever the change fits in one statement on one row, and it is the best choice for counters and stock levels, even on a busy row.

Optimistic locking

With optimistic locking, you read the row together with a version number, and when you write, you include the version in the condition, so the write succeeds only if nobody has changed the row since you read it.

For example, UPDATE docs SET title = 'Final', version = 8 WHERE id = 42 AND version = 7 updates zero rows if someone changed the document after you read version 7, and you then re-read and retry.

Nothing is locked while the user is editing, so this suits documents and profiles, where conflicts are rare. When many transactions update the same row at once, most version checks fail, and the retries add load when the system is busiest, so use an atomic update or a lock there.

Pessimistic locking

With pessimistic locking, you lock the row before you read it, usually with SELECT … FOR UPDATE, and other transactions that want the row wait until you commit. Because they wait instead of failing, there are no retries, which suits busy rows whose logic is too complex for one statement. The costs are added latency, blocking of others when a transaction holds locks while waiting for a user or another service, and the risk of deadlocks.

Fixing write skew

Write skew needs the transactions to conflict even though they write different rows. You can lock the rows the decision was based on, such as the admin rows, with SELECT … FOR UPDATE, or lock a parent row such as the team row in every membership change. When the decision depends on rows that do not exist yet, as in the room booking, use a unique constraint on room and time, or run the transaction as serializable.

Deadlocks

A deadlock happens when two transactions each hold a lock that the other needs, for example one locks account 1 and asks for account 2 while the other has locked account 2 and asks for account 1. The database detects the cycle and aborts one transaction, so the application must retry on that error. To make deadlocks rare, lock rows in the same order in every transaction and keep transactions short.

Transactions across services

When one operation changes data in several services, each with its own database, the usual choice is a saga combined with the outbox pattern, and two-phase commit is the alternative that is usually rejected.

Two-phase commit

Two-phase commit (2PC) uses a coordinator. In the first phase, the coordinator asks every participant to prepare, which means doing the work, holding the locks and promising that it can commit. If all vote yes, the coordinator tells everyone to commit, and if any votes no, all abort.

It gives real atomicity, but most service architectures avoid it. A participant that voted yes must hold its locks until it hears the decision, so a coordinator crash leaves other transactions waiting. Each commit also costs at least two round trips, and many services and brokers do not support the protocol.

Saga

A saga splits the operation into a sequence of local transactions, one in each service, where each success triggers the next step, usually through an event. If a step fails, the saga runs compensating actions for the completed steps, such as refunding a payment or releasing a seat. A compensation is a new business action that reverses an earlier one, not a rollback, because the earlier step is already committed and may have been seen by others.

A saga is coordinated either by choreography, where each service reacts to events and decides the next step, or by orchestration, where a central orchestrator tells each service what to do. Choreography needs no extra component but is hard to follow with many steps, and orchestration makes the flow explicit at the cost of one more component.

The main cost is that a saga gives up isolation, so other requests can see intermediate states, such as an order that is paid but not yet reserved. The order should show as pending until the saga finishes. Every step and compensation must be safe to run twice, because messages are delivered at least once and failed compensations are retried.

Outbox pattern

Each saga step must update its own database and publish an event, and if these are two separate writes, a crash between them loses the event or publishes one for an unsaved change. The outbox pattern writes the event to an outbox table in the same local transaction as the data change, so both are saved or neither is. A relay process then publishes unsent rows to the broker and marks them as sent. If it crashes after publishing but before marking, it publishes again, so delivery is at least once and consumers must ignore duplicates.

Why the default isolation level is not enough

Many databases default to read committed, so code that reads a value, changes it in the application and writes it back has a lost update bug that no single-request test will find. State which level you assume, and fix each race with an atomic update, a version check or a lock.

In the interview

Bring up transactions when two users can change the same data, such as stock, seats or balances, or when one action spans several services. Name the specific race and its fix, for example "two buyers can read the same stock, so I decrement it with a conditional update", and say that across services you would use a saga because two-phase commit blocks.

Questions to expect:

  • "What is write skew, and how do you prevent it?" Two transactions read the same rows, each decides a rule holds, and each writes a different row, so the rule breaks. Prevent it by locking the rows the decision was based on, locking a shared parent row, adding a unique constraint, or using serializable isolation.
  • "Optimistic or pessimistic locking?" Optimistic locking checks a version at write time and retries on conflict, which is cheap when conflicts are rare. Pessimistic locking locks first and makes others wait, which is better on a busy row. For a simple counter I would use an atomic update.
  • "Which isolation level would you use?" Read committed for ordinary statements, with atomic updates, version checks or locks for the specific races. Serializable only where a rule spans several rows.
  • "How do you handle deadlocks?" The database aborts one transaction, so the application retries on that error. To reduce them, lock rows in a consistent order and keep transactions short.
  • "Why not use two-phase commit across services?" Participants hold locks while waiting for the coordinator, so a coordinator crash blocks them, and every commit costs extra round trips. A saga avoids this by committing locally and undoing with compensations.
  • "How do you update the database and publish an event reliably?" Write the event to an outbox table in the same transaction as the data change, and let a relay publish it afterwards. The relay can publish twice, so consumers must be idempotent.
Placing an order across servicesStrong answer
Interviewer

Orders, payments and inventory are separate services. How do you keep them consistent?

You

I would use a saga and not a distributed transaction. Each service commits to its own database and publishes the next event through an outbox, and if inventory fails after payment, the payment service refunds the charge as a compensation. Consumers record the ids of events they have processed, because events can arrive twice.

Interviewer

The customer sees "paid" and then "cancelled". Is that acceptable?

You

It is the cost of giving up isolation. I would reserve stock before charging, so the common failure happens before money moves, and show the order as pending until the saga completes.

Quick check

Two reviewers each check that the article has another reviewer, then each unassigns themselves. Both commit under snapshot isolation, and the article has no reviewer. Which anomaly is this?

A seat counter is decremented about 500 times a second during a sale. What is the best way to prevent lost updates?

What to practise next

Read message queues and streams, then Design a Payment System, which uses sagas, idempotency and the outbox pattern.