Skip to content

ACID & Transactions ​

"These four properties, atomicity, consistency, isolation, and durability (ACID), describe the major highlights of the transaction paradigm." — Theo Härder & Andreas Reuter, "Principles of Transaction-Oriented Database Recovery", ACM Computing Surveys 15(4), December 1983

Summary: A transaction is a group of operations that the database treats as one unit; ACID names the four promises that unit makes (all-or-nothing, rule-respecting, unseen-while-running, survives-a-crash). Focus: What each property really promises and how it is built (undo, constraints, levels, WAL + fsync), how BEGIN / COMMIT / ROLLBACK / savepoints behave in PostgreSQL, MySQL, SQLite, Redis and MongoDB, and where in application code the transaction boundary belongs. Learning goal: Be able to draw the boundary of a use case's transaction, say what is and is not covered by it, handle a failed COMMIT, and know which neighbouring mechanism (isolation, WAL, saga, outbox) takes over where ACID stops.

This page is the complete reference for the transaction itself: the four ACID properties with their original definitions and the mechanism behind each, the statements that control a transaction (BEGIN, COMMIT, ROLLBACK, SAVEPOINT, ROLLBACK TO, RELEASE SAVEPOINT, SET CONSTRAINTS, SET TRANSACTION), autocommit and implicit transactions, nested transactions and what each library really does, transaction boundaries in application code, long transactions, read-only transactions, deferrable constraints, PREPARE TRANSACTION and the two-phase commit pointer, BASE versus ACID, and how MongoDB, Redis and SQLite define "transaction" by comparison. It does not re-teach three neighbours. Anomalies and levels are in Isolation Levels. WAL internals and recovery are in Durability, WAL & Crash Recovery. Transactions across several databases are in Distributed SQL, Consensus & 2PC. Row versions and the cost of old snapshots are in MVCC, VACUUM & Bloat; lock modes are in Locks & Concurrency.

Page map ​

If you are looking forGo to
The four properties in one tableEverything in one minute
Why transactions exist and the trade-offWhy transactions exist
Gray 1981, Härder & Reuter 1983 and what they actually saidWhere the vocabulary comes from
One block per property: atomicity, consistency, isolation, durabilityThe four properties, one by one
BEGIN, COMMIT, ROLLBACK, the transaction block, the aborted stateControlling a transaction
Autocommit and implicit transactions per productAutocommit and implicit transactions
SAVEPOINT, ROLLBACK TO, nested transactions in Laravel, Go, SQL ServerSavepoints and nested transactions
Constraint timing, DEFERRABLE INITIALLY DEFERRED, SET CONSTRAINTSDeferrable constraints
Read-only and DEFERRABLE read-only transactionsRead-only transactions
Long transactions, idle in transaction, timeoutsLong transactions
synchronous_commit, WAL flush, group commitDurability knobs
Where to put BEGIN in a web request or jobTransaction boundaries in application code
Redis, MongoDB, SQLite, MySQL, SQL Server, Oracle side by sideWhat each product calls a transaction
Error codes and a failed COMMITMechanics
SQL, Go and Laravel codeSolving the classic problems
BASE, 2PC, XA, sagas, outboxBeyond one database
Which tool for which situationChoosing
Monolith to distributed systemIn architecture
Reproduce it in two terminalsLab

Everything in one minute ​

The four properties. Every row is unpacked in the properties section.

PropertyIn plain wordsBuilt fromWhat it does NOT cover
AtomicityAll of it happens or none of itUndo information (InnoDB undo log) or invisibility of an aborted transaction's row versions (PostgreSQL MVCC)Emails sent, HTTP calls made, other databases
ConsistencyThe data obeys the declared rules before and afterPRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, CHECK, triggers, plus application rulesRules nobody wrote down
IsolationConcurrent transactions do not see each other's half-done workLocks, snapshots (MVCC), serialization checks; offered as levelsAnything outside one database
DurabilityA commit that was acknowledged survives a crashWAL / redo log flushed with fsync before the acknowledgement; group commit to share the flushA disk that lies, a lost data centre without replication

The statements.

StatementWhat it doesExample
BEGIN / START TRANSACTIONOpens a transaction blockBEGIN;
COMMITMakes the changes permanent and visibleCOMMIT;
ROLLBACKDiscards everything since BEGINROLLBACK;
SAVEPOINT nameMarks a point inside the blockSAVEPOINT before_bonus;
ROLLBACK TO nameUndoes work after the marker, block stays openROLLBACK TO before_bonus;
RELEASE SAVEPOINT nameForgets the marker, undoes nothingRELEASE SAVEPOINT before_bonus;
SET CONSTRAINTS ... DEFERREDPostpones deferrable constraint checks to COMMITSET CONSTRAINTS ALL DEFERRED;
SET TRANSACTION READ ONLYDeclares the block read-onlySET TRANSACTION READ ONLY;
PREPARE TRANSACTION 'id'Phase one of two-phase commit (PostgreSQL)PREPARE TRANSACTION 'tx-42';

The three things to do.

SituationDo this
A business operation changes several rowsOne transaction around exactly those database writes, opened in the use-case layer
The operation also calls a payment API, sends mail or publishes an eventKeep the call outside the transaction; publish after commit or through an outbox; make it idempotent
COMMIT returned an errorThe transaction did not commit; treat it like any failure and retry the whole use case only if it is safe to run again

Why transactions exist ​

Without transactions, every multi-step change is a bet that nothing fails between step one and step two. A transfer of 100 from account A to account B is two writes. A crash, a deadlock, a lost connection or a bug between them leaves 100 missing. Transactions turn the bet into a guarantee: the database either applies the whole group or none of it, and it does so while other users keep working.

You chooseYou getYou pay
No transaction (autocommit per statement)Lowest latency, no locks held across statementsPartial failures are permanent; no multi-statement invariants
Short transaction around one use caseAtomic business operation, rule checks at the boundaryLocks and snapshots held for the transaction's lifetime; retries on conflict
Long transaction (minutes)One consistent view for a big jobBlocked writers, bloat, replication delay, timeouts
Distributed transaction (2PC, XA)Atomic across several resource managersBlocking on coordinator failure, latency, operational burden

The everyday picture. A house purchase uses an escrow agent. The buyer's money, the seller's deed and the mortgage papers are held together, and the handover happens only when every condition is met. If one piece fails, the escrow returns everything, and nobody is left holding half the deal. That is atomicity. The escrow does not check that the house is worth the price (consistency is about declared rules), it does not stop someone from moving in before the papers are signed (isolation), and it does not matter if the notary's office burns down the day after, because the signed record was copied elsewhere first (durability).

Three common misunderstandings, up front ​

  • "ACID means the database enforces my business rules." It enforces the constraints you declared. Everything else is the application's job.
  • "Atomic means no one can see my changes half-done." That is isolation. The two get confused because PostgreSQL's tutorial phrases atomicity "from the point of view of other transactions".
  • "Wrapping a request in a transaction makes an external call atomic." A payment API call cannot be rolled back by your database. It needs an idempotency key and a compensating action.

Where the vocabulary comes from ​

Jim Gray's 1981 Tandem technical report, The Transaction Concept: Virtues and Limitations, is the earliest source read for this page for the idea that a unit of database work should be atomic and durable. Its central statement is that "Transactions must be atomic and durable: either all actions are done and the transaction is said to commit, or none of the effects of the transaction survive and the transaction is said to abort."

Gray also gives the legal analogy that makes atomicity easy to picture. A contract "either happens or it does not; either all are bound by the contract or none are".

Härder and Reuter's 1983 survey, Principles of Transaction-Oriented Database Recovery, is where the four-letter name appears in the text. They list four properties and then write "(ACID)". Secondary sources usually credit them with coining the acronym; earlier uses were not checked, so treat the attribution as the standard citation rather than a proven first use. The same paper says the properties "describe the major highlights of the transaction paradigm", and it defines consistency this way: each successful transaction "commits only legal results".

Gray's 1981 report lists consistency and isolation too, but its emphasis is on atomicity and durability, the two properties that depend most on the recovery machinery. Isolation is where most of the research happened after 1981; see Isolation Levels.

The four properties, one by one ​

Atomicity Must-know ​

In plain words: A transaction's changes take effect all together or not at all. If anything goes wrong halfway, the database puts everything back as it was.

Common misunderstanding: "Atomic means instantaneous, or that nobody can see the middle." Atomicity is about the outcome (all or nothing). Whether another session may see the middle is isolation. And it only covers the database's own data: an email that was sent stays sent.

Definition: PostgreSQL's tutorial states it as: "A transaction is said to be atomic: from the point of view of other transactions, it either happens completely or not at all."

How it is built. Two designs exist, and the difference matters when you read the other chapters.

EngineMechanism for "none of it"What ROLLBACK costs
PostgreSQLNo undo log. Every UPDATE writes a new row version into the table; the transaction id is recorded as aborted, and MVCC visibility rules treat that version as invisible. VACUUM reclaims it laterAlmost nothing: mark the transaction aborted; dead versions remain until VACUUM
MySQL InnoDBRow is changed in place; the old value goes to the undo log. ROLLBACK applies undo records backwardsProportional to the work done: a huge transaction can take as long to roll back as it took to run
OracleUndo segments (undo tablespace) hold prior values, used for both rollback and read consistencyProportional to the work done
SQL ServerTransaction log holds before-images; row-versioning options use tempdb or the persistent version storeProportional to the work done
SQLiteRollback journal (copy of original pages) or WAL; a rollback discards the journal / WAL framesSmall for typical sizes

The redo side (what survives a crash) is the other half of the machinery and is described under durability.

Timeline:

     Session A                                   Session B
1    BEGIN;
2    UPDATE accounts SET balance = balance - 100 WHERE id = 1;
3                                                SELECT balance FROM accounts WHERE id = 1;  -- old value
4    UPDATE accounts SET balance = balance + 100 WHERE id = 2;  -- ERROR: connection lost
5    -- server rolls the transaction back
6                                                SELECT balance FROM accounts WHERE id = 1;  -- old value
     -- the 100 never left account 1

Real scenarios: a transfer of money; creating an order header plus its lines; moving a user between two groups; a schema migration with several ALTER TABLE statements (transactional DDL in PostgreSQL and SQLite, not in MySQL or Oracle).

What provides it: a transaction block (explicit BEGIN or the implicit one around a single statement). Without it you do not have atomicity across statements.

Fix / how to use it:

sql
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1 AND balance >= 100;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;

Go and Laravel versions are in Solving the classic problems.

Consistency Must-know ​

In plain words: After a transaction commits, the data still obeys the rules. The database refuses the commit if a rule it knows about would be broken.

Common misunderstanding: "The C in ACID means the database keeps my data correct." It keeps the rules you declared. A rule such as "the sum of all balances must not change" is enforced only if someone encoded it, as a constraint, a trigger, or application code inside the transaction. Härder and Reuter's definition says a successful transaction "commits only legal results"; what is legal is decided by the rules the application and schema declare.

Definition: The database moves from one state that satisfies all declared integrity constraints to another. Consistency is the one property that is mostly a joint effort: the database provides the checking, the designer provides the rules. (The "C" in CAP is a different word with a different meaning, see Beyond one database.)

The constraint toolbox:

ConstraintRule it enforcesViolation SQLSTATE (PostgreSQL)MySQL error
PRIMARY KEY / UNIQUENo duplicates23505 unique_violation1062
NOT NULLA value must exist23502 not_null_violation1048
FOREIGN KEYThe referenced row exists; no orphans23503 foreign_key_violation1451 / 1452
CHECKA row-level predicate such as balance >= 023514 check_violation3819 (MySQL 8.0.16+)
Exclusion constraint (PostgreSQL)No two rows overlap (bookings)23P01 exclusion_violationnone
TriggerAnything you can code, including cross-row ruleswhatever the trigger raiseswhatever the trigger raises

Timeline:

     Session A
1    BEGIN;
2    INSERT INTO order_lines (order_id, product_id, qty) VALUES (999, 1, 1);
3    -- ERROR: insert or update on table "order_lines" violates foreign key constraint
4    -- SQLSTATE 23503. The block is now aborted.
5    COMMIT;   -- PostgreSQL performs a ROLLBACK and reports ROLLBACK

Real scenarios: CHECK (balance >= 0) stops overdrafts even if the application forgot the test; a foreign key stops an order line pointing at a deleted product; a unique index stops two signups with one email (see Isolation Levels for why a prior SELECT is not enough).

What provides it, and the limit. Constraints are checked inside the transaction (immediately per statement, or at commit if deferrable, see Deferrable constraints). They cannot see other databases, caches or services. A rule that spans two services is application logic with a saga or reconciliation.

Fix / how to use it: declare the rule in the schema first; use application code only for rules SQL cannot say.

sql
CREATE TABLE accounts (
    id      bigint PRIMARY KEY,
    owner   text   NOT NULL,
    balance bigint NOT NULL CHECK (balance >= 0)
);

Isolation Must-know ​

In plain words: Two transactions running at the same time should not trip over each other's unfinished work. How strictly the database enforces that is your choice of level.

Common misunderstanding: "I am inside a transaction, so I am fully isolated." Only at the level you chose, and the default (Read Committed in PostgreSQL, Oracle and SQL Server; Repeatable Read in MySQL InnoDB) still allows anomalies.

Definition: The result of concurrent transactions is as if some controlled interleaving had happened; the levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable, and the Snapshot Isolation variants) say which anomalies remain possible. This page needs exactly this much; the anomalies, the per-engine behaviour and the choice of level are in Isolation Levels.

Timeline: see the two-session timelines in Isolation Levels.

What provides it: locks (two-phase locking), snapshots (MVCC), serialization checks (PostgreSQL SSI). Details in MVCC, VACUUM & Bloat and Locks & Concurrency.

Durability Must-know ​

In plain words: When the database says "committed", the data is on disk (or on enough machines) and will still be there after a power cut.

Common misunderstanding: "COMMIT writes the table pages to disk." It does not. Commit writes a small log record to the write-ahead log and forces that log to stable storage; the table pages are written later and can be rebuilt from the log after a crash.

Definition: Härder and Reuter describe the user's need in these words: "the user must have a guarantee that the things the system says have happened have actually happened." Durability is a promise about what happened before the acknowledgement.

How it is built (overview). The write-ahead rule: the log record describing a change must reach stable storage before the changed page does, and the commit record must reach stable storage before the client hears "committed".

StepWhat happens
1Changes go to the shared buffers / buffer pool and are described by WAL (PostgreSQL) or redo log (InnoDB) records
2At COMMIT, a commit record is appended to the log
3The log is flushed to disk with fsync (or fdatasync, O_DSYNC, depending on wal_sync_method in PostgreSQL)
4Only then does the server answer "COMMIT"
5Dirty table pages are written lazily by the background writer and checkpoints
6After a crash, recovery replays the log from the last checkpoint (redo) and discards uncommitted work

Group commit. Flushing the log is the expensive step. When many transactions commit at nearly the same time, one flush can cover all of them: this is group commit. PostgreSQL batches naturally (whoever flushes covers everyone whose record is already in the buffer) and exposes commit_delay and commit_siblings to wait a little for company; InnoDB groups commits too, and innodb_flush_log_at_trx_commit controls whether each commit flushes (1, the default, is the durable setting), writes without flush (2) or flushes about once a second (0).

Timeline:

     Backend                                  WAL / disk
1    BEGIN; UPDATE ...                         -- change recorded in buffers + WAL buffer
2    COMMIT                                    -- append commit record
3                                              -- fsync(WAL)  <-- the durability point
4    "COMMIT" returned to client
5    ...                                       -- later: checkpoint writes the table pages
6    crash                                     -- recovery replays WAL: committed change is back

Real scenarios: a payment acknowledged to a customer must survive a crash; a counter for page views may not need to.

What provides it: the WAL with fsync = on (PostgreSQL default), synchronous_commit = on (default). Weaker settings trade durability for speed, see Durability knobs. For recovery details, checkpoints, torn pages and replication, see Durability, WAL & Crash Recovery.

Controlling a transaction ​

The picture below is the lifecycle of one session in PostgreSQL: autocommit, an open block with savepoints, the aborted state after an error, and the two ways out.

Idleautocommit on:one statement = one txnIn transaction (block)statements run, locks heldsavepoint s1 setROLLBACK TO s1 keeps the block openRELEASE s1 only drops the markerAborted blockonly ROLLBACK / ROLLBACK TO acceptedEndedchanges durable or gonethen back to IdleBEGINCOMMITstatement errorROLLBACK

BEGIN, COMMIT, ROLLBACK Must-know ​

In plain words: BEGIN says "start grouping", COMMIT says "keep it all", ROLLBACK says "throw it all away".

Common misunderstanding: "If a statement fails, the transaction rolls back by itself." In PostgreSQL it does not end; it goes into an aborted state that only COMMIT (which then rolls back) or ROLLBACK can leave.

Definition: In PostgreSQL, "a transaction is set up by surrounding the SQL commands of the transaction with BEGIN and COMMIT commands." A group of statements surrounded by BEGIN and COMMIT is sometimes called a transaction block in the tutorial's wording. ROLLBACK discards everything since BEGIN.

Timeline (PostgreSQL):

1    BEGIN;
2    INSERT INTO accounts VALUES (1, 'ana', 100);
3    INSERT INTO accounts VALUES (1, 'bob', 50);
4    -- ERROR: duplicate key value violates unique constraint "accounts_pkey"  (23505)
5    SELECT 1;
6    -- ERROR: current transaction is aborted, commands ignored until end of transaction block  (25P02)
7    ROLLBACK;

Real scenarios: a script that runs a dozen statements and stops on the first failure; a migration; a manual fix in psql where you want a chance to look before you COMMIT.

Per product:

ProductStartEndAfter a statement error inside the block
PostgreSQLBEGIN / START TRANSACTIONCOMMIT / END, ROLLBACK / ABORTBlock is aborted (25P02); only ROLLBACK / ROLLBACK TO / COMMIT accepted
MySQL InnoDBSTART TRANSACTION / BEGINCOMMIT, ROLLBACKOnly the failed statement is rolled back; the transaction stays open and usable
SQL ServerBEGIN TRANSACTIONCOMMIT TRANSACTION, ROLLBACK TRANSACTIONDepends on SET XACT_ABORT: ON rolls back the whole transaction on most run-time errors, OFF leaves it open
OracleImplicit at first DMLCOMMIT, ROLLBACKOnly the failed statement is rolled back
SQLiteBEGIN (DEFERRED default)COMMIT / END, ROLLBACKOnly the failed statement is rolled back, unless an ON CONFLICT ROLLBACK clause says otherwise

What it provides: the boundary of atomicity. Fix: always pair every BEGIN with exactly one of COMMIT or ROLLBACK on every code path; in code, use a helper that guarantees it, see Solutions.

The aborted transaction block (25P02) Important ​

In plain words: In PostgreSQL, after one error the rest of the block is useless until you roll back or roll back to a savepoint.

Common misunderstanding: "I can catch the error and carry on with the same transaction." You can only if you set a savepoint before the risky statement and ROLLBACK TO it. Otherwise every later statement fails with 25P02 in_failed_sql_transaction. MySQL InnoDB and Oracle behave the other way: the statement is undone, the transaction continues.

Definition: Transaction state "aborted": the engine keeps the block open so the client sees that an error occurred, but accepts only statements that end the block or roll back to a savepoint. COMMIT in this state is turned into ROLLBACK by the server.

Why it matters in code: a try/catch around one statement inside a transaction does not repair the transaction in PostgreSQL. The classic bug is catching a unique violation to "ignore duplicates" and then continuing in the same transaction, which fails on the next statement. Use INSERT ... ON CONFLICT DO NOTHING, or a savepoint around the risky statement.

Fix:

sql
BEGIN;
SAVEPOINT try_insert;
INSERT INTO users (email) VALUES ('a@example.com');   -- may violate UNIQUE
-- on error:
ROLLBACK TO try_insert;                               -- block is usable again
-- on success:
RELEASE SAVEPOINT try_insert;
COMMIT;

Transaction control statements outside a block Good to know ​

In plain words: Using COMMIT or SAVEPOINT when no transaction is open does different things in different products.

Statement outside a blockPostgreSQLMySQLSQLite
COMMIT / ROLLBACKWarning "there is no transaction in progress"No effectError "cannot commit - no transaction is active"
SAVEPOINT xError: SAVEPOINT can only be used in transaction blocks (25P01)Works if a transaction is active; in autocommit it has no useful effectStarts a transaction if none is open (a "SAVEPOINT transaction")
BEGIN inside a blockWarning "there is already a transaction in progress"Implicitly commits the current transaction firstError: cannot start a transaction within a transaction

PostgreSQL's SAVEPOINT reference says: "Savepoints can only be established when inside a transaction block."

Autocommit and implicit transactions ​

Autocommit and the implicit transaction Must-know ​

In plain words: If you never type BEGIN, each statement is its own tiny transaction that commits as soon as it succeeds.

Common misunderstanding: "No BEGIN means no transaction." Every statement always runs in a transaction. Without BEGIN you just get one transaction per statement, which gives you atomicity for that statement and nothing across statements.

Definition: PostgreSQL's tutorial describes it precisely: "If you do not issue a BEGIN command, then each individual statement has an implicit BEGIN and (if successful) COMMIT wrapped around it." That is autocommit mode, with an implicit transaction around each statement.

Timeline:

1    UPDATE accounts SET balance = balance - 100 WHERE id = 1;   -- implicit BEGIN ... COMMIT, durable now
2    -- process crashes here
3    UPDATE accounts SET balance = balance + 100 WHERE id = 2;   -- never runs; the 100 is gone

Real scenarios: the controller with two update() calls in the "before" snippet below; a cron script that runs three SQL files with psql -f; an ORM save() per model.

Per product:

ProductDefault modeHow to group statementsNotes
PostgreSQLAutocommit (client sends each statement on its own)BEGIN ... COMMIT; psql --single-transaction; psql variable AUTOCOMMITServer has no autocommit switch; it is a client behaviour. BEGIN is a real server command
MySQL / InnoDBautocommit = 1START TRANSACTION, or SET autocommit = 0 (then every statement joins an open transaction)DDL such as CREATE TABLE causes an implicit commit
SQL ServerAutocommitBEGIN TRANSACTION; or SET IMPLICIT_TRANSACTIONS ON (a transaction starts at the first statement and ends only when you commit)@@TRANCOUNT shows the nesting count
OracleThe server has no autocommit; a transaction starts at the first DML and ends at COMMIT / ROLLBACKClient tools may add autocommitDDL commits implicitly
SQLiteAutocommitBEGINTransaction around each statement unless BEGIN is used
JDBC / database driversOften autoCommit = true; PHP PDO autocommit onsetAutoCommit(false) / beginTransaction()Check the driver default

Implicit transactions you may not notice: a single UPDATE that touches a million rows is atomic (one transaction); a INSERT ... SELECT is atomic; a multi-row INSERT is atomic; TRUNCATE and DDL are transactional in PostgreSQL and SQLite but implicitly commit in MySQL and Oracle. Many drivers and ORMs open and close transactions for you (Eloquent's save() is one implicit transaction; a pooled database/sql call is a separate connection and transaction each time), so check what your library does before assuming a request is atomic.

Fix: group related statements explicitly with a transaction helper, see Solutions.

The transaction block in psql Good to know ​

psql shows the state in its prompt if you set PROMPT1 with %x: => is idle, =*> is inside a transaction block, =!> is an aborted block. \set AUTOCOMMIT off makes psql open a block before each first statement (a client feature, not a server mode). psql --single-transaction -f file.sql wraps the file in BEGIN / COMMIT.

Savepoints and nested transactions ​

Savepoints Must-know ​

In plain words: A savepoint is a bookmark inside a transaction. You can go back to the bookmark without throwing away the work before it.

Common misunderstanding: "A savepoint is a smaller, independent transaction." It is not. It cannot commit on its own; its work becomes permanent only when the outer transaction commits, and if the outer transaction rolls back the savepoint's work goes with it.

Definition: SAVEPOINT name marks a point. ROLLBACK TO [SAVEPOINT] name undoes everything after the marker and keeps the transaction (and the marker) open. RELEASE SAVEPOINT name discards the marker and keeps the work. Savepoints nest: rolling back to an earlier one destroys later ones.

Timeline:

1    BEGIN;
2    INSERT INTO orders (id) VALUES (1);          -- kept
3    SAVEPOINT bonus;
4    INSERT INTO bonuses (order_id) VALUES (1);
5    -- campaign closed, application decides to skip the bonus
6    ROLLBACK TO bonus;                           -- bonuses row gone, orders row stays
7    COMMIT;                                      -- orders row committed

Real scenarios: "try this optional step, carry on if it fails"; importing 10,000 rows and skipping a bad row without losing the other 9,999; the Laravel nested DB::transaction (below); test frameworks that wrap each test in a transaction and savepoints.

Per product:

ProductSyntaxNotes
PostgreSQLSAVEPOINT, ROLLBACK TO, RELEASESavepoints can only be established inside a transaction block; subtransactions cost shared memory: more than 64 open subtransactions in one transaction overflows the per-backend cache and can slow every snapshot (pg_subtrans pressure)
MySQL InnoDBSAVEPOINT, ROLLBACK TO SAVEPOINT, RELEASE SAVEPOINTSavepoints work inside InnoDB transactions; consult the MySQL manual for how row locks taken after a savepoint behave on ROLLBACK TO
SQL ServerSAVE TRANSACTION name, ROLLBACK TRANSACTION nameDifferent keyword; no RELEASE
OracleSAVEPOINT, ROLLBACK TO SAVEPOINTNo RELEASE
SQLiteSAVEPOINT, ROLLBACK TO, RELEASERELEASE of the outermost savepoint commits when no BEGIN was used
MongoDB, RedisNoneNo partial rollback

Fix / how to use it: one savepoint per risky statement, always released or rolled back; do not create one per row of a bulk loop without need (see the PostgreSQL subtransaction note above).

Nested transactions Important ​

In plain words: "Nested transaction" usually means "a savepoint with a friendlier name".

Common misunderstanding: "An inner commit() commits the inner part for real." In almost every system the inner commit is a no-op or a RELEASE. Only the outermost commit makes anything permanent, and an outer rollback undoes the inner work too.

Definition: True nested transactions (Moss 1981) are rare. What the products offer:

SystemWhat "nested" isInner failureOuter rollback
PostgreSQLNo nested transactions, only savepointsROLLBACK TOEverything undone
MySQLSTART TRANSACTION inside a transaction implicitly commits the firstn/an/a (the first part is already committed)
SQLite"Transactions created using BEGIN...COMMIT do not nest. For nested transactions, use the SAVEPOINT and RELEASE commands."ROLLBACK TOEverything undone
SQL ServerBEGIN TRAN increments @@TRANCOUNT; inner COMMIT only decrements; any ROLLBACK without a name rolls back everything to zeroRoll back everything or use SAVE TRANSACTIONEverything undone
LaravelDB::transaction inside a transaction emits a savepointRolls back to the savepoint and rethrowsEverything undone
Go database/sqlNone; Tx has no BeginYou may send SAVEPOINT as SQLn/a
pgx (Go)tx.Begin(ctx) returns a "pseudo nested" transaction implemented with a savepointRolls back to the savepointEverything undone

Laravel in detail. In ManagesTransactions::createTransaction, when a transaction is already open and the query grammar supports savepoints, the inner DB::transaction runs SAVEPOINT transN. If the inner closure throws, performRollBack runs ROLLBACK TO that savepoint and rethrows. DB::rollBack($toLevel) also takes a level. The outer transaction decides the rest.

Timeline (Laravel with PostgreSQL):

1    DB::transaction(outer)         -- BEGIN                       transactions = 1
2      move money
3      DB::transaction(inner)       -- SAVEPOINT trans2            transactions = 2
4        increment bonus
5        throw BonusUnavailable     -- ROLLBACK TO SAVEPOINT trans2 ; transactions = 1 ; rethrow
6      catch BonusUnavailable       -- outer continues
7    leaving outer                  -- COMMIT                      transfer kept, bonus gone

Go. database/sql has no nested transactions and no savepoint method. The Tx type has Commit, Rollback, and the Exec, Query, QueryRow, Prepare and Stmt families (with context-taking variants). You can still send SAVEPOINT and ROLLBACK TO as SQL through tx.Exec, but the package does not track them. If you use pgx directly, tx.Begin gives you a savepoint-based pseudo nested transaction.

Fix: put attempts and retry logic on the outermost call only (see Laravel); never rely on an inner commit being permanent.

Deferrable constraints ​

Constraint timing: IMMEDIATE, DEFERRED, SET CONSTRAINTS Important ​

In plain words: Normally a rule is checked right after each statement. A deferrable rule can be postponed to COMMIT, so you may be temporarily wrong in the middle.

Common misunderstanding: "Constraints are always checked per statement, so a circular foreign key or a swap of two unique values is impossible." With deferrable constraints, inserting two rows that reference each other, or swapping two unique values, works as long as the end state is valid.

Definition: PostgreSQL's SET CONSTRAINTS reference: "Upon creation, a constraint is given one of three characteristics: DEFERRABLE INITIALLY DEFERRED, DEFERRABLE INITIALLY IMMEDIATE, or NOT DEFERRABLE. The third class is always IMMEDIATE and is not affected by the SET CONSTRAINTS command."

Which constraints can be deferred:

ConstraintPostgreSQLMySQL InnoDBOracleSQL ServerSQLite
FOREIGN KEYYes (DEFERRABLE)No (checked immediately row by row)YesNo (use NOCHECK temporarily)Yes (DEFERRABLE INITIALLY DEFERRED)
UNIQUE / PRIMARY KEYYesNoYesNoNo
EXCLUDEYesnonenonenonenone

Timeline (PostgreSQL):

1    CREATE TABLE person (id int PRIMARY KEY, spouse int REFERENCES person(id) DEFERRABLE INITIALLY IMMEDIATE);
2    BEGIN;
3    SET CONSTRAINTS ALL DEFERRED;
4    INSERT INTO person VALUES (1, 2);       -- spouse 2 does not exist yet: accepted
5    INSERT INTO person VALUES (2, 1);
6    COMMIT;                                  -- foreign keys checked now: OK
     -- had row 2 never been inserted, COMMIT would fail with 23503

Real scenarios: circular references (employee and department head); loading a dump table by table; reordering a position column with a unique constraint (UPDATE ... SET position = position + 1 fails in the middle with an immediate unique constraint); ORM batches that insert children before parents.

In PostgreSQL CHECK and NOT NULL constraints are never deferrable.

Where the error appears: with a deferred constraint, the violation is raised at COMMIT, not at the statement that caused it. A COMMIT that returns an error must be handled (see A failed COMMIT). SET CONSTRAINTS takes a list of constraint names or ALL and affects only deferrable ones.

Fix:

sql
ALTER TABLE person
  ADD CONSTRAINT person_spouse_fk FOREIGN KEY (spouse) REFERENCES person (id)
  DEFERRABLE INITIALLY DEFERRED;

BEGIN;
SET CONSTRAINTS person_spouse_fk IMMEDIATE;   -- check right now instead of at COMMIT, to fail early
COMMIT;

PostgreSQL's unique constraint caveat: only UNIQUE constraints declared DEFERRABLE (not unique indexes) can be deferred, and a deferred unique check is slightly slower.

Read-only transactions ​

READ ONLY and DEFERRABLE Good to know ​

In plain words: You tell the database "this transaction will only read", and it can often do less work and give you stronger guarantees.

Common misunderstanding: "A read-only transaction is just a hint." In PostgreSQL it is enforced: any write fails with 25006 (read_only_sql_transaction). In MySQL it is an enforcement plus an optimisation (InnoDB skips transaction-id allocation for read-only transactions).

Definition: In PostgreSQL, BEGIN READ ONLY or SET TRANSACTION READ ONLY. The SET TRANSACTION reference says: "The DEFERRABLE transaction property has no effect unless the transaction is also SERIALIZABLE and READ ONLY. When all three of these properties are selected for a transaction, the transaction may block when first acquiring its snapshot, after which it is able to run without the normal overhead of a SERIALIZABLE transaction and without any risk of contributing to or being canceled by a serialization failure. This mode is well suited for long-running reports or backups."

Timeline:

1    BEGIN ISOLATION LEVEL SERIALIZABLE, READ ONLY, DEFERRABLE;
2    -- may wait here for a safe snapshot
3    SELECT sum(balance) FROM accounts;        -- consistent, never cancelled by 40001
4    COMMIT;

Real scenarios: a nightly export, pg_dump --serializable-deferrable, a report that must see one consistent state; routing read traffic to a replica (a replica is read-only: 25006 / "cannot execute INSERT in a read-only transaction").

Per product: PostgreSQL READ ONLY, DEFERRABLE, default_transaction_read_only; MySQL START TRANSACTION READ ONLY (InnoDB optimisation, writes error 1792); SQL Server has no read-only transaction but READ_COMMITTED_SNAPSHOT / SNAPSHOT; Oracle SET TRANSACTION READ ONLY (transaction-level read consistency); SQLite: a deferred transaction that never writes is a read transaction.

Fix / how to use it: in Go, db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}); in Laravel there is no dedicated API, so run DB::statement('SET TRANSACTION READ ONLY') right after beginTransaction() for PostgreSQL / MySQL.

Long transactions ​

A long transaction is a smell Must-know ​

In plain words: A transaction that stays open for a long time holds locks, blocks others, and stops cleanup. It is almost never intentional.

Common misunderstanding: "An idle transaction costs nothing because it is not running anything." A connection that has sent BEGIN and then waits is idle in transaction; it still holds its locks and its snapshot, and so blocks VACUUM from removing old rows. PostgreSQL's reference says an open transaction "prevents vacuuming away recently-dead tuples that may be visible only to this transaction; so remaining idle for a long time can contribute to table bloat."

Definition: A long transaction is one open far longer than the work needs. Typical causes: an HTTP/RPC call inside the transaction, a loop over a huge dataset, a client that crashed after BEGIN but whose connection is still open, a debugger on a breakpoint, an ORM session that spans a whole request including template rendering.

Consequences:

EffectMechanism
Blocked writers and long lock queuesRow and table locks are held until COMMIT / ROLLBACK
Table and index bloat (PostgreSQL)Dead tuples visible to the old snapshot cannot be removed, see MVCC, VACUUM & Bloat
Undo growth (InnoDB history list length)Purge cannot remove undo records the old read view may need
xmin horizon held back, replication slot retentionWAL cannot be recycled for slots tied to old transactions
Replication lag on a standbyConflicts between replay and long queries on the standby
Pool exhaustionEach idle-in-transaction session holds a connection, see Connection Pooling
Long rollbackInnoDB must undo what it did

Timeline:

     Session A (bug: HTTP call inside the transaction)        Session B
1    BEGIN;
2    UPDATE accounts SET balance = balance - 100 WHERE id=1;
3    -- calls payment provider, which takes 30 s
4                                                             UPDATE accounts SET ... WHERE id=1;   -- waits
5    ... 30 s later: COMMIT;
6                                                             -- continues after 30 s

Real scenarios: a PHP request that opens DB::transaction, calls a payment API and then writes the result; a nightly job that wraps a million-row backfill in one transaction; a developer's psql session left with BEGIN over lunch.

Timeouts that protect you (PostgreSQL):

ParameterMeaningSQLSTATE when it firesDefault
statement_timeoutAbort any statement that runs longer. "Setting statement_timeout in postgresql.conf is not recommended because it would affect all sessions."57014 query_canceled0 (off)
lock_timeoutAbort a statement that waits for a lock longer than this. "Unlike statement_timeout, this timeout can only occur while waiting for locks."55P03 lock_not_available0 (off)
idle_in_transaction_session_timeout"Terminate any session that has been idle (that is, waiting for a client query) within an open transaction for longer than the specified amount of time."25P030 (off)
idle_session_timeoutTerminate idle sessions that are not in a transaction57P050 (off)
transaction_timeout (PostgreSQL 17+)Limit the total length of a transaction. If it is shorter or equal to the idle-in-transaction or statement timeout, the longer one is ignored25P040 (off)
deadlock_timeoutHow long to wait before checking for a deadlock, see Deadlocks40P01 for the victim1 s

MySQL: innodb_lock_wait_timeout (default 50 s, error 1205), max_execution_time for SELECT, wait_timeout. SQL Server: SET LOCK_TIMEOUT (error 1222). SQLite: PRAGMA busy_timeout. Oracle: DDL_LOCK_TIMEOUT, resource manager limits.

Fix:

sql
-- Per role or database, not globally in postgresql.conf
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE app_user SET lock_timeout = '5s';
ALTER ROLE app_user SET statement_timeout = '30s';

-- Find offenders
SELECT pid, state, now() - xact_start AS xact_age, now() - state_change AS idle_for, left(query, 60)
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY xact_start;

For big backfills, batch: UPDATE ... WHERE id BETWEEN :a AND :b per transaction, with a pause.

Durability knobs ​

synchronous_commit and fsync Important ​

In plain words: You can make commits faster by not waiting for the disk, if you accept losing the last few commits after a crash.

Common misunderstanding: "Asynchronous commit can corrupt my database." It cannot. PostgreSQL's documentation says: "The risk that is taken by using asynchronous commit is of data loss, not data corruption." fsync = off is the dangerous switch: it "could result in arbitrarily bad corruption of the database state".

Definition: synchronous_commit decides when the server answers COMMIT.

Value (PostgreSQL)COMMIT waits forCrash of the primary losesNotes
on (default)Local WAL flush; with synchronous standbys also their flushNothing committedStandard durability
remote_applyStandby has replayed itNothingRead-your-writes on the standby
remote_writeStandby OS has received itNothing on a single failureCheaper than on for the standby leg
localLocal WAL flush onlyNothing on the primary; may be lost on failoverIgnores synchronous standbys
offNothingThe last few transactions (up to about three times wal_writer_delay)Per transaction setting, no corruption

The setting can be changed per transaction, so important commits stay synchronous while others are asynchronous: SET LOCAL synchronous_commit = off;. Certain commands such as DROP TABLE and PREPARE TRANSACTION are always synchronous. An immediate-mode shutdown is equivalent to a crash and loses unflushed asynchronous commits.

ProductEquivalent knob
MySQL InnoDBinnodb_flush_log_at_trx_commit (1 durable, 2 OS cache, 0 once a second), sync_binlog
SQL ServerDelayed durability (DELAYED_DURABILITY database option, COMMIT ... WITH (DELAYED_DURABILITY = ON))
OracleCOMMIT WRITE NOWAIT BATCH
SQLitePRAGMA synchronous (FULL, NORMAL, OFF) with WAL or rollback journal
Redisappendonly yes and appendfsync (always, everysec, no)
MongoDBWrite concern j: true (journaled), w: "majority"

Real scenarios: an event or metrics ingest where losing the last half second is fine (off); a payments table where it is not (on); a replicated cluster where remote_apply gives read-your-writes on a standby.

Transaction boundaries in application code ​

Where the boundary belongs Must-know ​

In plain words: Open the transaction in one place, around the database writes of one business operation, and nowhere else.

Common misunderstanding: "The whole HTTP request (or the whole job) should be one transaction so it is safe." Wider means longer locks, more conflicts, and no real safety for the external parts. The unit of atomicity is the business operation, not the request.

Definition: The boundary belongs in the use-case (application service) layer: it begins the transaction, calls repositories that reuse the same connection, and commits. Controllers parse input and format output; repositories run SQL on the connection they are handed; neither starts transactions.

HTTP handler / queue workerparse input, no BEGIN hereUse-case layer: BEGIN ... COMMITRepository A (same Tx)UPDATE accounts ...Repository B (same Tx)INSERT INTO ledger ...one connection, short, retryableDatabaseone session, one transactionNever inside the boundarypayment / HTTP API callsemail, SMS, broker publishsleep, user think timeAfter commitafterCommit hook, outbox relayidempotent side effects

Five rules:

RuleWhyViolation symptom
One connection per transactionA transaction is bound to one session; a second pooled connection is a different transactionRows written "inside" the transaction are invisible or not rolled back; deadlock with yourself
Open and close in the same functionA caller can see the whole lifecycle; use a helper (WithTx, DB::transaction)Leaked transactions, connections stuck idle in transaction
No external I/O insideHTTP, e-mail, queue publishing cannot be rolled back and hold locks while waitingLong transactions, double sends on retry
Side effects after commitPublish only what is true; use afterCommit or an outboxA job runs for a row that was rolled back
Make the body retryableDeadlocks and serialization failures retry the whole functionDuplicate effects on the second run

Timeline (the bug and the fix):

     Wrong                                      Right
1    BEGIN                                      BEGIN
2    UPDATE orders SET status='paid'            UPDATE orders SET status='paid'
3    dispatch(SendReceipt)   -- worker runs     INSERT INTO outbox (...)
4    COMMIT                  --    before this  COMMIT
5    ROLLBACK (late failure)    -- receipt for  -- relay / afterCommit dispatches SendReceipt
     --                            unpaid order

Real scenarios: a checkout that debits stock, creates an order, and charges a card; an admin action that updates a row and writes an audit record; a queue job that processes a message and records that it did.

What provides it: Go database/sql: BeginTx + defer tx.Rollback(); Laravel: DB::transaction, DB::afterCommit, afterCommit() on a job, after_commit queue option; frameworks without these: a unit-of-work object.

Fix: see Go and Laravel below.

afterCommit in Laravel Important ​

In plain words: Tell Laravel "run this only if the transaction really commits".

Common misunderstanding: "dispatch() inside DB::transaction runs after the transaction." By default the job is pushed immediately; a fast worker can pick it up before COMMIT and find nothing, or find data that is then rolled back.

Definition: The Laravel 13 queue documentation: you may set the after_commit connection option, and "when the after_commit option is true, you may dispatch jobs within database transactions; however, Laravel will wait until the open parent database transactions have been committed before actually dispatching the job." Per job: ProcessPodcast::dispatch($podcast)->afterCommit();. Generic callbacks: DB::afterCommit(fn () => ...), implemented in ManagesTransactions::afterCommit through the transactions manager.

Timeline:

1    DB::transaction(function () {
2        $order = Order::create([...]);
3        SendReceipt::dispatch($order)->afterCommit();   -- queued in memory, not pushed yet
4    });                                                 -- COMMIT, then the job is pushed
5    -- on rollback the callback is discarded

Limits: afterCommit is in-process memory. If the PHP process dies between COMMIT and the dispatch, the job is lost. For a guarantee use the outbox (below). Callbacks run again if the closure is retried, so jobs must be idempotent.

What each product calls a transaction ​

Product comparison Must-know ​

In plain words: "Transaction" means different things in different products; do not carry PostgreSQL assumptions into Redis or MongoDB.

Common misunderstanding: "Every database that says ACID gives the same guarantees." The words are shared; the scope, isolation and rollback behaviour are not.

ProductMulti-statement transactionRollbackIsolationNotes
PostgreSQLYes, BEGIN ... COMMIT, transactional DDLYes, instant (aborted xid)Read Committed default; Repeatable Read = snapshot; Serializable = SSISavepoints, deferrable constraints, PREPARE TRANSACTION
MySQL InnoDBYes; DDL implicitly commitsYes, via undoRepeatable Read default (snapshot + gap locks)MyISAM tables are not transactional
SQL ServerYes, BEGIN TRAN; @@TRANCOUNTYesRead Committed (locking) default; READ_COMMITTED_SNAPSHOT, SNAPSHOTXACT_ABORT, SAVE TRANSACTION, MSDTC for distributed
OracleYes, implicit startYes, undo segmentsRead Committed default; SERIALIZABLE is snapshotDDL commits implicitly; COMMIT WRITE options
SQLiteYes; single writerYesSerializable by design (one writer); snapshot readers in WALBEGIN IMMEDIATE, SQLITE_BUSY
MongoDBSingle-document operations are atomic; multi-document transactions on replica sets and sharded clustersAbortSnapshot read concern, write concern at commitCost and lifetime limit; model data to avoid them
RedisMULTI / EXEC, optional WATCHNo rollbackCommands run serially; no other client interleavesErrors in a queued command do not undo others
CockroachDBYes, distributedYesSerializable defaultClient must retry 40001

Redis. Redis transactions are a command queue. MULTI starts queuing; EXEC runs everything as one uninterrupted unit: "A request sent by another client will never be served in the middle of the execution of a Redis Transaction. This guarantees that the commands are executed as a single isolated operation." But "Redis does not support rollbacks of transactions since supporting rollbacks would have a significant impact on the simplicity and performance of Redis." A command that fails at run time does not undo the others; a command with a syntax error aborts the queue at EXEC time (EXECABORT). DISCARD drops the queue. WATCH adds optimistic locking: if a watched key is modified before EXEC, "the entire transaction will be aborted", and your code retries. So Redis gives isolation (serial execution) and, with appendfsync always, a durability story, but not atomicity in the all-or-nothing-on-error sense. See Redis.

1    WATCH balance:1
2    GET balance:1            -- 100
3    MULTI
4    DECRBY balance:1 30
5    EXEC                     -- (nil) if another client changed balance:1 after WATCH; else [70]

MongoDB. A write to one document, including its embedded documents and arrays, is atomic. Multi-document transactions exist ("MongoDB supports multi-document ACID transactions") on replica sets and sharded clusters, with snapshot read concern and a write concern at commit, but the docs warn: "In most cases, a distributed transaction incurs a greater performance cost over single document writes, and the availability of distributed transactions should not be a replacement for effective schema design." There is a transaction lifetime limit (transactionLifetimeLimitSeconds), so a MongoDB transaction must be short. See MongoDB.

SQLite. One writer at a time. BEGIN defaults to DEFERRED: the SQLite documentation says it "does not actually start until the database is first accessed"; a read can later be upgraded to a write and fail with SQLITE_BUSY. BEGIN IMMEDIATE "causes the database connection to start a new write immediately, without waiting for a write statement. The BEGIN IMMEDIATE might fail with SQLITE_BUSY if another write transaction is already active on another database connection." Use BEGIN IMMEDIATE for any transaction that will write, plus PRAGMA busy_timeout. See SQLite.

MySQL. autocommit=1 by default. DDL commits implicitly. InnoDB is transactional; MyISAM is not (a ROLLBACK there does nothing). START TRANSACTION WITH CONSISTENT SNAPSHOT pins a read view immediately. See MySQL Storage Engines.

Mechanics ​

A failed COMMIT Must-know ​

In plain words: COMMIT can fail, and when it does the transaction did not commit.

Common misunderstanding: "COMMIT always succeeds if every statement succeeded." Reasons it can fail: a deferred constraint (23503, 23505), a serialization failure at commit time (40001 under Repeatable Read / Serializable in PostgreSQL, and the commit can be the point where SSI aborts), a lost connection (the outcome is unknown!), a cancelled context in Go, a full disk, a synchronous standby that does not respond.

Definition: If COMMIT returns an error, the application must assume the transaction did not commit, except when the connection broke at the very moment of commit: then the commit might have happened and the client was not told.

Timeline (unknown outcome):

1    client: COMMIT  ---------------------------->  server: flushes WAL, marks committed
2    client:                    <---X--- connection dropped before the reply
3    client: retries the use case                    -- runs again: is the money moved twice?

What to do: make the use case idempotent (an idempotency key stored in the same transaction, a unique constraint on the business key, or a status check on retry), so that the retry either sees the work done or does it.

Error at COMMITPostgreSQL SQLSTATEMySQLRetry the whole transaction?
Deferred constraint violation23503, 23505, 23514n/a (no deferral)No: it is a data problem
Serialization failure400011213 (deadlock)Yes, with backoff
Deadlock detected40P011213Yes
Lock wait timeout55P031205Maybe, once
Statement or session timeout57014, 25P032013 lost connectionCheck outcome first
Connection lost during COMMITdriver error2013 / 2006Only if idempotent
25P02 (aborted block)COMMIT is turned into ROLLBACKn/aFind the first error

Go: tx.Commit() returns an error. "Tx.Commit will return an error if the context provided to BeginTx is canceled." After Commit or Rollback, "all operations on the transaction fail with ErrTxDone". That is why defer tx.Rollback() is safe after a successful commit: it returns sql.ErrTxDone, which you ignore. Laravel: DB::commit() throws; DB::transaction retries only on concurrency errors as determined by ConcurrencyErrorDetector (deadlock and 40001).

Error codes and states you will meet Must-know ​

SQLSTATEName (PostgreSQL)WhenTypical response
25001active_sql_transactionCommand not allowed inside a transaction blockFix the code path
25P01no_active_sql_transactionCommand needs a block (such as SAVEPOINT)Add BEGIN
25P02in_failed_sql_transactionStatement after an error in the same blockROLLBACK or ROLLBACK TO
25P03idle_in_transaction_session_timeoutSession killed for idling in a transactionFix the code that keeps it open
25006read_only_sql_transactionWrite in a read-only transactionUse a writable transaction
2D000invalid_transaction_terminationCOMMIT where it is not allowed (inside a function)Control transactions in a procedure
40001serialization_failureSerializable / Repeatable Read conflictRetry
40P01deadlock_detectedDeadlockRetry; see Deadlocks
55P03lock_not_availablelock_timeout, NOWAITBack off or fail
57014query_canceledstatement_timeout or cancelInvestigate the query

Solving the classic problems ​

One transaction around a use case ​

SolutionHowAdvantageCost / limitation
Transaction helper (WithTx, DB::transaction)Closure runs between BEGIN and COMMIT; rollback on errorCannot forget the end; no leaksThe closure must be safe to run again if retried
Explicit BEGIN / COMMIT / ROLLBACKManual controlNeeded for unusual flowsEasy to leak; always finally
Savepoint around an optional stepSAVEPOINT + ROLLBACK TOOptional work can fail without losing the restSubtransaction overhead in PostgreSQL if overused
Constraint instead of check-then-actCHECK, UNIQUE, FOREIGN KEYWorks under any concurrencyOnly for rules SQL can express
Outbox for eventsInsert the event in the same transactionAtomic with the data changeNeeds a relay and consumer idempotency

Go: a transfer without and with a transaction ​

The "before" code runs two Exec calls with no transaction. Each one commits on its own, so a failure between them loses the debited money.

go
// Package main shows a transfer written without a transaction.
// Each Exec runs on its own connection from the pool and commits immediately.
package main

import (
	"context"
	"database/sql"
	"log"
	"os"

	_ "github.com/jackc/pgx/v5/stdlib"
)

// transfer moves amount from one account to another using two separate statements.
func transfer(ctx context.Context, db *sql.DB, from, to, amount int64) error {
	if _, err := db.ExecContext(ctx,
		`UPDATE accounts SET balance = balance - $1 WHERE id = $2`, amount, from); err != nil {
		return err
	}
	// If this statement fails, or the process dies before it runs,
	// the debit above is already committed and the money is gone.
	if _, err := db.ExecContext(ctx,
		`UPDATE accounts SET balance = balance + $1 WHERE id = $2`, amount, to); err != nil {
		return err
	}
	return nil
}

func main() {
	db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	if err := transfer(context.Background(), db, 1, 2, 100); err != nil {
		log.Fatal(err)
	}
}

The "after" code opens one BeginTx with a context, defers Rollback (a no-op after a successful Commit), runs both statements, treats Commit as something that can fail, and retries the whole attempt only on PostgreSQL serialization failure (SQLSTATE 40001).

go
// Package main shows a transfer that runs inside one transaction and retries
// when PostgreSQL reports a serialization failure.
package main

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/jackc/pgx/v5/pgconn"
	_ "github.com/jackc/pgx/v5/stdlib"
)

const maxAttempts = 3

// errNoDebit means the UPDATE matched no row: the account is unknown or cannot cover the amount.
var errNoDebit = errors.New("debit rejected: unknown account or insufficient funds")

// transfer runs transferOnce up to maxAttempts times. Only a serialization
// failure (SQLSTATE 40001) is retried; every other error is returned at once.
func transfer(ctx context.Context, db *sql.DB, from, to, amount int64) error {
	var err error
	for attempt := 1; attempt <= maxAttempts; attempt++ {
		err = transferOnce(ctx, db, from, to, amount)
		if !isSerializationFailure(err) {
			return err
		}
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-time.After(time.Duration(attempt) * 50 * time.Millisecond):
		}
	}
	return fmt.Errorf("transfer: gave up after %d attempts: %w", maxAttempts, err)
}

// transferOnce is one complete attempt. The whole body must be safe to run again.
func transferOnce(ctx context.Context, db *sql.DB, from, to, amount int64) error {
	// SERIALIZABLE makes the database detect conflicts with concurrent
	// transactions; such a conflict surfaces as SQLSTATE 40001.
	tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
	if err != nil {
		return fmt.Errorf("begin: %w", err)
	}
	// Rollback after a successful Commit returns sql.ErrTxDone, which is harmless.
	// On every other path it undoes the partial work.
	defer func() { _ = tx.Rollback() }()

	res, err := tx.ExecContext(ctx,
		`UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1`, amount, from)
	if err != nil {
		return fmt.Errorf("debit: %w", err)
	}
	n, err := res.RowsAffected()
	if err != nil {
		return fmt.Errorf("debit rows: %w", err)
	}
	if n == 0 {
		return errNoDebit
	}

	if _, err := tx.ExecContext(ctx,
		`UPDATE accounts SET balance = balance + $1 WHERE id = $2`, amount, to); err != nil {
		return fmt.Errorf("credit: %w", err)
	}

	// Commit can also fail with 40001, so it goes through the same retry check.
	if err := tx.Commit(); err != nil {
		return fmt.Errorf("commit: %w", err)
	}
	return nil
}

// isSerializationFailure reports whether err carries SQLSTATE 40001.
func isSerializationFailure(err error) bool {
	var pgErr *pgconn.PgError
	return errors.As(err, &pgErr) && pgErr.Code == "40001"
}

func main() {
	db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	if err := transfer(context.Background(), db, 1, 2, 100); err != nil {
		log.Fatal(err)
	}
}

The context is part of the transaction's lifetime. The database/sql documentation says: "If the context is canceled, the sql package will roll back the transaction." A cancelled request cannot leave a half-finished transaction open, which is why the request context goes into BeginTx. The package does not retry and does not classify errors; the snippet unwraps *pgconn.PgError from pgx and checks the SQLSTATE.

A reusable helper, plus a read-only transaction and a savepoint sent as SQL:

go
package txutil

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
)

// WithTx runs fn inside one transaction. fn must use tx, never the *sql.DB.
// The deferred Rollback is a no-op after a successful Commit (it returns sql.ErrTxDone).
func WithTx(ctx context.Context, db *sql.DB, opts *sql.TxOptions, fn func(tx *sql.Tx) error) error {
	tx, err := db.BeginTx(ctx, opts)
	if err != nil {
		return fmt.Errorf("begin: %w", err)
	}
	defer func() {
		if rbErr := tx.Rollback(); rbErr != nil && !errors.Is(rbErr, sql.ErrTxDone) {
			// The original error is more useful; this one is only worth logging.
			_ = rbErr
		}
	}()

	if err := fn(tx); err != nil {
		return err
	}
	if err := tx.Commit(); err != nil {
		return fmt.Errorf("commit: %w", err)
	}
	return nil
}

// ReadOnlyReport shows a read-only transaction.
func ReadOnlyReport(ctx context.Context, db *sql.DB) (total int64, err error) {
	err = WithTx(ctx, db, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead}, func(tx *sql.Tx) error {
		return tx.QueryRowContext(ctx, `SELECT coalesce(sum(balance), 0) FROM accounts`).Scan(&total)
	})
	return total, err
}

// TryOptional sends SAVEPOINT as plain SQL because database/sql has no savepoint API.
func TryOptional(ctx context.Context, tx *sql.Tx, step func() error) error {
	if _, err := tx.ExecContext(ctx, `SAVEPOINT optional_step`); err != nil {
		return err
	}
	if err := step(); err != nil {
		if _, rbErr := tx.ExecContext(ctx, `ROLLBACK TO SAVEPOINT optional_step`); rbErr != nil {
			return rbErr
		}
		return nil // the optional step failed; the transaction is usable again
	}
	_, err := tx.ExecContext(ctx, `RELEASE SAVEPOINT optional_step`)
	return err
}

Three Go traps: using db.ExecContext inside the closure instead of tx.ExecContext (a second connection, outside the transaction, so no rollback and possible self-deadlock); returning from a function that never ends a transaction (a leaked connection stays idle in transaction); starting a goroutine that uses tx (a Tx is one connection, so statements serialise and Commit can race with them).

Laravel: a transfer without and with a transaction ​

The "before" controller runs two update() calls; each commits on its own.

php
<?php

// app/Http/Controllers/TransferController.php
// Assumes an accounts table with an integer balance column, and an Account model.
namespace App\Http\Controllers;

use App\Models\Account;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

final class TransferController
{
    public function store(Request $request): RedirectResponse
    {
        $from = Account::query()->findOrFail($request->integer('from_id'));
        $to = Account::query()->findOrFail($request->integer('to_id'));
        $amount = $request->integer('amount');

        // Two separate writes with no transaction. Each update commits on its own,
        // so if the second one fails, or the request dies between them, the money
        // has left $from and never arrives in $to.
        $from->update(['balance' => $from->balance - $amount]);
        $to->update(['balance' => $to->balance + $amount]);

        return back()->with('status', 'Transfer complete.');
    }
}

The "after" service shows three forms: DB::transaction with attempts: 3, a manual beginTransaction with commit in a try/finally, and a nested DB::transaction that shows savepoint behaviour.

php
<?php

// app/Exceptions/TransferExceptions.php
// Kept in one file for the snippet. A real app puts each class in its own file.
namespace App\Exceptions;

use RuntimeException;

final class InsufficientFunds extends RuntimeException {}

final class BonusUnavailable extends RuntimeException {}

// app/Services/TransferService.php
namespace App\Services;

use App\Exceptions\BonusUnavailable;
use App\Exceptions\InsufficientFunds;
use App\Models\Account;
use Illuminate\Support\Facades\DB;

final class TransferService
{
    // The closure runs in one transaction. Laravel retries the whole closure up to
    // 3 times when the error is a deadlock or a serialization failure (SQLSTATE 40001).
    public function transfer(int $fromId, int $toId, int $amount): void
    {
        DB::transaction(function () use ($fromId, $toId, $amount): void {
            $this->move($fromId, $toId, $amount);
        }, attempts: 3);
    }

    // The same work with explicit control. Commit is attempted once. The finally
    // block rolls back whenever the commit did not happen.
    public function transferManually(int $fromId, int $toId, int $amount): void
    {
        DB::beginTransaction();
        $committed = false;

        try {
            $this->move($fromId, $toId, $amount);
            DB::commit();
            $committed = true;
        } finally {
            if (! $committed) {
                DB::rollBack();
            }
        }
    }

    // Nested call. The inner DB::transaction runs as a SAVEPOINT inside the outer
    // transaction. If it throws, only its own writes are undone. The transfer
    // stays pending and is committed with the outer transaction.
    public function transferWithBonus(int $fromId, int $toId, int $amount): void
    {
        DB::transaction(function () use ($fromId, $toId, $amount): void {
            $this->move($fromId, $toId, $amount);

            try {
                DB::transaction(function () use ($toId): void {
                    Account::query()->whereKey($toId)->increment('balance', 5);

                    if ($this->bonusCampaignClosed()) {
                        throw new BonusUnavailable('The bonus campaign has closed.');
                    }
                });
            } catch (BonusUnavailable) {
                // Only the bonus credit was rolled back to the savepoint.
            }
        });
    }

    private function move(int $fromId, int $toId, int $amount): void
    {
        $debited = Account::query()
            ->whereKey($fromId)
            ->where('balance', '>=', $amount)
            ->decrement('balance', $amount);

        if ($debited === 0) {
            throw new InsufficientFunds("Account {$fromId} cannot cover {$amount}.");
        }

        Account::query()->whereKey($toId)->increment('balance', $amount);
    }

    private function bonusCampaignClosed(): bool
    {
        return true;
    }
}

The Laravel 13 documentation says: "If an exception is thrown within the transaction closure, the transaction will automatically be rolled back and the exception is re-thrown." The attempts argument "defines the number of times a transaction should be retried when a deadlock occurs."

The framework source goes further than the documentation. In Illuminate\Database\ConcurrencyErrorDetector, a PDOException with SQLSTATE 40001 counts as a concurrency error, so attempts also retries serialization failures, not only deadlocks. The retry re-runs the whole closure from the start, so the closure must not do external work. The attempts argument on an inner call does not retry the inner closure: the framework rolls back to the savepoint and throws upward, and the outermost DB::transaction is the one that retries. Put attempts on the outermost call. DB::beginTransaction(), DB::commit() and DB::rollBack() are the manual controls; use them only when a single closure cannot express the flow.

Side effects after commit, and a status-check idempotency guard:

php
<?php

namespace App\Services;

use App\Jobs\SendReceipt;
use App\Models\Order;
use Illuminate\Support\Facades\DB;

final class CheckoutService
{
    public function pay(int $orderId, string $idempotencyKey): Order
    {
        return DB::transaction(function () use ($orderId, $idempotencyKey): Order {
            // lockForUpdate serialises concurrent retries of the same order.
            $order = Order::query()->lockForUpdate()->findOrFail($orderId);

            if ($order->status === 'paid') {
                return $order; // a retry or duplicate request: do nothing twice
            }

            $order->update(['status' => 'paid', 'idempotency_key' => $idempotencyKey]);

            // Pushed only after the outermost transaction commits; dropped on rollback.
            SendReceipt::dispatch($order->id)->afterCommit();

            DB::afterCommit(function () use ($order): void {
                logger()->info('order paid', ['order' => $order->id]);
            });

            return $order;
        }, attempts: 3);
    }
}

The payment-provider call is not inside the closure. The charge is made first with an idempotency key (provider-side), or recorded as a pending row in one transaction and finished in a job in another.

SQL: the same ideas in plain statements ​

sql
-- Group + constraint: overdraft impossible even if the app forgets the check
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;   -- CHECK (balance >= 0) can fail here
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;

-- Idempotent write + outbox in the same transaction
BEGIN;
INSERT INTO payments (idempotency_key, order_id, amount)
VALUES ('k-123', 77, 100)
ON CONFLICT (idempotency_key) DO NOTHING;
INSERT INTO outbox (aggregate_id, type, payload) VALUES (77, 'PaymentTaken', '{"amount":100}');
COMMIT;

-- Safer defaults on a role
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '30s';

Beyond one database ​

BASE versus ACID Important ​

In plain words: ACID is the careful, strict style; BASE is the relaxed style used when you spread data over many machines and prefer availability.

Common misunderstanding: "BASE is the opposite of ACID, so a database is one or the other." BASE is a design attitude, not a standard: Basically Available, Soft state, Eventual consistency. A single product can offer both (MongoDB, DynamoDB transactions, CockroachDB).

Definition: BASE: the system stays available during partitions (Basically Available), state may change without input as replicas converge (Soft state), and replicas agree eventually if updates stop (Eventual consistency). The term is usually credited to Eric Brewer's group as a pun against ACID (a secondary attribution, not checked against a primary source); the underlying trade-off is in the CAP theorem and in Eventual Consistency in Database Systems.

AxisACIDBASE
PriorityCorrectness of each transactionAvailability and scale
ConflictsPrevented (locks, aborts)Tolerated and merged (last-write-wins, CRDTs, reconciliation)
ReadsLatest committed (per level)Possibly stale
Typical productsPostgreSQL, MySQL InnoDB, Oracle, SQL ServerCassandra, DynamoDB (default), Riak
Failure modeAbort, retry, blockDivergence, then repair

Timeline (eventual consistency):

1    write x=1 to replica A                 -- acknowledged
2    read x from replica B                  -- returns old x (stale)
3    ... replication ...
4    read x from replica B                  -- returns x=1

Real scenarios: a shopping cart that must always accept an item; a "likes" count that may lag; versus a bank ledger that must not.

Two-phase commit, XA and PREPARE TRANSACTION Important ​

In plain words: To commit atomically across two databases, a coordinator asks everyone "can you commit?" and only if all say yes does it tell all to commit.

Common misunderstanding: "2PC makes cross-service operations safe and simple." It blocks while the coordinator is down, adds latency, and requires every participant to support it. Most microservice stacks avoid it.

Definition: Phase 1 (prepare): each participant makes its changes durable and promises it can commit. Phase 2 (commit or abort): the coordinator decides and tells everyone. XA is the standard interface between a transaction manager and resource managers (JTA in Java, MySQL XA START / XA END / XA PREPARE / XA COMMIT). PostgreSQL exposes phase one as PREPARE TRANSACTION: "After this command, the transaction is no longer associated with the current session; instead, its state is fully stored on disk, and there is a very high probability that it can be committed successfully, even if a database crash occurs before the commit is requested." It is followed by COMMIT PREPARED 'id' or ROLLBACK PREPARED 'id'.

Timeline:

     Coordinator                  DB1                         DB2
1    BEGIN on both  ------------> BEGIN                       BEGIN
2    work           ------------> UPDATE ...                  INSERT ...
3    PREPARE        ------------> PREPARE TRANSACTION 't1'     PREPARE TRANSACTION 't1'
4    all yes -> decide COMMIT
5    COMMIT         ------------> COMMIT PREPARED 't1'         COMMIT PREPARED 't1'
     -- if the coordinator dies between 3 and 5, both hold locks until someone decides

The PostgreSQL reference warns: "PREPARE TRANSACTION is not intended for use in applications or interactive sessions. Its purpose is to allow an external transaction manager to perform atomic global transactions across multiple databases or other transactional resources." Prepared transactions appear in pg_prepared_xacts, need max_prepared_transactions > 0, and a forgotten one holds locks and blocks VACUUM: "it is best to keep the prepared-transaction feature disabled by setting max_prepared_transactions to zero" unless a transaction manager tracks them.

Consensus-based distributed SQL (Spanner, CockroachDB, YugabyteDB) runs 2PC on top of replicated groups; see Distributed SQL, Consensus & 2PC.

Sagas, outbox and idempotency Important ​

In plain words: When one transaction cannot span services, you chain several local transactions and undo earlier steps with compensating actions if a later step fails.

Common misunderstanding: "A saga gives me ACID across services." It gives atomicity of outcome through compensation, but no isolation: other users see intermediate states. Consistency is eventual.

Definition: A saga is a sequence of local transactions, each with a compensating action. The outbox pattern writes the event in the same local transaction as the data change, and a relay publishes it later, so "update the database" and "publish the event" cannot diverge. Both rely on idempotency: running a step twice has the same effect as once. Details: Saga Pattern, Transactional Outbox Pattern, Idempotent Consumers & the Inbox Pattern, Delivery Guarantees.

Timeline (order saga):

1    Order service:    BEGIN; INSERT order (PENDING); INSERT outbox OrderCreated; COMMIT
2    relay:            publish OrderCreated
3    Payment service:  BEGIN; charge (idempotency key = order id); INSERT outbox PaymentTaken; COMMIT
4    Stock service:    BEGIN; reserve; FAIL (out of stock)
5    Stock service:    publish StockFailed
6    Payment service:  refund (compensation)
7    Order service:    mark CANCELLED

Eventual consistency pointer Good to know ​

If replicas, caches or projections are updated after the commit, readers can see old data for a short time. That is eventual consistency; the database side is in Eventual Consistency in Database Systems, and read-your-writes on replicas is in Replication, Read Replicas & Failover.

Choosing ​

SituationRecommendationExtra techniqueReason
Multi-row update in one databaseOne transaction in the use-case layerCHECK/FOREIGN KEY constraintsAtomic, cheap
Two optional parts of one operationSavepoint around the optional partROLLBACK TO on failureKeeps the main work
Insert children before parents or swap unique valuesDEFERRABLE INITIALLY DEFERREDSET CONSTRAINTS ALL IMMEDIATE to fail earlyPostpone checks to commit
Report that must be consistentREAD ONLY, Repeatable Read or SERIALIZABLE READ ONLY DEFERRABLERun on a replicaOne snapshot, no abort
Operation also sends mail or calls an APITransaction only for the database partafterCommit or outbox; idempotency keyExternal effects cannot be rolled back
Update across two servicesSaga with compensationOutbox + idempotent consumersNo shared transaction
Update across two databases you ownAvoid; if needed, 2PC with a transaction managerPREPARE TRANSACTION, reconciliation jobBlocking on coordinator failure
High-volume counters, logs, metricssynchronous_commit = off for that transactionBatch commitsLoss of last moments acceptable
Money, stock, bookingson (default) durability, Serializable or FOR UPDATERetries with backoffA lost commit is costly
Redis check-and-setWATCH + MULTI/EXEC, or a Lua scriptRetry loopNo rollback, but optimistic conflict detection
MongoDB cross-document ruleRedesign to a single document; else a multi-document transactionShort transactionsTransactions cost more than single writes
SQLite writerBEGIN IMMEDIATEbusy_timeoutAvoids deferred-upgrade SQLITE_BUSY

In architecture: from a single process to a distributed system ​

Decide transaction boundaries when you design the use case, not when you write the query. The question at each scale is the same: which operations must be atomic, and what is the mechanism that makes them atomic at this scale?

Monolith: one process, one database ​

How it shows up: every use case is one local transaction; the ORM or a helper opens it; constraints enforce the rules. This is the case ACID was designed for.

Simplest correct usage: DB::transaction or WithTx around the use case; CHECK / FOREIGN KEY / UNIQUE for invariants; afterCommit for notifications; timeouts on the role (idle_in_transaction_session_timeout, lock_timeout).

Example (simple): POST /transfers debits one account, credits another, and inserts a ledger row in one transaction. Nothing else is needed.

Example (complex): checkout debits stock with UPDATE ... WHERE stock >= :qty, creates an order and lines, records a payment row with an idempotency key, and inserts an outbox row, all in one transaction; a relay later publishes OrderPlaced, and a mailer job is dispatched afterCommit. A retry (deadlock) re-runs the closure safely because of the idempotency key.

Modular monolith and multiple databases ​

How it shows up: modules own their tables (and sometimes separate schemas or databases). A use case that touches two modules in one database can still be one transaction, but doing so couples the modules' schemas and deployments.

Rules: keep one module as the transaction owner and call the other through an in-process interface that takes the same connection (or a domain event handled after commit); do not let two modules each open their own transaction on the same connection. If modules use separate databases, the monolith has already lost cross-module atomicity; treat them as microservices (saga + outbox) even though they share a process.

Example: an Orders module and a Loyalty module in one PostgreSQL database. The order use case commits; a domain event OrderPlaced is recorded in an outbox table; the Loyalty module consumes it in its own transaction. The tables stay private to each module.

Microservices: sagas, outbox and no shared transaction ​

What survives: atomicity and consistency inside each service's database. What does not: isolation and atomicity across services. Use sagas for coordination, the outbox for reliable event publishing, idempotent consumers for duplicates, and reconciliation jobs for drift.

Example flow (API and messages):

1    POST /orders                       Order service: BEGIN; order PENDING; outbox(OrderCreated); COMMIT
2    OrderCreated  --broker-->          Payment service: charge with idempotency key; outbox(PaymentTaken)
3    PaymentTaken  --broker-->          Stock service: reserve; outbox(StockReserved)  | on failure: outbox(StockFailed)
4    StockReserved --broker-->          Order service: mark CONFIRMED
5    StockFailed   --broker-->          Payment service: refund (compensate); Order service: mark CANCELLED

Where a synchronous call is unavoidable (payment), its idempotency key is the protection against the unknown outcome of a timed-out call. Do not hold a database transaction open while it runs.

Distributed data: replicas, caches and distributed SQL ​

Replicas: a commit is durable on the primary (and optionally on synchronous standbys through synchronous_commit = remote_write or remote_apply), but a replica may lag. A read that follows a write needs read-your-writes routing (read from the primary, or wait for the replay position). See Replication, Read Replicas & Failover.

Caches: a cache is outside the transaction. Invalidate after commit, not before, and expect a window of staleness; stale-while-revalidate and versioned keys narrow it. See Eventual Consistency in Database Systems for the staleness trade-off.

Distributed SQL: Spanner, CockroachDB and YugabyteDB offer ACID transactions across nodes by running consensus (Raft or Paxos) per range and 2PC across ranges; the client sees ordinary BEGIN / COMMIT plus mandatory retry on 40001. See Distributed SQL, Consensus & 2PC.

Where the concept breaks: a commit acknowledged by a primary that then fails over before the standby received it is lost unless a synchronous standby was used; clocks differ across nodes, so "commit time" is not a global order unless the system provides one (TrueTime, hybrid logical clocks).

Scaling path: 1x, 10x, 100x ​

LoadTypical designTransaction-related change
1x: one app, one primaryShort transactions, default levelAdd constraints, timeouts, a WithTx helper
10x: replicas, a pool, a queueRead replicas, PgBouncer, background jobsPool in transaction mode (no session state), afterCommit, idempotent jobs, metrics for retries and idle in transaction
100x: sharding or distributed SQL, servicesShards, sagas, outboxTransactions stay inside one shard or service; cross-shard work uses sagas; synchronous_commit tuned per workload; group commit and batching for throughput

Lab ​

Setup (PostgreSQL in Docker):

bash
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
docker exec -it pg psql -U postgres
sql
CREATE TABLE accounts (id int PRIMARY KEY, owner text NOT NULL, balance bigint NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'ana', 100), (2, 'bob', 50);

Experiment 1: atomicity and the aborted block (one terminal)

sql
BEGIN;
UPDATE accounts SET balance = balance - 80 WHERE id = 1;
UPDATE accounts SET balance = balance - 80 WHERE id = 1;   -- ERROR: violates check constraint (23514)
SELECT * FROM accounts;                                    -- ERROR: current transaction is aborted (25P02)
COMMIT;                                                    -- prints ROLLBACK
SELECT * FROM accounts;                                    -- ana still 100

Experiment 2: savepoint rescue

sql
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
SAVEPOINT s1;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;  -- ERROR (23514)
ROLLBACK TO s1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;
SELECT * FROM accounts;   -- ana 70, bob 80

Experiment 3: visibility and locks (two terminals A and B)

A:  BEGIN; UPDATE accounts SET balance = balance + 1 WHERE id = 1;
B:  SELECT balance FROM accounts WHERE id = 1;          -- old value, not blocked
B:  UPDATE accounts SET balance = balance + 1 WHERE id = 1;   -- waits
A:  COMMIT;                                              -- B continues

Experiment 4: idle in transaction and the timeout

A:  BEGIN; SELECT 1;     -- then do nothing
B:  SELECT pid, state, now() - state_change FROM pg_stat_activity WHERE state = 'idle in transaction';
A:  SET idle_in_transaction_session_timeout = '5s';   -- wait 6 seconds, then any statement
A:  -- FATAL: terminating connection due to idle-in-transaction timeout  (25P03)

Experiment 5: deferred constraint

sql
CREATE TABLE person (id int PRIMARY KEY, spouse int REFERENCES person(id) DEFERRABLE INITIALLY DEFERRED);
BEGIN;
INSERT INTO person VALUES (1, 2);
INSERT INTO person VALUES (2, 1);
COMMIT;                                  -- OK
BEGIN;
INSERT INTO person VALUES (3, 99);
COMMIT;                                  -- ERROR at COMMIT: violates foreign key constraint (23503)

Experiment 6: asynchronous commit (observe, do not run in production)

sql
SET synchronous_commit = off;
BEGIN; INSERT INTO accounts VALUES (3, 'cy', 10); COMMIT;   -- returns before the WAL flush
SHOW synchronous_commit;

Common misconceptions ​

BeliefReality
ACID means the database enforces my business rulesIt enforces declared constraints only; Härder and Reuter's "legal results" are defined outside the database
Atomic means no one can see my changes half-doneThat is isolation; atomicity is all-or-nothing outcome
No BEGIN means no transactionEvery statement runs in its own implicit transaction
An error inside a block lets me continue the transactionIn PostgreSQL the block is aborted (25P02); use a savepoint. MySQL and Oracle undo only the statement
An inner commit() commits the inner partNested transactions are savepoints; only the outermost commit makes anything permanent
COMMIT cannot failDeferred constraints, serialization failures and lost connections make it fail; an unknown outcome needs idempotency
A transaction around the HTTP request makes the external call atomicThe payment provider cannot be rolled back; use idempotency keys and compensation
Idle-in-transaction connections cost nothingThey hold locks and snapshots and block VACUUM; set idle_in_transaction_session_timeout
Asynchronous commit corrupts dataIt loses the last few commits after a crash, never corrupts; fsync = off is the dangerous one
Redis MULTI/EXEC is the same as a SQL transactionNo rollback; a failing command does not undo the others
BASE is the opposite of ACID so you pick one productBASE is an attitude; many products offer both
Two-phase commit is a free way to do cross-service transactionsIt blocks on coordinator failure; use sagas unless you truly need it

Cheat sheet ​

TopicWhat to remember
AtomicityAll or nothing; PostgreSQL: aborted xid is invisible; InnoDB: undo log
ConsistencyConstraints you declared; the rest is application code
IsolationLevels; see Isolation Levels
DurabilityWAL flushed with fsync before COMMIT returns; synchronous_commit
Group commitOne flush covers many commits; commit_delay, innodb_flush_log_at_trx_commit
AutocommitEach statement is its own transaction without BEGIN
Aborted blockPostgreSQL 25P02; ROLLBACK or ROLLBACK TO
SavepointSAVEPOINT, ROLLBACK TO, RELEASE SAVEPOINT; not a separate transaction
NestedLaravel savepoints; Go has none; attempts on the outermost call
DeferrableDEFERRABLE INITIALLY DEFERRED, SET CONSTRAINTS; errors appear at COMMIT
Read-onlyREAD ONLY; SERIALIZABLE READ ONLY DEFERRABLE for long reports
Timeoutsidle_in_transaction_session_timeout, statement_timeout, lock_timeout
BoundaryUse-case layer, one connection, no external I/O, afterCommit
Failed COMMITAssume not committed; idempotent retry
Across servicesSaga + outbox + idempotency; 2PC/XA only with a transaction manager
Redis / MongoDB / SQLiteMULTI/EXEC/WATCH, no rollback; multi-document transactions are costly; BEGIN IMMEDIATE

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Which of the four properties does a rolled-back transaction demonstrate, and how does PostgreSQL implement "none of it" without an undo log? Important ​

Answer

Answer: Atomicity. PostgreSQL leaves the new row versions in the table, records the transaction id as aborted, and MVCC visibility rules make those versions invisible; VACUUM removes them later. InnoDB instead applies its undo log backwards.

2 — Why can a database with all four ACID properties still end up with wrong business data? Must-know ​

Answer

Answer: Consistency covers only the declared constraints. A rule nobody encoded (as a constraint, trigger or application check inside the transaction) is not enforced.

3 — What happens to the rest of a PostgreSQL transaction block after one statement fails, and how do you continue anyway? Must-know ​

Answer

Answer: The block is aborted: later statements fail with 25P02 until ROLLBACK. To continue, set a SAVEPOINT before the risky statement and ROLLBACK TO it on failure.

4 — What does the commit path write to disk, and what does synchronous_commit = off change? Important ​

Answer

Answer: A commit record in the WAL flushed with fsync. With off the server does not wait for the flush, so a crash can lose the last few transactions but cannot corrupt the database.

5 — In Laravel, an inner DB::transaction throws and the outer catches it. What SQL ran and what is kept? Important ​

Answer

Answer: SAVEPOINT transN then ROLLBACK TO SAVEPOINT transN. The outer transaction continues, and its own work is committed at the outer commit.

6 — Why should attempts be set on the outermost DB::transaction only? Good to know ​

Answer

Answer: An inner call rolls back to its savepoint and throws a concurrency exception upward without retrying; only the outermost call can restart the whole transaction.

7 — Which constraint types can be DEFERRABLE in PostgreSQL, and when is a deferred violation reported? Good to know ​

Answer

Answer: UNIQUE, PRIMARY KEY, FOREIGN KEY and EXCLUDE; CHECK and NOT NULL cannot. The error is raised at COMMIT (or at SET CONSTRAINTS ... IMMEDIATE).

8 — A request opens a transaction, calls a payment API, then writes the result. Name two things that go wrong. Must-know ​

Answer

Answer: The transaction is long (locks held for the API's latency, bloat), and the external call cannot be rolled back, so a retry or rollback leaves a charged customer with no order. Move the call outside, use an idempotency key, record intent in the transaction and finish with a job.

9 — COMMIT returns a network error. Did it commit? Must-know ​

Answer

Answer: Unknown. It may have committed before the connection dropped. The use case must be idempotent so a retry either finds the work done or does it once.

10 — How does Redis MULTI/EXEC differ from a SQL transaction? Must-know ​

Answer

Answer: Commands run serially without interleaving (isolation), but there is no rollback: a failing command does not undo the others. WATCH adds optimistic checking.

11 — Why use BEGIN IMMEDIATE in SQLite for a transaction that will write? Important ​

Answer

Answer: A deferred transaction that starts with a read and later tries to write can fail with SQLITE_BUSY at the upgrade point; IMMEDIATE takes the write lock up front.

12 — When do you reach for a saga and an outbox instead of a transaction? Must-know ​

Answer

Answer: When the operation spans services or databases. The outbox makes "change data" and "publish event" atomic locally; the saga coordinates later steps with compensation, with idempotent consumers.

Glossary ​

TermMeaning
ACIDAtomicity, Consistency, Isolation, Durability; the name appears in Härder & Reuter 1983
AtomicityAll of a transaction's changes happen or none do
ConsistencyA committed transaction leaves the data satisfying its declared rules
IsolationConcurrent transactions do not expose their intermediate states; offered as levels
DurabilityAn acknowledged commit survives a crash
TransactionA group of operations treated as one unit
BEGINOpens a transaction block
COMMITEnds the transaction and makes its changes permanent
ROLLBACKEnds the transaction and discards its changes
Transaction blockThe statements between BEGIN and COMMIT/ROLLBACK
AutocommitEach statement is committed on its own when it succeeds
Implicit transactionThe transaction a database wraps around a statement issued without BEGIN
SAVEPOINTA named marker inside a transaction
ROLLBACK TOUndo work after a savepoint without ending the transaction
RELEASE SAVEPOINTDrop a savepoint marker, keep the work
Nested transactionUsually a savepoint presented as an inner transaction
Aborted blockPostgreSQL state after an error, 25P02, until rollback
Undo logPrior values kept (InnoDB, Oracle) to roll back and for old read views
Redo logLog of changes to replay after a crash (InnoDB redo; PostgreSQL WAL)
WALWrite-ahead log: changes are logged before data pages are written
fsyncSystem call forcing buffered writes to stable storage
Group commitOne log flush covers several concurrent commits
synchronous_commitPostgreSQL setting for how long COMMIT waits for the WAL flush and standbys
ConstraintA declared rule: PRIMARY KEY, UNIQUE, NOT NULL, CHECK, FOREIGN KEY
CHECKA row-level predicate enforced by the database
FOREIGN KEYA reference that must point to an existing row
DEFERRABLE INITIALLY DEFERREDA constraint checked at COMMIT instead of after each statement
SET CONSTRAINTSSwitches deferrable constraints between IMMEDIATE and DEFERRED in a transaction
Idle in transactionA session that has opened a transaction and is waiting without running a statement
idle_in_transaction_session_timeoutPostgreSQL setting that terminates such sessions
statement_timeoutPostgreSQL limit on one statement's run time
lock_timeoutPostgreSQL limit on waiting for a lock
Read-only transactionA transaction declared to forbid writes
BASEBasically Available, Soft state, Eventual consistency
Eventual consistencyReplicas converge if updates stop
2PCTwo-phase commit: prepare, then commit or abort, across participants
XAStandard interface between a transaction manager and resource managers
PREPARE TRANSACTIONPostgreSQL phase one of 2PC; followed by COMMIT PREPARED or ROLLBACK PREPARED
SagaA chain of local transactions with compensating actions
OutboxAn event table written in the same transaction as the data, published by a relay
IdempotencyRunning an operation twice has the same effect as once
afterCommitLaravel hook that runs a callback or dispatches a job only after the outermost commit
DB::transaction attemptsLaravel's retry count on deadlock / 40001, applied at the outermost call
sql.TxGo database/sql transaction handle bound to one connection
BeginTxGo call that starts a transaction with a context and TxOptions
TxOptionsGo struct with Isolation and ReadOnly
ErrTxDoneGo error returned for any use of a finished transaction
Context cancellationIn Go, cancelling the BeginTx context rolls the transaction back
MULTI / EXECRedis command queue executed without interleaving, no rollback
WATCHRedis optimistic check: abort EXEC if a watched key changed
MongoDB multi-document transactionA transaction over several documents, with a lifetime limit
BEGIN IMMEDIATESQLite: take the write lock at BEGIN

References ​

Built by Morteza Negahi