Skip to content

Transactions and isolation levels

Introduction

Bundle multi-step operations into one unit: it counts only if everything succeeds, and if something fails midway it is as if nothing happened.

Why use it

Transactions give four classic guarantees (ACID for short):

  • Atomicity: all or nothing.
  • Consistency: data always obeys the rules (for example balances stay non-negative).
  • Isolation: concurrent transactions do not interfere with each other.
  • Durability: once committed, data survives even a power cut.

How to do it

  1. Put writes that must succeed together in one transaction, and roll back (undo) on failure.
  2. Keep transactions short: wrap only database work—do not call external APIs or wait for user input inside them.
  3. Know the isolation levels: how much concurrent transactions may “see” of each other when they touch the same data.
    • Read committed (default on most databases, including PostgreSQL and SQL Server): you only see data others have committed.
    • Repeatable read (MySQL InnoDB default): reading the same row twice in one transaction returns the same result.
    • Serializable: strictest—like running one at a time; safest and slowest. Higher levels are safer but reduce concurrency. Most business code can stay on the default; critical cases (for example grabbing stock) add row locks or optimistic concurrency (check a version number on update).

Component comparison

Local database transaction

Built into the frameworkOpsLow

Bundle multi-step writes in the same database; commit only if all succeed, and roll back everything if an error occurs midway.

Best forMulti-step writes inside one database, such as order + order lines, or debit + bookkeeping.

Avoid whenThe operation spans multiple services or databases and needs an eventually consistent approach.

Pros

The database guarantees ACID, the most reliable and simplest consistency mechanism

One line of framework code opens it, and errors roll back automatically

Most business needs nothing beyond it

Cons

Only covers a single database, and cannot span services or databases

A transaction holds connections and locks, and the longer it lasts the worse concurrency gets, even dragging down the connection pool

Calls to external APIs inside a transaction cannot be rolled back with it and also lengthen the hold time

Optimistic locking (version number)

Built into the frameworkOpsLow

Take no lock up front; on update, check "has anyone else changed this row since I read it" (using a version number), and if so report a conflict and let the caller retry.

Best forAdmin edit forms, document collaboration, and ordinary business where stock contention is not fierce.

Avoid whenThe same row is modified concurrently at high frequency (such as hot product stock), where retries pile up.

Pros

It does not hold a lock for long, so concurrent reads and writes perform better

A good fit when conflicts are rare, such as the occasional simultaneous edit

It stops a later save from quietly overwriting an earlier save

Cons

On a conflict you retry or tell the user, which is one more layer than a normal update

When conflicts are very frequent, a flood of failed retries makes it slower instead

Every piece of code that changes that row must check the version, or the lock is useless

Pessimistic locking (SELECT ... FOR UPDATE)

Built into the frameworkOpsLow

Lock the row as soon as you read it, so anyone who wants to change it must queue and wait until I commit.

Best forStrongly consistent updates to hot data, such as deducting stock or balance.

Avoid whenThe transaction does slow work (calling external APIs), or conflicts are rare and optimistic locking is enough.

Pros

When conflicts are common, requests queue instead of failing and retrying in large numbers

The logic is direct: lock this row first, then read it, then change it

It is reliable for strong consistency, such as taking stock or deducting a balance

Cons

While the lock is held, others are blocked, and one slow transaction slows the whole queue

Waiting on each other's locks causes deadlocks, so you need one lock order and retry handling

It must run inside a transaction, or the lock is released immediately

Saga (step-by-step execution + compensation)

Self-hosted open sourceOpen sourceOpsHigh

Split a long cross-service process into multiple local transactions; when a step fails, run "reverse operations" in turn (such as refund, release stock) to undo what was already done.

Best forOrder-inventory-payment flows genuinely split into multiple services, each with its own database.

Avoid whenThe business is still within one database: a local transaction is simpler and more reliable, and introducing Saga too early is over-engineering.

Pros

Without a distributed transaction, work across services can still end up consistent

Each step is a short local transaction and is not locked for long

The process state can be tracked, and a failure has a clear compensation

Cons

Every step needs a compensation, so both the work and the places to fail increase

Intermediate states are visible, so consistency is eventual rather than immediate

You need messaging or a workflow, and you still have to handle duplicates and idempotency

Checklist

  • Multi-table / multi-step writes live in one transaction
  • Transactions do not call external APIs or do long computation
  • High-contention cases (stock, balances) use locks or version numbers
  • You know your database’s default isolation level
  • Retriable endpoints are paired with idempotency