Skip to content

Idempotency keys

An idempotency key turns “create this order” into “create the order with this key”. The client generates a unique key for each operation it intends to do once, and sends the same key on every attempt at it. The server uses the key to recognise a retry: the first time it sees a key it does the work and saves the answer under that key, and every later request with the same key gets the saved answer without the work being done again.

Stripe’s documentation describes exactly this. A client generates the key, the server uses it to recognise retries, and Stripe suggests V4 UUIDs or another random string with enough entropy to avoid collisions, up to 255 characters, and no sensitive data such as email addresses. What the server saves is the status code and body of the first request made with that key, whether it succeeded or failed, and a later request with the same key returns the same result, including a 500 error.

Mental model. The key is the reference number on a cheque. The bank pays a given reference once. Present the same cheque again and the clerk does not pay, but reads out what happened the first time.

Three rules make the idea work, and a sketch that leaves one out is a bug.

Replay, do not redo. A repeated key gets the saved answer. That also fixes the false failure of the last lesson: the client that timed out asks again and learns what happened.

Compare the request, not just the key. Stripe compares the incoming parameters with those of the original request and returns an error if they differ, to prevent accidental misuse. A client that reuses a key for a different operation has a bug, and replaying the first answer to it would hide the bug.

Save the key and the work together. If the server does the work and crashes before it saves the key, the retry does the work again. If it saves the key first and crashes before the work, the retry is told the work was done when it was not. A real server saves both in one transaction, and has to handle two requests with the same key arriving at once, for example with a unique constraint on the key. Stripe notes that it saves a result only once execution of an endpoint has begun: a request that fails validation, or conflicts with one executing at the same moment, saves nothing and can be retried.

The example is a payment API run two ways, with and without keys. A client sends a charge of 25, loses the response, and retries twice, so each server receives the same request three times.

C# exampleThree requests with one key, one charge
idempotency-key.cs
// An idempotency key: the client sends the same key on every retry,
// and the server runs the work once and replays the saved answer afterwards.
var plain = new PaymentApi(useKeys: false);
var keyed = new PaymentApi(useKeys: true);
// The client sends a charge, the response is lost, so it retries twice.
// Both servers receive the same request three times.
foreach (var api in new[] { plain, keyed })
{
for (var attempt = 1; attempt <= 3; attempt++)
api.Charge("key-order-42", "alice", 25);
Console.WriteLine($"{api.Name,-17} requests={api.Requests} charges={api.Charges.Count} total={api.Charges.Sum()} replies={string.Join(",", api.Replies)}");
}
// A different key is a different operation, so it is charged.
keyed.Charge("key-order-43", "alice", 25);
Console.WriteLine($"{"new key",-17} requests={keyed.Requests} charges={keyed.Charges.Count} total={keyed.Charges.Sum()}");
// The same key with a different body is a client bug: reject it instead of replaying the wrong answer.
try { keyed.Charge("key-order-42", "alice", 99); }
catch (InvalidOperationException e) { Console.WriteLine($"{"reused key",-17} rejected: {e.Message}"); }
class PaymentApi(bool useKeys)
{
// key -> (fingerprint of the request, the answer we gave)
private readonly Dictionary<string, (string Fingerprint, string Reply)> _saved = [];
private int _nextChargeId = 1;
public string Name => useKeys ? "with key" : "without key";
public int Requests { get; private set; }
public List<int> Charges { get; } = [];
public List<string> Replies { get; } = [];
public string Charge(string key, string customer, int amount)
{
Requests++;
var fingerprint = $"{customer}:{amount}";
if (useKeys && _saved.TryGetValue(key, out var seen))
{
if (seen.Fingerprint != fingerprint) throw new InvalidOperationException($"key {key} was used with a different request");
Replies.Add(seen.Reply);
return seen.Reply; // replay: no second charge
}
Charges.Add(amount); // the side effect, done once per key
var reply = $"charge-{_nextChargeId++}";
if (useKeys) _saved[key] = (fingerprint, reply);
Replies.Add(reply);
return reply;
}
}
// A real server saves the key and the side effect in one transaction, and handles two requests
// with the same key arriving at once (a unique constraint on the key, or a lock). This sketch is single-threaded.
Output
without key requests=3 charges=3 total=75 replies=charge-1,charge-2,charge-3
with key requests=3 charges=1 total=25 replies=charge-1,charge-1,charge-1
new key requests=4 charges=2 total=50
reused key rejected: key key-order-42 was used with a different request

This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.

Without keys the server charges three times, for a total of 75, and gives three different answers. With a key it receives the same three requests, charges once, for a total of 25, and answers all three with the same charge. A request with a new key is a new operation and is charged: 4 requests in all and 2 charges. Reusing the first key with a different amount is rejected.

The sketch is single-threaded and keeps its keys in memory, so it shows the rule and not the engineering. The comment at the end of the file says what a real one adds.

An operation that sets a value to a given state does the same thing when repeated. One that adds to a state does not. Sort these.

Challenge

Safe to repeat, or does it need a key?

A retry or a redelivery runs an operation again. Put each operation under the heading that says whether repeating it is harmless as it stands or needs an idempotency key, or an id kept by the consumer.

Sorting needs JavaScript.

Categories

Safe to repeat
Doing it twice leaves the same state as doing it once.
Needs a key
Doing it twice changes the result, so repeats must be recognised.
  1. Line 1 of 6Set the status of order 42 to shipped.
  2. Line 2 of 6GET the details of order 42.
  3. Line 3 of 6DELETE the session with id abc.
  4. Line 4 of 6POST a charge of 25 to a payment API.
  5. Line 5 of 6Add 1 to the stock count when a message arrives.
  6. Line 6 of 6Send a confirmation email for each order-created message.

Check your answers at least once before looking at the answers.

The client has to keep the key until it has an answer, and send the same one. A client that makes up a new key for every attempt gets no protection at all: each attempt is a new operation. The key belongs to the intent, for example one order in the cart, and not to the HTTP attempt. Stripe adds that it will generate a new request if a key is reused after the original has been pruned, so the server cannot keep keys for ever either. The next lesson is about that limit.

  • A client-chosen key lets the server do an operation once and answer every retry with the saved result.
  • The server compares the request with the original and rejects a reused key with a different request.
  • Key and work must be saved together, and two requests with one key at once need a unique constraint or a lock.
  • In the example, three requests with one key make one charge of 25 instead of three charges totalling 75.
  • Setting a state is idempotent by nature, and adding to one needs a key.

Next: Duplicate messages.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.