Who changes the data?
Two requests decrement the same stock. This is where atomic UPDATE and locking come in.
CONCURRENCYConcurrency, locking, transactions and the Transactional Outbox pattern explained visually. From stock errors to reliable Kafka messages.
Imagine building a shop with ms-pedidos, ms-inventario, MySQL or PostgreSQL, and Kafka. When many people buy at once, three different questions arise:
Two requests decrement the same stock. This is where atomic UPDATE and locking come in.
CONCURRENCYThe order must commit completely or roll back completely. This is where the transaction comes in.
ATOMICITYThe order is saved, but Kafka may be down. This is where Transactional Outbox comes in.
RELIABLE MESSAGINGThis guide is based on the attached PDF “Write concurrency with Spring Boot” (17 pages) and our earlier explanation of Outbox, rollback, locking and Kafka. The Outbox section expands on the PDF. All browser simulations are conceptual: to verify real locks, run the examples against an SQL database.
Imagine there are 10 units of a game console. Ana wants 3 and Bruno wants 4. If both read the same stock before either saves, they can calculate different results and overwrite each other. This is a lost update.
stock >= 0. For an account, saldo >= 0. Rules that must always hold are called invariants.The correct stock would be 3. This error does not require ten servers: it can happen with two threads in the same Spring Boot application. And @Transactional on its own does not eliminate every read-modify-write race.
| Anomaly | What happens | Typical protection |
|---|---|---|
| Lost update | Two transactions overwrite an update. | Versioning, locking or conditional UPDATE. |
| Dirty read | You read data that another transaction may still roll back. | READ COMMITTED or higher. |
| Non-repeatable read | The same read returns a different value. | Isolation appropriate to the database engine. |
| Phantom / write skew | Two transactions violate a rule over a set of rows. | Constraints, appropriate locks, SERIALIZABLE. |
| Deadlock | Two transactions wait for each other. | Consistent access order and selective retries. |
Data safety does not depend on Java applications seeing one another. If they all access the same primary MySQL or PostgreSQL database, the database coordinates locks and versions.
synchronized?It only coordinates threads in the same JVM. Its monitor is not shared between replicas. volatile, ReentrantLock and a @Service singleton bean are not distributed SQL locks either.@Transactional: all or nothing… with caveats.A transaction is like a draft: changes can be made, but they are not committed for the rest of the system until COMMIT. If an error requires rollback, that transaction's changes are undone.
@Service
@RequiredArgsConstructor
public class PedidoService {
private final PedidoRepository pedidos;
private final OutboxRepository outbox;
@Transactional
public void crearPedido(Pedido pedido) {
Pedido guardado = pedidos.save(pedido);
OutboxEvent evento = new OutboxEvent();
evento.setTipoEvento("PEDIDO_CREADO");
evento.setContenido("{\"pedidoId\":" + guardado.getId() + "}");
outbox.save(evento);
// COMMIT al salir del método si todo va bien
}
}
setContenido()?This was one of our questions. If setContenido() throws a RuntimeException that escapes the transactional method, Spring marks the transaction for rollback. The order is not committed either, even if save()was already called. But if the exception is caught and suppressed, the method may still end in COMMIT.
Choose a failure and see what actually remains in the database.
Tip: first try a failure in setContenido() and then the case with catch.
| Exception | Default rollback | Note |
|---|---|---|
RuntimeException | ✔ Yes | If it reaches the transactional interceptor. |
Error | ✔ Yes | Default rule. |
| Checked exception | ✖ No | Use rollbackFor where appropriate. |
| Caught exception | It depends | If the error is hidden and the transaction is not marked rollback-only, it may COMMIT. |
@Transactional from another method in the same class may bypass the proxy. And REQUIRES_NEW opens a separate transactional scope: do not treat it as part of the same COMMIT.Instead of reading stock, subtracting in Java and saving afterwards, ask SQL to do everything in a single conditional statement.
public interface ProductoRepository extends JpaRepository<Producto, Long> {
@Modifying
@Query("""
UPDATE Producto p
SET p.stock = p.stock - :cantidad,
p.version = p.version + 1
WHERE p.id = :id
AND p.stock >= :cantidad
""")
int descontar(@Param("id") Long id,
@Param("cantidad") int cantidad);
}
@Service
@RequiredArgsConstructor
public class InventarioService {
private final ProductoRepository productos;
@Transactional
public void descontar(Long id, int cantidad) {
if (cantidad <= 0) throw new IllegalArgumentException();
int filas = productos.descontar(id, cantidad);
if (filas != 1) {
throw new IllegalStateException("Sin stock o producto inexistente");
}
}
}
The return value int indicates how many rows were updated. 0 means the condition was not met. The example also increments version explicitly: JPA bulk update queries do not automatically increment @Version.
Ideal for editing data when conflicts are uncommon. With @Version, Hibernate detects whether someone changed the record since you read it.
@Entity
@Table(name = "productos")
public class Producto {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Integer stock;
@Version
private Long version;
// getters, setters...
}
-- Dos transacciones leen stock=10, version=0.
-- La primera actualiza:
UPDATE productos
SET stock = 7, version = 1
WHERE id = 1 AND version = 0;
-- 1 fila actualizada.
-- La segunda intenta actualizar con version antigua:
UPDATE productos
SET stock = 6, version = 1
WHERE id = 1 AND version = 0;
-- 0 filas: conflicto; su transacción se revierte.
If a conflict occurs, you can return HTTP 409 Conflict or retry the entire operation in a new transaction, rereading and revalidating. Never continue with a transaction marked for rollback.
With PESSIMISTIC_WRITE, a transaction acquires an SQL write lock before making decisions about the record. Another transaction needing an incompatible lock must wait or may time out.
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT p FROM Producto p WHERE p.id = :id")
Optional<Producto> buscarParaActualizar(@Param("id") Long id);
@Transactional
public void descontarConLock(Long id, int cantidad) {
if (cantidad <= 0) throw new IllegalArgumentException();
Producto producto = repo.buscarParaActualizar(id)
.orElseThrow();
if (producto.getStock() < cantidad)
throw new IllegalStateException("Stock insuficiente");
producto.setStock(producto.getStock() - cantidad);
// El bloqueo se mantiene hasta commit/rollback.
}
For MySQL/InnoDB or PostgreSQL, the SQL usually has a form equivalent to SELECT ... FOR UPDATE. A normal read may still see a committed version through MVCC: a write lock does not automatically block every read.
This is the main lab. Run the same two purchases with four strategies: no protection, atomic UPDATE, optimistic and pessimistic locking. Advance step by step to see how the result changes.
Press “Next step” to advance through the story.
| Mechanism | Benefit | Cost / caution | Typical use |
|---|---|---|---|
| Atomic UPDATE | A single conditional SQL operation. | Cannot express every complex rule. | Stock and counters. |
| @Version | Does not lock on read. | May fail and require a retry or 409. | Entity editing. |
| FOR UPDATE | Reads under a lock before deciding. | Waiting, deadlocks, lower throughput. | Multistep rules. |
The isolation level defines which concurrent changes a transaction can observe. MySQL/InnoDB and PostgreSQL do not have identical semantics at every level: verify the behaviour of your production database engine.
Minimal guarantees. PostgreSQL effectively treats this as READ COMMITTED.
Prevents dirty reads, but does not automatically make read-modify-write safe.
Tries to stabilise reads. PostgreSQL and InnoDB differ.
Equivalent to a serial ordering; may abort transactions and require retries.
-- No permitir stock negativo:
ALTER TABLE productos
ADD CONSTRAINT ck_stock CHECK (stock >= 0);
-- La misma plaza no puede reservarse dos veces:
CREATE UNIQUE INDEX uk_reserva_plaza
ON reservas(evento_id, plaza_id);
-- Elegir trabajos sin esperar por filas bloqueadas:
SELECT id FROM trabajos
WHERE estado = 'PENDIENTE'
ORDER BY id
FOR UPDATE SKIP LOCKED
LIMIT 10;SKIP LOCKED is useful for distributing jobs among consumers; it does not guarantee that a required job runs immediately: it simply skips locked rows. For concurrent inserts, consider UPSERT and unique keys instead of “SELECT then INSERT”.
Moving €200 from account 1 to account 2 requires two changes within the same transaction: subtract from one and add to the other. When locking two rows, acquire their locks in a fixed order to reduce deadlocks.
@Transactional
public void transferir(Long origen, Long destino, BigDecimal importe) {
if (origen.equals(destino) || importe.signum() <= 0)
throw new IllegalArgumentException();
Long primero = Math.min(origen, destino);
Long segundo = Math.max(origen, destino);
Cuenta c1 = repo.buscarParaActualizar(primero).orElseThrow();
Cuenta c2 = repo.buscarParaActualizar(segundo).orElseThrow();
Cuenta desde = c1.getId().equals(origen) ? c1 : c2;
Cuenta hacia = c1.getId().equals(destino) ? c1 : c2;
if (desde.getSaldo().compareTo(importe) < 0)
throw new IllegalStateException("Saldo insuficiente");
desde.setSaldo(desde.getSaldo().subtract(importe));
hacia.setSaldo(hacia.getSaldo().add(importe));
}
An optimistic conflict or deadlock may be recoverable. But retrying an operation must repeat reading, validation and writing, within a new transaction. And if an HTTP request is repeated after a timeout, you need an idempotency key to avoid charging or decrementing twice.
@Service
@RequiredArgsConstructor
public class RetiroFacade {
private final RetiroTransaccional tx;
public void retirarConReintento(Long id, BigDecimal importe) {
for (int intento = 1; intento <= 3; intento++) {
try {
tx.retirar(id, importe); // otro bean + nueva tx
return;
} catch (ObjectOptimisticLockingFailureException ex) {
if (intento == 3) throw ex;
// En producción: backoff + jitter.
}
}
}
}
@Service
class RetiroTransaccional {
@Transactional
public void retirar(Long id, BigDecimal importe) {
// Releer, validar y guardar desde cero.
}
}
A client calls POST /pedidos with Idempotency-Key: pedido-7a9twice. The operations table stores that key as UNIQUE and returns the already committed result instead of creating a second purchase. The operation and its key must commit in the same transaction.
▶ Open the HTTP and Kafka idempotency labs →
ms-inventario. They are related problems, but do not use the same record.Imagine your shop saves an order in MySQL and then tries to notify Kafka. If MySQL commits but Kafka fails, you get an order without a notification. If you publish first and the database then fails, Kafka may announce an order that does not exist.
Two operations on different systems. They do not form a single database transaction.
The order and record commit together; publishing is a later, recoverable step.
Order and outbox in the same SQL transaction.
The publisher retries when Kafka is unavailable.
Kafka may receive the same event more than once: use idempotency.
We will use a traditional structure organised by responsibility (domain, application, infrastructure, dto) without requiring hexagonal architecture. The snippets show the main components; they are not intended as a ready-to-run Maven project.
CREATE TABLE pedidos (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
estado VARCHAR(32) NOT NULL
);
CREATE TABLE outbox (
id VARCHAR(36) PRIMARY KEY,
tipo_evento VARCHAR(100) NOT NULL,
agregado_id BIGINT NOT NULL,
payload TEXT NOT NULL,
estado VARCHAR(20) NOT NULL DEFAULT 'PENDIENTE',
creado_en TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
enviado_en TIMESTAMP NULL
);
CREATE INDEX ix_outbox_estado_creado ON outbox(estado, creado_en);
@Service
@RequiredArgsConstructor
public class PedidoService {
private final PedidoRepository pedidoRepository;
private final OutboxRepository outboxRepository;
private final ObjectMapper objectMapper;
@Transactional
public Long crearPedido(CrearPedidoRequest request) {
Pedido pedido = new Pedido();
pedido.setEstado("PENDIENTE");
Pedido guardado = pedidoRepository.save(pedido);
PedidoCreadoEvent payload = new PedidoCreadoEvent(
UUID.randomUUID().toString(), guardado.getId(),
request.productoId(), request.cantidad()
);
String json;
try {
json = objectMapper.writeValueAsString(payload);
} catch (JsonProcessingException ex) {
throw new IllegalStateException("Error serializando el evento", ex);
}
OutboxEvent evento = new OutboxEvent();
evento.setId(payload.eventoId());
evento.setTipoEvento("PEDIDO_CREADO");
evento.setAgregadoId(guardado.getId());
evento.setPayload(json);
evento.setEstado("PENDIENTE");
outboxRepository.save(evento);
return guardado.getId();
}
}
The serialisation exception is converted to RuntimeException to ensure the default rollback behaviour. The eventoId field identifies the event consistently across repeated publications.
@Component
@RequiredArgsConstructor
public class OutboxPublisher {
private final OutboxRepository repository;
private final KafkaTemplate<String, String> kafka;
@Scheduled(fixedDelay = 5000)
public void publicar() {
List<OutboxEvent> pendientes =
repository.findTop100ByEstadoOrderByCreadoEnAsc("PENDIENTE");
for (OutboxEvent evento : pendientes) {
try {
kafka.send("pedidos.creados",
evento.getAgregadoId().toString(),
evento.getPayload()).get(10, TimeUnit.SECONDS);
// Pasa a ENVIADO tras confirmación del productor.
evento.setEstado("ENVIADO");
evento.setEnviadoEn(Instant.now());
repository.save(evento);
} catch (Exception ex) {
// Registrar error: se reintentará en la siguiente pasada.
}
}
}
}
FOR UPDATE SKIP LOCKEDstrategy, and recover abandoned jobs. Evaluate the cost before holding an SQL lock during a slow Kafka call. Alternative: CDC (for example, Debezium) over the transaction log.@KafkaListener(topics = "pedidos.creados", groupId = "inventario")
public void recibir(String json) throws Exception {
PedidoCreadoEvent evento = mapper.readValue(json, PedidoCreadoEvent.class);
inventarioService.aplicarEvento(evento);
}
@Transactional
public void aplicarEvento(PedidoCreadoEvent e) {
// INSERT con clave UNIQUE(evento_id): si ya está, es duplicado.
// Este INSERT y el descuento de stock deben ser una sola TX.
// Marcar como procesado sin descontar sería incorrecto.
if (!procesados.registrarSiEsNuevo(e.eventoId())) return;
int filas = productos.descontarStock(e.productoId(), e.cantidad());
if (filas != 1) throw new StockInsuficienteException();
// El commit confirma juntos registro del ID + descuento.
}
To retry an event after a stock error, exception handling and retry/DLT policies must be designed explicitly. In a real order flow, an inventory failure usually produces a rejection event and an order transition, rather than infinite retries.
The idea of registrarSiEsNuevo() in the previous snippet can be implemented with a unique constraint. Recording the event ID and decrementing stock must take part in the same MySQL transaction; if either fails, both must roll back.
CREATE TABLE eventos_procesados (
evento_id VARCHAR(36) PRIMARY KEY,
procesado_en TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- MySQL 8 / InnoDB: si existe la clave, no se inserta.
INSERT IGNORE INTO eventos_procesados(evento_id)
VALUES ('abc-123');
-- PostgreSQL equivalente:
-- INSERT INTO eventos_procesados(evento_id)
-- VALUES ('abc-123') ON CONFLICT DO NOTHING;
@Repository
@RequiredArgsConstructor
public class EventoProcesadoDao {
private final JdbcTemplate jdbc;
public boolean registrarSiEsNuevo(String eventoId) {
int filas = jdbc.update("""
INSERT IGNORE INTO eventos_procesados(evento_id)
VALUES (?)
""", eventoId);
return filas == 1;
}
}
@Service
@RequiredArgsConstructor
public class InventarioService {
private final EventoProcesadoDao procesados;
private final ProductoRepository productos;
@Transactional
public void aplicarEvento(PedidoCreadoEvent e) {
if (!procesados.registrarSiEsNuevo(e.eventoId())) return;
int filas = productos.descontar(e.productoId(), e.cantidad());
if (filas != 1) throw new IllegalStateException("Sin stock");
}
}
This example demonstrates deduplication for MySQL, combining JDBC and JPA in the same correctly configured Spring transaction. PostgreSQL would use a different INSERT. To distinguish duplicates from other SQL errors, handle integrity and connection errors explicitly. Insufficient-stock rejection and compensating-event publication belong to the system's business flow.
With one replica, the educational publisher helps explain the pattern. Across replicas, design a message claim with a lease expiry. Claiming and publishing are separate phases:
PENDIENTE with FOR UPDATE SKIP LOCKED and mark them PUBLICANDO, with worker_id and lease_until.ENVIADO while checking that the worker still owns the claim.Another common implementation is CDC: tools such as Debezium watch the database transaction log and forward Outbox INSERTs. This reduces polling, but adds infrastructure and operational work.
Kafka transactions can provide guarantees within Kafka, but JPA's @Transactional annotation does not automatically turn MySQL and Kafka into one atomic transaction. Transaction synchronisation mechanisms and specialised cases exist, but Outbox remains a common way to persist the message to publish alongside business data.
Watch the three components: SQL order, Outbox row and Kafka event. Choose where the failure occurs and see how the system recovers—or why it needs idempotency.
Imagine buying a ticket and losing your Internet connection just after pressing “Pay”. You do not know whether the purchase reached the server. You press again. Should you end up with two purchases? No. The system must recognise that this is the same business attempt. That is idempotency.
Requests and messages can arrive again. A persistent identifier prevents the same operation from being applied twice.
A header Idempotency-Key identifies the client's attempt. The same attempt does not create another order.
A eventoId identifies the business message. Redelivery does not decrement stock again.
Try the same key, change the body, cause a timeout or send two simultaneous requests. See what is actually saved in the simulated database.
An operation commits only once per key and content.
| Key | Request fingerprint | Status | Order |
|---|---|---|---|
| No keys yet. | |||
A new key creates an order. Repeating the same key and content retrieves the result without creating another order.
A constraint UNIQUE(ambito, clave) on the primary MySQL database coordinates all Spring Boot replicas. The second transaction may wait until the first commits or rolls back. It must then verify that the request fingerprint matches. Exact waiting behaviour and errors depend on the engine and isolation level.
CREATE TABLE idempotencia_http (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
ambito VARCHAR(80) NOT NULL,
clave VARCHAR(120) NOT NULL,
hash_peticion CHAR(64) NOT NULL,
estado VARCHAR(20) NOT NULL,
http_status SMALLINT NULL,
respuesta_json JSON NULL,
pedido_id BIGINT NULL,
creado_en TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY uk_operacion (ambito, clave)
) ENGINE=InnoDB;
-- La clave distingue un intento de negocio;
-- el hash impide reutilizarla con otro cuerpo.
A practical MySQL implementation can claim the key first with an INSERT and write the order, Outbox event and result within a single transaction. This snippet outlines the main responsibilities, not a complete Maven class.
@Transactional
public RespuestaPedido crear(CrearPedidoRequest request, String clave) {
validarClaveYRequest(clave, request);
String hash = sha256(canonicalizar(request));
// INSERT con UNIQUE(ambito, clave). Si la clave existe,
// se consulta la petición anterior en una transacción sana.
boolean nueva = claves.intentarRegistrar("CREAR_PEDIDO", clave, hash);
if (!nueva) {
OperacionGuardada previa = claves.buscar("CREAR_PEDIDO", clave);
if (!previa.hashPeticion().equals(hash)) {
throw new ClaveReutilizadaException(); // HTTP 409
}
if (previa.completada()) return previa.respuestaGuardada();
throw new OperacionEnCursoException(); // HTTP 409 / 202
}
Pedido pedido = pedidos.save(Pedido.desde(request));
eventosOutbox.save(eventoPedidoCreado(pedido));
RespuestaPedido respuesta = RespuestaPedido.desde(pedido);
claves.marcarCompletada(clave, pedido.getId(), respuesta);
return respuesta;
}
// La operación de alta se protege con UNIQUE en MySQL.
// Si usas un INSERT que lanza DuplicateKeyException, gestiona
// ese conflicto FUERA de la transacción fallida, en otra nueva.
DuplicateKeyException within the same @Transactional and continue as though nothing happened. Use an engine-specific conditional insert, or handle the conflict from an outer facade and open a separate read transaction.| HTTP situation | Decision | Suggested result |
|---|---|---|
| New key + valid body | Save the result, order and Outbox together | 201 Created |
| Same key + same body, already committed | Replay the saved response without repeating effects | Original response |
| Same key + different body | Reject improper reuse | 409 Conflict |
| Same key, first request still processing | Wait, return an in-progress status or respond with a conflict according to the contract | 202 / 409 |
| No key | Cannot identify a retry as the same operation | Require a key for critical operations |
An Outbox publisher may publish the same event again if it crashes after sending to Kafka. The consumer must deduplicate by eventoId, not by quantity or product name.
Compare an idempotent consumer with one that does not record events.
With protection, the event row and stock decrement commit in the same SQL transaction.
CREATE TABLE eventos_procesados (
consumidor VARCHAR(80) NOT NULL,
evento_id VARCHAR(60) NOT NULL,
PRIMARY KEY (consumidor, evento_id)
) ENGINE=InnoDB;
@Service
@RequiredArgsConstructor
public class InventarioService {
private final JdbcTemplate jdbc;
@Transactional
public void consumir(PedidoCreadoEvent e) {
// MySQL 8 + InnoDB. Si ya existe, no repetir efecto.
int nuevas = jdbc.update("""
INSERT IGNORE INTO eventos_procesados(consumidor, evento_id)
VALUES ('ms-inventario', ?)
""", e.eventoId());
if (nuevas == 0) return;
int filas = jdbc.update("""
UPDATE inventario
SET stock = stock - ?
WHERE producto_id = ? AND stock >= ?
""", e.cantidad(), e.productoId(), e.cantidad());
if (filas != 1) {
// Error transitorio: lanzar excepción → se revierten
// TAMBIÉN el INSERT de eventos_procesados.
// Sin stock real: diseñar rechazo de negocio y Outbox
// dentro de esta TX, no un retry infinito.
throw new IllegalStateException("Stock no disponible");
}
}
}
The consumer must commit its offset or ACK after its database commits . If the event is received again because that ACK failed, the unique constraint prevents a second decrement. Transient database errors must remain retryable without prematurely marking the event as processed.
Idempotency-Key recognises a repeated request.KafkaeventoId recognises a repeated delivery.SQLThe keys or IDs table and the business effect share the same transaction.The browser helps you understand, but real testing requires MySQL/InnoDB or PostgreSQL (for example, with Testcontainers) and concurrent transactions. H2 does not replace the production engine's actual locking semantics.
BEGIN;
SELECT * FROM cuentas
WHERE id = 1 FOR UPDATE;
UPDATE cuentas
SET saldo = 800
WHERE id = 1;
COMMIT; -- libera el lockBEGIN;
SELECT * FROM cuentas
WHERE id = 1 FOR UPDATE;
-- ESPERA a que A termine
UPDATE cuentas
SET saldo = 600
WHERE id = 1;
COMMIT;In PostgreSQL with READ COMMITTED, the second session typically waits and reads the newly committed state. Stricter isolation may cause aborts. Do not assume every engine gives the same result.
CountDownLatch or CyclicBarrier.pg_stat_activity, pg_locks, pg_stat_statements. MySQL: performance_schema.data_locks, data_lock_waits, SHOW ENGINE INNODB STATUS. Monitor connection pools, p95/p99 latency and queues.Eleven real situations. Choose an answer and get an immediate explanation. No registration required.
Answer the questions to see your score.
Either all operations in a transaction commit, or they roll back together.
Two or more operations overlap in time and the result depends on their actual execution order.
Hibernate detects changes to managed entities and generates UPDATE statements on flush.
Multiversion concurrency control: allows many normal reads to see committed versions without waiting for certain write locks.
A row lock acquired before a business decision to coordinate incompatible changes.
A number checked on update to detect whether someone changed the entity first.
A pending-message table and a process that publishes those messages recoverably to a broker.
Applying a repeated operation without executing its effect a second time.
A mechanism that captures changes from the database transaction log and forwards events, for example when publishing events from an Outbox table.
@Lock in repositories.@Modifying and modifying queries.