Transactions and Isolation Levels: MVCC, Lost Updates, Write Skew, and Spring Transaction Boundaries
System Design series · Part 3 Storage basics (4 of 8)
- SQL vs NoSQL: Choose a Database by Access Pattern, Not by Buzzword
- Indexes and B+Trees: From Disk Pages to Composite Indexes, Index-Defeating Queries, and Keyset Pagination
- B-Tree vs LSM-Tree: In-Place Updates vs Append-Only, and the Write, Read, and Space Amplification Trade-offs
- Transactions and Isolation Levels: MVCC, Lost Updates, Write Skew, and Spring Transaction Boundaries
- File and Object Storage: Block vs File vs Object, Direct Multipart Uploads, Metadata Consistency, and Upload Security
- Bloom Filters and HyperLogLog: Trading a Little Error for a Lot of Memory, and What to Do When Someone Games the Estimate
- Full-Text Search and Inverted Indexes: Chinese Tokenization, BM25 Ranking, Index Sync, and the Authorization Boundary of Search
- Geohash and Geospatial Indexes: Cell Boundaries in Nearby Search, Redis GEO, and How Distance Leaks Location
System Design series Part 3-4 | Previous: B-Tree vs LSM-Tree | Next: File and Object Storage | Series map
Scenario and problem
Before the annual talk sign-up from the series introduction goes live, a few more requirements arrive:
- Seats must never be oversold
- Talks come in morning and afternoon sessions, and a member can sign up for only one talk per time slot
- The organizer can add seats at short notice
- A successful sign-up sends a confirmation email
After a load test, QA reports three problems: 3,000 seats but 3,012 sign-ups; a member signed up for two talks in the same time slot; and after the organizer raised the limit from 3,000 to 3,500, the remaining seats no longer add up. Every line of the code looks right, and all of it is wrapped in @Transactional.
- Member 101 signs up, and transaction A reads the remaining seats first. All of the code is wrapped in @Transactional.
- 1 seat left, so the Java code decides the sign-up can go ahead.
- At the same moment, member 102's transaction B reads the remaining seats too.
- A has not committed yet, so B also reads 1 and also decides it can sign up.
- Transaction A sets the seats to 0, inserts a sign-up, and commits.
- Transaction B computes 0 from the 1 it read, writes it back, inserts a sign-up, and commits. A's decrement is overwritten. This is called a lost update.
- Both people are signed up, but the seats went down by only one. "One talk per time slot" breaks the same way: two sign-ups sent at the same time each find "not signed up yet", so each one inserts a row.
@Transactional does not mean there are no concurrency problems. What a transaction guarantees, and what it does not, depends on the isolation level and on how the code reads and writes.
The simplest approach and its limits
The most intuitive way to write it is “read it, decide in Java, write it back”. When two requests arrive at the same time, the timeline looks like this:
| Time | Transaction A (member 101) | Transaction B (member 102) |
|---|---|---|
| t1 | SELECT remaining → 1 |
|
| t2 | SELECT remaining → 1 |
|
| t3 | UPDATE ... SET remaining = 0, insert the sign-up, COMMIT |
|
| t4 | UPDATE ... SET remaining = 0, insert the sign-up, COMMIT |
Both transactions read “1 seat left” and both sign-ups succeed, but remaining is decremented only once: B overwrote A’s decrement. This is called a lost update.
“One talk per time slot” has the same problem: member 7 submits sign-ups for two different morning talks at the same time, each transaction queries “does member 7 already have a morning sign-up?” and gets “no”, and so each one inserts a row.
Let’s actually run it with two threads and two connections at the same time. Besides these two approaches, the program below also runs the fixes introduced later:
Test program (H2 in-memory database, READ COMMITTED; java -cp h2.jar RegistrationRaceDemo.java)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/** Two transactions sign up at the same time; compares the results of different approaches. Uses an H2 in-memory database at READ COMMITTED. */
public class RegistrationRaceDemo {
static final String URL = "jdbc:h2:mem:race;DB_CLOSE_DELAY=-1";
interface Attempt {
String run(Connection c, long memberId, long eventId, CyclicBarrier together) throws Exception;
}
public static void main(String[] args) throws Exception {
execute("CREATE TABLE event (id BIGINT PRIMARY KEY, slot VARCHAR(20) NOT NULL,"
+ " remaining INT NOT NULL, version INT NOT NULL)");
execute("CREATE TABLE registration (event_id BIGINT NOT NULL, member_id BIGINT NOT NULL, slot VARCHAR(20) NOT NULL)");
System.out.println("1 seat left; members 101 and 102 sign up for the same event at the same time:");
seatRace("Read, then write", RegistrationRaceDemo::readModifyWrite);
seatRace("Conditional UPDATE", RegistrationRaceDemo::conditionalUpdate);
seatRace("SELECT ... FOR UPDATE", RegistrationRaceDemo::selectForUpdate);
seatRace("Optimistic lock (version) + retry", RegistrationRaceDemo::optimistic);
System.out.println();
System.out.println("Member 7 signs up for two events in the same time slot at the same time (rule: one per time slot):");
slotRace("Check, then insert", false);
slotRace("With UNIQUE (member_id, slot)", true);
}
// ---- Approach 1: read, then write ----
static String readModifyWrite(Connection c, long memberId, long eventId, CyclicBarrier together) throws Exception {
int remaining = queryInt(c, "SELECT remaining FROM event WHERE id = ?", eventId);
together.await(5, TimeUnit.SECONDS); // start writing only after both sides have read
if (remaining <= 0) {
return "Sold out";
}
update(c, "UPDATE event SET remaining = ? WHERE id = ?", remaining - 1, eventId);
register(c, memberId, eventId);
c.commit();
return "Registered";
}
// ---- Approach 2: combine the check and the change into one UPDATE ----
static String conditionalUpdate(Connection c, long memberId, long eventId, CyclicBarrier together) throws Exception {
together.await(5, TimeUnit.SECONDS);
int updated = update(c, "UPDATE event SET remaining = remaining - 1"
+ " WHERE id = ? AND remaining > 0", eventId);
if (updated == 0) {
c.rollback();
return "Sold out";
}
register(c, memberId, eventId);
c.commit();
return "Registered";
}
// ---- Approach 3: lock the row as soon as it is read ----
static String selectForUpdate(Connection c, long memberId, long eventId, CyclicBarrier together) throws Exception {
together.await(5, TimeUnit.SECONDS);
int remaining = queryInt(c, "SELECT remaining FROM event WHERE id = ? FOR UPDATE", eventId);
if (remaining <= 0) {
c.rollback();
return "Sold out";
}
update(c, "UPDATE event SET remaining = ? WHERE id = ?", remaining - 1, eventId);
register(c, memberId, eventId);
c.commit();
return "Registered";
}
// ---- Approach 4: optimistic lock; on write, check the version is unchanged, and start over if it changed ----
static String optimistic(Connection c, long memberId, long eventId, CyclicBarrier together) throws Exception {
for (int attempt = 1; attempt <= 3; attempt++) {
int[] row = queryInts(c, "SELECT remaining, version FROM event WHERE id = ?", eventId);
int remaining = row[0];
int version = row[1];
if (attempt == 1) {
together.await(5, TimeUnit.SECONDS);
}
if (remaining <= 0) {
c.rollback();
return "Sold out (attempt " + attempt + ")";
}
int updated = update(c, "UPDATE event SET remaining = ?, version = version + 1"
+ " WHERE id = ? AND version = ?", remaining - 1, eventId, version);
if (updated == 1) {
register(c, memberId, eventId);
c.commit();
return "Registered (attempt " + attempt + ")";
}
c.rollback(); // someone else changed the version: give up this attempt and read again
}
return "Out of retries";
}
// ---- One sign-up per time slot ----
static String checkThenInsert(Connection c, long memberId, long eventId, CyclicBarrier together) throws Exception {
String slot = queryString(c, "SELECT slot FROM event WHERE id = ?", eventId);
int existing = queryInt(c, "SELECT COUNT(*) FROM registration WHERE member_id = ? AND slot = ?", memberId, slot);
together.await(5, TimeUnit.SECONDS); // start writing only after both sides have checked
if (existing > 0) {
return "Slot conflict";
}
register(c, memberId, eventId);
c.commit();
return "Registered";
}
static void seatRace(String title, Attempt attempt) throws Exception {
execute("DELETE FROM registration");
execute("DELETE FROM event");
execute("INSERT INTO event VALUES (42, 'SAT-AM', 1, 0)");
List<String> results = race(attempt, new long[][] {{101, 42}, {102, 42}});
System.out.printf(" %s: %s | seats left: %d | registrations: %d%n", title, results,
scalar("SELECT remaining FROM event WHERE id = 42"), scalar("SELECT COUNT(*) FROM registration"));
}
static void slotRace(String title, boolean uniqueConstraint) throws Exception {
execute("DELETE FROM registration");
execute("DELETE FROM event");
execute("INSERT INTO event VALUES (42, 'SAT-AM', 100, 0), (43, 'SAT-AM', 100, 0)");
execute(uniqueConstraint
? "CREATE UNIQUE INDEX IF NOT EXISTS uk_member_slot ON registration (member_id, slot)"
: "DROP INDEX IF EXISTS uk_member_slot");
List<String> results = race(RegistrationRaceDemo::checkThenInsert, new long[][] {{7, 42}, {7, 43}});
System.out.printf(" %s: %s | member 7 registrations in SAT-AM: %d%n", title, results,
scalar("SELECT COUNT(*) FROM registration WHERE member_id = 7 AND slot = 'SAT-AM'"));
}
static List<String> race(Attempt attempt, long[][] requests) throws Exception {
CyclicBarrier together = new CyclicBarrier(requests.length);
ExecutorService pool = Executors.newFixedThreadPool(requests.length);
try {
List<Future<String>> futures = new ArrayList<>();
for (long[] request : requests) {
futures.add(pool.submit(() -> {
try (Connection c = DriverManager.getConnection(URL)) {
c.setAutoCommit(false);
c.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
try {
return attempt.run(c, request[0], request[1], together);
} catch (SQLException e) {
c.rollback();
return "Failed (SQLState " + e.getSQLState() + ")";
}
}
}));
}
List<String> results = new ArrayList<>();
for (Future<String> future : futures) {
results.add(future.get(10, TimeUnit.SECONDS));
}
results.sort(null);
return results;
} finally {
pool.shutdownNow();
}
}
static void register(Connection c, long memberId, long eventId) throws SQLException {
update(c, "INSERT INTO registration (event_id, member_id, slot) SELECT id, ?, slot FROM event WHERE id = ?",
memberId, eventId);
}
static int update(Connection c, String sql, Object... params) throws SQLException {
try (PreparedStatement ps = prepare(c, sql, params)) {
return ps.executeUpdate();
}
}
static int queryInt(Connection c, String sql, Object... params) throws SQLException {
try (PreparedStatement ps = prepare(c, sql, params); ResultSet rs = ps.executeQuery()) {
rs.next();
return rs.getInt(1);
}
}
static int[] queryInts(Connection c, String sql, Object... params) throws SQLException {
try (PreparedStatement ps = prepare(c, sql, params); ResultSet rs = ps.executeQuery()) {
rs.next();
return new int[] {rs.getInt(1), rs.getInt(2)};
}
}
static String queryString(Connection c, String sql, Object... params) throws SQLException {
try (PreparedStatement ps = prepare(c, sql, params); ResultSet rs = ps.executeQuery()) {
rs.next();
return rs.getString(1);
}
}
static PreparedStatement prepare(Connection c, String sql, Object... params) throws SQLException {
PreparedStatement ps = c.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
return ps;
}
static void execute(String sql) throws SQLException {
try (Connection c = DriverManager.getConnection(URL); Statement s = c.createStatement()) {
s.execute(sql);
}
}
static int scalar(String sql) throws SQLException {
try (Connection c = DriverManager.getConnection(URL)) {
return queryInt(c, sql);
}
}
}1 seat left; members 101 and 102 sign up for the same event at the same time:
Read, then write: [Registered, Registered] | seats left: 0 | registrations: 2
Conditional UPDATE: [Registered, Sold out] | seats left: 0 | registrations: 1
SELECT ... FOR UPDATE: [Registered, Sold out] | seats left: 0 | registrations: 1
Optimistic lock (version) + retry: [Registered (attempt 1), Sold out (attempt 2)] | seats left: 0 | registrations: 1
Member 7 signs up for two events in the same time slot at the same time (rule: one per time slot):
Check, then insert: [Registered, Registered] | member 7 registrations in SAT-AM: 2
With UNIQUE (member_id, slot): [Failed (SQLState 23505), Registered] | member 7 registrations in SAT-AM: 1Five runs in a row gave the same result. CyclicBarrier makes both sides finish reading before either starts writing, which stretches the window in which the race can happen. In production this window is only a few milliseconds, so you normally cannot catch it in testing; it shows up only under a load test or when many users act at the same time.
Core mechanism
What a transaction guarantees
| Meaning | Common misconception | |
|---|---|---|
| Atomicity | Every change in the transaction succeeds, or all of them are undone | It does not mean “other transactions cannot interrupt it” |
| Consistency | The data follows rules the application defines (for example remaining >= 0) |
This is the application’s responsibility; the database can only help enforce the constraints you declare: NOT NULL, UNIQUE, CHECK, foreign keys |
| Isolation | How much concurrent transactions interfere with each other | It comes in levels, and the default in mainstream databases is not full isolation |
| Durability | Once committed, it survives a crash | Achieved by writing the redo log/WAL to disk |
MVCC: reads do not block writes, and writes do not block reads
InnoDB and PostgreSQL both use MVCC (multi-version concurrency control): each row keeps several versions, and a plain SELECT reads a snapshot as of some point in time without taking any locks, while a change has to take that row’s row lock.
When the snapshot is taken depends on the isolation level:
- READ COMMITTED: every
SELECTstatement takes its own new snapshot - REPEATABLE READ: MySQL takes it at the first read in the transaction, PostgreSQL at the first query or data-modifying statement in the transaction; the whole transaction then reads the same snapshot
The key point: a plain SELECT and an UPDATE may not see the same world. The MySQL documentation says so plainly: in a REPEATABLE READ transaction, a plain SELECT reads the snapshot, while UPDATE, DELETE, and SELECT ... FOR UPDATE read the latest committed data and take locks. The documentation even advises against mixing the two kinds of read in one REPEATABLE READ transaction, because the results are hard to reason about.
That is exactly how a lost update happens: the decision is based on the snapshot (the old value), but the write lands on the latest data.
Concurrency anomalies
| Anomaly | What it looks like in the sign-up system |
|---|---|
| Dirty read | Reading a seat count that another transaction has not committed yet and later rolls back |
| Non-repeatable read | The same transaction reads the remaining seats twice and gets two different numbers |
| Phantom | The same transaction queries “member 7’s morning sign-ups” twice, and the second time there is one more row |
| Lost update | Both transactions read 1 left, each writes back 0, and one of the decrements disappears |
| Write skew | Two transactions each confirm “member 7 has no morning sign-up”, then each inserts a sign-up for a different talk; together they break the rule |
Write skew is the hardest to spot: the two transactions write different rows, so there is no row lock conflict between them, and the usual isolation levels cannot stop it at all.
How isolation levels actually behave
The SQL standard defines isolation levels by “which anomalies are prohibited”, but implementations differ a lot from one database to another. Taking the “read, then write” code as the baseline:
| Anomaly | READ COMMITTED | MySQL REPEATABLE READ | PostgreSQL REPEATABLE READ | SERIALIZABLE |
|---|---|---|---|---|
| Dirty read | No | No | No | No |
| Non-repeatable read | Possible | No | No | No |
Phantom (plain SELECT) |
Possible | No | No | No |
| Lost update | Possible | Possible | No: the transaction that writes later gets a serialization error | No |
| Write skew | Possible | Possible | Possible | No |
- Defaults: InnoDB uses REPEATABLE READ, PostgreSQL uses READ COMMITTED
- MySQL’s REPEATABLE READ does not stop lost updates:
UPDATEworks directly on the latest data and does not check whether the value you read is already stale. PostgreSQL’s REPEATABLE READ does: if a row you are about to change was changed and committed by someone else after your transaction started, it throws an error (SQLSTATE40001), and the whole transaction has to start over - SERIALIZABLE is implemented differently: MySQL makes plain
SELECTs take shared locks too, so conflicting transactions wait on each other and often end in a deadlock; PostgreSQL uses Serializable Snapshot Isolation, which takes no extra locks and, when it detects a read/write dependency that could violate serializability, makes one of the transactions fail. With either one, you must be ready to retry
Comparing options
| Approach | How it works | Pros | Cost | Fits |
|---|---|---|---|---|
Conditional UPDATE |
The check and the change are in one statement, and the database decides using the latest value | Simplest and fastest, no retries needed | Can only express rules on a single row that fit in a SQL condition | Decrementing seats, stock, balances |
SELECT ... FOR UPDATE (pessimistic lock) |
Lock the row when reading it; everyone else waits in line | You can make complex decisions in Java | Locks are held longer, so throughput on a hot row drops; deadlocks are possible | Complex decisions, frequent conflicts |
Optimistic lock (version column) |
On write, check the version is unchanged; start over if it changed | No lock held while reading | Lots of retries once conflicts are frequent | Edits with few conflicts, such as changing an event in the back-office tool |
| Unique constraint | Turn “cannot exist together” into a unique index | Guaranteed by the database, the most reliable | The rule has to reduce to “this set of columns cannot repeat” | Write-skew rules: one sign-up per member per time slot, each coupon used once |
| SERIALIZABLE | Let the database prevent every anomaly | No need to analyze each race one by one | MySQL: more locks and deadlocks; PostgreSQL: serialization failures to handle | Complex rules that are hard to turn into constraints, at low volume |
A few rules of thumb:
- If it can be a conditional
UPDATE, do not read first. The series introduction worked out that the throughput ceiling of a hot row is about “1 ÷ the lock time of each transaction”.SELECT ... FOR UPDATEholds the lock from the moment it reads, so the Java logic in between and the round trips between the application and the database all count as lock time - The fix for write skew is to turn the conflict into a conflict on the same row. A unique constraint is the most direct way: both transactions have to insert
(member_id = 7, slot = 'SAT-AM'), so the second one always fails. When the rule cannot be expressed as a unique constraint (for example “meeting room bookings cannot overlap”), lock a shared row first instead (for exampleSELECT ... FROM member WHERE id = 7 FOR UPDATE), so that operations for the same member queue up - Optimistic locking suits data that “people” edit: the organizer rarely changes an event, conflicts are rare, and one retry is enough
In Java
1. Entity: optimistic lock and unique constraint
package signup;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.Version;
@Entity
@Table(name = "event")
public class Event {
@Id
private Long id;
@Column(nullable = false, length = 20)
private String slot;
@Column(nullable = false)
private int capacity;
@Column(nullable = false)
private int remaining;
@Version
private long version;
protected Event() {
}
public String getSlot() {
return slot;
}
/** The organizer changes the seat limit: the number already registered stays the same, and the remaining seats follow. */
public void changeCapacity(int newCapacity) {
int registered = capacity - remaining;
if (newCapacity < registered) {
throw new IllegalArgumentException("The seat limit cannot be lower than the number already registered: " + registered);
}
capacity = newCapacity;
remaining = newCapacity - registered;
}
}package signup;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
@Entity
@Table(name = "registration",
uniqueConstraints = @UniqueConstraint(name = "uk_member_slot", columnNames = {"member_id", "slot"}))
public class Registration {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "event_id", nullable = false)
private long eventId;
@Column(name = "member_id", nullable = false)
private long memberId;
@Column(nullable = false, length = 20)
private String slot;
protected Registration() {
}
public Registration(long eventId, long memberId, String slot) {
this.eventId = eventId;
this.memberId = memberId;
this.slot = slot;
}
}In production, the unique constraint belongs in a migration; @UniqueConstraint only has an effect when you let Hibernate generate the schema (the same as @Index in the Indexes and B+Trees post).
2. Repository: conditional UPDATE
package signup;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface EventRepository extends JpaRepository<Event, Long> {
/** Check and decrement in one UPDATE. A bulk update bypasses optimistic locking, so increment version yourself. */
@Modifying
@Query("""
update Event e
set e.remaining = e.remaining - 1, e.version = e.version + 1
where e.id = :id and e.remaining > 0
""")
int takeSeat(@Param("id") long id);
}An easy-to-miss problem hides here. The JPA specification says a bulk update maps directly to a database UPDATE: it bypasses the optimistic lock check and does not increment version automatically. If you leave out e.version = e.version + 1:
- The organizer loads the event and reads
remaining = 10,version = 5 - Meanwhile someone signs up;
takeSeatdecrementsremainingto 9, butversionis still 5 - The organizer saves. By default Hibernate updates every column, and the
versioncheck passes, soremainingis written back with a value computed from 10, and the sign-up that just happened “disappears”
This is exactly why “the remaining seats no longer add up” in the scenario.
3. Inside the transaction: the hot row goes last
package signup;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class RegistrationService {
private final EventRepository events;
private final RegistrationRepository registrations;
public RegistrationService(EventRepository events, RegistrationRepository registrations) {
this.events = events;
this.registrations = registrations;
}
/** One sign-up is one transaction: if any step fails, the whole sign-up does not happen. */
@Transactional
public void register(long memberId, long eventId) {
Event event = events.findById(eventId)
.orElseThrow(() -> new IllegalArgumentException("Event not found: " + eventId));
// a second sign-up in the same time slot violates uk_member_slot here
registrations.saveAndFlush(new Registration(eventId, memberId, event.getSlot()));
// the hot row comes last: the shortest possible time from taking the row lock to commit
if (events.takeSeat(eventId) == 0) {
throw new SoldOutException(eventId); // RuntimeException: rolls back together with the INSERT above
}
}
@Transactional
public void changeCapacity(long eventId, int newCapacity) {
Event event = events.findById(eventId)
.orElseThrow(() -> new IllegalArgumentException("Event not found: " + eventId));
event.changeCapacity(newCapacity); // if version does not match at commit, an optimistic lock exception is thrown
}
}- Order matters:
findByIdis a plain read and takes no lock; inserting the sign-up locks only the new row;takeSeatcomes last and takes the row lock on theeventrow, so the lock is held only for the short stretch “from the last statement to commit” saveAndFlush: explicitly sends theINSERTat this line, so a unique constraint violation happens here. When the primary key isIDENTITY, Hibernate in fact runs theINSERTright away onsave; but withSEQUENCEor other strategies, theINSERTis delayed until flush or even commit. WritingsaveAndFlushmakes the behavior independent of the primary key strategySoldOutExceptionis aRuntimeException: by default Spring rolls back only onRuntimeExceptionandError, not on checked exceptions
4. Outside the transaction: retries and exception translation
package signup;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.resilience.annotation.Retryable;
import org.springframework.stereotype.Service;
/** Sits outside the transaction: every retry calls RegistrationService, which opens a brand-new transaction. */
@Service
@Retryable(includes = ConcurrencyFailureException.class, maxRetries = 3, delay = 50, jitter = 20, multiplier = 2)
public class RegistrationFacade {
private final RegistrationService service;
public RegistrationFacade(RegistrationService service) {
this.service = service;
}
public RegistrationResult register(long memberId, long eventId) {
try {
service.register(memberId, eventId);
return RegistrationResult.REGISTERED;
} catch (SoldOutException e) {
return RegistrationResult.SOLD_OUT;
} catch (DataIntegrityViolationException e) {
// the only constraint this transaction can violate is uk_member_slot; never expose the constraint name or SQL to callers
return RegistrationResult.SLOT_CONFLICT;
}
}
public void changeCapacity(long eventId, int newCapacity) {
service.changeCapacity(eventId, newCapacity);
}
}package signup;
import org.springframework.context.annotation.Configuration;
import org.springframework.resilience.annotation.EnableResilientMethods;
@Configuration
@EnableResilientMethods
public class ResilienceConfig {
}@Retryable is the retry support built into Spring Framework 7, enabled with @EnableResilientMethods. Three design points:
Retries must sit outside the transaction. Once a transaction fails, it is already marked for rollback, so retrying inside the same transaction is pointless; you have to roll back and open a new transaction with a new snapshot before you can read the version someone else just committed. Verified with H2:
Verification program (Spring 7.0.10 + H2, simulating an optimistic lock conflict with JdbcClient)
package retrycheck;
import java.util.Map;
import javax.sql.DataSource;
import org.h2.jdbcx.JdbcDataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.resilience.annotation.EnableResilientMethods;
import org.springframework.resilience.annotation.Retryable;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/** Checks that with @Retryable outside the transaction, every retry is a new transaction and reads the new version someone else committed. */
public class RetryOutsideTransactionCheck {
public static class CapacityService {
private final JdbcClient jdbc;
private final DataSource dataSource;
private int attempt;
public CapacityService(JdbcClient jdbc, DataSource dataSource) {
this.jdbc = jdbc;
this.dataSource = dataSource;
}
@Transactional
public void changeCapacity(long eventId, int newCapacity) throws Exception {
attempt++;
Map<String, Object> row = jdbc.sql("SELECT capacity, remaining, version FROM event WHERE id = ?")
.param(eventId).query().singleRow();
int capacity = (Integer) row.get("CAPACITY");
int remaining = (Integer) row.get("REMAINING");
long version = (Long) row.get("VERSION");
if (attempt == 1) {
try (var other = dataSource.getConnection(); var st = other.createStatement()) {
// simulate another request completing a sign-up and committing right now
st.executeUpdate("UPDATE event SET remaining = remaining - 1, version = version + 1 WHERE id = " + eventId);
}
}
int registered = capacity - remaining;
int updated = jdbc.sql("UPDATE event SET capacity = ?, remaining = ?, version = version + 1 WHERE id = ? AND version = ?")
.params(newCapacity, newCapacity - registered, eventId, version).update();
System.out.printf("Attempt %d: in transaction=%s, read remaining=%d, version=%d, rows updated: %d%n", attempt,
TransactionSynchronizationManager.isActualTransactionActive(), remaining, version, updated);
if (updated == 0) {
throw new OptimisticLockingFailureException("event " + eventId + " was modified by another transaction");
}
}
}
@Retryable(includes = ConcurrencyFailureException.class, maxRetries = 3, delay = 50, jitter = 20, multiplier = 2)
public static class CapacityFacade {
private final CapacityService service;
public CapacityFacade(CapacityService service) {
this.service = service;
}
public void changeCapacity(long eventId, int newCapacity) throws Exception {
System.out.printf("When the facade is called: in transaction=%s%n", TransactionSynchronizationManager.isActualTransactionActive());
service.changeCapacity(eventId, newCapacity);
}
}
@Configuration
@EnableTransactionManagement
@EnableResilientMethods
public static class Config {
@Bean
public DataSource dataSource() {
JdbcDataSource ds = new JdbcDataSource();
ds.setURL("jdbc:h2:mem:retry;DB_CLOSE_DELAY=-1");
return ds;
}
@Bean
public PlatformTransactionManager transactionManager(DataSource ds) {
return new DataSourceTransactionManager(ds);
}
@Bean
public JdbcClient jdbcClient(DataSource ds) {
return JdbcClient.create(ds);
}
@Bean
public CapacityService capacityService(JdbcClient jdbc, DataSource ds) {
return new CapacityService(jdbc, ds);
}
@Bean
public CapacityFacade capacityFacade(CapacityService service) {
return new CapacityFacade(service);
}
}
public static void main(String[] args) throws Exception {
try (var ctx = new AnnotationConfigApplicationContext(Config.class)) {
JdbcClient jdbc = ctx.getBean(JdbcClient.class);
jdbc.sql("CREATE TABLE event (id BIGINT PRIMARY KEY, capacity INT, remaining INT, version BIGINT)").update();
jdbc.sql("INSERT INTO event VALUES (42, 100, 10, 0)").update(); // 90 already registered
ctx.getBean(CapacityFacade.class).changeCapacity(42, 120);
System.out.println("Final: " + jdbc.sql("SELECT capacity, remaining, version FROM event WHERE id = 42").query().singleRow());
}
}
}When the facade is called: in transaction=false
Attempt 1: in transaction=true, read remaining=10, version=0, rows updated: 0
When the facade is called: in transaction=false
Attempt 2: in transaction=true, read remaining=9, version=1, rows updated: 1
Final: {CAPACITY=120, REMAINING=29, VERSION=2}When the facade is called, there is no transaction. Attempt 1 reads version=0, but before it updates, another request has already committed a sign-up, so it updates 0 rows. Attempt 2 is a brand-new transaction: it reads remaining=9, version=1, and the update succeeds. The 91 people already registered are not overwritten.
Always restrict which exceptions are retried. By default @Retryable retries on any exception, 3 times, 1 second apart, so even a business error like “the seat limit cannot be lower than the number already registered” gets retried. ConcurrencyFailureException is Spring’s common parent class for concurrency conflicts. Measured with the JDBC exception translator in Spring 7.0.10:
| Database error | Translated exception | Parent class |
|---|---|---|
| MySQL 1213 deadlock | DeadlockLoserDataAccessException (deprecated) |
PessimisticLockingFailureException |
| MySQL 1205 lock wait timeout | CannotAcquireLockException |
PessimisticLockingFailureException |
| PostgreSQL 40001 serialization failure | CannotSerializeTransactionException (deprecated) |
PessimisticLockingFailureException |
| MySQL 1062 duplicate key | DuplicateKeyException |
DataIntegrityViolationException |
PessimisticLockingFailureException and OptimisticLockingFailureException (thrown when an optimistic lock fails) both extend ConcurrencyFailureException. Two of the subclasses are deprecated but still thrown, so name the parent class in catch blocks and retry conditions, not the subclasses. A duplicate key is a DataIntegrityViolationException, and retrying will not make it succeed, so it is left out of the retry set.
Catch DataIntegrityViolationException outside the transaction. If you catch it inside RegistrationService and return a result, the exception has already passed through the repository’s transaction interceptor, and the whole transaction is marked rollback-only; when the method returns normally, Spring tries to commit and throws UnexpectedRollbackException.
5. Side effects go after commit
The confirmation email must not be sent inside the transaction. The transaction might roll back after the email goes out (the user gets a confirmation email for a sign-up that does not exist), or it might be retried (the user gets two). Use @TransactionalEventListener to send it only after commit, as shown in Caching in Depth; to guarantee “if it committed, the email will go out”, you need the outbox from Part 7-3 Sagas and the Outbox Pattern.
Pitfalls and gotchas
- Assuming
@Transactionalmeans no concurrency problems: a transaction only guarantees atomicity; how isolated it is depends on the isolation level and on how you read and write - Assuming MySQL’s REPEATABLE READ prevents lost updates: it does not; a plain
SELECTreads the snapshot, andUPDATEwrites to the latest data - Switching the whole system to SERIALIZABLE: MySQL’s locks and deadlocks go up sharply; PostgreSQL’s serialization failures increase. Both need retries, and both lower throughput
- Wrapping a
@Transactionalmethod insynchronized: the commit happens in the proxy after the method returns, sosynchronizedis already released before the commit; and with more than one machine it does nothing at all (see the stateless services post) - Calling your own
@Transactionalor@Retryablemethod from inside the same class: self-invocation does not go through the proxy, so the annotation does nothing - Checked exceptions do not roll back: to roll back, throw a
RuntimeExceptionor setrollbackFor - MySQL’s lock wait timeout defaults to 50 seconds and rolls back only that statement: unless
innodb_rollback_on_timeoutis on, the transaction itself is still alive, and if the code swallows the exception and goes on to commit, it leaves half-written data behind - Chasing deadlocks as bugs: deadlocks are normal in concurrent systems, and InnoDB detects them right away and rolls back one of the transactions. What you actually need to do is retry the whole transaction, and have every transaction access data in the same order to make deadlocks less likely
- Calling external services inside a transaction: while you call a payment or SMS API, the transaction holds its connection and locks the whole time. With a pool of 10 connections and a 2-second external call, the whole service can handle at most 5 such requests per second (for connection pool tuning, see the HikariCP tuning post)
- Transactions that never end: MVCC has to keep old versions until the oldest snapshot no longer needs them (InnoDB’s undo log, PostgreSQL’s dead tuples), so one transaction someone forgot to end makes tables keep bloating and queries keep slowing down
Security
- A race condition is itself a vulnerability: reusing a coupon, deducting a gift card balance twice, and claiming a referral reward more than once are all the same “check, then change” race (limit overrun). Research PortSwigger published in 2023 demonstrated a technique for getting dozens of requests to reach the server almost simultaneously, so an attacker does not need luck. Rate limiting cannot stop it, because the requests all stay within the limit; fix it in the data layer with a conditional
UPDATEor a unique constraint - Locks can be used to take a service down: with an API that runs
SELECT ... FOR UPDATEon a hot row, every request waiting in line for the lock holds a database connection, for up to 50 seconds. An attacker only has to keep sending a small number of requests to exhaust the connection pool and take unrelated APIs down with it. Shorten the lock wait (in MySQL you canSET SESSION innodb_lock_wait_timeoutper connection; PostgreSQL useslock_timeout), prefer a conditionalUPDATE, and rate-limit these APIs (Part 8 Abuse Prevention) - Audit records vanish along with the rollback: if you write audit records such as “login failed” and “authorization denied” inside the business transaction, they disappear when the transaction rolls back, which erases exactly the traces of the attack. Write security audit records in a separate transaction (
Propagation.REQUIRES_NEW) or outside the transaction. Note thatREQUIRES_NEWtakes another connection, so at peak each request holds two at once; include that when you size the connection pool - Error messages leak the schema: returning the database exception’s message straight to the frontend exposes table names, constraint names, even SQL. Turn it into a business result as
RegistrationFacadedoes, and write the details only to server-side logs
When to use it, and when not to
- Quantity checks on a single row (seats, stock, balances): conditional
UPDATE - “Cannot exist together” rules: unique constraint
- Complex decisions, frequent conflicts: pessimistic lock, with the lock held as briefly as possible
- Edits with few conflicts: optimistic lock plus retries outside the transaction
- Rules that span many rows, are hard to turn into constraints, and run at low volume: SERIALIZABLE plus retries; PostgreSQL’s SSI suits this better than MySQL’s lock-based implementation
- Do not: call external services inside a transaction, use
synchronizedto solve database concurrency problems, or retry without restricting the exceptions - Across several services or databases: a single database’s transaction is no longer enough; you need distributed locks or a saga (Part 7)
If you are following the beginner path in the series map, read Part 6-2 Timeouts, Retries, Backoff, and Jitter next.
References
- Hal Berenson et al., “A Critique of ANSI SQL Isolation Levels”, SIGMOD 1995
- Dan R. K. Ports, Kevin Grittner, “Serializable Snapshot Isolation in PostgreSQL”, VLDB 2012
- Martin Kleppmann, Designing Data-Intensive Applications, O’Reilly, 2017, Chapter 7
- MySQL 8.4 Reference Manual — Transaction Isolation Levels: https://dev.mysql.com/doc/refman/8.4/en/innodb-transaction-isolation-levels.html
- MySQL 8.4 Reference Manual — Consistent Nonlocking Reads: https://dev.mysql.com/doc/refman/8.4/en/innodb-consistent-read.html
- MySQL 8.4 Reference Manual — InnoDB Error Handling: https://dev.mysql.com/doc/refman/8.4/en/innodb-error-handling.html
- PostgreSQL 18 Documentation — Transaction Isolation: https://www.postgresql.org/docs/18/transaction-iso.html
- PostgreSQL 18 Documentation — Serialization Failure Handling: https://www.postgresql.org/docs/18/mvcc-serialization-failure-handling.html
- Jakarta Persistence Specification — Bulk Update and Delete Operations: https://jakarta.ee/specifications/persistence/
- Spring Framework Reference — Declarative Transaction Management: https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative.html
- Spring Framework Reference — Resilience Features: https://docs.spring.io/spring-framework/reference/core/resilience.html
- James Kettle, “Smashing the state machine: the true potential of web race conditions”, PortSwigger Research, 2023: https://portswigger.net/research/smashing-the-state-machine
- Interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments