PRACTICAL GUIDE · JAVA / SPRING DATA JPA

Concurrency does not fail every time.
That is what makes it so dangerous.

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

16 chapters5 simulatorsJava + SQL with examplesPostgreSQL · MySQL/InnoDB
“

The main rule: first define what must never become false (business invariants); then choose the mechanism that guarantees that rule under concurrency.

01A @Transactional does not eliminate races by itself
02One JVM or ten: the database coordinates them
03The right solution depends on the operation

Before locking: understand what can break

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

◎

Atomicity

A transaction commits all its changes or none. This does not mean a value read by another transaction remains valid.

ACID · A
◇

Isolation

Determines which concurrent effects can be observed. Details depend on the engine and configured isolation level.

ACID · I
▣

Invariant

A rule that must always hold: stock ≥ 0, one seat per event, an operation charged only once.

DOMAIN
⇄

Interleaving

The order in which threads/transactions advance. Bugs arise when that order changes, not because Java calculates incorrectly.

RACE CONDITION

Example: an account with €1,000

Two 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.
}
!
Why is @Transactional not enough?

A transaction protects its own atomicity, but two transactions can read the same previous state. You need a concurrency policy appropriate to the invariant.

QUICK MAP · EVERYTHING AT A GLANCE

Common concurrency problems

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.

08problems
grouped
4 groups · 8 problems visible
01Writes and business rulesA transaction may commit an incorrect result or break a rule governing the whole set.2 problems
01Lost updateOne write overwrites anotherConditional atomic UPDATE for simple changes
Example

Two €200 withdrawals read €1,000; both save €800, although the correct balance after two committed withdrawals would be €600.

Why it happens

Both transactions calculate their new value from an old read. The last UPDATE overwrites an earlier change.

How to mitigate it

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 simulator
05Write skewTwo valid rows break a global ruleConstraints where the model permits, locks on a coordinating resource or SERIALIZABLE with transaction retries
Example

Two doctors go off call: each transaction checks that the other remains active and updates a different row; after both commit, nobody is on call.

Why it happens

There is not necessarily a lost UPDATE: operations change different rows yet still invalidate the set-wide invariant.

How to mitigate it

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 skew
02Reads and isolation levelsOther transactions' changes alter what a transaction observes during its queries.3 problems
02Dirty readReading uncommitted dataREAD COMMITTED or stronger isolation prevents dirty reads in common transactional engines
Example

T1 changes the balance from 1,000 to 500 but has not committed. T2 reads 500, then T1 executes ROLLBACK.

Why it happens

T2 observed a value that never became a committed database state.

How to mitigate it

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 reads
03Non-repeatable readThe same row changes between readsUse appropriate isolation or locking reads when a stable view is required
Example

T1 queries an item's stock and sees 10 units. T2 commits a change to 8. T1 queries again and sees 8.

Why it happens

Within the same transaction, the second read gets a different committed version from the first.

How to mitigate it

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 reads
04Phantom readRows appear or disappear in a queryIsolation that stabilises the query
Example

T1 counts four reservations for an event. T2 inserts another reservation and commits. Repeating the set query, T1 may find five.

Why it happens

The query is a predicate over a set of rows, not simply rereading one record by ID.

How to mitigate it

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 reads
03Locking and contentionLocks protect integrity but also introduce waits and operational risks.2 problems
06DeadlockTwo transactions wait in a cycleLock resources in a stable order, keep transactions short and retry recoverable victims
Example

T1 locks account A and waits for B; T2 locks B and waits for A. Neither can proceed without releasing something.

Why it happens

Each transaction waits for a lock held by the other. The engine detects this and usually aborts a victim, depending on its mechanisms.

How to mitigate it

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 deadlock
08Hot row / contentionEvery request competes for one rowBatching, key partitioning, batch aggregation or redesigning the hotspot while preserving integrity
Example

Thousands of requests update the same counter or stock for a popular SKU. Wait times and p95/p99 latency rise.

Why it happens

One row becomes a bottleneck even when updates are logically correct.

How to mitigate it

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 performance
04Repeated HTTP requestsNetwork retries can duplicate a business effect even when the database loses no writes.1 problem
07Double submit / duplicate retryThe same intent arrives twicePersisted Idempotency-Key with UNIQUE, payload hash, state and recoverable result
Example

A payment commits, but its HTTP response is lost. The browser retries and the server charges again.

Why it happens

A lock serialises operations but cannot itself distinguish two legitimate requests from two deliveries of the same intent.

How to mitigate it

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 requests

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

One instance or ten? The rule is the same

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.

INTERACTIVE DIAGRAM

Where does coordination live?

Local protection

synchronized only coordinates threads sharing that monitor in that process.

Shared protection

@Version, FOR UPDATE, UNIQUE and UPDATE are resolved where the authoritative data resides.

Two independent databases

A DB-A lock does not protect DB-B. A different consistency and coordination design is needed.

Two transactions. Four strategies. One balance.

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.

LAB 01 · WITHDRAWAL OPERATION

Lost-update simulator

Controlled scenario
Two requests try to withdraw the same amount.
DATABASE BALANCE€1,000
VERSIONv0
COMMITTED OPERATIONS0/2
STATEReady
TRANSACTION INTERLEAVINGStep 0 of 0
Step explanation

Choose a strategy and advance step by step.

    IMPLEMENTATION

    Java / Spring

    i
    A simulation teaches the mechanism, not the engine's semantics.

    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.

    The anomalies isolation aims to prevent

    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.

    LAB 02 · ISOLATION STORIES

    Discover the interleaving

    DIRTY READ
    STEP 1 / 4

    How to prevent it

    Stock and reservations: the invariant comes first

    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().

    LAB 03 · STOCK

    Last units for sale

    Two buyers try to purchase units from shared inventory.

    Click simulate.

    DATABASE RULE

    The event's last seat

    If two transactions try to reserve the same seat, a unique index is the definitive protection for that key.

    The UNIQUE index has not received any requests yet.
    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).

    Deadlocks: when nobody can proceed

    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.

    LAB 04 · TRANSFER

    Acquisition order matters

    What works

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

    Locking does not prevent charging twice

    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.

    LAB 05 · NETWORK RETRIES

    One purchase, several HTTP attempts

    Idempotency-Key
    Configure the scenario and run it.
    i
    The server must record the key and result under a unique constraint, coordinated with the business operation. It must also handle concurrent requests in progress, partial failures and payload changes for the same key.

    The key is part of the HTTP contract

    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.

    Six tools, six different trade-offs

    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.

    StrategyBest forAcross multiple JVMsMain trade-off
    Conditional UPDATEStock, balances, countersYesSimple rules expressible in one statement
    @Version (optimistic)Editing with infrequent collisionsYesConflict and possible retry/409
    FOR UPDATE (pessimistic)Several decisions in one transactionYesWaits, locking and deadlocks
    UNIQUE / CHECK / FKStructural invariantsYesSchema design and violation handling
    SERIALIZABLEComplex set-wide rulesYesAborts, overhead and full retries
    Java locksIn-memory state in one JVMNoDoes not protect data shared across replicas
    A
    SIMPLE OPERATIONS · FIRST CHOICE

    Atomic conditional UPDATE

    Generally efficient

    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.

    Advantages

    • Reduces round trips between application and database.
    • Avoids the vulnerable pattern SELECT → cálculo → UPDATE.
    • Protects across replicas connected to the same primary.
    • Excellent for quantities, counters and simple transitions.

    Disadvantages and limits

    • Complex business rules are difficult to express in one statement.
    • May create a highly contested row under heavy traffic.
    • JPQL bulk updates do not automatically synchronise the JPA context or increment @Version.
    • Does not guarantee idempotency for two identical requests.
    // 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.
    B
    ENTITY EDITING · RARE COLLISIONS

    Optimistic locking with @Version

    Does not wait before reading

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

    Advantages

    • Holds no write locks while the user edits.
    • Good for profiles, documents and settings.
    • Scales well when collision probability is low.
    • Supports editing conflicts in the UI (HTTP 409).

    Disadvantages and limits

    • The user may need to reconcile changes.
    • Frequent collisions cause aborts and repeated work.
    • Retries must reread and validate in a new transaction.
    • A long web edit must carry the client's version to the server; loading a fresh version just before saving does not detect a stale form.
    @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.
        }
    }
    In an editing API, accompany the received version with 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.
    C
    MULTI-STEP OPERATIONS · HIGH CONTENTION

    Pessimistic locking with FOR UPDATE

    May wait

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

    Advantages

    • Allows multi-step logic over protected state.
    • Avoids repeated work when collisions are frequent.
    • The database coordinates locks across different JVMs.
    • Useful for transfers and delicate transitions.

    Disadvantages and limits

    • Waiting increases latency, especially p95 and p99.
    • May cause deadlocks or timeouts.
    • Transactions must be short and acquire locks in order.
    • Semantics depend on engine, isolation and index access.
    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
    }
    Never perform the 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.
    D
    CROSS-CUTTING INTEGRITY · FINAL DEFENCE

    SQL constraints: UNIQUE, CHECK and foreign keys

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

    Advantages

    • Protects all write paths to that database.
    • Makes structural invariants explicit.
    • UNIQUE prevents double occupancy of the same seat.

    Disadvantages and limits

    • Some set-wide rules require additional design.
    • Violations must become business errors.
    • Does not itself prevent two successive valid charges without an idempotency key.
    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;
    PostgreSQL and common SQL examples. The syntax of UPSERT differs in MySQL (ON DUPLICATE KEY UPDATE). Check types, engine and constraint support in your version.
    E
    SETS OF ROWS · STRONG ISOLATION

    SERIALIZABLE and global rules

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

    Advantages

    • Aims for a result equivalent to some serial order.
    • Can prevent anomalies difficult to protect by locking one row.
    • Reduces manual concurrency rules if every path participates correctly.

    Disadvantages and limits

    • Aborts are expected: full retries required.
    • Tracking overhead, contention or locking, depending on the engine.
    • Does not solve irreversible external effects or idempotency.
    @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.
    }
    PostgreSQL and MySQL/InnoDB do not implement REPEATABLE READ and SERIALIZABLE through identical mechanisms. Never infer a specific query's guarantees from the isolation level's name alone.
    F
    CONSUMERS · WORK DISTRIBUTION

    SQL queues with SKIP LOCKED

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

    Advantages

    • Distributes jobs across processes.
    • Reduces waits between consumers.
    • Needs no extra queue service for moderate workloads.

    Disadvantages and limits

    • The returned set is not a globally consistent snapshot.
    • Requires states, retries, job recovery and visibility.
    • A dedicated broker may suit growing volumes better.
    -- 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;
    Exact syntax, indexes and the order of LIMIT/locking depend on the dialect. Design orphaned-job recovery before production use.
    !
    What about Redis / Redisson / advisory locks?

    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.

    READ COMMITTED, REPEATABLE READ and SERIALIZABLE

    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.

    LevelCore ideaImportant caveat
    READ UNCOMMITTEDMinimal guarantees, depending on implementation.PostgreSQL treats it as READ COMMITTED; MySQL/InnoDB allows dirty reads at this level.
    READ COMMITTEDEach statement normally sees an appropriate committed snapshot.Does not prevent every read-modify-write race; repeated reads may differ.
    REPEATABLE READGreater stability during the transaction.PostgreSQL uses snapshot isolation with possible concurrent-write aborts; InnoDB combines consistent reads and locking reads.
    SERIALIZABLECommitted transactions are equivalent to some serial order.May cause blocking or aborts; operations must support safe retries.

    What MVCC means

    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.

    Which should I choose here?

    The following interactive matrix recommends a starting point, not a universal configuration. Validate a good decision against invariants, contention tests and real engine behaviour.

    GUIDED MATRIX

    Describe your operation

    Guidelines

    Practical comparison: not every conflict is alike

    Low complexity
    Handle conflict
    Blocking risk
    Greater operational demands

    Qualitative teaching bars, not benchmarks or real latency measurements. Costs depend on the use case, workload and database.

    Problems that look like concurrency but stem from configuration

    Annotations help only when actually applied. Spring uses transactional proxies by default; method boundaries, exceptions and the persistence context can completely change the result.

    01Self-invocation: 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() { /* ... */ }
    }
    02Default rollback vs checked exceptions⌄

    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 { /* ... */ }
    03REQUIRES_NEW and pool pressure⌄

    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.

    04Bulk UPDATE and stale managed entities⌄

    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.

    05Locks acquired outside transaction scope⌄

    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.

    06An asynchronous replica read decides a write⌄

    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.

    07A timeout does not mean COMMIT failed⌄

    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.

    i
    Retries: outside the failed transaction.

    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.

    The definitive test is a real database

    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.

    ⌁

    Testcontainers

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

    Retries and failures

    Force reads of the same version, contention, timeouts, deadlocks, replica failures and repeated HTTP attempts.

    Distinguish recoverable from unrecoverable errors.
    ▥

    Connection pool

    20 connections × 20 instances = up to 400 connections. Tune HikariCP against the global limit and traffic.

    Never block threads indefinitely waiting for a connection.
    ↗

    Observability

    Measure transaction latency, lock waits, optimistic conflicts, deadlocks, retries and p95/p99.

    Throughput can rise while the user experience deteriorates.

    A reproducible integration test example

    JUnit · Testcontainers · PostgreSQL

    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();
            }
        }
    }
    Example structure: use real entity constructors/seeds and the JUnit, Spring Boot Test and Testcontainers dependencies. @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.

    What to instrument in production

    pg_stat_activity / pg_locksPostgreSQL: sessions and locks
    pg_stat_statementsQueries and aggregate cost
    performance_schema.data_lock_waitsMySQL/InnoDB: waits
    SQLSTATE 40001 / 40P01Serialisation / deadlock in PostgreSQL
    MySQL 1213 / 1205Common deadlocks / lock timeouts
    p95 / p99 / retry rateQuality of service under load

    Essential tests

    Your pre-deployment checklist

    Tick each item as you validate it. Progress is saved locally in this browser; nothing is sent to a server.

    CONCURRENCY AUDIT

    Production readiness

    0 / 14

    Would you make the right decision?

    Five questions to reinforce the differences between atomicity, distributed locks, idempotency, version conflicts and global rules.

    QUESTION 1 / 50 points

    Sources and example limitations

    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.

    Supplied source material

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

    Scope

    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.

    CV & portfolio · ES / EN
    EspañolEnglish