Build Log / Entry 005 / Platform

Making payment retries safe with idempotency keys.

A retried payment capture can charge a customer twice. An idempotency key on every attempt, and a ledger that enforces it in Postgres, make retries safe.

The short version

  • A timeout doesn't mean a request failed: retrying a payment without an idempotency key can charge twice.
  • Derive the idempotency key from the business operation and send the same key on every attempt.
  • Enforce the key with a unique constraint in Postgres, and handle all four cases: done, in flight, stale and mismatched.
  • Prove it under concurrency: fifty simultaneous captures and a dropped acknowledgement must each produce one charge.
Published
Read
7 min
Written by
Platform team
Stack
Java 21 · Spring · Spring Retry · PostgreSQL
In this entry · 5 sections
  1. 01Where the duplicate comes from
  2. 02Make the key part of the request
  3. 03Four answers to a repeated key
  4. 04Proving it
  5. 05What the tests show

Every distributed system retries. The network drops a response, a pod restarts mid-request, a load balancer times out a healthy call. Sooner or later the same request arrives twice, and for a payment capture, that can mean charging a customer twice.

This entry comes from a payments platform we worked on, where retries were handled by a hand-written loop with no way for the ledger to recognize a repeat. It walks through the failure, the fix, and the tests that prove it.

Where the duplicate comes from

The failure is almost always the same shape: the ledger commits the capture, the acknowledgement is lost on the way back, and the gateway (correctly, from its point of view) tries again.

Fig. 005.1: The retry path. Step 3 is where naive retries double-charge.

Here is the loop we find most often. It looks responsible: a bounded number of attempts, exponential backoff, a specific exception rather than a blanket catch.

PaymentGateway.java
public CaptureResult capture(CaptureRequest req) throws InterruptedException {
  for (int attempt = 1; ; attempt++) {
      try {
          return ledger.post("/captures", req);    // no key: every attempt looks brand new
      } catch (SocketTimeoutException timeout) {   // the capture may already be committed
          if (attempt == 4) throw new CaptureFailedException(req.orderId(), timeout);
          Thread.sleep(200L << (attempt - 1));     // back off, then charge again
      }
  }
}
005.2: the anti-pattern. Nothing tells the ledger that attempt two is attempt one again.Java 21 · the version without a key

The flaw is in what the catch assumes. A timeout means the gateway didn’t hear back; it doesn’t mean the ledger didn’t act. When the acknowledgement is the thing that got lost, the capture has already been committed, and the next pass through the loop sends an identical request that the ledger has no way to recognize. It does exactly what it was asked: it captures again. Four attempts, up to four charges, and every log line along the way says the retry logic worked.

Make the key part of the request

The fix is to derive a key from the business operation, not the HTTP request, and send it on every attempt. Compare this with 005.2: the retry policy barely changes, but now every attempt carries the same identity. Same order, same attempt family, same key.

PaymentGateway.java
@Retryable(maxAttempts = 4, backoff = @Backoff(delay = 200, multiplier = 2))
public CaptureResult capture(CaptureRequest req) {
  String key = IdempotencyKey.of(req.orderId(), "capture");
  return ledger.post("/captures", req, key);   // same key on every attempt
}
005.3: Lines 3 and 4 are the whole idea.Java 21 · Spring Retry 2.0

On the other side, the ledger doesn’t trust the caller to behave. It enforces uniqueness in the one place that can’t be raced: the database.

Four answers to a repeated key

A unique key on its own only tells you a second attempt arrived. It doesn’t tell you what to do with it, and “do nothing” is the wrong answer: the caller still needs a result, and it needs the same result the first attempt got, not an error.

The ledger inserts the key, with a hash of the request, before it does any work, as its own short transaction. A unique-constraint violation on that insert means this capture has already been started. What happens next depends on the state of that earlier attempt, and there are four cases to handle: it finished, it’s still running, it died partway through, or the key arrived with a different request.

LedgerCaptureService.java
public CaptureResult capture(CaptureRequest req, String key) {
  try {
      keys.insert(key, req.hash());              // own transaction; fails if the key exists
  } catch (DuplicateKeyException conflict) {
      return resolve(key, req);
  }
  try {
      CaptureResult result = doCapture(req, key);
      keys.complete(key, result);                // store the answer for every later retry
      return result;
  } catch (RuntimeException failed) {
      keys.delete(key);                          // failed: free the key so a retry can run
      throw failed;
  }
}

private CaptureResult resolve(String key, CaptureRequest req) {
  IdempotencyRecord existing = keys.find(key);
  if (!existing.requestHash().equals(req.hash())) {
      throw new IdempotencyKeyReusedException(key);   // same key, different request
  }
  if (existing.result() != null) {
      return existing.result();                  // finished: same answer, no new charge
  }
  if (keys.deleteIfStale(key, LEASE)) {          // died mid-capture: one caller reclaims it
      return capture(req, key);
  }
  throw new CaptureInFlightException(key);       // still running: ask again shortly
}
005.4: one insert decides who does the work; every other caller reads, waits, or reclaims.Java 21 · Spring · Postgres · illustrative

A finished capture under a repeated key is a success: the caller gets the stored result, exactly as if the duplicate had never happened. A capture still in flight is a caller arriving too early; the ledger answers with a conflict, the gateway turns that into CaptureInFlightException, and the same @Retryable policy that handles timeouts waits and asks again. A key that arrives with a different request is rejected outright, because answering it with the first request’s result would hide a bug in the caller.

The fourth case is the one a first version usually misses. If the capture fails, the key is deleted so a retry can run. If the process dies partway through, nothing deletes it, and without a way out, that order could never be captured. deleteIfStale is that way out: a single DELETE ... WHERE key = ? AND result IS NULL AND created_at < ?, so only one caller can reclaim a stale key, and a fresh one is never touched. The lease has to be longer than the slowest capture can take, and when the capture calls an outside payment processor, the same idempotency key goes with it, so a reclaimed capture can’t charge twice there either.

Proving it

A code review can convince you the logic reads correctly. It can’t convince you the race condition isn’t there, because the race condition only shows up under concurrency, and concurrency is exactly what a single-threaded test doesn’t have.

So the test that matters fires the same capture at the service many times at once, deliberately, and checks what came out the other end:

PaymentGatewayConcurrencyTest.java
@Test
void concurrentCapturesOfSameOrder_resultInExactlyOneCharge() throws Exception {
  CaptureRequest req = sameOrderRequest();
  int callers = 50;
  var pool = Executors.newFixedThreadPool(callers);
  var ready = new CountDownLatch(callers);
  var go = new CountDownLatch(1);

  List<Future<CaptureResult>> futures = IntStream.range(0, callers)
      .mapToObj(i -> pool.submit(() -> {
          ready.countDown();
          go.await();
          return gateway.capture(req);
      }))
      .toList();

  ready.await();
  go.countDown();              // release all 50 at once

  Set<CaptureResult> results = drain(futures);
  assertThat(results).hasSize(1);                               // every caller got the same answer
  assertThat(ledgerRows(req.orderId())).hasSize(1);              // and only one row exists to back it
}
005.5: fifty callers, one order, one charge.JUnit 5 · ExecutorService

A second test reproduces the failure from the top of this entry: a gateway that commits the capture, then has the acknowledgement dropped before it reaches the caller, forcing a real @Retryable retry on the wire. A WireMock stub takes the first response away entirely; the retried request still carries the same idempotency key, and the assertion is the same one that matters in production: one ledger row, one result, no second charge, regardless of how many times the network made the client ask again.

What the tests show

Together, the two tests cover both ways a duplicate arrives: many callers at once, and one caller retrying after a lost acknowledgement. In both, the ledger ends with one row and every caller gets the same result. The guarantee rests on a unique constraint in Postgres, a retry policy that treats an in-flight duplicate as a reason to wait, and the cleanup that frees a key when a capture fails or stalls. None of it depends on every caller getting its own retry logic right.

Let's Discuss
Your Ideas

Tell us what you're building. We'll tell you how we'd approach it.

Schedule a call