Atomicity
A transaction commits all its changes or none. This does not mean a value read by another transaction remains valid.
ACID · ATwo requests read the same record. Each believes it is right. Only one ends up writing what you expected. Learn to detect, reproduce and resolve these races in Spring Boot, even across multiple instances.
The main rule: first define what must never become false (business invariants); then choose the mechanism that guarantees that rule under concurrency.
@Transactional does not eliminate races by itselfConcurrency occurs when two or more operations on shared data overlap in time. Two instructions need not run at the exact same nanosecond: interleaved reads and writes are enough.
A transaction commits all its changes or none. This does not mean a value read by another transaction remains valid.
ACID · ADetermines which concurrent effects can be observed. Details depend on the engine and configured isolation level.
ACID · IA rule that must always hold: stock ≥ 0, one seat per event, an operation charged only once.
DOMAINThe order in which threads/transactions advance. Bugs arise when that order changes, not because Java calculates incorrectly.
RACE CONDITIONTwo customers withdraw €200. If both withdrawals commit, the balance must be €600. If both read €1,000, separately calculate €800 and save that value, the final balance is €800. This is a lost update.
The danger: it does not always fail. With a purely sequential order, the same code might return €600 and pass simple tests.
// Patrón vulnerable: read → modify → write
@Transactional
public void retirar(Long id, BigDecimal importe) {
Cuenta cuenta = repo.findById(id).orElseThrow();
validarSaldo(cuenta.getSaldo(), importe);
cuenta.setSaldo(cuenta.getSaldo().subtract(importe));
// Sin @Version ni lock: posible actualización perdida.
}A transaction protects its own atomicity, but two transactions can read the same previous state. You need a concurrency policy appropriate to the invariant.
The guide's problems grouped by type, with examples, causes and mitigations. Here we distinguish phantom read of write skew because they are different phenomena. We also include contention and HTTP idempotency.
Two €200 withdrawals read €1,000; both save €800, although the correct balance after two committed withdrawals would be €600.
Both transactions calculate their new value from an old read. The last UPDATE overwrites an earlier change.
Conditional atomic UPDATE for simple changes; @Version to detect conflicts; FOR UPDATE for multiple validations.
Keep in mind: @Transactional alone does not prevent this read-modify-write race. With @Version, retry the entire operation in a new transaction or return a conflict.
Run lost-update simulatorTwo doctors go off call: each transaction checks that the other remains active and updates a different row; after both commit, nobody is on call.
There is not necessarily a lost UPDATE: operations change different rows yet still invalidate the set-wide invariant.
Constraints where the model permits, locks on a coordinating resource or SERIALIZABLE with transaction retries.
Keep in mind: @Version on each doctor is insufficient when different rows are updated. Protection must cover the set that defines the rule.
Explore write skewT1 changes the balance from 1,000 to 500 but has not committed. T2 reads 500, then T1 executes ROLLBACK.
T2 observed a value that never became a committed database state.
READ COMMITTED or stronger isolation prevents dirty reads in common transactional engines.
Keep in mind: PostgreSQL treats READ UNCOMMITTED as READ COMMITTED; always check the engine's effective isolation.
Explore dirty readsT1 queries an item's stock and sees 10 units. T2 commits a change to 8. T1 queries again and sees 8.
Within the same transaction, the second read gets a different committed version from the first.
Use appropriate isolation or locking reads for a stable view; combine this with explicit protection when writing.
Keep in mind: READ COMMITTED may allow this. REPEATABLE READ provides engine-specific read guarantees; it does not automatically replace invariant design.
Explore non-repeatable readsT1 counts four reservations for an event. T2 inserts another reservation and commits. Repeating the set query, T1 may find five.
The query is a predicate over a set of rows, not simply rereading one record by ID.
Isolation that stabilises the query; business constraints, range locks where appropriate or SERIALIZABLE for set-wide rules.
Keep in mind: Exact snapshot and range-lock semantics differ between PostgreSQL and InnoDB. A stable read alone does not ensure a global rule remains intact.
Explore phantom readsT1 locks account A and waits for B; T2 locks B and waits for A. Neither can proceed without releasing something.
Each transaction waits for a lock held by the other. The engine detects this and usually aborts a victim, depending on its mechanisms.
Lock resources in a stable order, keep transactions short and retry recoverable victims.
Keep in mind: Deadlocks still need retry handling; slow HTTP calls should never be made while holding locks.
Simulate a deadlockThousands of requests update the same counter or stock for a popular SKU. Wait times and p95/p99 latency rise.
One row becomes a bottleneck even when updates are logically correct.
Batching, key partitioning, batch aggregation or redesigning the hotspot while preserving integrity.
Keep in mind: This is a performance problem, not an isolation anomaly. Scaling Spring Boot replicas does not automatically remove data contention.
Review performanceA payment commits, but its HTTP response is lost. The browser retries and the server charges again.
A lock serialises operations but cannot itself distinguish two legitimate requests from two deliveries of the same intent.
Persisted Idempotency-Key with UNIQUE, payload hash, state and recoverable result; coordinated with the business transaction.
Keep in mind: An external operation requires an additional protocol, such as outbox or reconciliation. Relying on the client's timeout is not enough.
Simulate duplicate requestsSelect any problem to expand its explanation. “Simulate” links lead to this blog's labs. These are teaching examples: exact behaviour depends on the engine and isolation.
A @Service singleton exists per Spring context, not per distributed system. The synchronized, volatile and ReentrantLock of one JVM do not coordinate other replicas. Locks and versions on the same transactional primary do.
synchronized only coordinates threads sharing that monitor in that process.
@Version, FOR UPDATE, UNIQUE and UPDATE are resolved where the authoritative data resides.
A DB-A lock does not protect DB-B. A different consistency and coordination design is needed.
Run the same scenario with vulnerable code, optimistic locking, pessimistic locking and a UPDATE conditional statement. Watch the order, who waits, who fails and the final value. This is a deterministic browser simulation, not queries against a real database.
Choose a strategy and advance step by step.
The interleaving is forced to reveal the race. In real PostgreSQL and MySQL, waits, aborts, snapshots and range locks depend on queries, indexes and isolation. Verify with Testcontainers tests.
Consider two transactions, T1 and T2, sharing data. Switch anomalies and step through their stories visually. These examples are conceptual; not every engine allows each anomaly at every level.
A ticket cannot be sold twice; stock cannot be negative. Often the safest protection is a conditional SQL statement or a constraint UNIQUE, rather than a SELECT followed by an save().
Two buyers try to purchase units from shared inventory.
Click simulate.
If two transactions try to reserve the same seat, a unique index is the definitive protection for that key.
CREATE UNIQUE INDEX uk_reserva_asiento
ON reservas(evento_id, asiento_id);With a violation of UNIQUE you must catch the error and respond consistently (e.g. 409).
Transferring money touches two accounts. If T1 locks A and needs B while T2 locks B and needs A, both wait. The engine usually detects the cycle and aborts a victim.
If every path locking the same two rows requests them in a stable order, this reverse-order cycle is eliminated. Not every deadlock disappears: other accesses, indexes and queries also matter.
@Transactional
public void transferir(Long origen, Long destino,
BigDecimal importe) {
Long primero = Math.min(origen, destino);
Long segundo = Math.max(origen, destino);
Cuenta a = repo.buscarParaActualizar(primero).orElseThrow();
Cuenta b = repo.buscarParaActualizar(segundo).orElseThrow();
// Validar + debitar + acreditar en la misma transacción.
}A client may send the same request again after a timeout even though the first COMMIT has completed. A lock serialises operations; it does not know they represent the same intent.
A purchase or transfer's identity does not depend on how many HTTP requests arrive. Store a unique key, a payload digest, its state and a recoverable result. Coordinate the business write and result record in the same local transaction whenever feasible.
Benefit: network retries can be safe. Costs: storage, expiry, races between in-progress requests and recovery design. Effects in external systems need another protocol, such as outbox and reconciliation.
-- PostgreSQL: diseño orientativo de idempotencia
CREATE TABLE operaciones_http (
clave VARCHAR(100) PRIMARY KEY,
hash_payload VARCHAR(64) NOT NULL,
estado VARCHAR(20) NOT NULL,
respuesta_json JSONB
);
-- En una transacción de negocio:
-- 1. Reclamar clave con UNIQUE.
-- 2. Si existe, comparar hash del payload.
-- 3. Si terminó, devolver resultado guardado.
-- 4. Si está en curso, esperar/rechazar/reintentar
-- según el protocolo documentado.
-- 5. Registrar efecto y resultado de forma consistente.There is no universal lock. The choice depends on whether you update a value, edit an entity, coordinate multiple rows or execute operations that networks may repeat. Each solution has an operational cost and a different failure mode.
| Strategy | Best for | Across multiple JVMs | Main trade-off |
|---|---|---|---|
| Conditional UPDATE | Stock, balances, counters | Yes | Simple rules expressible in one statement |
| @Version (optimistic) | Editing with infrequent collisions | Yes | Conflict and possible retry/409 |
| FOR UPDATE (pessimistic) | Several decisions in one transaction | Yes | Waits, locking and deadlocks |
| UNIQUE / CHECK / FK | Structural invariants | Yes | Schema design and violation handling |
| SERIALIZABLE | Complex set-wide rules | Yes | Aborts, overhead and full retries |
| Java locks | In-memory state in one JVM | No | Does not protect data shared across replicas |
Instead of reading saldo, subtracting in Java and saving, let the database validate and modify in a single statement. The WHERE saldo >= :importe is part of the protection; insufficient funds affect 0 rows. Check that result. With real concurrency, operations may wait or abort depending on isolation and engine.
SELECT → cálculo → UPDATE.@Version.// Repository: Spring Data JPA / JPQL. Cuenta tiene @Version.
@Modifying
@Query("""
update Cuenta c
set c.saldo = c.saldo - :importe,
c.version = c.version + 1
where c.id = :id
and c.saldo >= :importe
""")
int retirarSaldo(@Param("id") Long id,
@Param("importe") BigDecimal importe);
// Service: valida importe > 0 antes de ejecutar.
@Transactional
public void retirar(Long id, BigDecimal importe) {
if (importe == null || importe.signum() <= 0) {
throw new IllegalArgumentException("Importe inválido");
}
int filas = repo.retirarSaldo(id, importe);
if (filas != 1) throw new SaldoInsuficienteException();
}SaldoInsuficienteException represents a domain exception you must define. This illustrative JPQL query assumes the provider supports arithmetic on the mapped type. After a bulk update, do not reuse a loaded entity without refreshing it.@VersionHibernate stores a column version and conditions the write on the version read. If another transaction has committed a change, the UPDATE based on the old version affects 0 rows. A conflict is detected at flush/commit and the transaction becomes invalid.
@Entity
@Table(name = "cuentas")
public class Cuenta {
@Id private Long id;
@Column(precision = 19, scale = 2, nullable = false)
private BigDecimal saldo;
@Version private Long version;
// Constructor JPA, getters y operaciones de dominio.
}
@Service
public class CuentaOptimistaService {
private final CuentaRepository repo;
public CuentaOptimistaService(CuentaRepository repo) {
this.repo = repo;
}
@Transactional
public void retirar(Long id, BigDecimal importe) {
validarImportePositivo(importe); // definir en dominio
Cuenta c = repo.findById(id).orElseThrow();
if (c.getSaldo().compareTo(importe) < 0) {
throw new SaldoInsuficienteException();
}
c.setSaldo(c.getSaldo().subtract(importe));
// Hibernate comprueba @Version al hacer flush/commit.
}
}ETag / If-Match or a version field, and avoid overwriting changes from an old form; define a clear conflict response. Details depend on the JPA model and HTTP contract.FOR UPDATERequest a row write lock inside the transaction before making the business decision. An incompatible lock must wait or fail. A normal query may still read a committed version through MVCC; a write lock does not mean “nobody can read”.
public interface CuentaRepository
extends JpaRepository<Cuenta, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select c from Cuenta c where c.id = :id")
Optional<Cuenta> buscarParaActualizar(@Param("id") Long id);
}
@Service
public class CuentaPesimistaService {
private final CuentaRepository repo;
public CuentaPesimistaService(CuentaRepository repo) {
this.repo = repo;
}
@Transactional
public void retirar(Long id, BigDecimal importe) {
validarImportePositivo(importe);
Cuenta c = repo.buscarParaActualizar(id).orElseThrow();
if (c.getSaldo().compareTo(importe) < 0) {
throw new SaldoInsuficienteException();
}
c.setSaldo(c.getSaldo().subtract(importe));
} // commit y liberación del lock
}SELECT FOR UPDATE in one transaction and the save in another: the lock would already be released. Avoid external HTTP calls or human interactions while holding the lock.UNIQUE, CHECK and foreign keysA critical rule must survive Java bugs, batch jobs and third-party applications writing to the same table. Constraints do not replace all concurrency controls, but prevent the database from committing forbidden states.
UNIQUE prevents double occupancy of the same seat.ALTER TABLE cuentas
ADD CONSTRAINT ck_saldo_no_negativo CHECK (saldo >= 0);
CREATE UNIQUE INDEX uk_evento_asiento
ON reservas (evento_id, asiento_id);
-- PostgreSQL: contador sin SELECT-then-INSERT
INSERT INTO contadores(clave, total)
VALUES ('evento:42', 1)
ON CONFLICT (clave)
DO UPDATE SET total = contadores.total + 1;UPSERT differs in MySQL (ON DUPLICATE KEY UPDATE). Check types, engine and constraint support in your version.SERIALIZABLE and global rulesUseful when each transaction queries a set and makes a decision another transaction could invalidate over different rows. In PostgreSQL, dangerous dependencies may cause a serialisation error rather than blocking from the outset.
@Transactional(isolation = Isolation.SERIALIZABLE)
public void asignarGuardia() {
// Leer el conjunto relevante y aplicar la regla
// de negocio dentro de esta transacción.
// Error de serialización → reintentar transacción completa.
}REPEATABLE READ and SERIALIZABLE through identical mechanisms. Never infer a specific query's guarantees from the isolation level's name alone.SKIP LOCKEDDifferent workers can claim batches of jobs without waiting for rows another worker has locked. Useful for a queue, but not for “this specific row must be reserved”: SKIP LOCKED temporarily skips occupied records.
-- PostgreSQL: ejemplo conceptual de reclamación de trabajos
BEGIN;
SELECT id FROM trabajos
WHERE estado = 'PENDIENTE'
ORDER BY id
FOR UPDATE SKIP LOCKED
LIMIT 10;
-- Marcar esos IDs como EN_PROGRESO dentro de la transacción.
COMMIT;LIMIT/locking depend on the dialect. Design orphaned-job recovery before production use.They can coordinate resources beyond one RDBMS row or across different systems, but introduce expiry, partial failures and fencing-token requirements. A Redis distributed lock does not replace the transaction or constraints in the database storing the data. For relational rows, start with SQL guarantees.
Isolation levels limit observable effects, but are not a universal “no bugs” switch. The same name does not imply the same control algorithm in PostgreSQL and MySQL/InnoDB.
| Level | Core idea | Important caveat |
|---|---|---|
| READ UNCOMMITTED | Minimal guarantees, depending on implementation. | PostgreSQL treats it as READ COMMITTED; MySQL/InnoDB allows dirty reads at this level. |
| READ COMMITTED | Each statement normally sees an appropriate committed snapshot. | Does not prevent every read-modify-write race; repeated reads may differ. |
| REPEATABLE READ | Greater stability during the transaction. | PostgreSQL uses snapshot isolation with possible concurrent-write aborts; InnoDB combines consistent reads and locking reads. |
| SERIALIZABLE | Committed transactions are equivalent to some serial order. | May cause blocking or aborts; operations must support safe retries. |
Multi-Version Concurrency Control lets readers see appropriate committed versions without necessarily blocking a writer. That is why a normal SELECT can continue while another process holds a FOR UPDATE; a locking read differs from a consistent read.
Visibility, condition revalidation and waits differ across engines and isolation levels. Do not replace real tests with a generic table.
// El aislamiento se pide en el límite transaccional.
@Transactional(isolation = Isolation.READ_COMMITTED)
public void ejecutar() {
// SQL dentro de una misma transacción.
}
// No equivale a serializar todas las peticiones.
// Elegir el nivel forma parte del diseño de concurrencia.The following interactive matrix recommends a starting point, not a universal configuration. Validate a good decision against invariants, contention tests and real engine behaviour.
Qualitative teaching bars, not benchmarks or real latency measurements. Costs depend on the use case, workload and database.
Annotations help only when actually applied. Spring uses transactional proxies by default; method boundaries, exceptions and the persistence context can completely change the result.
this.metodoTransactional()⌄An internal call within the same bean bypasses the usual proxy. The called method's transaction configuration may not apply. Move it to another service, use an explicit design with TransactionTemplate or a compatible mechanism if needed.
@Service class Servicio {
public void ejecutar() {
this.guardar(); // salta el proxy transaccional
}
@Transactional
public void guardar() { /* ... */ }
}The usual configuration rolls back on RuntimeException and Error, not automatically on every checked exception. You can use rollbackFor, or review your Spring version's global configuration. Never silently catch an exception that should abort the operation.
@Transactional(rollbackFor = IOException.class)
public void importar() throws IOException { /* ... */ }REQUIRED joins an existing transaction or creates one. REQUIRES_NEW starts an independent transaction and may need another connection while the previous one remains occupied. Many threads doing this can exhaust the connection pool.
A bulk query UPDATE does not automatically update objects already loaded in the persistence context. Mixing direct updates and old entities may use stale data; design the transaction boundary and explicitly synchronise where appropriate.
A FOR UPDATE protects a decision for the transaction's lifetime. Acquiring it in a method that ends before modification loses that guarantee. Keep the protected read, check and write within the same boundary.
A read replica may lag. A critical validation against it may use stale state even when the primary is correct. Route write decisions to the authoritative source or an explicit consistency protocol.
The client may lose the response after commit. Repeating the request without an idempotency key may duplicate the effect. Explicitly define how to recover an already committed operation's result.
After a deadlock (40P01 in PostgreSQL), serialisation conflict (40001) or optimistic-locking failure, identify which exceptions are truly recoverable. Rerun the entire operation in a new transaction with limits, jittered backoff and idempotency criteria.
// Patrón: fachada externa al servicio transaccional.
@Service
class RetiroFacade {
private final RetiroTx tx;
RetiroFacade(RetiroTx tx) { this.tx = tx; }
public void retirarConRetry(Long id, BigDecimal importe) {
for (int i = 1; i <= 3; i++) {
try {
tx.retirar(id, importe); // cada llamada: nueva transacción
return;
} catch (ObjectOptimisticLockingFailureException ex) {
if (i == 3) throw ex;
// Backoff con jitter fuera de la transacción.
}
}
}
}
@Service
class RetiroTx {
@Transactional
public void retirar(Long id, BigDecimal importe) {
// RELEER + validar + modificar + confirmar.
}
}This teaching snippet requires imports, domain implementation and backoff/interruption handling. Never automatically retry every exception or operations that already caused external effects.
H2 does not necessarily reproduce PostgreSQL or InnoDB locks, isolation and SQLSTATE codes. Validate guarantees using the real engine in Testcontainers, separate transactions, controlled interleavings and invariant assertions.
Start real PostgreSQL/MySQL. Run two tasks on different threads, each through a transactional proxy.
Validate final data and response, not merely the absence of exceptions.Force reads of the same version, contention, timeouts, deadlocks, replica failures and repeated HTTP attempts.
Distinguish recoverable from unrecoverable errors.20 connections × 20 instances = up to 400 connections. Tune HikariCP against the global limit and traffic.
Never block threads indefinitely waiting for a connection.Measure transaction latency, lock waits, optimistic conflicts, deadlocks, retries and p95/p99.
Throughput can rise while the user experience deteriorates.The idea is to launch two real operations from separate transactions. This test checks a conditional UPDATE case with a €1,000 balance and two €200 withdrawals. Implement the service and repository as described above.
// Ejemplo integrable: imports convencionales omitidos por brevedad.
@Testcontainers
@SpringBootTest
class RetiroConcurrenteIT {
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:17");
@Autowired CuentaAtomicaService service;
@Autowired CuentaRepository repository;
@Autowired TransactionTemplate transactionTemplate;
@Test
void dosRetirosConcurrentesMantienenElSaldo() throws Exception {
Long id = transactionTemplate.execute(status -> {
// Crear cuenta nueva con saldo 1000.00.
return repository.save(new Cuenta(new BigDecimal("1000.00"))).getId();
});
ExecutorService pool = Executors.newFixedThreadPool(2);
CountDownLatch listos = new CountDownLatch(2);
CountDownLatch disparo = new CountDownLatch(1);
try {
Callable<Void> retiro = () -> {
listos.countDown();
if (!disparo.await(5, TimeUnit.SECONDS)) {
throw new AssertionError("No arrancó la prueba");
}
service.retirar(id, new BigDecimal("200.00"));
return null;
};
Future<Void> f1 = pool.submit(retiro);
Future<Void> f2 = pool.submit(retiro);
assertTrue(listos.await(5, TimeUnit.SECONDS));
disparo.countDown();
f1.get(10, TimeUnit.SECONDS);
f2.get(10, TimeUnit.SECONDS);
BigDecimal saldo = transactionTemplate.execute(status ->
repository.findById(id).orElseThrow().getSaldo());
assertEquals(0, saldo.compareTo(new BigDecimal("600.00")));
} finally {
disparo.countDown();
pool.shutdownNow();
}
}
}
@ServiceConnection requires appropriate integration with your Spring Boot version. Latches coordinate startup, not a specific commit order; forcing an @Version collision requires barriers after instrumented reads.Tick each item as you validate it. Progress is saved locally in this browser; nothing is sent to a server.
Five questions to reinforce the differences between atomicity, distributed locks, idempotency, version conflicts and global rules.
This content builds on the supplied technical concurrency guide, extended with official Spring, Hibernate, PostgreSQL and MySQL documentation. Simulations visualise specific interleavings, not a full scheduler or SQL-engine emulation.
“Write concurrency with Spring Boot: one instance, multiple replicas, JPA/Hibernate, PostgreSQL and MySQL”. November 2026 edition. Modella CRM design guide, revised 22 November 2026.
These examples illustrate patterns and decisions. They do not include all imports, security configuration, migrations, controllers or a runnable Spring Boot application. Adapt and test them with your versions before production use.