Idempotency: making retries and redelivered messages harmless
Clients retry after timeouts and brokers deliver messages more than once, so every write in a distributed system can arrive twice. This page shows a retry that charges a customer twice, then runs each fix with Spring and H2: operations that are idempotent by design, idempotency keys, concurrent duplicates, an HTTP endpoint with Spring Boot and deduplicating message consumers.
Contents
What idempotency means and why retries need it A retry that charges twice Operations that are idempotent by design Idempotency keys Duplicates that arrive at the same time An idempotent HTTP endpoint with Spring Boot Idempotent message consumers Keys in practice: scope, expiry and storage Choosing a technique
What idempotency means and why retries need it
An operation is idempotent when doing it twice has the same effect as doing it once. Setting a customer's city to Lisbon is idempotent: the second time changes nothing. Subtracting 30 from a balance is not: every repeat takes another 30.
This matters because distributed systems repeat requests all the time, on purpose:
- Client retries: a client that gets a timeout does not know whether the server failed before or after doing the work. Retrying is the only safe way to make sure the work happens, and it repeats the work if it already did.
- Proxies and libraries: load balancers, HTTP clients and resilience libraries retry on their own, often without the application knowing.
- Message brokers: Kafka, RabbitMQ and SQS deliver at least once. A consumer that crashes before acknowledging a message gets it again, and an
outbox relay can publish the same message twice.
Since repeats cannot be prevented, the receiver has to make them harmless. "Exactly once" in practice means at-least-once delivery plus idempotent processing.
| Technique | How it detects a repeat | Best for |
|---|---|---|
| Absolute writes and upserts | It does not need to: the second write sets the same value | Updating a profile, a setting, a projection |
| Conditional state transitions | The WHERE status = ... | Order and payment status changes |
| Version checks (optimistic locking) | The expected version has moved on | Concurrent edits of one record |
| Idempotency key with a stored response | The key is already in a table | HTTP POST |
| Processed-message table | The message id is already in a table | Message and event consumers |
HTTP defines which methods must be idempotent. RFC 9110 lists GETHEADOPTIONSPUTDELETEPOSTPATCH
A retry that charges twice
The simplest failure is a lost response. The server charges the account and commits, then the response is lost on the way back, as when a read times out. The client retries, as any well-behaved client would:
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
public class RetryDuplicates {
@Configuration
@EnableTransactionManagement
static class Config {
@Bean
DataSource dataSource() {
return new DriverManagerDataSource("jdbc:h2:mem:retry;DB_CLOSE_DELAY=-1");
}
@Bean
JdbcTemplate jdbc(DataSource dataSource) {
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
jdbc.execute("CREATE TABLE accounts (id VARCHAR(10) PRIMARY KEY, balance INT)");
jdbc.execute("CREATE TABLE payments (id INT AUTO_INCREMENT PRIMARY KEY,"
+ " account VARCHAR(10), amount INT)");
jdbc.update("INSERT INTO accounts VALUES ('ada', 100)");
return jdbc;
}
@Bean
PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
PaymentService paymentService(JdbcTemplate jdbc) {
return new PaymentService(jdbc);
}
}
static class PaymentService {
private final JdbcTemplate jdbc;
PaymentService(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Transactional
public void charge(String account, int amount) {
jdbc.update("UPDATE accounts SET balance = balance - ? WHERE id = ?", amount, account);
jdbc.update("INSERT INTO payments (account, amount) VALUES (?, ?)", account, amount);
}
}
/** The network between client and server: it loses the first response. */
static class Network {
private int calls;
void call(Runnable request) {
calls++;
request.run();
if (calls == 1) {
throw new IllegalStateException("read timed out");
}
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
PaymentService service = context.getBean(PaymentService.class);
Network network = new Network();
for (int attempt = 1; attempt <= 3; attempt++) {
try {
network.call(() -> service.charge("ada", 30));
System.out.println("attempt " + attempt + ": 200 OK");
break;
} catch (IllegalStateException e) {
System.out.println("attempt " + attempt + ": " + e.getMessage()
+ ", client retries");
}
}
JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
System.out.println("payments: " + jdbc.queryForList(
"SELECT amount FROM payments ORDER BY id", Integer.class));
System.out.println("balance : " + jdbc.queryForObject(
"SELECT balance FROM accounts WHERE id = 'ada'", Integer.class)
+ " (expected 70)");
}
}
}
attempt 1: read timed out, client retries
attempt 2: 200 OK
payments: [30, 30]
balance : 40 (expected 70)
- Attempt 1 reached the server, which charged 30 and committed. Only the response was lost, so the client saw a timeout.
- Attempt 2 charged again and succeeded. The client now believes it paid once, but the payments table holds two charges of 30, and the balance is 40 instead of 70.
Nothing in this program is wrong in isolation: the service is transactional and the client retries on timeout. The bug is in the combination, which is why idempotency is a property of the API design rather than of one method.
Operations that are idempotent by design
The cheapest fix is to write operations so that repeating them does nothing. This program delivers three statements twice each, then shows a version check between two writers:
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
public class NaturalIdempotency {
public static void main(String[] args) {
JdbcTemplate jdbc = new JdbcTemplate(
new DriverManagerDataSource("jdbc:h2:mem:natural;DB_CLOSE_DELAY=-1"));
jdbc.execute("CREATE TABLE accounts (id VARCHAR(10) PRIMARY KEY, balance INT)");
jdbc.execute("CREATE TABLE orders (id INT PRIMARY KEY, status VARCHAR(10),"
+ " version INT)");
jdbc.execute("CREATE TABLE addresses (customer VARCHAR(10) PRIMARY KEY,"
+ " city VARCHAR(20))");
jdbc.update("INSERT INTO accounts VALUES ('ada', 100)");
jdbc.update("INSERT INTO orders VALUES (7, 'PAID', 1)");
System.out.println("Each statement is delivered twice:");
for (int delivery = 1; delivery <= 2; delivery++) {
int relative = jdbc.update(
"UPDATE accounts SET balance = balance - 30 WHERE id = 'ada'");
int transition = jdbc.update("UPDATE orders SET status = 'SHIPPED',"
+ " version = version + 1 WHERE id = 7 AND status = 'PAID'");
int upsert = jdbc.update("MERGE INTO addresses (customer, city) KEY (customer)"
+ " VALUES ('ada', 'Lisbon')");
System.out.printf(" delivery %d: rows changed: balance %d, status %d, address %d%n",
delivery, relative, transition, upsert);
}
System.out.println("balance = " + jdbc.queryForObject(
"SELECT balance FROM accounts", Integer.class) + " (expected 70)");
System.out.println("order = " + jdbc.queryForMap(
"SELECT status, version FROM orders"));
System.out.println("address = " + jdbc.queryForList(
"SELECT city FROM addresses", String.class));
System.out.println("Version check: two writers both read version 2");
int first = jdbc.update("UPDATE orders SET status = 'DELIVERED', version = 3"
+ " WHERE id = 7 AND version = 2");
int second = jdbc.update("UPDATE orders SET status = 'RETURNED', version = 3"
+ " WHERE id = 7 AND version = 2");
System.out.println(" first writer changed " + first + " row, second writer changed "
+ second + " rows; order = " + jdbc.queryForMap("SELECT status FROM orders"));
}
}
Each statement is delivered twice:
delivery 1: rows changed: balance 1, status 1, address 1
delivery 2: rows changed: balance 1, status 0, address 1
balance = 40 (expected 70)
order = {STATUS=SHIPPED, VERSION=2}
address = [Lisbon]
Version check: two writers both read version 2
first writer changed 1 row, second writer changed 0 rows; order = {STATUS=DELIVERED}
- The relative update
changed a row both times, and the balance fell to 40.balance = balance - 30 - The transition
changed 1 row the first time and 0 the second, because the order was no longerSET status = 'SHIPPED' ... WHERE status = 'PAID' . The version stayed at 2. The row count tells the caller that the second delivery was a repeat.PAID - The upsert,
in H2 orMERGE INTO ... KEY (customer) in PostgreSQL, set the city to Lisbon twice and left one row.INSERT ... ON CONFLICT DO UPDATE - In the version check, both writers expected version 2. The first changed 1 row and moved the version to 3, so the second changed 0 rows and its
status never overwroteRETURNED . JPA'sDELIVERED does the same and throws@Version on 0 rows.OptimisticLockingFailureException
Prefer this style wherever the domain allows: send "set the quantity to 3" rather than "add 1", and model changes as transitions between states. It needs no extra table and no cleanup. Operations that create something new or move money cannot be expressed that way, which is where idempotency keys come in.
Idempotency keys
For a request that is not naturally idempotent, the client generates a unique key, usually a UUID, and sends it with the request and every retry of it. The server stores the key with the response, and answers a repeat from the table instead of doing the work again. This service runs six calls against one account:
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
public class IdempotencyKeys {
record ChargeRequest(String account, int amount) {
// A real service stores a SHA-256 hash of the request body.
String fingerprint() {
return account + ":" + amount;
}
}
record Result(int status, String body) {
}
@Configuration
@EnableTransactionManagement
static class Config {
@Bean
DataSource dataSource() {
return new DriverManagerDataSource("jdbc:h2:mem:keys;DB_CLOSE_DELAY=-1");
}
@Bean
JdbcTemplate jdbc(DataSource dataSource) {
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
jdbc.execute("CREATE TABLE accounts (id VARCHAR(10) PRIMARY KEY,"
+ " balance INT CHECK (balance >= 0))");
jdbc.execute("CREATE TABLE payments (id INT AUTO_INCREMENT PRIMARY KEY,"
+ " account VARCHAR(10), amount INT)");
jdbc.execute("""
CREATE TABLE idempotency_keys (
idem_key VARCHAR(64) PRIMARY KEY,
request_fingerprint VARCHAR(64) NOT NULL,
status INT,
body VARCHAR(200))""");
jdbc.update("INSERT INTO accounts VALUES ('ada', 100)");
return jdbc;
}
@Bean
PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
PaymentService paymentService(JdbcTemplate jdbc) {
return new PaymentService(jdbc);
}
}
static class PaymentService {
private final JdbcTemplate jdbc;
PaymentService(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Transactional
public Result charge(String key, ChargeRequest request) {
try {
jdbc.update("INSERT INTO idempotency_keys (idem_key, request_fingerprint)"
+ " VALUES (?, ?)", key, request.fingerprint());
} catch (DuplicateKeyException e) {
return replay(key, request);
}
jdbc.update("UPDATE accounts SET balance = balance - ? WHERE id = ?",
request.amount(), request.account());
jdbc.update("INSERT INTO payments (account, amount) VALUES (?, ?)",
request.account(), request.amount());
Integer id = jdbc.queryForObject("SELECT MAX(id) FROM payments", Integer.class);
Result result = new Result(201, "{\"paymentId\":" + id + "}");
jdbc.update("UPDATE idempotency_keys SET status = ?, body = ? WHERE idem_key = ?",
result.status(), result.body(), key);
return result;
}
private Result replay(String key, ChargeRequest request) {
Map<String, Object> row = jdbc.queryForMap(
"SELECT * FROM idempotency_keys WHERE idem_key = ?", key);
if (!row.get("REQUEST_FINGERPRINT").equals(request.fingerprint())) {
return new Result(422, "key already used for a different request");
}
return new Result((Integer) row.get("STATUS"), row.get("BODY") + " (replayed)");
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
PaymentService service = context.getBean(PaymentService.class);
List<Object[]> calls = List.of(
new Object[] {"first request ", "k-1", new ChargeRequest("ada", 30)},
new Object[] {"retry, same key ", "k-1", new ChargeRequest("ada", 30)},
new Object[] {"same key, other amount", "k-1", new ChargeRequest("ada", 99)},
new Object[] {"new key, fails ", "k-2", new ChargeRequest("ada", 500)},
new Object[] {"retry of k-2, fixed ", "k-2", new ChargeRequest("ada", 500)},
new Object[] {"new key ", "k-3", new ChargeRequest("ada", 20)});
for (Object[] call : calls) {
try {
Result r = service.charge((String) call[1], (ChargeRequest) call[2]);
System.out.println(call[0] + " " + call[1] + " -> " + r.status() + " "
+ r.body());
} catch (RuntimeException e) {
System.out.println(call[0] + " " + call[1] + " -> 500 "
+ e.getClass().getSimpleName());
JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
jdbc.update("UPDATE accounts SET balance = balance + 1000");
System.out.println(" (account topped up by 1000)");
}
}
JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
System.out.println("payments: " + jdbc.queryForList(
"SELECT amount FROM payments ORDER BY id", Integer.class));
System.out.println("keys : " + jdbc.queryForList(
"SELECT idem_key FROM idempotency_keys ORDER BY idem_key", String.class));
}
}
}
first request k-1 -> 201 {"paymentId":1}
retry, same key k-1 -> 201 {"paymentId":1} (replayed)
same key, other amount k-1 -> 422 key already used for a different request
new key, fails k-2 -> 500 DataIntegrityViolationException
(account topped up by 1000)
retry of k-2, fixed k-2 -> 201 {"paymentId":2}
new key k-3 -> 201 {"paymentId":3}
payments: [30, 500, 20]
keys : [k-1, k-2, k-3]
- The first request with
inserted the key, charged 30 and saved the responsek-1 in the key's row.{"paymentId":1} - The retry with
hit the primary key, so the service loaded the saved row and returned the same 201 and the same payment id, marked as replayed. The client cannot tell a replay from the original, which is the point.k-1 - Reusing
with amount 99 returned 422. The service stores a fingerprint of the request, herek-1 , and refuses a key that comes back with a different body. Without that check, a client bug that reused keys would silently get the wrong payment back.account:amount - The charge of 500 under
broke the balance check. Because the key was inserted in the same transaction, the rollback removed it too, so after the top-up the retry withk-2 ran for real and created payment 2.k-2 - The final table holds three payments, 30, 500 and 20, one per key, although the service received six calls.
The order inside the transaction matters: insert the key first, then do the work, then save the response. The insert is both the check and the claim, which the next section shows is what makes it safe under concurrency.
Duplicates that arrive at the same time
Retries are not always sequential. A client with a short timeout, or two instances of a message consumer, can send the same request twice within milliseconds. This program sends two copies of one request at the same moment, using a barrier to make the overlap certain:
import java.util.Arrays;
import java.util.concurrent.CyclicBarrier;
import javax.sql.DataSource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionTemplate;
public class ConcurrentRetries {
static JdbcTemplate jdbc;
static TransactionTemplate transaction;
/** Check first, then charge, then record the key. */
static String checkThenAct(String key, CyclicBarrier bothChecked) throws Exception {
Integer seen = jdbc.queryForObject(
"SELECT COUNT(*) FROM seen_keys WHERE idem_key = ?", Integer.class, key);
bothChecked.await();
if (seen > 0) {
return "duplicate, skipped";
}
transaction.executeWithoutResult(status -> {
jdbc.update("INSERT INTO payments (amount) VALUES (30)");
jdbc.update("INSERT INTO seen_keys VALUES (?)", key);
});
return "charged";
}
/** Claim the key with an INSERT in the same transaction as the charge. */
static String claimFirst(String key, CyclicBarrier bothReady) throws Exception {
bothReady.await();
try {
transaction.executeWithoutResult(status -> {
jdbc.update("INSERT INTO claimed_keys VALUES (?)", key);
jdbc.update("INSERT INTO payments (amount) VALUES (30)");
});
return "charged";
} catch (DuplicateKeyException e) {
return "duplicate, skipped";
}
}
interface Attempt {
String run(String key, CyclicBarrier barrier) throws Exception;
}
static void race(String label, Attempt attempt) throws InterruptedException {
jdbc.update("DELETE FROM payments");
CyclicBarrier barrier = new CyclicBarrier(2);
String[] results = new String[2];
Thread[] threads = new Thread[2];
for (int i = 0; i < 2; i++) {
int n = i;
threads[i] = new Thread(() -> {
try {
results[n] = attempt.run("k-77", barrier);
} catch (Exception e) {
results[n] = e.toString();
}
});
threads[i].start();
}
for (Thread t : threads) {
t.join();
}
Arrays.sort(results);
System.out.println(label);
System.out.println(" requests: " + String.join(" / ", results));
System.out.println(" payments: " + jdbc.queryForObject(
"SELECT COUNT(*) FROM payments", Integer.class));
}
public static void main(String[] args) throws InterruptedException {
DataSource dataSource = new DriverManagerDataSource("jdbc:h2:mem:race;DB_CLOSE_DELAY=-1");
jdbc = new JdbcTemplate(dataSource);
transaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
jdbc.execute("CREATE TABLE payments (id INT AUTO_INCREMENT PRIMARY KEY, amount INT)");
jdbc.execute("CREATE TABLE seen_keys (idem_key VARCHAR(64))");
jdbc.execute("CREATE TABLE claimed_keys (idem_key VARCHAR(64) PRIMARY KEY)");
System.out.println("Two copies of the same request arrive at the same moment.");
race("Check, then act:", ConcurrentRetries::checkThenAct);
race("Claim the key with a primary-key INSERT:", ConcurrentRetries::claimFirst);
}
}
Two copies of the same request arrive at the same moment.
Check, then act:
requests: charged / charged
payments: 2
Claim the key with a primary-key INSERT:
requests: charged / duplicate, skipped
payments: 1
- Check, then act: both requests ran
before either had recorded the key, both saw 0, and both charged. Two payments were made. Any "look first, then write" check has this gap, however short.SELECT COUNT(*) - Claim first: both requests tried to
the key, which is a primary key. The database let one insert through and made the other wait until the first transaction committed, then failed it withINSERT . One payment was made.DuplicateKeyException
The unique constraint is what makes the pattern correct, because the database is the one place where both requests meet. A key held only in memory, or in a cache without an atomic "set if absent", repeats the check-then-act gap. In the claim-first version the second request waits until the first one has finished. The IETF draft for the Idempotency-Key
An idempotent HTTP endpoint with Spring Boot
Over HTTP, the key travels in a request header. The Idempotency-Key
package idempotency.api;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
public class IdempotentApi {
record ChargeRequest(String account, int amount) {
}
@RestController
static class PaymentController {
private final JdbcTemplate jdbc;
PaymentController(JdbcTemplate jdbc) {
this.jdbc = jdbc;
jdbc.execute("CREATE TABLE payments (id INT AUTO_INCREMENT PRIMARY KEY,"
+ " account VARCHAR(10), amount INT)");
jdbc.execute("CREATE TABLE idempotency_keys (idem_key VARCHAR(64) PRIMARY KEY,"
+ " fingerprint VARCHAR(64), status INT, body VARCHAR(200))");
}
@PostMapping("/payments")
@Transactional
public ResponseEntity<String> charge(
@RequestHeader(name = "Idempotency-Key", required = false) String key,
@RequestBody ChargeRequest request) {
if (key == null) {
return ResponseEntity.badRequest().body("{\"error\":\"Idempotency-Key required\"}");
}
String fingerprint = request.account() + ":" + request.amount();
try {
jdbc.update("INSERT INTO idempotency_keys (idem_key, fingerprint) VALUES (?, ?)",
key, fingerprint);
} catch (DuplicateKeyException e) {
Map<String, Object> saved = jdbc.queryForMap(
"SELECT * FROM idempotency_keys WHERE idem_key = ?", key);
if (!saved.get("FINGERPRINT").equals(fingerprint)) {
return ResponseEntity.unprocessableContent()
.body("{\"error\":\"key reused with a different body\"}");
}
return ResponseEntity.status((Integer) saved.get("STATUS"))
.header("Idempotent-Replayed", "true").body((String) saved.get("BODY"));
}
jdbc.update("INSERT INTO payments (account, amount) VALUES (?, ?)",
request.account(), request.amount());
Integer id = jdbc.queryForObject("SELECT MAX(id) FROM payments", Integer.class);
String body = "{\"paymentId\":" + id + ",\"amount\":" + request.amount() + "}";
jdbc.update("UPDATE idempotency_keys SET status = 201, body = ? WHERE idem_key = ?",
body, key);
return ResponseEntity.status(201).body(body);
}
}
static void post(HttpClient client, String base, String key, String json) throws Exception {
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(base + "/payments"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json));
if (key != null) {
builder.header("Idempotency-Key", key);
}
HttpResponse<String> response =
client.send(builder.build(), HttpResponse.BodyHandlers.ofString());
System.out.println("POST /payments key=" + key + " " + json);
System.out.println(" -> " + response.statusCode() + " " + response.body()
+ response.headers().firstValue("Idempotent-Replayed")
.map(v -> " [Idempotent-Replayed: " + v + "]").orElse(""));
}
public static void main(String[] args) throws Exception {
SpringApplication app = new SpringApplication(IdempotentApi.class);
app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
"logging.level.root", "WARN"));
try (ConfigurableApplicationContext context = app.run(args)) {
int port = ((WebServerApplicationContext) context).getWebServer().getPort();
String base = "http://localhost:" + port;
HttpClient client = HttpClient.newHttpClient();
String body = "{\"account\":\"ada\",\"amount\":30}";
post(client, base, "9f1c-01", body);
post(client, base, "9f1c-01", body);
post(client, base, "9f1c-01", "{\"account\":\"ada\",\"amount\":99}");
post(client, base, null, body);
JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
System.out.println("payments in the database: " + jdbc.queryForList(
"SELECT amount FROM payments", Integer.class));
}
}
}
POST /payments key=9f1c-01 {"account":"ada","amount":30}
-> 201 {"paymentId":1,"amount":30}
POST /payments key=9f1c-01 {"account":"ada","amount":30}
-> 201 {"paymentId":1,"amount":30} [Idempotent-Replayed: true]
POST /payments key=9f1c-01 {"account":"ada","amount":99}
-> 422 {"error":"key reused with a different body"}
POST /payments key=null {"account":"ada","amount":30}
-> 400 {"error":"Idempotency-Key required"}
payments in the database: [30]
- The first
created payment 1 and returned 201.POST - The retry with key
returned the same 201 and the same body, plus an9f1c-01 header. That header is not part of the draft; it is a common addition that helps with debugging.Idempotent-Replayed: true - The same key with amount 99 returned 422, and the request without a key returned 400. Both status codes are the ones the draft recommends.
- Only one payment of 30 exists, after four requests.
The program is in a package, idempotency.api@SpringBootApplicationHandlerInterceptor
Idempotent message consumers
A message consumer has the same problem, with the broker as the retrying client. It records each message id it has processed and skips ids it has seen. Where that record is written decides whether it works. Each consumer here crashes halfway through the first delivery, and the broker delivers the message again:
import javax.sql.DataSource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionTemplate;
public class ConsumerDedup {
static JdbcTemplate jdbc;
static TransactionTemplate transaction;
static void addPoints() {
jdbc.update("UPDATE points SET total = total + 50 WHERE customer = 'ada'");
}
static void recordId(String id) {
jdbc.update("INSERT INTO processed_messages VALUES (?)", id);
}
static void crash(boolean crash) {
if (crash) {
throw new IllegalStateException("consumer killed");
}
}
interface Consumer {
void handle(String messageId, boolean crashHalfway);
}
static void deliverTwice(String label, Consumer consumer) {
jdbc.update("UPDATE points SET total = 0");
jdbc.update("DELETE FROM processed_messages");
for (int delivery = 1; delivery <= 2; delivery++) {
try {
consumer.handle("m-41", delivery == 1);
} catch (IllegalStateException | DuplicateKeyException e) {
// the broker will redeliver after a crash; a duplicate is skipped
}
}
System.out.printf("%-46s ada has %d points (expected 50)%n", label,
jdbc.queryForObject("SELECT total FROM points", Integer.class));
}
public static void main(String[] args) {
DataSource dataSource = new DriverManagerDataSource("jdbc:h2:mem:dedup;DB_CLOSE_DELAY=-1");
jdbc = new JdbcTemplate(dataSource);
transaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource));
jdbc.execute("CREATE TABLE points (customer VARCHAR(10) PRIMARY KEY, total INT)");
jdbc.execute("CREATE TABLE processed_messages (message_id VARCHAR(40) PRIMARY KEY)");
jdbc.update("INSERT INTO points VALUES ('ada', 0)");
System.out.println("Message m-41 (+50 points). The consumer crashes halfway,"
+ " and the broker redelivers:");
deliverTwice("1. Apply, then record the id (two commits):", (id, crash) -> {
Integer seen = jdbc.queryForObject(
"SELECT COUNT(*) FROM processed_messages WHERE message_id = ?",
Integer.class, id);
if (seen == 0) {
addPoints();
crash(crash);
recordId(id);
}
});
deliverTwice("2. Record the id, then apply (two commits):", (id, crash) -> {
recordId(id);
crash(crash);
addPoints();
});
deliverTwice("3. Record the id and apply in one transaction:", (id, crash) ->
transaction.executeWithoutResult(status -> {
recordId(id);
crash(crash);
addPoints();
}));
}
}
Message m-41 (+50 points). The consumer crashes halfway, and the broker redelivers:
1. Apply, then record the id (two commits): ada has 100 points (expected 50)
2. Record the id, then apply (two commits): ada has 0 points (expected 50)
3. Record the id and apply in one transaction: ada has 50 points (expected 50)
- Consumer 1 applied the points and committed, then crashed before recording the id. The redelivery found no record and applied the points again: 100 instead of 50.
- Consumer 2 recorded the id first and committed, then crashed before applying. The redelivery was skipped as a duplicate, so the points were lost: 0 instead of 50.
- Consumer 3 did both in one transaction. The crash rolled back both, the redelivery applied the message once, and ada has 50.
The id and the effect must commit together. That is easy when both live in the same database. When the effect is a call to another system, such as an email provider, it cannot be in the transaction; then pass the message id on as that system's idempotency key, so the duplicate is caught one step further along. With Spring Kafka, the listener container commits offsets only after the listener has processed the records, so a crash before that point produces exactly the redelivery shown here. See
Keys in practice: scope, expiry and storage
- Who generates the key: the client, once per logical operation, before the first attempt. A key generated per attempt is useless, and a key derived from the request body treats two genuine identical payments as one.
- Scope: store keys per client or per account, with the primary key on (client, key). Otherwise one client's key can collide with another's, and one client could read another's stored response.
- Expiry: keys only need to outlive the client's retries. Keep them for a fixed period, often 24 hours, publish that period in the API documentation as the draft asks, and delete older rows with a
scheduled job. - What to store: the status code and body of the first response, so a replay is identical. Do not store responses to requests that failed and rolled back, so the client can fix the problem and retry.
- Where to store: in the same database and transaction as the business data. Redis with
works for claiming a key, but it cannot commit together with a database write, so a crash can leave the key without the data or the reverse.SET key value NX EX - Retries: a client that retries quickly and forever turns a short outage into a flood. Retry with exponential backoff and jitter and a limit, as the
Spring Retry page shows.
Choosing a technique
| Situation | Use |
|---|---|
| Setting a value or replacing a resource | An absolute write, upsert or PUT |
| Moving an order or payment through states | A conditional update on the current status, checking the row count |
| Concurrent edits of one record | A version column, or JPA @Version |
A POST | An Idempotency-Key |
| A key reused with a different body | A stored fingerprint and a 422 response |
| Kafka, RabbitMQ or SQS consumers | A processed-message table written in the same transaction as the effect |
| An effect outside your database, such as a payment provider | Pass your key or message id on as that provider's idempotency key |
Three rules cover most cases: assume every request and message can arrive twice, claim the key with a unique constraint rather than checking first, and commit the key and the effect in one transaction. Related pages: