Database transaction

On this page 8

A database transaction is a sequence of read and write operations that a database management system treats as one indivisible unit of work: either every change becomes permanent together, or none of them does. In Databases, the transaction is the basic mechanism that keeps data correct under concurrency and failure, and it is the concept on which the guarantees of ACID, isolation levels and recovery are built.

A transfer that debits one account and credits another is the classic case. If the server crashes between the two updates, a correctly implemented transaction guarantees that the system restarts with both updates applied or neither, never with money missing or duplicated.

How a database transaction works

A transaction has a clear lifecycle with defined boundaries. It begins explicitly with a statement such as BEGIN or START TRANSACTION, or implicitly when a client in autocommit mode issues a single statement. It ends with a Commit, which makes all changes durable and visible to others, or with a Rollback, which discards them.

Inside the engine, two subsystems cooperate. The concurrency control manager decides what each transaction may see and when it must wait, using locks, multiversion concurrency control (MVCC) or both. The recovery manager records every change in a write-ahead log before the modified data pages reach disk, so that committed work can be replayed and unfinished work undone after a crash.

The following table summarizes the states a transaction passes through and what the engine does in each one.

StateMeaningWhat the engine does
ActiveStatements are executingAcquires locks or snapshots, writes log records
Partially committedLast statement finishedFlushes the commit record to the log
CommittedCommit record is durableReleases locks, makes changes visible
FailedError, conflict or abort requestStops further work on the transaction
AbortedChanges have been undoneApplies undo information, releases locks
Transaction states and engine behavior

The decisive moment is the durable write of the commit record. Once that record is on stable storage, the transaction counts as committed even if the data pages themselves are written much later.

The ACID guarantees behind a transaction

The behavior expected from a transaction is usually summarized by the four ACID properties. Each property is delivered by a different internal mechanism, which explains why engines can relax one guarantee without abandoning the others.

PropertyGuaranteeTypical mechanism
AtomicityAll changes or noneUndo log, rollback segments
ConsistencyDeclared constraints hold after commitConstraint checks, triggers, application logic
IsolationConcurrent work does not interfereLocking, MVCC, conflict detection
DurabilityCommitted data survives crashesWrite-ahead log, fsync, replication
ACID properties and how engines implement them

Consistency is the property most often misunderstood. The database can enforce only the rules it has been told about, such as primary keys, foreign keys and check constraints. A business rule that exists only in application code is protected by a transaction solely if the code reads and writes inside the same transaction with an adequate isolation level.

Isolation levels and concurrency anomalies

Isolation determines how much concurrent transactions can observe of one another. Full isolation, called serializable isolation, makes the outcome equivalent to running transactions one at a time, but it costs throughput through waiting or aborts. Weaker levels allow specific concurrency anomalies in exchange for better performance.

The table below shows which anomalies each common level permits. Exact behavior varies by engine; for example, PostgreSQL implements repeatable read as snapshot isolation, which prevents phantom reads but still allows write skew.

Isolation levelDirty readNon-repeatable readPhantom readWrite skew
Read uncommittedPossiblePossiblePossiblePossible
Read committedPreventedPossiblePossiblePossible
Repeatable readPreventedPreventedEngine dependentPossible
Snapshot isolationPreventedPreventedPreventedPossible
SerializablePreventedPreventedPreventedPrevented
Anomalies permitted at common isolation levels

Most production systems run at read committed by default, which is the default in PostgreSQL, Oracle Database and SQL Server, while MySQL InnoDB defaults to repeatable read. Developers who assume stronger guarantees than the default provides are a frequent source of lost updates and silent data corruption.

Local, distributed and long-running transactions

Transactions differ by scope and duration, and each variant carries its own costs. A local transaction touches one database instance and is cheap to coordinate. A distributed transaction spans several resources and needs a coordination protocol such as two-phase commit, which adds network round trips and a blocking risk if the coordinator fails.

VariantScopeCoordinationMain trade-off
Local transactionSingle databaseEngine internalFast, but limited to one system
Distributed transactionSeveral databases or queuesTwo-phase commit, XAStrong guarantees, higher latency
Nested work with savepointsPart of one transactionSavepoint markersPartial rollback without full abort
SagaSeveral servicesCompensating actionsNo global isolation, eventual consistency
Transaction variants compared

Microservice architectures often replace distributed transactions with sagas, a chain of local transactions in which each step has a compensating action. A saga gives up isolation between steps, so intermediate states are visible, and the application must tolerate them.

Designing transactions in practice

Good transaction design keeps units of work short, explicit and well bounded. A transaction that holds locks or an old snapshot while waiting for user input, a remote API call or a long report blocks other sessions, inflates undo or version storage and raises the probability of deadlocks.

  • Keep transactions short: perform slow external calls before or after the transaction, not inside it.
  • Choose the isolation level deliberately for each workload instead of relying on the default.
  • Retry on serialization failures and deadlock errors, because these aborts are expected behavior at strict levels.
  • Access rows in a consistent order to reduce deadlocks between concurrent transactions.
  • Use optimistic locking with a version column when conflicts are rare and transactions span user think time.

The next table maps common symptoms to their usual causes and remedies.

SymptomLikely causeFix
Frequent deadlock errorsInconsistent lock orderOrder row access, shorten transactions
Growing version or undo storageIdle transaction holding old snapshotSet idle timeouts, close sessions promptly
Counter values lost under loadRead-modify-write at read committedAtomic update or SELECT ... FOR UPDATE
Rising commit latencySynchronous log flush per commitGroup commit, faster log storage
Transaction problems, causes and fixes

Limitations and common misconceptions

A transaction is not a universal correctness guarantee. It protects only the operations executed inside its boundaries on resources that participate in it. Sending an email or calling a payment gateway from inside a transaction cannot be rolled back, so such side effects need idempotency or an outbox pattern.

Another misconception is that a commit acknowledged to the client is always safe. Durability depends on configuration: settings that disable synchronous log flushing or acknowledge commits before replicas confirm them trade a small window of possible data loss for lower latency. Finally, a serializable level does not remove the need for retries, because the engine guarantees correctness precisely by aborting conflicting transactions.

Explained without jargon

Think of a database transaction as a sealed envelope of instructions. The database opens the envelope and carries out every instruction inside, but it only announces the result when all of them have succeeded. If anything goes wrong halfway, it puts everything back exactly as it was.

This matters because many tasks consist of several steps that only make sense together, such as taking money from one account and adding it to another. The key idea is simple: a transaction is all or nothing, so other people never see a half-finished job, and a crash never leaves the data in a broken state.

A typical use case

An online ticket shop sells seats for a concert with 2,000 places. When a customer checks out, the application starts a transaction, locks the chosen seat rows with SELECT ... FOR UPDATE, confirms the seats are still free, inserts an order row, marks the seats as sold and then commits. The payment authorization happens before the transaction starts, so locks are held for only a few milliseconds.

During a sales rush, two customers occasionally choose the same seat at the same moment. The second transaction waits for the lock, then finds the seat already sold and returns a clear message instead of creating a duplicate booking. The result is zero double-sold seats across thousands of concurrent checkouts, and a crash during checkout leaves no orphaned orders because the unfinished transaction is rolled back on restart.