SaaS Development

Idempotency Keys From Checkout to Webhook: Retries That Can't Charge Twice

The usual explanation for a double charge is "we forgot the idempotency key". In code review, the more common cause is a key that exists and still lets the duplicate through. The handler looks the key up, finds nothing, does the work, and saves the key at the end. Two retries that arrive 40 milliseconds apart both find nothing, and both charge the card.

That gives this guide a narrow, testable claim. An idempotency key protects you only if it is claimed atomically before the side effect runs. A key that is looked up first and written afterwards records what happened; it does not stop it from happening twice.

Retries are not an edge case during peak traffic. Black Friday falls on 27 November this year, and that weekend is when phones drop off networks mid-checkout, payment providers slow down and load balancers time out. Every one of those failures becomes a retry somewhere in your stack. Shopify has also stopped treating this as optional for some operations: from Admin API version 2026-04, 17 inventory and refund mutations fail at runtime if you call them without an idempotency key.

The sections below walk the whole path. Where the key is created, how the server claims it, what a retry gets back, how long keys live, how to pass them to Stripe and Shopify, and how to deduplicate the webhooks that come back. The examples use TypeScript and Postgres, a common Next.js pairing, but every pattern translates directly to PHP and MySQL.

What idempotency means for an API request

An operation is idempotent when doing it twice leaves the system in the same state as doing it once. HTTP already defines some methods this way. RFC 9110 lists PUT, DELETE and the safe methods (GET, HEAD, OPTIONS and TRACE) as idempotent, and notes that a client can retry them automatically after a communication failure. POST is not on that list, and POST is what creates orders, payments, refunds and subscriptions.

Idempotency keys close that gap. The client attaches a unique value to any request that changes state. The server records the first outcome under that value, and a later request carrying the same value receives that outcome instead of triggering the work again. Stripe has run its API on this design for years: it saves the status code and body of the first request made with a key, and retries with the same key get the saved response (Stripe API reference).

The IETF HTTP APIs working group is standardising the same idea as an Idempotency-Key request header. The draft reached version 09 on 21 November 2026 and is still an Internet-Draft rather than an RFC (draft-ietf-httpapi-idempotency-key-header), but its status codes are already a sensible default for your own API.

The definition is about state, not about responses. A retried request can receive a slightly different response, such as a header saying it was replayed, as long as it does not create a second charge. The AWS Builders' Library frames the goal as returning a reply with the same meaning as the original success, so that retries stay invisible to the calling code (Making retries safe with idempotent APIs).

Where duplicate requests come from in a checkout

Duplicate requests in a checkout rarely come from customers clicking twice, although they do that too. Most come from infrastructure doing exactly what it was designed to do. Before writing any code, list every component that can resend a request, because each one needs either a key or a deduplication rule.

In a typical ecommerce stack, that list includes:

  • The browser or app. A double click, a back navigation that resubmits a form, or a mobile client that reconnects after a network switch and resends its last request.

  • Your own client code. Fetch wrappers, SDKs and data-fetching libraries that retry on a timeout or a 5xx response.

  • The edge. Load balancers, proxies and serverless platforms that retry an upstream call or replay it on a fresh instance after a timeout.

  • Your queue. Most job queues and message brokers deliver at least once, so a worker can receive the same job twice after a crash or an expired visibility timeout.

  • Your providers' webhooks. Stripe retries webhook delivery for up to three days with exponential backoff in live mode (Stripe webhooks). Shopify retries a failed delivery 8 times over the next four hours and counts any response outside the 200 range, including a redirect, as a failure (Shopify webhook duplicates).

  • Your outbound calls. When your server calls Stripe or Shopify and the response is lost, your code cannot tell whether the operation happened, so it retries as well.

The last item does the most damage, because the original request reached the provider and succeeded. Only the answer was lost. Without a key, the retry looks exactly like a new purchase.

Why check-then-act lets duplicates through

The most common idempotency implementation reads well and fails under load. It looks like this:

// Fails under concurrency: the read and the write are separate steps
const existing = await db.idempotencyKey.findUnique({ where: { key } });
if (existing) return existing.response;
 
const charge = await chargeCustomer(order);
await db.idempotencyKey.create({ data: { key, response: charge } });
return charge;

Run two copies of that request at the same moment and trace them. Request A reads the table and finds nothing. Request B reads the table 40 milliseconds later, while A is still waiting on the payment provider, and also finds nothing. Both call chargeCustomer. A writes the key. B then tries to write it and either fails on a unique constraint after the card has already been charged, or succeeds because there is no constraint at all.

Concurrent duplicates are precisely the case idempotency exists for. A client that times out after ten seconds and retries will usually send its second attempt while the first is still running, because the server never stopped working; only the client gave up waiting. Any design that reads first and writes later leaves a window for a duplicate, and peak traffic widens that window because every request takes longer.

A faster read does not fix it. The fix is to make claiming the key the first write, so that the database decides which request owns the operation.

The claim-first pattern: insert the key before any side effect

Claim-first means the very first thing the handler does is try to insert the key. A unique constraint guarantees that only one insert can succeed. The request that wins does the work, and every other request with the same key is told that the work is in progress or already finished.

A minimal Postgres table looks like this:

create table idempotency_keys (
  scope           text        not null,  -- account or customer id
  key             text        not null,
  request_hash    text        not null,
  status          text        not null default 'in_progress',
  recovery_point  text        not null default 'started',
  response_code   int,
  response_body   jsonb,
  locked_until    timestamptz not null default now() + interval '30 seconds',
  created_at      timestamptz not null default now(),
  primary key (scope, key)
);
 
create index idempotency_keys_created_at on idempotency_keys (created_at);

Scope every key to an account or customer. Keys come from clients, and one customer's key should never collide with, or reveal the existence of, another customer's request. It is the same tenant-isolation principle that runs through any multi-tenant SaaS architecture.

The claim itself is a single statement:

const claimed = await sql`
  insert into idempotency_keys (scope, key, request_hash)
  values (${accountId}, ${key}, ${requestHash})
  on conflict (scope, key) do nothing
  returning key
`;
 
if (claimed.length === 0) {
  return handleExistingKey(accountId, key, requestHash);
}
// This request owns the key. Do the work.

Postgres resolves on conflict do nothing at the constraint (PostgreSQL INSERT). If two transactions race, one inserts the row and the other gets zero rows back. MySQL gives the same guarantee with INSERT IGNORE or INSERT ... ON DUPLICATE KEY UPDATE against a unique index. What matters is that the decision happens inside the database, not in application code between two queries.

When the work finishes, the winning request records the outcome:

await sql`
  update idempotency_keys
  set status = 'completed', recovery_point = 'finished',
      response_code = ${statusCode}, response_body = ${body}
  where scope = ${accountId} and key = ${key}
`;

The locked_until column handles a request that claims a key and then dies, whether through a crashed instance or a serverless function that hit its time limit. Without a lock expiry, that key stays in_progress forever and the customer can never complete the purchase. With one, a later request can take over the key once the lock has expired, provided the work is designed so that taking over is safe. The section on partial failure covers how.

Where to create the idempotency key

An idempotency key has to represent one user intent, not one HTTP request. That single rule decides where it is generated.

For a checkout, generate the key when the payment step renders and keep it until the payment succeeds. Every retry of "pay for this cart", whether a timeout, a double click or a reconnect, then sends the same key. When the operation succeeds, generate a fresh key for the next intent. Shopify gives the same guidance for its own directive: regenerate the key on page load and after a successful operation (Shopify changelog).

'use client';
import { useState } from 'react';
 
export function PayButton({ cartId }: { cartId: string }) {
  const [intentKey, setIntentKey] = useState(() => crypto.randomUUID());
  const [pending, setPending] = useState(false);
 
  async function pay() {
    setPending(true);
    try {
      const res = await fetch('/api/checkout/pay', {
        method: 'POST',
        headers: { 'Idempotency-Key': intentKey, 'Content-Type': 'application/json' },
        body: JSON.stringify({ cartId }),
      });
      if (res.ok) setIntentKey(crypto.randomUUID());
    } finally {
      setPending(false);
    }
  }
 
  return <button onClick={pay} disabled={pending}>Pay now</button>;
}

Disabling the button is a courtesy to the customer, not a safety mechanism. The server has to behave correctly when the button is bypassed, the request is replayed, or the page is open in two tabs.

Two mistakes come up repeatedly. The first is generating the key inside the fetch call, which produces a new key for every attempt and defeats the design entirely. The second is deriving the key from data that can repeat across genuine intents, such as a cart id on its own. A customer who pays for a cart, has the order cancelled, and pays again for the same cart has made two real purchases. Use a random UUID for user-driven actions, and reserve deterministic keys for server-to-server work where the business identity really is unique, for example refund:${orderId}:${refundRequestId}.

Stripe recommends V4 UUIDs or another random string with enough entropy, accepts keys up to 255 characters, and advises against putting personal data such as email addresses in them (Stripe API reference). Those are good rules for your own API too.

Fingerprint the request so a reused key cannot change the operation

A key on its own tells you that a request claims to be a retry. It does not prove it. A client bug that reuses a key for a different cart or a different amount should not receive the old response as though nothing were wrong, and it must never be allowed to proceed.

The answer is a request fingerprint: a hash of the parts of the request that define the operation, stored with the key and compared on every repeat.

import { createHash } from 'node:crypto';
 
function canonical(value: unknown): string {
  if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
  if (value !== null && typeof value === 'object') {
    const entries = Object.entries(value as Record<string, unknown>)
      .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
      .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`);
    return `{${entries.join(',')}}`;
  }
  return JSON.stringify(value) ?? 'null';
}
 
export function fingerprint(method: string, path: string, body: unknown) {
  return createHash('sha256').update(`${method} ${path} ${canonical(body)}`).digest('hex');
}

Sorting keys recursively stops two identical payloads from producing different hashes just because a client serialised fields in a different order.

Every serious implementation makes this check. Stripe compares incoming parameters with the original request and returns an error if they differ. Shopify returns IDEMPOTENCY_KEY_PARAMETER_MISMATCH when the same key arrives with different parameters. The IETF draft recommends HTTP 422 for the situation, and points out that a server without fingerprints cannot detect the reuse at all.

Decide deliberately what goes into the hash. Include every field that changes the effect: amount, currency, cart or order id, line items and customer. Leave out fields that legitimately vary between retries, such as a client timestamp or a tracing header. When a field is in doubt, include it. A false mismatch is a visible error that someone will fix; a missed mismatch is a silent wrong charge.

What a retry should receive back

When the claim fails, the handler is in one of four situations, and each deserves a different response.

Stored state

Fingerprint matches

Response

completed

Yes

Replay the stored status code and body

in_progress, lock still valid

Yes

409 Conflict with a Retry-After header

in_progress, lock expired

Yes

Take over the key and resume from the recovery point

Any

No

422 Unprocessable Content

The 409 and 422 codes follow the IETF draft, which recommends 409 for a request that arrives while the original is still being processed and 422 for a key reused with a different payload. Shopify signals the concurrent case with IDEMPOTENCY_CONCURRENT_REQUEST.

async function handleExistingKey(scope: string, key: string, hash: string) {
  const [row] = await sql`
    select * from idempotency_keys where scope = ${scope} and key = ${key}
  `;
  if (row.request_hash !== hash) {
    return json(422, { error: 'idempotency_key_reused_with_different_request' });
  }
  if (row.status === 'completed') {
    return json(row.response_code, row.response_body, { 'Idempotent-Replayed': 'true' });
  }
  if (new Date(row.locked_until) > new Date()) {
    return json(409, { error: 'request_in_progress' }, { 'Retry-After': '2' });
  }
  return resumeFromRecoveryPoint(scope, key, row.recovery_point);
}

The take-over in resumeFromRecoveryPoint must itself be a conditional update (set locked_until = now() + interval '30 seconds' where locked_until < now()), so that two retries arriving after the lock expired cannot both resume the work.

Providers disagree on one detail worth knowing: whether a stored failure should be replayed. Stripe's v1 API replays the saved response even when it was a 500 error, so a retry with the same key does not run the operation again. Stripe's v2 API takes the other route and retries failed or partially failed work to completion where it can. Neither is wrong. Replaying failures is simpler and safer for money movement, but it means the client has to generate a new key to try again after a genuine failure. Whichever you choose, document it, because client developers will build their retry logic around it.

One case is clear-cut. Never store a result for a request that failed validation before any work began. Stripe does not, and the client should be free to correct the input and resend with the same key.

How long to keep idempotency keys

An idempotency key is only useful while you still have it. Retention has to outlast the longest window in which a duplicate can arrive, and that window is set by whichever system retries the longest, which is usually not yours.

Source of retries

Window (checked 23 November 2026)

What it means for you

Stripe API idempotency (v1)

Keys can be pruned once they are 24 hours old

Outbound retries to Stripe must finish well inside a day

Shopify @idempotent directive

Duplicates rejected for up to 24 hours

Same rule for inventory and refund calls

Stripe webhook delivery

Up to 3 days in live mode

Keep processed event ids for at least 3 days

Shopify webhook delivery

8 retries over 4 hours

Keep processed delivery ids for at least a day

Your own clients and queues

Whatever you configured

Measure it, then double it

The Shopify 24-hour figure comes from a Shopify staff reply in the developer forum in January 2026, not from the changelog, so treat it as current behaviour rather than a contract (community.shopify.dev thread). The same thread is a useful reminder that platform changes roll out in stages: early testers saw duplicates accepted on 2026-04 until the enforcement reached their store.

For your own API, 24 hours is a reasonable default for user-driven actions and seven days is a reasonable default for webhook event ids. Remove old rows with a scheduled job (delete from idempotency_keys where created_at < now() - interval '1 day') rather than cleaning up inside requests, and keep the index on created_at so the job stays cheap. Redis with a TTL works well as a fast pre-check, but keep the durable record in the same database as the orders, so that the key and the business data can change in one transaction.

Passing idempotency keys to Stripe and Shopify

Your own key protects your endpoint. It does nothing for the call your server makes to a provider, and that call is where a lost response turns into a second charge. Derive the provider key from your own key, so that the same customer intent always produces the same downstream key.

With Stripe's Node library, the key goes in the request options:

const paymentIntent = await stripe.paymentIntents.create(
  { amount: order.totalMinor, currency: order.currency, customer: order.stripeCustomerId },
  { idempotencyKey: `pi:${accountId}:${intentKey}` },
);

Stripe accepts idempotency keys on every v1 POST request. Sending one with GET or DELETE has no effect, because those requests are idempotent by definition.

Shopify uses a GraphQL directive rather than a header. It goes after the mutation's arguments and before the selection set. This is the form Shopify documents, with the key as a literal:

mutation {
  inventoryAdjustQuantities(input: { ... }) @idempotent(key: "4f5b6ebf-143c-4da5-8d0f-fb8553bfd85d") {
    inventoryAdjustmentGroup { id }
    userErrors { code message }
  }
}

GraphQL also allows directive arguments to come from variables, which keeps keys out of query strings. Confirm that form against your API version in a development store before relying on it, because the documented examples all use literals.

The directive stopped being optional in 2026. Shopify made it mandatory for 17 inventory and refund mutations, including refundCreate, inventoryAdjustQuantities and inventorySetQuantities, in Admin API version 2026-04. The changelog adds a detail that catches teams out: the directive does not appear as required in the schema, but calling those mutations without it fails at runtime (Shopify changelog). Type generation and schema validation will not warn you.

Apps still pinned to 2026-01 can call those mutations without a key today, but only for as long as that version is supported. Shopify supports each stable version for a minimum of 12 months, and when a version is no longer accessible, requests fall forward to the oldest accessible stable version (Shopify API versioning). Once 2026-01 is retired, an unkeyed refund call lands on a version that rejects it. Adding the directive now is a few lines of code. Finding out through failed refunds is much more expensive.

Deduplicating webhooks by the right ID

Webhooks are the other half of the loop, and they arrive at least once by design. Stripe and Shopify both state that an endpoint can receive the same event more than once. The receiver needs the same claim-first discipline, keyed on the provider's identifier.

Which identifier matters, and Shopify's two headers are easy to confuse. Shopify's documentation says to use X-Shopify-Webhook-Id to deduplicate individual deliveries. X-Shopify-Event-Id is shared by deliveries that came from the same merchant action when you have several subscriptions to one topic, so it is for correlation, not deduplication. For Stripe, store the event id. Stripe also notes that it occasionally generates two separate Event objects for the same change and suggests combining the object id in data.object with the event type to catch those. It is explicit that the created timestamp should not be used to decide whether an event has already been processed. If you are moving a Shopify app to the newer event system, the same rules carry over; our Next Gen Events migration guide covers the delivery side.

A Next.js route handler for Stripe, claiming the event before any work:

export async function POST(req: Request) {
  const raw = await req.text();
  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(
      raw, req.headers.get('stripe-signature') ?? '', process.env.STRIPE_WEBHOOK_SECRET!,
    );
  } catch {
    return new Response('Invalid signature', { status: 400 });
  }
 
  const claimed = await sql`
    insert into webhook_inbox (provider, event_id, type, payload)
    values ('stripe', ${event.id}, ${event.type}, ${raw}::jsonb)
    on conflict (provider, event_id) do nothing
    returning event_id
  `;
 
  if (claimed.length > 0) await queue.enqueue('process-webhook', { eventId: event.id });
  return new Response(null, { status: 200 });
}

The handler verifies the signature against the raw body, records the event, queues the real work and returns 200 immediately. Stripe asks for a 2xx before any complex logic, and Shopify allows five seconds for the entire request, so slow processing inside the handler becomes timeouts, the timeouts become retries, and the retries become the duplicates you were trying to remove. This table is usually called an inbox: a durable record of everything received, worked through by a background job at its own pace, with the unique constraint doing the deduplication. Treat the endpoint as the public API it is, with signature checks, rate limits and payload validation, as set out in our OWASP API Top 10 guide.

Neither provider promises order. Stripe does not guarantee that events arrive in the order they were generated, and Shopify's documentation recommends a reconciliation job that uses its APIs to recover anything missed. A worker that receives invoice.paid before invoice.created should fetch the current state from the API rather than fail.

Making the side effect itself idempotent

Keys and inboxes stop duplicate requests from starting duplicate work. The last line of defence is making the work itself safe to repeat, so that a duplicate that slips past every other check still cannot change the outcome. Database constraints do most of this job.

Three patterns cover most checkout logic.

Conditional state transitions. Move an order to its next state only if it is still in the expected state, and check how many rows changed.

update orders
set status = 'paid', paid_at = now()
where id = $1 and status = 'pending_payment';
-- 0 rows updated: another worker already handled it, so do not fulfil again

Unique constraints on business facts. One payment record per payment intent, one shipment per order line, one stock reservation per cart line. With the constraint in place, a duplicate insert fails loudly instead of quietly creating a second shipment.

Upserts for values that should converge. Syncing a customer, a product or an inventory level from a webhook should write the latest known state rather than apply a delta. Writing "quantity is 12" twice is harmless; applying "minus 1" twice is a stock error. Shopify's compare-and-swap field, changeFromQuantity, which became required for several inventory mutations alongside the directive in 2026-04, exists to protect inventory writes from exactly this class of bug.

Keys work per request, and bugs do not respect request boundaries. A worker that crashes after sending the confirmation email but before marking its job as done will run again. Only a state check or a constraint stops the second email.

Handling partial failure when step two of three crashes

A checkout handler rarely does one thing. It creates the order, charges the card, reserves stock and sends a confirmation. If the process dies after the charge but before the reservation, the retry must not charge again, and it must still reserve the stock. A key alone cannot express that, because the operation is half done.

The approach Brandur Leach set out in Implementing Stripe-like Idempotency Keys in Postgres still holds up. Split the handler into atomic phases, each committed in its own transaction between calls to external systems, and record a recovery point on the key after each phase:

type RecoveryPoint = 'started' | 'order_created' | 'charge_created' | 'stock_reserved' | 'finished';

Then write each phase so it can run again safely:

  • Order creation is an insert guarded by a unique constraint on the idempotency key, so a rerun finds the existing order.

  • The charge uses a provider key derived from your key, so a rerun returns the existing charge.

  • Stock reservation relies on a unique constraint per cart line.

  • The confirmation email goes into an outbox table written in the same transaction as the final state change, and a separate worker sends it once.

When a later request takes over an expired key, it reads the recovery point and continues from there instead of starting again. External calls that cannot be protected by a key, such as an email provider or a shipping-label API without idempotency support, belong at the end, after the state that proves they are needed has been committed, and behind an outbox so they run once.

This is more structure than a single function, and it is only worth it for operations that move money or stock. For a newsletter signup, a unique constraint on the email address is the whole design.

Testing retries before peak traffic

Idempotency code that has never handled a concurrent duplicate is untested, however clean it looks. Testing it takes an afternoon. Every test in this section is also in the Retry Safety Worksheet with its pass condition.

Start by firing the same request twenty times in parallel with one key and counting the side effects:

KEY=$(uuidgen)
seq 20 | xargs -P 20 -I{} curl -s -o /dev/null -w "%{http_code}\n" \
  -X POST https://staging.example.com/api/checkout/pay \
  -H "Idempotency-Key: $KEY" -H "Content-Type: application/json" \
  -d '{"cartId":"cart_test_123"}' | sort | uniq -c

The test passes when the payment provider's test dashboard shows one charge, your key table shows one completed row, and every other response is either a replay or a 409. Twenty 200 responses with twenty charges means the claim is not atomic.

Then run the failure cases that matter:

  • Same key, different body. Expect a 422 and no charge.

  • Crash mid-request. Kill the server process inside the handler, wait for the lock to expire, and retry. Expect the work to resume from its recovery point rather than restart.

  • Webhook replay. The Stripe CLI resends an event with stripe events resend <event_id> for up to 30 days after it was created. The second delivery should be recorded once and processed once.

  • Missing Shopify directive. Against a development store on 2026-04 or later, call refundCreate without @idempotent. Expect the runtime error, so you know your error handling surfaces it.

Run the parallel test in a staging environment with production-like latency. Duplicate windows grow as requests slow down, so a test against a fast local database can pass while production fails.

A rollout order for an existing checkout

Most teams reading this already have a checkout in production and a few days before peak traffic. Retrofitting everything at once during a change freeze is the wrong move. The order below puts the highest-value protection first, and each step is small enough to ship and roll back on its own.

  1. Pass provider idempotency keys on every outbound Stripe POST and every Shopify inventory or refund mutation. It is a small diff with the largest payoff, because it covers the lost-response case.

  2. Add a webhook inbox with a unique constraint on the provider's delivery or event id, and move processing to a background worker that acknowledges quickly.

  3. Add conditional state transitions to the order status updates that trigger fulfilment and email.

  4. Add the claim-first key table to your own payment endpoint, and generate the key per intent on the client.

  5. Add request fingerprints and the 409 and 422 responses.

  6. Add recovery points and an outbox to multi-step handlers.

  7. Schedule key cleanup and alert on any key stuck in in_progress.

If the first three steps ship before the weekend and the rest follow in December, the checkout is already protected against the duplicates peak traffic produces most often. The standard to hold is simple: any request your system receives twice should produce one charge, one refund and one email.

Frequently asked questions about idempotency keys

What is an idempotency key?

An idempotency key is a unique value a client sends with a request that changes state, such as creating a payment. The server stores the first outcome under that key and returns the same outcome for any retry carrying it, so a repeated request cannot create a second charge, order or refund.

Should the client or the server generate the idempotency key?

The client should generate it, because only the client knows which attempts belong to the same intent. Create it when the action begins (for example, when the payment step renders), reuse it on every retry, and replace it after success. The server generates its own derived keys for the calls it makes to providers such as Stripe.

How long should I store idempotency keys?

Store them for longer than the longest retry window that can reach you. Twenty-four hours suits user-driven API requests and matches Stripe's minimum. Webhook event ids need longer: Stripe retries for up to three days in live mode, so keep processed ids for at least that long.

Do I still need idempotency keys if I disable the pay button after a click?

Yes. Disabling the button only prevents one source of duplicates. Timeouts, network reconnects, proxies, queues and the server's own retries to the payment provider all resend requests without the button being involved.

Is the Shopify @idempotent directive required?

It is required for 17 inventory and refund mutations, including refundCreate and inventoryAdjustQuantities, from Admin API version 2026-04. The schema does not mark it as required, but calls without it fail at runtime. On 2026-01 it is optional until that version is retired.

Can I use Redis instead of Postgres for idempotency keys?

Redis works well as a fast first check, using SET key value NX with an expiry. Keep the durable record in the same database as your orders, though, so the key claim and the business data can be committed in one transaction and survive a cache flush.

Keep reading

All articles