Zum Inhalt springen
Alle Artikel

Dieser Artikel ist auf Englisch.

4 Min. Lesezeit

Idempotency keys, explained

A request times out. Did it work? Idempotency keys let a client retry without creating duplicates. How they work, what a server must store, and the edge cases that matter in practice.

Vom TaskToHuman-Team

  • Idempotenz
  • Zuverlässigkeit

Your code sends a request to create something: a payment, an order, an approval task. The connection drops before the response arrives. Did the server create it or not?

You can't tell. If you don't retry, you may have lost the request. If you retry, you may create it twice: two refunds, two shipments, two approval requests in someone's inbox. Idempotency keys exist to remove that dilemma.

What "idempotent" means

An operation is idempotent if doing it twice has the same effect as doing it once. Reading a record is idempotent. Setting a field to a value is idempotent. "Create a new task" is not: each call creates another one.

An idempotency key makes a non-idempotent operation behave idempotently from the client's point of view. The client generates a unique key for each intended operation and sends it with the request. The server remembers which keys it has seen. If the same key arrives again, the server doesn't perform the operation a second time; it returns the result of the first one.

POST /v1/tasksIdempotency-Key: refund-4821Content-Type: application/json{ "task_type": "approve_refund", "title": "Refund €249 to order #4821?" }

Now the client can retry freely after a timeout, a crash or a deploy. Either the first request worked, and the retry returns the same task, or it didn't, and the retry creates it.

Choosing the key

The key identifies the intent, not the HTTP request. Two rules:

  • The same intent always gets the same key. If your code crashes and restarts, it must produce the same key for the same refund. A random UUID generated in memory just before the call is lost in a crash, so prefer a key derived from your own data, like refund-4821, or a UUID stored with the record before the first attempt.
  • Different intents never share a key. If a customer legitimately gets two refunds for the same order, the key must tell them apart, for example refund-4821-2.

Keep keys short and free of personal data. They tend to end up in logs.

What the server has to do

A correct implementation is more than "look up the key". The server needs to handle four cases.

1. A new key. Perform the operation and store the key together with the result, atomically. If the operation and the key are written separately, a crash between the two brings back the duplicate problem.

2. A key seen before, same request. Return the stored result. It helps to say so: TaskToHuman answers 200 OK with an Idempotent-Replayed: true header instead of 201 Created, so the client can tell a replay from a creation if it cares.

3. A key seen before, different request. This is almost always a bug in the client: a key reused for a different refund. Silently returning the old result would hide it. The server should store a hash of the request body with the key and answer with an error when they don't match. TaskToHuman returns 409 with the code idempotency_conflict.

4. Two requests with the same key at the same moment. A client that retries aggressively can send the second attempt while the first is still running. Both look up the key, neither finds it, both create. The fix is a database constraint: a unique index on the key, so only one insert can win, and the loser reads and returns the winner's result.

Scope and lifetime

Two more decisions shape the behaviour.

Scope. Keys should be unique per account, not globally, so one customer's keys can never collide with another's. TaskToHuman also separates test and live mode: a key used with a test API key never replays a live task, and the other way round.

Lifetime. A server can't keep every key forever. Some APIs expire keys after a day. TaskToHuman keeps a key for as long as the task it created exists, which covers any realistic retry window.

Idempotency on the receiving end

Keys protect the server from duplicate requests. The same problem exists in the other direction: when a server sends you webhooks or callbacks, it retries on timeouts too, and you may receive the same event twice.

The solution mirrors the one above. The sender includes a stable event identifier in every delivery (TaskToHuman sends TTH-Event-Id, the same on every retry), and your receiver stores the identifiers it has processed, in the same transaction as the change the event triggers. A repeated event is acknowledged and skipped.

A short client recipe

JavaScript
async function createApproval(order) {  // Stored with the order before the first attempt, so a crash and restart reuse it.  const key = order.approvalKey ?? (await saveApprovalKey(order, `refund-${order.id}`));  for (let attempt = 1; attempt <= 5; attempt++) {    let response;    try {      response = await fetch("https://api.tasktohuman.com/v1/tasks", {        method: "POST",        headers: {          Authorization: `Bearer ${process.env.TTH_API_KEY}`,          "Content-Type": "application/json",          "Idempotency-Key": key,        },        body: JSON.stringify({ task_type: "approve_refund", title: `Refund ${order.amount} to order #${order.id}?` }),      });    } catch {      response = undefined; // network error or timeout: the task may or may not exist, so retry with the same key    }    if (response?.ok) return response.json(); // 201 Created, or 200 with Idempotent-Replayed: true    if (response && response.status < 500 && response.status !== 429) {      const problem = await response.json(); // 409 idempotency_conflict, 400 validation_failed …      throw new Error(`Task not created: ${problem.code}`); // a client error: fix the request, don't retry    }    await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 250)); // back off before retrying  }  throw new Error("Task API unavailable");}

The important parts: the key is created once and stored, the request body is the same on every attempt, client errors are not retried, and network errors, server errors and rate limits are retried with a growing pause. (When a server sends a Retry-After header with a 429, wait at least that long.)

Summary

  • Send an idempotency key with every request that creates something.
  • Derive the key from the intent and store it before the first attempt.
  • On the server: store key, request hash and result atomically, reject a reused key with a different body, and use a unique index for concurrent retries.
  • On the receiving side, deduplicate events by their identifier.

The details for TaskToHuman's API are in the idempotency page of the developer docs.

Setzen Sie einen Menschen dorthin, wo es zählt.

Beginnen Sie mit einem Aufgabentyp und einer Person, die ihn beantwortet.

Ihre Menschen antworten über einen Link, ohne Konto.