All posts
Performance·10 min read

Database Transactions and Isolation Levels: ACID, Locks, and Deadlocks

Transactions are how databases keep your data correct when many things happen at once. Learn what ACID really means, which isolation level to pick, and how to stop deadlocks from waking you up at night.

Timothy Murphy
Database Transactions and Isolation Levels: ACID, Locks, and Deadlocks

Two customers buy the last item in stock at the same moment. Both requests read "quantity: 1", both decide the sale is fine, and both write "quantity: 0". You've sold one item twice.

Transactions exist to stop exactly this. But wrapping code in BEGIN and COMMIT isn't automatically enough — the isolation level decides how much protection you actually get, and the wrong choice leads to bugs that only show up under load.

What a Transaction Actually Is

A transaction is a group of statements that succeed or fail as one unit:

BEGIN;

UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;

COMMIT;

If the second UPDATE fails, ROLLBACK undoes the first one. Money never vanishes into the gap between two statements.

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
-- something went wrong
ROLLBACK;

MySQL uses START TRANSACTION or BEGIN; PostgreSQL accepts both.

ACID, Without the Jargon

Atomicity — all of it happens or none of it does. No half-finished transfers.

Consistency — the database ends up in a valid state. Constraints, foreign keys, and checks still hold when the transaction commits.

Isolation — concurrent transactions don't corrupt each other's view of the data. This is the one with dials to turn, and the rest of this post.

Durability — once you get a successful COMMIT, the data survives a power cut. This is why databases flush to disk before acknowledging, and why that flush setting is not one to disable casually.

Savepoints: Partial Rollback

Sometimes you want to undo part of a transaction without losing the whole thing. In MySQL:

BEGIN;

INSERT INTO orders (customer_id, total) VALUES (42, 99.00);

SAVEPOINT before_items;

INSERT INTO order_items (order_id, product_id) VALUES (LAST_INSERT_ID(), 7);
-- this failed, but keep the order
ROLLBACK TO SAVEPOINT before_items;

COMMIT;

The order survives, the failed item insert doesn't. LAST_INSERT_ID() is MySQL's; in PostgreSQL, get the new ID with INSERT ... RETURNING id. Savepoints matter even more in PostgreSQL, where any error aborts the whole transaction: ROLLBACK TO SAVEPOINT is the only way to carry on after one.

Most ORMs use savepoints to implement nested transactions, which is worth knowing when you're debugging why an inner "transaction" didn't really roll back.

The Four Things That Go Wrong

Isolation levels are defined by which of these anomalies they permit.

Dirty read — you read data another transaction wrote but hasn't committed. If it rolls back, you acted on data that never existed.

Non-repeatable read — you read a row twice in one transaction and get different values, because someone else committed a change in between.

Phantom read — you run the same WHERE clause twice and get a different number of rows, because someone inserted or deleted matching rows.

Lost update — two transactions read the same value, both modify it, and the second write overwrites the first. This is the out-of-stock scenario from the intro.

The Four Isolation Levels

LevelDirty readNon-repeatable readPhantom read
READ UNCOMMITTEDPossiblePossiblePossible
READ COMMITTEDPreventedPossiblePossible
REPEATABLE READPreventedPreventedPossible*
SERIALIZABLEPreventedPreventedPrevented

* In practice, both prevent phantoms at REPEATABLE READ. PostgreSQL reads from one snapshot for the whole transaction. InnoDB does the same for plain reads, and takes gap locks for locking reads such as SELECT ... FOR UPDATE.

Lost updates aren't in the standard's table, and the two engines differ. At REPEATABLE READ, PostgreSQL refuses the second of two conflicting writes with a serialization error, which your code retries. MySQL lets both writes through, so the read-then-write pattern from the intro still loses an update unless you lock the row (see SELECT FOR UPDATE below).

Setting the level for one transaction is written differently in each database. In PostgreSQL, put it inside the transaction:

BEGIN ISOLATION LEVEL REPEATABLE READ;
-- ...
COMMIT;

In MySQL, set it just before the transaction starts, and it applies to that next transaction only:

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
START TRANSACTION;
-- ...
COMMIT;

Don't swap them: PostgreSQL ignores SET TRANSACTION before BEGIN, with nothing but a warning, and the transaction runs at the default level.

The Defaults Differ, and It Matters

  • MySQL/InnoDB defaults to REPEATABLE READ
  • PostgreSQL defaults to READ COMMITTED
  • SQL Server defaults to READ COMMITTED

This catches people migrating between databases. A long-running report in MySQL sees a consistent snapshot from the moment of its first read. The same code in PostgreSQL sees each statement's own fresh snapshot, so totals can shift mid-report. Neither is wrong, but the behavior isn't the same.

READ UNCOMMITTED is almost never the right answer. The performance gain is minimal on modern engines and you're trading correctness for it. Skip it.

Locks: How Isolation Is Enforced

Databases use locks (and multi-version snapshots) to keep transactions apart.

  • Shared locks allow concurrent reads but block writes.
  • Exclusive locks block everything else on that row.
  • Row-level locks affect single rows; table-level locks affect everything. Row-level is what you want, and it's what InnoDB and PostgreSQL use for normal UPDATE statements.

SELECT FOR UPDATE

This is the tool for the inventory problem. It reads a row and locks it, so nobody else can change it until you commit:

BEGIN;

SELECT quantity FROM inventory
WHERE product_id = 7
FOR UPDATE;

-- quantity is 1, and no one else can touch this row right now
UPDATE inventory SET quantity = quantity - 1 WHERE product_id = 7;

COMMIT;

The second customer's SELECT ... FOR UPDATE waits until the first commits, then reads 0 and correctly refuses the sale.

Variants worth knowing:

  • FOR SHARE (PostgreSQL) / FOR SHARE or LOCK IN SHARE MODE (MySQL) — others can read, nobody can write
  • NOWAIT — fail immediately instead of waiting for the lock
  • SKIP LOCKED — ignore locked rows entirely, which is how you build a job queue that multiple workers can safely poll
-- a simple worker queue: each worker grabs a different job
BEGIN;
SELECT id FROM jobs
WHERE status = 'pending'
ORDER BY created_at
LIMIT 1
FOR UPDATE SKIP LOCKED;
-- mark it running, commit, then process it

Atomic Updates Beat Locks

Often you don't need explicit locking at all. Let the database do the arithmetic:

UPDATE inventory
SET quantity = quantity - 1
WHERE product_id = 7 AND quantity > 0;

Check the affected row count. If it's zero, the item was out of stock and nothing changed. A single statement is atomic, so there's no window for a lost update. This pattern is simpler and faster than SELECT FOR UPDATE whenever it fits.

Optimistic Locking

For long user-facing edits, holding a database lock while someone fills in a form is a bad idea. Use a version column instead:

UPDATE documents
SET content = 'new text', version = version + 1
WHERE id = 42 AND version = 7;

If someone else saved first, version is now 8, zero rows match, and you can tell the user their copy is stale. No locks held across user think-time.

Deadlocks

A deadlock is two transactions each holding a lock the other wants:

Transaction A: locks row 1, then wants row 2
Transaction B: locks row 2, then wants row 1

Neither can proceed. The database detects this and kills one, returning an error like Deadlock found when trying to get lock (MySQL, error 1213) or deadlock detected (PostgreSQL, SQLSTATE 40P01).

Deadlocks are normal in a busy system. The goal is to make them rare and to handle the ones that happen.

Reducing Deadlocks

1. Touch rows in a consistent order. This is the big one. If every transaction updates accounts in ascending ID order, the circular wait can't form:

-- always lock the lower ID first
SELECT * FROM accounts WHERE id IN (1, 2) ORDER BY id FOR UPDATE;

2. Keep transactions short. Open late, commit early. Never hold a transaction open across an HTTP request to a third-party API.

3. Do no I/O inside a transaction. No sending emails, no calling payment providers, no uploading files. Queue that work and let it run after the commit.

4. Index your WHERE clauses. Without an index, InnoDB may lock far more rows than you intended while scanning. A missing index turns a row lock into something closer to a table lock. Our guide to indexes covers how to spot this.

5. Batch large writes. A single DELETE of a million rows holds locks for a long time. Chunk it into batches of a few thousand, committing between each.

Always Retry

Because a deadlock victim's transaction is rolled back entirely, retrying is usually safe and is the correct response:

$attempts = 0;

while (true) {
    try {
        DB::transaction(function () {
            // your work here
        });
        break;
    } catch (\Illuminate\Database\QueryException $e) {
        if (++$attempts >= 3 || ! $this->isDeadlock($e)) {
            throw $e;
        }
        usleep(random_int(50_000, 200_000) * $attempts);
    }
}

Laravel's DB::transaction() accepts a number of attempts as its second argument and retries deadlocks itself, though straight away, with no backoff:

DB::transaction(function () {
    // your work
}, 3);

The random backoff in the first version matters. If both transactions retry at the same instant, they can deadlock again.

Long Transactions Are Expensive

Both MySQL and PostgreSQL use multi-version concurrency control: old row versions are kept around so open transactions can still see their snapshot. A transaction left open for hours means:

  • PostgreSQL can't vacuum those dead rows, so tables bloat and scans slow down
  • MySQL grows the undo log and history list, hurting read performance

Watch for open transactions with:

-- PostgreSQL
SELECT pid, now() - xact_start AS duration, state, query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY duration DESC;

-- MySQL
SELECT * FROM information_schema.innodb_trx
ORDER BY trx_started;

An "idle in transaction" connection sitting there for twenty minutes is a bug in your application, not a database problem.

Gotchas That Bite People

Autocommit is on by default. Every standalone statement is its own transaction. Two UPDATE statements without an explicit BEGIN are two transactions, and a crash between them leaves you half-done.

DDL isn't transactional in MySQL. CREATE TABLE, ALTER TABLE, and TRUNCATE cause an implicit commit and cannot be rolled back. PostgreSQL does support transactional DDL, which is why PostgreSQL migrations can roll back cleanly and MySQL ones often can't.

A failed statement doesn't always roll back the transaction. In PostgreSQL, an error aborts the transaction and every subsequent statement fails until you roll back. In MySQL, the failed statement is rolled back but the transaction continues (except after a deadlock, which rolls back the whole transaction). Same code, very different outcomes.

Errors inside a transaction still need handling. Catching an exception and carrying on without rolling back leaves the connection in a broken state.

A Practical Checklist

  • Wrap multi-statement writes in an explicit transaction
  • Keep transactions as short as possible, and do external calls outside them
  • Use SELECT ... FOR UPDATE when you must read-then-write the same row
  • Prefer a single atomic UPDATE with a guard in the WHERE clause where you can
  • Access rows in a consistent order to avoid deadlocks
  • Retry deadlock errors with randomized backoff
  • Understand your database's default isolation level before assuming behavior
  • Monitor for long-running open transactions

Try It in LunoDB

Concurrency is much easier to understand when you can watch it happen. The classic experiment needs two sessions that each keep their own connection open, so start with two psql or mysql terminal windows:

  • In window one, run BEGIN; and a SELECT ... FOR UPDATE
  • In window two, try to update the same row and watch it wait
  • Commit in window one and see window two immediately complete

That five-second experiment teaches locking better than any diagram. While it's running, use LunoDB to watch what the database sees:

  • Query information_schema.innodb_trx or pg_stat_activity in a query tab to see the open transactions and who is waiting
  • Open the Process List on a MySQL, MariaDB, or PostgreSQL connection to see every running session
  • Re-run the query after the commit and watch the waiting session clear

Conclusion

Transactions are cheap insurance against a category of bug that's very hard to reproduce and very embarrassing in production. The essentials:

  • Group related writes into one transaction
  • Know your isolation level and what it does and doesn't prevent
  • Lock deliberately with FOR UPDATE, or avoid locking with atomic updates
  • Expect deadlocks and retry them
  • Keep transactions short

Download LunoDB to explore transactions and locks against your own database, and see our post on database security for keeping that data safe once it's correct.

Try it in LunoDB.

Run every example from this guide against your own database, with an AI assistant that knows your schema.

Free forever · Mac, Windows and Linux
Keep reading

More from the blog

All posts