Video in progress

How does REPEATABLE READ actually work in PostgreSQL, and how do you handle the error "could not serialize access due to concurrent update"?

Under REPEATABLE READ the snapshot is taken once, at the transaction's first query, and doesn't change until the end, so this is snapshot isolation. If another transaction has modified and committed a row you want to update after your snapshot, PostgreSQL raises error 40001 instead of waiting. The fix is to re-run the whole transaction.

📖 Answer

Under READ COMMITTED, an UPDATE takes the new version of the row and carries on. REPEATABLE READ can't do that: the transaction lives in an old snapshot, and seeing the new version would break consistency. So it stops:

ERROR: could not serialize access due to concurrent update
SQLSTATE: 40001

This isn't a bug, it's part of the guarantee. The application has to expect it and re-run the transaction from the start, not just the last query, because the earlier reads are stale too.

@Retryable(retryFor = CannotAcquireLockException.class,
           maxAttempts = 3, backoff = @Backoff(delay = 50, multiplier = 2))
@Transactional(isolation = Isolation.REPEATABLE_READ)
public void recalculate(long id) { ... }

Spring usually translates 40001 into the CannotAcquireLockException or ConcurrencyFailureException family; check the exact class in your version via the log. The retry has to be outside @Transactional, otherwise the retry happens inside that same broken transaction.

When I choose REPEATABLE READ: a report or export consists of several queries and all of them must see the state at the same moment. A read-only transaction doesn't hit serialization errors. Where there are writes and a lot of contention, though, errors and retries pile up, and you have to check that in a load test.

PostgreSQL's REPEATABLE READ is stronger than the standard: no phantom reads either, but write skew is possible.