Back to all posts
·7 min read

Transaction isolation levels in practice: race conditions, row locks and deadlocks

Wrapping code in a transaction often feels like the point where things become safe. The tests pass and everything works locally. Problems only show up when several requests hit the same row at the same time: stock goes negative, the same coupon is redeemed twice, two on-call engineers take time off at once. These bugs appear under load, rarely, and they are hard to reproduce.

In this post I look at transaction isolation levels from a practical angle: which anomalies actually matter, what the default level does not protect you from, when to choose a row lock and when a stricter level, and how to reduce deadlocks. The examples use PostgreSQL and .NET (EF Core, Npgsql), but the concepts carry over to other relational databases to a large degree.

What a transaction guarantees, and what it doesn't

A transaction makes sure its changes are applied either all together or not at all. That is the atomicity guarantee, and it is very valuable. But atomicity does not mean that other concurrently running transactions won't change the data you have read. That is the domain of isolation, and isolation is not an on/off switch but a level.

Levels are defined by which concurrency anomalies they allow. The higher the level, the fewer anomalies you see, but in return you either wait on more locks or the database aborts some transactions with an error and you have to retry them. Choosing the right level is therefore a design decision that has to be made together with the application's error and retry behaviour.

Anomalies you meet in real applications

Rather than memorising the textbook list, it is more useful to focus on the four situations I see most often in applications:

  • Lost update: Two requests read the same row, compute the new value in the application and write it back. The second write erases the effect of the first. The classic example is reading the stock, subtracting one and saving it.
  • Non-repeatable read: Within the same transaction you read the same row twice and see a different value because another transaction changed it in between.
  • Phantom: You run the same query with the same condition twice, and the second time newly inserted rows appear.
  • Write skew: Two transactions read the same set, each updates a different row believing it respects the rule, and together they violate it. A rule like "at least one person must remain on call" can be broken by two people requesting leave at the same moment.

None of these anomalies show up in tests run by a single user. That is why, while writing the code, you need to ask explicitly: "what happens if two requests change this row at the same time?"

The default level and atomic updates

PostgreSQL's default level is Read Committed. At this level each statement sees the data committed as of the moment it started. There are no dirty reads, but a read-compute-write cycle is exposed to lost updates. In most cases the cleanest fix is to let the database do the computation:

UPDATE products
SET stock = stock - @quantity
WHERE id = @id AND stock >= @quantity;

This statement reads and writes in a single step. A second transaction trying to update the same row waits for the first to finish and re-evaluates the condition against the current value. If the number of affected rows is zero, there was not enough stock, and the application can return that as a business rule error. Likewise, for uniqueness rules it is both simpler and correct to define a unique index and catch the violation, instead of "check whether it exists, then insert" in the application.

For conflicts between the version a user saw on screen and the version they save, the optimistic concurrency approach I covered earlier (a version column) is a better fit. Atomic updates and optimistic concurrency together solve most cases safely under Read Committed.

Row locks: SELECT ... FOR UPDATE

Sometimes the computation does not fit into a single UPDATE statement; you need to read the row, check several rules and write to other tables. In that case locking the row while reading it puts other transactions working on the same row in line:

BEGIN;
SELECT balance FROM accounts WHERE id = @id FOR UPDATE;
-- apply the rules, insert the ledger entry
UPDATE accounts SET balance = @newBalance WHERE id = @id;
COMMIT;

FOR UPDATE prevents other transactions from updating or locking the same row until the transaction ends. On queue-like tables, FOR UPDATE SKIP LOCKED skips locked rows so that multiple workers can pick up different records.

The price of a lock is waiting. The longer the transaction holding the lock runs, the longer everyone else waits. So keep the locked region small and don't wait on HTTP calls, file operations or user interaction inside a transaction. Calls to external services should happen before or after the transaction, using a pattern such as the outbox if needed.

Stricter levels: Repeatable Read and Serializable

When you don't know in advance which rows to lock, as with write skew, a row lock is not enough, because the problem is not the consistency of existing rows but of the set as a whole. In PostgreSQL, Repeatable Read provides a consistent snapshot for the whole transaction and aborts attempts to update the same row concurrently with an error. Serializable guarantees that transactions produce the same result as if they had run one after another, and it catches write skew as well.

This guarantee comes with a condition: when the database detects a conflict, it aborts one of the transactions with a serialization failure (SQLSTATE 40001). That error is not a malfunction; it is part of the contract. Code that uses a strict level must therefore be written so it can run the transaction again from the start:

public async Task<T> RunSerializableAsync<T>(
    Func<AppDbContext, CancellationToken, Task<T>> work,
    CancellationToken ct)
{
    for (var attempt = 1; ; attempt++)
    {
        await using var db = await _factory.CreateDbContextAsync(ct);
        await using var tx = await db.Database
            .BeginTransactionAsync(IsolationLevel.Serializable, ct);
        try
        {
            var result = await work(db, ct);
            await tx.CommitAsync(ct);
            return result;
        }
        catch (Exception ex) when (IsRetryable(ex) && attempt < 3)
        {
            await Task.Delay(TimeSpan.FromMilliseconds(20 * attempt), ct);
        }
    }
}

private static bool IsRetryable(Exception ex) =>
    (ex as PostgresException ?? ex.InnerException as PostgresException)?.SqlState
        is PostgresErrorCodes.SerializationFailure
        or PostgresErrorCodes.DeadlockDetected;

Two details matter here. A new DbContext is created for every attempt; entities tracked by a previous attempt must not leak into the next one. Second, everything inside work must be safe to run again: sending an email or calling an external API does not belong in this block.

In practice, rather than making everything Serializable, a good balance is to protect the few critical flows that carry a write skew risk this way and keep the rest on Read Committed with atomic statements.

Reducing deadlocks

A deadlock is two transactions waiting for locks held by each other. PostgreSQL detects this and aborts one of them with error 40P01. The retry logic above covers that case too, but frequent deadlocks are a design signal.

The most effective measure is to always acquire locks in the same order. If code that transfers money between two accounts locks them by ID order rather than by source and target, two transfers in opposite directions cannot block each other. Sorting rows first in batch updates has the same effect. Beyond that, keeping transactions short, writing queries with indexed conditions so they don't lock unnecessary rows, and putting an upper bound on waiting with lock_timeout prevent problems from silently piling up.

Testing and observing concurrency

Concurrency bugs can only be tested with concurrency. In an integration test against a real database, starting the same operation dozens of times in parallel with Task.WhenAll and then verifying the invariant (stock never goes negative, the total balance is preserved) catches most of these bugs before production. In-memory providers don't emulate locking and isolation behaviour, so they are no use for these tests.

In production you need to measure serialization failures, deadlocks and lock wait times. In PostgreSQL, the log_lock_waits setting logs long lock waits, and the pg_stat_activity and pg_locks views show who is waiting on whom at that moment. Tracking the retry count as a metric also reveals which flow is most prone to conflicts.

Conclusion

Choosing an isolation level is not a database setting but a decision about how business rules are protected under concurrent requests. My default approach is this: start with atomic updates and unique indexes on Read Committed, use row locks for complex read-write flows, and combine Serializable with retries for critical rules that carry a write skew risk. Acquiring locks in a consistent order, keeping transactions short and testing concurrency against a real database make sure these decisions behave as expected in production.