BEFORE YOU START

One story. Three different problems.

Imagine building a shop with ms-pedidos, ms-inventario, MySQL or PostgreSQL, and Kafka. When many people buy at once, three different questions arise:

01

Who changes the data?

Two requests decrement the same stock. This is where atomic UPDATE and locking come in.

CONCURRENCY
02

What is saved if something fails?

The order must commit completely or roll back completely. This is where the transaction comes in.

ATOMICITY
03

How does the news get delivered?

The order is saved, but Kafka may be down. This is where Transactional Outbox comes in.

RELIABLE MESSAGING

This 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.

CHAPTER 01 · THE PROBLEM

What is a concurrency race?

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.

The rule that must never be brokenFor inventory, 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.

Other anomalies worth knowing

AnomalyWhat happensTypical protection
Lost updateTwo transactions overwrite an update.Versioning, locking or conditional UPDATE.
Dirty readYou read data that another transaction may still roll back.READ COMMITTED or higher.
Non-repeatable readThe same read returns a different value.Isolation appropriate to the database engine.
Phantom / write skewTwo transactions violate a rule over a set of rows.Constraints, appropriate locks, SERIALIZABLE.
DeadlockTwo transactions wait for each other.Consistent access order and selective retries.
CHAPTER 02 · ARCHITECTURE

One Spring Boot instance or ten?

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.

LAB 01 / ARCHITECTURE

Change the deployment

LIVE
Does 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.
CHAPTER 03 · ATOMICITY

@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
    }
}

What if the failure occurs exactly in 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.

LAB 02 / ROLLBACK

Break the transaction yourself

Choose a failure and see what actually remains in the database.

SIMULATION
ORDER IN MYSQL—
OUTBOX EVENT—
TRANSACTIONNot run
  1. Choose a scenario and press “Run”.

Tip: first try a failure in setContenido() and then the case with catch.

ExceptionDefault rollbackNote
RuntimeException✔ YesIf it reaches the transactional interceptor.
Error✔ YesDefault rule.
Checked exception✖ NoUse rollbackFor where appropriate.
Caught exceptionIt dependsIf the error is hidden and the transaction is not marked rollback-only, it may COMMIT.
Two Spring pitfallsCalling a method annotated with @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.
CHAPTER 04 · STRATEGY 1

Atomic UPDATE: check and change together.

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.

The small printThe UPDATE is atomic, but may have to wait for write locks. Do not mix a bulk UPDATE with an already loaded, stale entity in the same JPA context without refreshing the entity or clearing the context.
CHAPTER 05 · STRATEGY 2

Optimistic locking: trust, but verify.

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.

CHAPTER 06 · STRATEGY 3

Pessimistic locking: reserve the row first.

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.

CHAPTER 07 · MAIN LAB

Three mechanisms, side by side.

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.

LAB 03 / CONCURRENCY RACE

Two users, one product

EXPERIMENT
TRANSACTION AMYSQL · PRODUCT #1 TRANSACTION B
A
AnaPending
Read: —
COMMITTED STOCK10
version 0
🔓 No active lock
B
BrunoPending
Read: —
STEP 0
Ready to run

Press “Next step” to advance through the story.

Expected result: with both purchases committed, the correct stock is 3. If an operation fails, show that rejection or retry it deliberately.

Which should I choose?

MechanismBenefitCost / cautionTypical use
Atomic UPDATEA single conditional SQL operation.Cannot express every complex rule.Stock and counters.
@VersionDoes not lock on read.May fail and require a retry or 409.Entity editing.
FOR UPDATEReads under a lock before deciding.Waiting, deadlocks, lower throughput.Multistep rules.
HELP ME CHOOSE

Tell me what you need to protect

CHAPTER 08 · THE SQL ENGINE

Isolation, constraints and integrity.

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.

01

READ UNCOMMITTED

Minimal guarantees. PostgreSQL effectively treats this as READ COMMITTED.

02

READ COMMITTED

Prevents dirty reads, but does not automatically make read-modify-write safe.

03

REPEATABLE READ

Tries to stabilise reads. PostgreSQL and InnoDB differ.

04

SERIALIZABLE

Equivalent to a serial ordering; may abort transactions and require retries.

Constraints are your last line of defence

-- 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”.

CHAPTER 09 · MULTIROW OPERATIONS

Transfers and deadlocks.

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));
}
LAB 04 / DEADLOCK

What happens when locks are acquired in different orders?

A deadlock is not an eternal lockThe engine usually detects it and aborts one transaction. Still, keep transactions short, index correctly, configure timeouts and retry only safe operations.
CHAPTER 10 · RETRIES

Retrying does not mean blindly repeating.

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.
    }
}
🔑
HTTP idempotency key

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 →

Two different kinds of idempotencyThe HTTP key protects against duplicate client requests. The Kafka event ID protects against duplicate consumption in ms-inventario. They are related problems, but do not use the same record.
CHAPTER 11 · DISTRIBUTED MESSAGING

Transactional Outbox: the mailbox that never loses letters.

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.

✕Direct delivery
① Save order COMMIT ✓
② Send to Kafka FAILS ✕
③ Inventory Never finds out

Two operations on different systems. They do not form a single database transaction.

✓Outbox pattern
① Save order Same TX
② Save Outbox record Same TX
③ Publisher → Kafka With retries

The order and record commit together; publishing is a later, recoverable step.

The full picture

ClientPOST /pedidosms-pedidos@TransactionalMySQLordersorder #15outboxevent E-15A SINGLE COMMITPublisherreads / retriesKafkapedidos.creadosms-inventarioidempotency + stockPublishing does not happen withinthe order COMMIT.

The pattern's real contract

01Local atomicity

Order and outbox in the same SQL transaction.

02Eventual delivery

The publisher retries when Kafka is unavailable.

03Duplicates are possible

Kafka may receive the same event more than once: use idempotency.

Outbox is not end-to-end exactly-once deliveryThe pattern prevents event loss from the classic dual-write problem, but does not eliminate all duplicates. Consumer idempotency is essential to a complete solution.
CHAPTER 12 · SPRING BOOT CODE

Guided implementation of the Outbox pattern.

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.

📁 ms-pedidos
├── domain/Pedido.java · OutboxEvent.java
├── application/PedidoService.java · OutboxPublisher.java
├── infrastructure/repository/PedidoRepository.java · OutboxRepository.java
├── infrastructure/config/SchedulingConfig.java
└── dto/PedidoCreadoEvent.java

12.1. The tables must live together

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);

12.2. Save the order + message in the same transaction

@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.

12.3. The basic publisher

@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.
            }
        }
    }
}
Educational example, not a complete multiworker algorithmWith multiple publishers, two may read the same row. In production, use claim/lease with an owner and expiry, or a suitable 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.

12.4. Idempotent consumer

@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.

12.5. Actually preventing double decrements

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.

12.6. What about multiple publishers in production?

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:

1In a short transaction, select rows PENDIENTE with FOR UPDATE SKIP LOCKED and mark them PUBLICANDO, with worker_id and lease_until.
2Commit that transaction and release the locks. Publish messages to Kafka without retaining the SQL locks.
3After Kafka confirms, mark ENVIADO while checking that the worker still owns the claim.
4If the process disappears, recover messages whose leases expired. Republishing may produce duplicates: retain idempotency.

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.

12.7. Outbox versus a Kafka transaction

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.

CHAPTER 13 · INTERACTIVE EXPERIMENT

Now make Kafka fail.

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.

LAB 05 / OUTBOX AND FAILURES

Distributed failure machine

STATE MACHINE
🧾Orders tableEmpty
→
📮Outbox tableEmpty
→
📨Kafka0 messages
→
📦InventoryStock 10
EVENT LOG SIMULATED
> Choose a scenario and advance step by step.
An event may be published more than once, but the consumer must apply its effect only once.
CHAPTER 14 · PROTECTION AGAINST REPETITION

Idempotency: repeat a request without repeating its effect.

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.

KEY IDEAThe same operation identifier → a single committed effect.

Requests and messages can arrive again. A persistent identifier prevents the same operation from being applied twice.

Two distinct idempotency boundaries

AHTTP · ms-pedidos
Client→POST /pedidos→MySQL

A header Idempotency-Key identifies the client's attempt. The same attempt does not create another order.

idempotencia_http table
BKafka · ms-inventario
Kafka→Consumer→Stock

A eventoId identifies the business message. Redelivery does not decrement stock again.

eventos_procesados table
Why is a lock not enough?A lock can serialise two simultaneous requests, but both may be individually valid and produce two purchases. Idempotency recognises that they belong to the same operation, even when they arrive minutes apart or at different Spring Boot replicas.

Lab 06 · Repeat HTTP requests

Try the same key, change the body, cause a timeout or send two simultaneous requests. See what is actually saved in the simulated database.

LAB 06 / DUPLICATE REQUESTS

POST /pedidos + Idempotency-Key

An operation commits only once per key and content.

LAB
Try removing the key: requests cannot be deduplicated.
Same key + different content → conflict.
Orders created0
Keys recorded0
Latest HTTP result—
idempotencia_http table · simulated MySQLWatch the same ID reuse the response
KeyRequest fingerprintStatusOrder
No keys yet.
Enter a key and press “Send POST”.

A new key creates an order. Repeating the same key and content retrieves the result without creating another order.

What if two requests arrive at exactly the same time?

Request AINSERT key K→ Reserves the keySaves the order and resultCOMMIT ✓
Request BINSERT key K→ Waits on UNIQUEDoes not create another orderReceives the saved response

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.

MySQL schema for HTTP requests

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.

Spring Boot: save the key, order and Outbox together

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.
An important implementation detailSome engines or JPA paths mark the transaction for rollback after a UNIQUE violation. Do not catch 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 situationDecisionSuggested result
New key + valid bodySave the result, order and Outbox together201 Created
Same key + same body, already committedReplay the saved response without repeating effectsOriginal response
Same key + different bodyReject improper reuse409 Conflict
Same key, first request still processingWait, return an in-progress status or respond with a conflict according to the contract202 / 409
No keyCannot identify a retry as the same operationRequire a key for critical operations

Lab 07 · Kafka may deliver the event twice

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.

LAB 07 / EVENT REDELIVERY

Is stock decremented twice?

Compare an idempotent consumer with one that does not record events.

LAB
Every redelivery retains the same ID.
Change the mode and reset to compare.
Product #7 stock10
IDs already processed0
Messages delivered0
Message evt-15 requests a decrement of 2 units.

With protection, the event row and stock decrement commit in the same SQL transaction.

Java + MySQL: record and decrement in a single 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.

HTTPIdempotency-Key recognises a repeated request.KafkaeventoId recognises a repeated delivery.SQLThe keys or IDs table and the business effect share the same transaction.
Idempotency does not mean universal “exactly-once”This technique provides a single business effect per valid identifier within the protected database. Kafka deliveries, HTTP retries and external service calls still have their own guarantees. Define key retention, request fingerprints, client scope and failed-result policies.
CHAPTER 15 · TAKING IT TO PRODUCTION

Testing real concurrency.

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.

Two SQL sessions: one blocks the other

BEGIN;
SELECT * FROM cuentas
WHERE id = 1 FOR UPDATE;

UPDATE cuentas
SET saldo = 800
WHERE id = 1;

COMMIT; -- libera el lock
BEGIN;
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.

How to organise a load test

1Start the real database with Testcontainers and initialise stock=10 and version=0.
2Launch two simultaneous operations from different transactions using CountDownLatch or CyclicBarrier.
3Force both initial reads to the same state to measure the optimistic collision.
4Verify results, retries, errors and that stock never becomes negative.
5Repeat with two Spring Boot processes against the same primary database; then introduce a Kafka failure.

Production checklist

0 of 10 checks
Useful observabilityPostgreSQL: 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.
CHAPTER 16 · SELF-ASSESSMENT

Did you understand the concepts? Check for yourself.

Eleven real situations. Choose an answer and get an immediate explanation. No registration required.

0 / 11

Answer the questions to see your score.

CHAPTER 17 · KEEP LEARNING

Glossary, references and next steps.

Atomicity

Either all operations in a transaction commit, or they roll back together.

Concurrency / race condition

Two or more operations overlap in time and the result depends on their actual execution order.

Dirty checking

Hibernate detects changes to managed entities and generates UPDATE statements on flush.

MVCC

Multiversion concurrency control: allows many normal reads to see committed versions without waiting for certain write locks.

Pessimistic lock

A row lock acquired before a business decision to coordinate incompatible changes.

Optimistic version

A number checked on update to detect whether someone changed the entity first.

Outbox / publisher

A pending-message table and a process that publishes those messages recoverably to a broker.

Idempotency

Applying a repeated operation without executing its effect a second time.

CDC / Change Data Capture

A mechanism that captures changes from the database transaction log and forwards events, for example when publishing events from an Outbox table.

Documentation consulted

✦ FROM THEORY TO PROJECT

The next step is to run these same cases against your ms-pedidos and ms-inventario.

First reproduce a lost update with two threads. Then fix it using each strategy. Finally, stop Kafka just after an order commits and demonstrate that Outbox recovers without decrementing stock twice.

Experiment again ↑