Video in progress
If two requests with the same `Idempotency-Key` arrive at the same time, what do you do so that both don't get executed?
"Check first, then execute" is open to a race: both requests fail to see the key and both execute. You have to claim the key atomically before starting the work, with an INSERT under a unique constraint or SET NX in Redis, and the second request gets a 409 or waits.
📖 Answer
The wrong version:
if (repo.findByKey(key).isEmpty()) { // both threads see it as empty
Payment p = provider.charge(req); // charged twice
repo.save(new IdempotencyRecord(key, p));
}
With a mobile app where "Pay" is tapped twice, or a network library's automatic retry, the two requests arrive milliseconds apart and land on different pods.
The right order is to claim first, then do the work:
try {
repo.insert(new IdempotencyRecord(key, hash(req), Status.IN_PROGRESS)); // unique PK
} catch (DuplicateKeyException e) {
IdempotencyRecord existing = repo.get(key);
if (!existing.requestHash().equals(hash(req))) throw new KeyReusedException();
if (existing.status() == Status.DONE) return existing.response();
throw new RequestInProgressException(); // 409, the client retries later
}
Payment p = provider.charge(req, key);
repo.complete(key, p);
The INSERT has to be in a separate transaction that commits right away; otherwise the second request doesn't see it and sits waiting on the unique constraint.
Another case: the first request wrote IN_PROGRESS, went to the provider, and the pod crashed. So the key doesn't stay "in progress" forever, I add a locked_until deadline. After it passes, the next attempt asks the provider for the status by that key, which is why it's important to pass the same idempotency key to the external provider too.
Sign up to mark studied questions and save your progress.