idempotency-demo · PaymentFacade.java

Idempotency Workflow

How a POST /payments with an Idempotency-Key charges at most once, even with retries, a different body or concurrent requests.

The path of one request

The dashed box is a database transaction. Every IdempotencyReserver method opens its own (REQUIRES_NEW), so each change is committed before the facade moves on.

Client Idempotency-Key PaymentController POST /payments PaymentFacade SHA-256(body) 201 · 200 · 409 · 422 IdempotencyReserver REQUIRES_NEW own tx idempotency_ record UNIQUE(idem_key) reserve complete release findByKey(key) · IdempotencyRepository PaymentService process() · 2 s only if reserved executions++ GET /payments/executions
PaymentService is reached only by the request that reserved the key. The counter behind GET /payments/executions shows how many real charges happened.

How createPayment decides

Every request ends in exactly one of five answers. Only the top row calls the provider.

findByKey(key) is there a row? reserve() INSERT PROCESSING process() charge once complete() COMPLETED + body 201 no ok ok release() DELETE 500 · key free to retry provider throws read the winner findByKey(key) UNIQUE violation handleExisting() hash first, then status yes hash ≠ stored status = PROCESSING status = COMPLETED 422 Unprocessable Entity 409 Conflict · still running 200 OK · stored response no new charge
The hash is compared before the status, so a different body gets 422 even while the first request is still PROCESSING. The amber path is the race of scenario D: the INSERT hits the UNIQUE key and the loser answers from the winner's row.

States of a row in idempotency_record

no row PROCESSING COMPLETED reserve(): INSERT complete(): UPDATE release(): DELETE when the provider fails same key meanwhile → 409 same key → 200 replay
A row is created as PROCESSING, so a second request sees it while the 2-second charge is running. release() is the only way back to “no row”, and only when the provider failed.

The five scenarios

ScenarioRecord foundHTTPReal charges
A · First requestNew key pago-001none201 Created1
B · Retry, same keySame body againCOMPLETED, same hash200 OK0
C · Different bodySame key, amount 999.00hash differs4220
D · Concurrent requests2+ concurrent, same new keyone INSERT wins; the rest see PROCESSING201 4091
E · Provider failureProvider throwsrow deleted by release()500 → 2011 (on retry)
2 chargesafter the five curl steps of the README (pago-001 and pago-002)

Sequence diagram per scenario

Each scenario step by step, with every call between classes and the database.

Versión en español