System Design Part 5 Service communication

Idempotency and Idempotency Keys: Making Retries Safe

Bill.Lin 17 min read

System Design series Part 5-4 | Previous: Pub/Sub and Delivery Semantics | Next: Real-Time Updates | Series map

Read first: Part 5-1 REST, gRPC, and GraphQL, Part 5-3 Pub/Sub and Delivery Semantics.

Scenario and problem

A user on the MRT taps “Sign up and pay”. The request reaches the server, the sign-up succeeds, and the payment goes through, but the response is lost on its way back over the network. After 10 seconds with no response, the app shows “Network error, please try again”. The user taps again.

The second request the server receives is identical to the first. If the server processes it as usual, the user is charged twice.

The response is lost, so the user taps again8 / 8
The response is lost, so the user taps againAppServerPaymentsSign up and payChargeSuccessResponse lostWaits 10 s, shows a network errorTap againCharge againCharged twice
  1. A user on the MRT taps "Sign up and pay".
  2. The server creates the sign-up and charges the user through the payment provider.
  3. The charge succeeds.
  4. The server replies with success, but the response is lost on its way back over the network.
  5. The app gets no response and shows "Network error, please try again". It cannot tell whether the request never arrived, failed during processing, or succeeded and only the response was lost.
  6. The user taps again. The second request the server receives is identical to the first.
  7. The server processes it as usual and charges again.
  8. The same sign-up is charged twice. Retries happen at every layer: users tapping again, HTTP clients, the API gateway, calls between services, and message queue redelivery.

This is not a rare case. After a network timeout, the client cannot tell whether the request “never arrived”, “arrived but failed”, or “succeeded but the response was lost”. Retries happen at every layer:

The previous post showed that “exactly-once” in a messaging system is really “at-least-once + idempotent processing”. APIs are no different: for retries to be safe, the operation itself must be idempotent.

The simplest approach and its limits

  • Disable the button on the frontend after submitting: it stops double clicks, but not retries after a timeout, the app being closed and reopened, or automatic retries in the network layer
  • A unique key in the database: add a unique index on (lecture_id, member_id) so the same member cannot sign up for the same talk twice. This works well for sign-ups, but it has two limits:
    • The retried request gets an “already signed up” error, even though the first attempt actually succeeded. The client has to handle this error specially to know that “it actually succeeded”
    • Not every operation has a natural unique key. You can buy two extra handouts or top up twice; “the same content” does not mean “the same operation”

Core mechanism

What idempotent means

An operation is idempotent when running it once and running it many times have the same effect on the system’s state. Note that it is the effect, not the response: deleting the same record a second time may return 404, but the state of the data is no different.

The HTTP specification defines the semantics of each method: GET, HEAD, PUT, and DELETE are idempotent, POST is not, and PATCH may or may not be (REST, gRPC, and GraphQL post). This is a semantic promise, and the implementation has to keep it: a PUT that “adds 1 every time it is called” violates the specification.

Making the operation idempotent by design

Before adding an Idempotency Key, see whether the operation itself can be designed to be idempotent:

Approach Example Idempotent?
Set to a value UPDATE registration SET status = 'CANCELLED' Yes
Increment or decrement a value UPDATE lecture SET remaining = remaining - 1 No
Conditional update with the expected version ... SET status = 'PAID', version = 8 WHERE id = ? AND version = 7 Yes: on a retry the version no longer matches, so it does not update again
The client chooses the resource ID PUT /v1/registrations/{client-generated UUID} Yes: the second call just overwrites the same record
A natural unique key (lecture_id, member_id) unique index Duplicate writes are rejected

If you can design it this way, you need no extra mechanism. But operations like “create a payment” or “buy one extra handout” are not idempotent by nature, and that is when you need an Idempotency Key.

Idempotency Key

The client generates a unique key (for example a UUIDv4) for each logical operation and sends it in the Idempotency-Key header. Retries reuse the same key. The server remembers the result of each key; when the same key comes in again, it returns the previous result directly instead of running the operation again.

sequenceDiagram
    participant A as App
    participant S as Sign-up service
    participant DB as Database
    A->>S: POST /v1/registrations<br/>Idempotency-Key: 6f1c…
    S->>DB: Record key, create sign-up, store response (one transaction)
    DB-->>S: Committed
    S--xA: 201 Created (response lost on the network)
    Note over A: Timeout, retry with the same key
    A->>S: POST /v1/registrations<br/>Idempotency-Key: 6f1c…
    S->>DB: Look up key
    DB-->>S: Already processed, response was 201 and sign-up #918
    S-->>A: 201 Created (same content as the first time)

The IETF httpapi working group has a draft for the Idempotency-Key header (draft-07, October 2025). It is not an RFC yet, but many payment and cloud service APIs adopted the same approach long ago. The draft defines the header’s value as a Structured Field string, which needs double quotes (Idempotency-Key: "6f1c…"), while many existing APIs accept an unquoted value. Pick one and write it into your API docs; the examples in this post use an unquoted UUID. The error responses the draft recommends:

Situation Response
An operation that requires a key arrives without one 400
The same key with a different request body 422
An earlier request with the same key is still being processed 409

Decisions to make in the design

Key scope: a key only has meaning within the same user and the same operation. The table’s primary key is (user ID, key), not just the key. See Security below for why.

Request fingerprint: record a hash of the first request’s content. The same key with different content means a client bug (for example, the key is stored in a global variable and every operation uses the same one), so return 422 rather than another operation’s result.

Concurrent duplicate requests: the user double-taps, and two requests with the same key arrive almost at the same time. If both first ask “does this key exist?” and both get “no”, both run. The fix is to let the database’s unique key be the referee:

  • When the operation only touches the local database, put “write the key”, “run the business logic”, and “store the response” in the same transaction, and write the key first. When the second request writes the same key, it waits for the first transaction to finish: if the first one commits, the second gets a unique key violation and reads the stored response instead; if the first one rolls back, the second runs normally. You need no “in progress” state, and a crash leaves no half-written record
  • When the operation calls an external service (a payment provider, for example), you cannot wait on the external call inside a database transaction. Split it into two steps: first commit an “in progress” key, then call the external service, and finally mark the key “completed” and store the response. A retry of an in-progress key gets 409. A crash can leave the key stuck in progress, so you need a recovery process: query the payment provider, or resend to it, with the same derived key (the payment side must be idempotent too), then fill in the result

Which results to remember:

  • Successful results: always remember them
  • Business failures (no seats left, for example): you can remember them so retries get a consistent answer, or not remember them so retries are judged again. Choose one explicitly and write it into the API docs
  • 5xx and transient errors: do not remember them. Otherwise a single database connection timeout makes this key fail forever. The same-transaction design satisfies this naturally: when the transaction rolls back, the key does not remain either

Retention period: keys cannot be kept forever. The retention period must be longer than the longest time a client may keep retrying (24 hours, for example), and it goes into the API docs. A request sent with the same key after it expires is treated as a new operation.

Passing it all the way down

When the sign-up service calls the payment provider, that call can also time out and be retried, so idempotency has to hold at every layer. The sign-up service should not forward the user’s key to the payment provider as is; it derives a new key instead, such as {member ID}:{user's key}:charge. That way, when the same user operation is retried, the key sent to the payment provider is the same; different operations, or different external calls within the same operation, get different keys.

Message consumers follow the same idea, except that the key is the event ID (the deduplication table in the Pub/Sub post).

Comparing options

Approach Pros Limits Best for
Natural unique key Simple, guaranteed by the database Retries get an error instead of the original result; not every operation has a natural key Operations a person can do only once
Conditional update (version number) No extra table Only works for updating existing data State transitions, edits
Client-generated ID + PUT Matches HTTP semantics, idempotent by nature The client must be able to generate IDs, and the API design has to support it Creating resources
Idempotency Key table (in the same database as the business data) General-purpose, returns consistent results, commits together with the business data One more table, needs cleanup Creation operations that are not idempotent by nature, such as payments and add-on purchases
Idempotency Key in Redis Fast, TTL cleans up automatically Not in the same transaction as the database: a crash after the business data commits but before the Redis write means a retry runs the operation again The business logic already has other protection, and the key only reduces duplicate work

In Java

1. The table

sql
CREATE TABLE idempotency_record (
    owner_id        BIGINT       NOT NULL,
    idem_key        VARCHAR(64)  NOT NULL,
    request_hash    CHAR(64)     NOT NULL,
    response_status INT,
    response_body   JSON,
    created_at      TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    PRIMARY KEY (owner_id, idem_key),
    KEY idx_created_at (created_at)
);

2. Storing the key and the response

java
@Repository
public class IdempotencyStore {

    private final JdbcClient jdbc;

    public IdempotencyStore(JdbcClient jdbc) {
        this.jdbc = jdbc;
    }

    /** Claims this key. Concurrent requests with the same key wait here for the earlier transaction to finish; returns false when the key already exists. */
    public boolean tryClaim(long ownerId, String key, String requestHash) {
        try {
            jdbc.sql("""
                            INSERT INTO idempotency_record (owner_id, idem_key, request_hash)
                            VALUES (:ownerId, :key, :hash)
                            """)
                    .param("ownerId", ownerId)
                    .param("key", key)
                    .param("hash", requestHash)
                    .update();
            return true;
        } catch (DuplicateKeyException e) {
            return false;
        }
    }

    public void complete(long ownerId, String key, StoredResponse response) {
        jdbc.sql("""
                        UPDATE idempotency_record
                           SET response_status = :status, response_body = :body
                         WHERE owner_id = :ownerId AND idem_key = :key
                        """)
                .param("status", response.status())
                .param("body", response.body())
                .param("ownerId", ownerId)
                .param("key", key)
                .update();
    }

    public Optional<IdempotencyRecord> find(long ownerId, String key) {
        return jdbc.sql("""
                        SELECT request_hash AS requestHash, response_status AS responseStatus,
                               response_body AS responseBody
                          FROM idempotency_record
                         WHERE owner_id = :ownerId AND idem_key = :key
                        """)
                .param("ownerId", ownerId)
                .param("key", key)
                .query(IdempotencyRecord.class)
                .optional();
    }
}

public record StoredResponse(int status, String body) {}

public record IdempotencyRecord(String requestHash, int responseStatus, String responseBody) {

    public StoredResponse response() {
        return new StoredResponse(responseStatus, responseBody);
    }
}

3. Doing it all in one transaction

java
@Service
public class IdempotentRegistrationService {

    private static final String OPERATION = "POST /v1/registrations";

    private final IdempotencyStore store;
    private final RegistrationService registrations;
    private final TransactionTemplate transactions;
    private final ObjectMapper objectMapper;

    public IdempotentRegistrationService(IdempotencyStore store, RegistrationService registrations,
                                         TransactionTemplate transactions, ObjectMapper objectMapper) {
        this.store = store;
        this.registrations = registrations;
        this.transactions = transactions;
        this.objectMapper = objectMapper;
    }

    public StoredResponse register(long memberId, String key, RegistrationRequest request) {
        String requestHash = fingerprint(request);
        try {
            return transactions.execute(status -> {
                if (!store.tryClaim(memberId, key, requestHash)) {
                    throw new KeyAlreadyUsedException();
                }
                Registration registration = registrations.register(request.lectureId(), memberId, request.ticketType());
                StoredResponse response = new StoredResponse(201,
                        objectMapper.writeValueAsString(RegistrationView.from(registration)));
                store.complete(memberId, key, response);
                return response;
            });
        } catch (KeyAlreadyUsedException e) {
            IdempotencyRecord existing = store.find(memberId, key).orElseThrow();
            if (!existing.requestHash().equals(requestHash)) {
                throw new IdempotencyKeyMismatchException();     // maps to 422
            }
            return existing.response();
        }
    }

    /** Build the fingerprint from explicit fields, not a hash of the whole JSON string: a different field order or whitespace would cause a false mismatch. */
    private static String fingerprint(RegistrationRequest request) {
        String canonical = OPERATION + "|" + request.lectureId() + "|" + request.ticketType();
        try {
            byte[] digest = MessageDigest.getInstance("SHA-256").digest(canonical.getBytes(StandardCharsets.UTF_8));
            return HexFormat.of().formatHex(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }
    }

    private static final class KeyAlreadyUsedException extends RuntimeException {
    }
}
  • tryClaim first, then the business logic: concurrent duplicate requests wait at the INSERT, so they do not both run
  • Handle unique key violations only around tryClaim. registrations.register can also throw DuplicateKeyException because of the (lecture_id, member_id) unique index; that means “this member already signed up with another key”, which is a different case and must not be treated as “this key was already processed”
  • A business exception (no seats left, for example) rolls back the whole transaction, so the key does not remain either, and a retry is judged again. Here we choose not to remember business failures
  • KeyAlreadyUsedException is thrown inside the transaction, and the stored record is looked up outside the transaction, after the rollback: in PostgreSQL, once a statement fails, the transaction cannot run any more queries, and a query outside the transaction is always able to see the record another transaction committed
  • Spring Boot 4 uses Jackson 3, whose writeValueAsString throws an unchecked exception, so it can be called directly inside the lambda; Jackson 2’s JsonProcessingException is a checked exception and has to be wrapped separately

4. Controller and cleanup

java
private static final Pattern VALID_KEY = Pattern.compile("[0-9a-fA-F-]{36}");    // accept only the UUID format

@PostMapping("/v1/registrations")
public ResponseEntity<String> register(@AuthenticationPrincipal Member member,
                                       @RequestHeader("Idempotency-Key") String key,
                                       @Valid @RequestBody RegistrationRequest request) {
    if (!VALID_KEY.matcher(key).matches()) {
        return ResponseEntity.badRequest().build();
    }
    StoredResponse response = service.register(member.id(), key, request);
    return ResponseEntity.status(response.status())
            .contentType(MediaType.APPLICATION_JSON)
            .body(response.body());
}
java
@Scheduled(cron = "0 */10 * * * *")
public void purgeExpiredKeys() {
    int deleted;
    do {                                                        // delete in batches to avoid locking many rows at once
        deleted = jdbc.sql("""
                        DELETE FROM idempotency_record
                         WHERE created_at < NOW(3) - INTERVAL 24 HOUR
                         LIMIT 5000
                        """)
                .update();
    } while (deleted == 5000);
}

5. Client: one key per operation

java
String idempotencyKey = UUID.randomUUID().toString();           // generated when the user taps the button, reused on retries
RegistrationView view = retryWithBackoff(() -> restClient.post()     // retryWithBackoff stands for any bounded retry mechanism (see the Timeout and Retry post in Part 6)
        .uri("/v1/registrations")
        .header("Idempotency-Key", idempotencyKey)
        .body(request)
        .retrieve()
        .body(RegistrationView.class));

The code above follows the official Spring Framework and Spring Boot documentation and has not been compiled or run. The SQL uses MySQL.

Pitfalls and gotchas

  • A new key on every retry: generating the key inside the retry loop means no idempotency at all. Generate the key once, when “the user decides to do this”
  • Read, then write: with “run it if the key is not found”, concurrent requests both run. Let a unique key or a lock decide who goes first
  • Key in Redis, business data in the database: the two are not in the same transaction, and a crash leaves them inconsistent. If the business data is in the database, put the key in the same database
  • Remembering a 5xx: one transient error is remembered permanently, and the key fails forever after
  • Retention shorter than the retry window: the app resends after a day offline, the key has already been purged, and the operation runs a second time
  • The same key used across different APIs: include the operation type in the fingerprint or the primary key
  • Deduplicating by content: “the same person sending the same content within one minute is a duplicate” blocks legitimate repeat purchases. Whether a request is a duplicate is decided by the client’s key, not guessed from the content
  • A reverse proxy or service mesh automatically retrying POST: make sure retries apply only to idempotent methods, or only to requests that carry an Idempotency Key
  • Confusing different unique key violations: a violation in the idempotency table and one in a business table mean completely different things; handle them separately

Security

  • Key scope must be bound to the user: if keys are globally unique, an attacker who obtains (or guesses) someone else’s key can send a request with it and receive that person’s last response, which may contain their name and payment details; or the attacker can use up someone’s key first, so that person’s real request is treated as a duplicate or gets 422. The primary key must include the authenticated user ID, and every lookup must include it too
  • Keys must be unpredictable: use random values such as UUIDv4, not sequential numbers or timestamps (Security in the Distributed IDs post)
  • Limit key format and count: without limits on length and format, an attacker can stuff in very long strings or huge numbers of distinct keys and blow up the table. Validate the format, limit the length, and rate limit creation operations
  • Stored responses are sensitive data too: response content needs the same access control and retention period as the business data; do not write whole responses to logs
  • Idempotency is not replay protection: an attacker who captures a request can resend it with a new key, and the server treats it as a new operation. Replay protection comes from authentication, short-lived tokens, and CSRF protection, not from Idempotency Keys
  • Fingerprint checks stop key misuse: without a fingerprint check, the same key with different content gets the first request’s successful result directly, and the client may wrongly believe the second operation succeeded too

When to use it, and when not to

  • Use an Idempotency Key: for POSTs that are not idempotent by nature and costly to repeat, such as creating payments, orders, and add-on purchases; when calling external payment providers and third-party APIs, also send the idempotency keys they support
  • Try something simpler first: if there is a natural unique key, use it; use conditional updates for state transitions; if the client can choose the ID, use PUT
  • Not needed: reads that are already idempotent, such as GET; operations that are completely harmless to repeat

References

Comments