Video in progress

How does an idempotency key work? Explain a simple implementation.

The client generates a unique key (a UUID, for example) for each logical operation and sends it in a request header. The server stores the key together with the result; if a request with the same key comes again, it returns the stored result without doing the operation again.

📖 Answer

POST /api/payments
Idempotency-Key: 6f1c2a7e-3b0d-4c55-9a51-0c2b8f1e4d10

A simplified version on the server side:

@Transactional
public PaymentResponse pay(String key, PaymentRequest req) {
    return idempotencyRepo.findById(key)
        .map(saved -> saved.toResponse())         // a repeated request
        .orElseGet(() -> {
            PaymentResponse res = doCharge(req);  // the real operation
            idempotencyRepo.save(new IdempotencyRecord(key, res));
            return res;
        });
}

The key column in the database must have a UNIQUE (or primary key) constraint. Otherwise two parallel requests both see "not found" and both make the payment; the constraint stops one of them with an error.

In practice two more things get added: cleaning up keys after some time (say, 24 hours), and returning an error if the same key comes with a different body.

The client creates the key, because only it knows "this is a repeat of that same request".