josesaid / idempotency-demo
Idempotency Keys ✿ charge at most once
A Spring Boot payments endpoint that charges at most once per Idempotency-Key, even with client retries, a reused key with another body, or several requests racing with the same key.
Stack
| Language | Java 21 |
| Framework | Spring Boot 3.3.5 (Web, Data JPA) |
| Database | H2 in memory, table idempotency_record with UNIQUE(idem_key) |
| Messaging / Cloud / Docker | Not used |
| Build | Maven 3.9+ · port 8080 |
Endpoints
| Method | Path | Description |
POST | /payments | Creates a payment; requires the Idempotency-Key header |
GET | /payments/executions | How many real charges happened |
Run it
git clone https://github.com/josesaid/idempotency-demo.git
cd idempotency-demo
mvn spring-boot:run # or: mvn test
Scenarios
| Scenario | Answer | Diagrams |
| A · First request | 201 | EN · ES |
| B · Retry with the same key | 200 stored response | EN · ES |
| C · Same key, different body | 422 | EN · ES |
| D · Concurrent requests | 201 409 | EN · ES |
| E · Provider failure | 500 → 201 | EN · ES |
Key ideas
- Reserve before charging:
IdempotencyReserver.reserve commits a PROCESSING row in its own transaction (REQUIRES_NEW) before the provider is called.
- The database decides races: concurrent requests all pass the first lookup; the
UNIQUE constraint lets only one INSERT win, and the rest answer 409 from the winner's row.
- Hash before status: a SHA-256 of the body is stored with the key, so reusing a key for another payment gets
422.
- Replay, don't recharge: completed keys return the stored response with
200.
- Release on failure: if the provider throws, the row is deleted so the key can be retried.
- Relation to Kafka: this demo does not use Kafka, but the same pattern applies to Kafka consumers. Kafka delivers at least once, so a consumer can receive the same event twice. Using the event ID as the idempotency key, with a
UNIQUE table that records processed IDs, makes the consumer apply each event only once. See outbox-demo for the producer side.