A client sends POST /payments. The network hiccups, the client times out and sends the same request again. Did the customer just pay twice?
Without protection, yes. Retries are not a corner case: mobile apps retry on flaky connections, API gateways retry on 5xx, users double-click "Pay", and message consumers redeliver. Every one of those can turn into a second charge if the server treats each request as new.
The standard answer is an idempotency key: the client generates a unique key per logical operation and sends it in a header. The server promises that the same key produces the same effect once, no matter how many times it arrives. Stripe, Adyen and PayPal all work this way.
The idea is simple. The details are where duplicate charges sneak back in: two requests racing with the same key, a key reused for a different amount, or a provider that fails halfway. I built a small Spring Boot project, idempotency-demo, that handles those cases and proves them with tests. This article walks through what it contains and why each piece is there.
- Source: https://github.com/josesaid/idempotency-demo
- Project page: https://josesaid.github.io/idempotency-demo/
- Diagrams: English · español
What the repo contains
| Item | Value |
|---|---|
| Language | Java 21 |
| Framework | Spring Boot 3.3.5 (Web, Data JPA) |
| Database | H2 in memory, table idempotency_record
|
| Endpoints |
POST /payments, GET /payments/executions
|
| Tests | 3 integration tests, including 8 concurrent requests |
com.mx.development.jose.said
├── idempotency/
│ ├── IdempotencyRecord.java entity: UNIQUE key, request hash, status, stored response
│ ├── IdempotencyRepository.java findByKey
│ └── IdempotencyReserver.java reserve / complete / release, each in its own transaction
└── payment/
├── PaymentController.java POST /payments
├── PaymentFacade.java the idempotency logic
└── PaymentService.java simulated provider (2 s latency, counts real charges)
PaymentService sleeps two seconds on purpose, so concurrent requests really overlap, and counts how many times it actually ran. GET /payments/executions exposes that counter, which makes "did we charge twice?" a question you can answer with one curl.
The contract
Every request ends in exactly one of these answers:
| Situation | Answer | Provider called? |
|---|---|---|
| New key | 201 Created |
Yes, once |
| Same key, same body, already completed |
200 OK with the stored response |
No |
| Same key, same body, still processing | 409 Conflict |
No |
| Same key, different body | 422 Unprocessable Entity |
No |
| Provider throws | Key released, error returned | Retry may charge |
Only the first row ever reaches the provider.
The record: a key, a hash and a status
@Entity
@Table(name = "idempotency_record")
public class IdempotencyRecord {
public enum Status { PROCESSING, COMPLETED }
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// The database, not the application, guarantees one row per key
@Column(name = "idem_key", nullable = false, unique = true, length = 100)
private String key;
// SHA-256 of the request body: detects a key reused for another payment
@Column(name = "request_hash", nullable = false, length = 64)
private String requestHash;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private Status status;
// What retries get back once the payment is done
@Column(name = "response_body", columnDefinition = "TEXT")
private String responseBody;
}
Three fields carry the whole design:
-
unique = trueon the key is the real lock. More on that below. -
requestHashlets the server tell "the same request again" from "a different request with a recycled key". -
status+responseBodylet the server say "still working" (409) or replay the original answer (200).
Reserve before you charge
The facade's main method is short:
public ResponseEntity<PaymentResponse> createPayment(String key, PaymentRequest request) {
String hash = requestHash(request);
Optional<IdempotencyRecord> existing = repo.findByKey(key);
if (existing.isEmpty()) {
try {
reserver.reserve(key, hash); // try to be first
} catch (DataIntegrityViolationException e) {
// Another request with the same key won the race: answer from its row
return handleExisting(repo.findByKey(key).orElseThrow(), hash);
}
return process(key, request);
}
return handleExisting(existing.get(), hash);
}
The key step is reserve. Before calling the provider, the facade inserts a row with status PROCESSING and commits it. That commit is what lets every other request see "someone is already charging this key".
@Service
public class IdempotencyReserver {
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void reserve(String key, String requestHash) {
// saveAndFlush forces the INSERT now; a duplicate key throws right here
repo.saveAndFlush(new IdempotencyRecord(key, requestHash));
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void complete(String key, String responseJson) {
IdempotencyRecord record = repo.findByKey(key).orElseThrow();
record.setStatus(IdempotencyRecord.Status.COMPLETED);
record.setResponseBody(responseJson);
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void release(String key) {
repo.findByKey(key).ifPresent(repo::delete);
}
}
Two details matter here:
-
REQUIRES_NEW: each method commits on its own. If the reservation lived inside one big transaction that also wrapped the two-second provider call, no other request could see thePROCESSINGrow until the end. That is exactly the window where duplicates happen. -
A separate bean:
@Transactionalworks through a Spring proxy. IfPaymentFacadecalled its own@Transactionalmethod, the proxy would be bypassed and the annotation silently ignored. Moving these methods intoIdempotencyReservermakes them go through the proxy.
The common mistake
This version looks fine and is wrong:
// ❌ Check-then-act: both concurrent requests pass the check
if (repo.findByKey(key).isEmpty()) {
PaymentResponse r = paymentService.process(request); // charged twice
repo.save(new IdempotencyRecord(key, hash, r));
}
Two requests that arrive together both see "no row" and both charge. The lookup is only an optimization. The protection is the UNIQUE constraint plus inserting before charging.
Who wins a race? The database
Scenario D in the repo sends two (in the test, eight) requests with the same new key at the same time:
- Both run
findByKeyand both getOptional.empty(). - Both call
reserve. Request A's INSERT commits first. - Request B's INSERT hits the unique index; H2 raises error 23505, Spring translates it to
DataIntegrityViolationException. - B catches it, reads A's row, sees
PROCESSINGand answers 409 Conflict. - A charges, stores the response and answers 201.
- When B retries later, it finds
COMPLETEDand gets 200 with A'spaymentId.
The full step-by-step diagram is on the project page: Scenario D · Concurrent requests.
Hash first, then status
private ResponseEntity<PaymentResponse> handleExisting(IdempotencyRecord record, String hash) {
if (!record.getRequestHash().equals(hash)) {
return ResponseEntity.unprocessableEntity().build(); // same key, different body
}
if (record.getStatus() == IdempotencyRecord.Status.PROCESSING) {
return ResponseEntity.status(HttpStatus.CONFLICT).build(); // still running
}
return ResponseEntity.ok(fromJson(record.getResponseBody())); // replay stored response
}
The order matters. If a client reuses pago-001 for a 999.00 payment, replaying the stored 150.00 response would hide a client bug and the customer would never be charged the 999.00. Checking the SHA-256 of the body first turns that bug into a clear 422, even while the original request is still PROCESSING.
The hash is computed over the JSON that Jackson produces for PaymentRequest:
private String requestHash(PaymentRequest request) {
byte[] digest = MessageDigest.getInstance("SHA-256")
.digest(mapper.writeValueAsBytes(request));
return HexFormat.of().formatHex(digest);
}
When the provider fails: release the key
private ResponseEntity<PaymentResponse> process(String key, PaymentRequest request) {
try {
PaymentResponse response = paymentService.process(request);
reserver.complete(key, toJson(response));
return ResponseEntity.status(HttpStatus.CREATED).body(response);
} catch (RuntimeException e) {
reserver.release(key); // free the key so the client can retry
throw e;
}
}
Without release, a failed payment would leave its row in PROCESSING forever, and every retry would get 409. Deleting the row, again in its own transaction, makes the key usable again.
One honest caveat: releasing is only safe when you know the provider did not charge. After an ambiguous timeout, a production system should ask the provider for the payment status (ideally passing the same idempotency key downstream) before releasing.
Proving it with tests
The integration test fires eight requests with the same key and counts real charges:
@Test
void peticionesConcurrentesMismaClave_cobranUnaSolaVez() throws Exception {
String key = UUID.randomUUID().toString();
int before = executions();
ExecutorService pool = Executors.newFixedThreadPool(8);
List<Callable<ResponseEntity<PaymentResponse>>> tasks = new ArrayList<>();
for (int i = 0; i < 8; i++) {
tasks.add(() -> post(key, request("250.00")));
}
List<Future<ResponseEntity<PaymentResponse>>> futures = pool.invokeAll(tasks);
// ... collect status codes ...
assertThat(executions() - before).as("real charges").isEqualTo(1);
assertThat(statuses.stream().filter(s -> s == HttpStatus.CREATED).count()).isEqualTo(1);
}
The other two tests check that a retry returns the same paymentId with a single charge, and that a reused key with another body gets 422. When the suite runs you will see seven Unique index or primary key violation lines in the log: those are the seven losers of the race, which is exactly what should happen.
Try it yourself
git clone https://github.com/josesaid/idempotency-demo.git
cd idempotency-demo
mvn spring-boot:run
curl -i -X POST http://localhost:8080/payments \
-H "Content-Type: application/json" -H "Idempotency-Key: pago-001" \
-d '{"accountFrom":"ACC-1","accountTo":"ACC-2","amount":150.00,"currency":"MXN"}'
# 201 the first time, 200 with the same paymentId on every retry
curl http://localhost:8080/payments/executions
# {"executions":1}
The diagrams
The project page has an overview (the path of one request, the decision flow and the states of a row) plus one sequence diagram per scenario, in English and Spanish:
| Scenario | English | Español |
|---|---|---|
| A · First request (201) | Diagram | Diagrama |
| B · Retry with the same key (200) | Diagram | Diagrama |
| C · Same key, different body (422) | Diagram | Diagrama |
| D · Concurrent requests (201 + 409) | Diagram | Diagrama |
| E · Provider failure (500 → 201) | Diagram | Diagrama |
Best practices checklist
- ✅ Let the database enforce uniqueness of the key; never rely on a read-then-write check.
- ✅ Reserve before calling the external system, and commit the reservation in its own transaction.
- ✅ Store a hash of the request and reject reused keys with a different body (
422). - ✅ Store the response and replay it; the retry must look like success to the client.
- ✅ Answer 409 while the first request is in flight, so clients back off and retry.
- ✅ Release the key only when you are sure nothing was charged.
- ⚠️ Add a TTL or cleanup job; the demo keeps records forever.
- ⚠️ Scope keys per client or account in multi-tenant systems, so two clients cannot collide.
Performance notes
The happy path costs one indexed SELECT, one INSERT and one UPDATE, each a short transaction. Retries cost a single SELECT and never touch the provider. The losers of a race fail fast on the unique index instead of waiting on a lock. In production, keep idem_key indexed (the UNIQUE constraint does that), keep the stored response small, and purge old rows on a schedule.
Takeaways
Idempotency keys are not about the header; they are about where the guarantee lives. In this repo it lives in a UNIQUE constraint, a reservation committed before the charge, a hash that catches misuse, and a stored response that makes retries boring. Clone idempotency-demo, run mvn test, and watch eight concurrent requests produce exactly one charge.
If you read my previous article on the transactional outbox, this is the other half of the story: the outbox makes sure events are delivered at least once, and idempotency makes sure "at least once" never becomes "charged twice".
Top comments (0)