idempotency-demo · sequence diagram

Scenario D · Concurrent requests

Two requests with the same new key arrive at the same time. Both see no row, but the UNIQUE constraint lets only one INSERT win. Answers: 201 and 409.

own transaction · A alt · duplicate key own transaction Client Arequest A Client Brequest B PaymentFacadebehind the controller IdempotencyReserverREQUIRES_NEW H2idempotency_record PaymentServicesimulated provider Both requests arrive at once (pago-002) POST pago-002 · request A POST pago-002 · request B findByKey · A Optional.empty() findByKey · B Optional.empty() both see no row The race is decided by the UNIQUE key reserve · A INSERT pago-002 PROCESSING COMMIT reserve · B INSERT pago-002 UNIQUE violation · ROLLBACK DataIntegrityViolationException findByKey · B reads A's row PROCESSING, same hash 409 Conflict · still processing Only request A charges process · A executions++ · sleep 2 s PaymentResponse (APPROVED) complete · A UPDATE status=COMPLETED, response_body COMMIT 201 Created Request B retries later POST pago-002 · retry findByKey COMPLETED, same hash 200 OK · same paymentId Result: 1 real charge for 2 concurrent requests (the test does it with 8)
Solid arrows: calls. Dashed: replies. Red: errors. Amber: conflicts. Dashed blue boxes: database transactions (each IdempotencyReserver method opens its own); amber boxes: alternative branches.

What to look for