Square CloudSquare Cloud

Idempotency in APIs: what it is and how to implement it

An operation is idempotent when repeating it has the same effect as running it once. In an API, that lets you retry a request after a network failure without charging or creating anything twice.

Updated 7 min read

Learning objectives

After reading this article you will be able to:

  • Understand idempotency and which HTTP methods are idempotent
  • Implement the Idempotency-Key header with Redis or a unique constraint
  • Protect webhook processing against events delivered more than once
On this page

The customer clicks pay, the request reaches the server, the payment is created and, on the way back, the connection drops. On the client side, there's no way to know whether the order went through. Retrying may charge twice; not retrying may leave the purchase unpaid.

Idempotency is what makes that retry safe. It matters for payments, order creation, webhooks, queues and any integration that repeats requests when something fails, which is nearly all of them.

What is idempotency?#

An operation is idempotent when running it several times has the same effect as running it once. "Set the balance to 100" is idempotent: running it ten times leaves the balance at 100. "Add 10 to the balance" isn't: running it ten times adds 100.

In HTTP, the definition is about the effect on the server, not the response. RFC 9110 says a method is idempotent when the intended effect of several identical requests is the same as that of a single one. The first DELETE /orders/7 usually returns 200 and the following ones 404, but the final state is the same: the order doesn't exist. Writing each call to a log doesn't break idempotency either.

Which HTTP methods are idempotent?#

Method Safe Idempotent
GET, HEAD, OPTIONS, TRACE Yes Yes
PUT No Yes
DELETE No Yes
POST No No
PATCH No No

Safe means the method changes nothing; every safe method is also idempotent. PATCH comes from RFC 5789, which defines it as neither safe nor idempotent, although a specific PATCH can be written to be idempotent (setting a field instead of incrementing it).

The table has a practical consequence: RFC 9110 says a client shouldn't automatically retry a request with a non-idempotent method unless it knows that request is idempotent in practice or that the original was never applied. That's why libraries and proxies may retry a GET after a connection failure, but not a POST.

And the table is a promise, not a guarantee: if your PUT handler increments a counter, it breaks the contract. Method semantics are covered in what is a REST API.

How does an idempotency key work?#

An idempotency key is a unique value the client generates for each operation, such as a UUID v4, and sends in the Idempotency-Key header. It's the most widely adopted fix for POST, the method that creates things (an order, a payment) and isn't idempotent. The server stores the key with the result of the first run; if the same key arrives again, it returns the stored result instead of running the operation again.

The pattern is described in an IETF Internet-Draft from the HTTPAPI working group. It isn't an RFC yet; check its current status on the datatracker. The draft says to respond with:

  • 400 when the key is missing on an operation that requires it;
  • 409 when a request with the same key is still being processed;
  • 422 when the key is reused with a different body.

In the draft, the value is a Structured Fields String, written in quotes. The expiry policy is up to each API, which should publish it.

Stripe is the best-known reference. In its v1 API, it stores the status code and body of the first request made with a key, once execution has begun, 500 errors included, and returns that response on retries; it compares the new request's parameters with the original's and errors if they differ; it accepts keys up to 255 characters, which can be removed once they're at least 24 hours old.

The detail that breaks most integrations sits in the client: the key is per operation, not per attempt.

js
async function createOrder(data) {
  const key = crypto.randomUUID(); // generated once and reused on every attempt
  for (let attempt = 1; attempt <= 3; attempt++) {
    try {
      const response = await fetch("https://api.example.com/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Idempotency-Key": `"${key}"` },
        body: JSON.stringify(data),
      });
      // 409: the first attempt is still running; 5xx: temporary failure
      if (response.status !== 409 && response.status < 500) return response;
    } catch {
      // network failure: retry with the same key
    }
    if (attempt < 3) await new Promise((done) => setTimeout(done, 500 * 2 ** attempt));
  }
  throw new Error("Could not create the order");
}

How do you implement it with Redis?#

Redis solves the hard part, which is concurrency: SET with the NX option only writes if the key doesn't exist yet, in a single atomic operation, and EX makes the key expire on its own. The flow is to reserve the key, run the operation, store the response and, on retries, return what was stored.

js
// npm install express redis
import { createHash, randomUUID } from "node:crypto";
import express from "express";
import { createClient } from "redis";

const redis = createClient({ url: process.env.REDIS_URL });
redis.on("error", (err) => console.error("Redis:", err.message));
await redis.connect();

const app = express();
app.use(express.json());

const TTL_PROCESSING = 60; // if the process dies midway, the reservation is gone in 1 minute
const TTL_RESPONSE = 24 * 60 * 60; // the response is kept for 24 hours

// replace with the INSERT in your database: this is the operation that must not run twice
async function saveOrder(data) {
  return { id: randomUUID(), ...data };
}

app.post("/orders", async (req, res) => {
  const key = req.get("Idempotency-Key");
  if (!key) return res.status(400).json({ error: "Send the Idempotency-Key header" });

  const id = `idem:${key}`;
  const fingerprint = createHash("sha256").update(JSON.stringify(req.body ?? {})).digest("hex");

  const reserved = await redis.set(id, JSON.stringify({ state: "processing", fingerprint }), {
    condition: "NX",
    expiration: { type: "EX", value: TTL_PROCESSING },
  });

  if (!reserved) {
    const saved = JSON.parse((await redis.get(id)) ?? "null");
    if (saved && saved.fingerprint !== fingerprint) {
      return res.status(422).json({ error: "Key already used with a different body" });
    }
    if (!saved || saved.state === "processing") {
      return res.status(409).json({ error: "A request with this key is still in progress" });
    }
    return res.status(saved.status).json(saved.body); // replays the original response
  }

  try {
    const order = await saveOrder(req.body);
    const record = { state: "done", fingerprint, status: 201, body: order };
    await redis.set(id, JSON.stringify(record), {
      expiration: { type: "EX", value: TTL_RESPONSE },
    });
    res.status(201).json(order);
  } catch (err) {
    await redis.del(id); // frees the key for a new attempt
    throw err;
  }
});

app.listen(Number(process.env.PORT) || 3000);

The fingerprint (a hash of the body) is what lets you answer 422 to whoever reuses the key with different data. The status codes follow the IETF draft. The limit of this design: the operation and storing the response aren't atomic. If the process dies between the two, the reservation expires and a retry runs the operation again. When that costs money, keep the key in the same database as the operation.

What about a unique constraint in the database?#

If the operation already writes to a relational database, the table itself can hold the key. A UNIQUE column makes the database reject the second row, and the key goes into the same transaction as the effect:

sql
ALTER TABLE orders ADD COLUMN idempotency_key text UNIQUE;
js
// npm install pg
import pg from "pg";

const db = new pg.Pool({ connectionString: process.env.DATABASE_URL });

export async function createOrderOnce(key, product, quantity) {
  const inserted = await db.query(
    `INSERT INTO orders (idempotency_key, product, quantity)
     VALUES ($1, $2, $3)
     ON CONFLICT (idempotency_key) DO NOTHING
     RETURNING id, product, quantity`,
    [key, product, quantity],
  );
  if (inserted.rowCount === 1) return { order: inserted.rows[0], replayed: false };

  // the key already existed: return the order created the first time
  const existing = await db.query(
    "SELECT id, product, quantity FROM orders WHERE idempotency_key = $1",
    [key],
  );
  return { order: existing.rows[0], replayed: true };
}

PostgreSQL handles concurrency: if two requests with the same key arrive together, the second waits for the first one's transaction to finish; if it committed, the second hits DO NOTHING. Answer with the same status in both cases. If you haven't connected Node.js to the database yet, see how to connect PostgreSQL to Node.js. In MySQL, the same UNIQUE column works with INSERT ... ON DUPLICATE KEY UPDATE in place of ON CONFLICT; in MongoDB, a unique index makes the second insert fail, and your code treats that error as a replay. To compare with the Redis design, see Redis as a cache or as a database.

How do you handle webhooks delivered more than once?#

Webhook senders deliver "at least once". Stripe warns that an endpoint may receive the same event more than once and recommends logging the IDs you've processed; in live mode, it keeps retrying for up to three days. On GitHub, when you request a redelivery, it arrives with the same X-GitHub-Delivery as the original. The event ID, then, is already your idempotency key.

sql
CREATE TABLE processed_events (
  id text PRIMARY KEY,
  received_at timestamptz NOT NULL DEFAULT now()
);
js
// npm install express pg
import express from "express";
import pg from "pg";

const db = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const app = express();

app.post("/webhooks/payments", express.raw({ type: "application/json" }), async (req, res) => {
  // verify the signature with the raw body before going on
  const event = JSON.parse(req.body.toString("utf8"));
  const client = await db.connect();
  try {
    await client.query("BEGIN");
    const inserted = await client.query(
      "INSERT INTO processed_events (id) VALUES ($1) ON CONFLICT DO NOTHING",
      [event.id],
    );
    if (inserted.rowCount === 1) {
      // adding credit isn't idempotent: it only runs on the first delivery
      await client.query("UPDATE wallets SET balance = balance + $1 WHERE user_id = $2", [
        event.data.amount,
        event.data.user_id,
      ]);
    }
    await client.query("COMMIT");
  } catch (err) {
    await client.query("ROLLBACK");
    throw err;
  } finally {
    client.release();
  }
  res.sendStatus(200); // duplicate or not, the 2xx makes the sender stop redelivering
});

app.listen(Number(process.env.PORT) || 3000);

Recording the ID and applying the effect in the same transaction avoids both failure modes: marking as processed and failing midway, or processing and not marking. Verifying the signature and answering quickly still apply; what is a webhook covers both. If processing is heavy, push it to a queue and apply the same rule to the jobs, as shown in how to run background jobs.

What are the common mistakes?#

Mistake What happens Fix
Generating a new key on every attempt The server sees two different operations and runs both Generate the key once per operation and reuse it on retries
Keeping keys in process memory A restart wipes them, and a second instance can't see the first one's keys Store them in Redis or the database
Expiring the key before the last retry A late retry runs the operation again A TTL longer than the retry window of the client or the sender
Ignoring the body A key reused by mistake returns another operation's response Compare the body's fingerprint and answer 422
Leaving side effects outside the transaction An email sent before the commit goes out again on the retry Send it after the commit or through a queue with the same protection

How to do this on Square Cloud#

Key storage has to be shared and survive a restart. Both options in this article are available as hosting on Square Cloud from the Standard plan: Redis, with persistence and from 512 MB, and PostgreSQL, from 1024 MB. You create the database from the dashboard and copy the connection URL into an environment variable, such as the REDIS_URL and DATABASE_URL in the examples.

TLS is required: Redis uses rediss://, the client has to trust the CA the dashboard provides and, for PostgreSQL, also presents the certificate (.pem). Pass those files to the examples' createClient and pg.Pool; without them, the connection fails as described in the certificate error when connecting to a database. Redis closes idle clients after 5 minutes, so handle reconnection in your client; the usual errors are in Redis connection errors. Each database accepts up to 256 connections.

With the API in more than one application on the same custom domain, load balancing spreads requests round-robin, without sticky sessions, so a retry can land on another instance: one more reason to keep the key in Redis or the database, never in memory. The Hobby plan doesn't include database hosting. See runtimes, plans and limits on the API hosting page.

API hosting

APIs in always-on containers, with no cold starts

API hosting

FAQs

Is POST idempotent?

No. RFC 9110 defines PUT, DELETE and the safe methods (GET, HEAD, OPTIONS and TRACE) as idempotent. To retry a POST safely, the API needs its own mechanism, such as an idempotency key.

Is Idempotency-Key an official standard?

It isn't an RFC yet. The header is described in an Internet-Draft from the IETF HTTPAPI working group, still in progress, and APIs such as Stripe's already use it. The current status is on the IETF datatracker.

How long should I keep an idempotency key?

At least as long as the client may retry. In Stripe's v1 API, for example, keys can be removed once they are at least 24 hours old; the IETF draft leaves the policy to each API, which should publish it.

Are idempotent and safe the same thing?

No. A safe method changes nothing on the server, like GET. An idempotent one may change state, but repeating it doesn't change the outcome: two DELETEs of the same resource leave the server in the same state as one.

How do I avoid processing the same webhook twice?

Store the ID of every event you process, in a table with a primary key or in Redis, and discard the ones already there. Answer duplicates with a 2xx too, so the sender stops redelivering.

Next articleHow to host a Rust API (Axum or Actix)To host a Rust API, read the port from PORT, listen on 0.0.0.0, build with cargo build --release and handle SIGTERM. Full code for both Axum and Actix Web.