Free

Payments · E-commerce · Reliability

A double-click, a retry, or a flaky network is all it takes to create two orders. How a client-generated checkout key, stored server-side, turns an at-least-once world into an exactly-once outcome.
November 25, 2026·8 min read·By Abhay Chauhan (Full Stack Developer)

Double Charges Are a Design Smell: Idempotency at the Payment Boundary

#Payments#E-commerce#Reliability#API Design#Distributed Systems#Security
The short answer: Order creation is not naturally idempotent: the same request sent twice creates two orders. The fix is an idempotency key — a unique checkout ID generated once per cart, stored client-side and sent with every submission. The server searches existing orders for that key before creating a new one and, on a hit, returns the existing order instead of creating another. Clear the key only after a confirmed success.

A user clicked "Place order" twice. Two orders appeared. Both were charged.

This is not a user error, and it is not a rare edge case. It is the default behavior of any system that treats a POST as a one-to-one mapping between request and side effect. Networks retry, browsers retry, users retry, and tabs duplicate. If your order endpoint is not idempotent, you are running an at-least-once system with exactly-once assumptions.


1. The key must be generated once, not per attempt

The first decision is where the key lives. If you generate a fresh UUID inside the submit handler, every retry gets a new key and nothing is deduplicated. The key must be created once per checkout session and reused:

ts
useEffect(() => {
  const existing = localStorage.getItem('wc_checkout_id');
  if (existing) {
    setCheckoutId(existing);
    return;
  }
  const id = typeof crypto !== 'undefined' && crypto.randomUUID
    ? crypto.randomUUID()
    : `${Math.random().toString(36).slice(2)}${Math.random().toString(36).slice(2)}`;
  setCheckoutId(id);
  localStorage.setItem('wc_checkout_id', id);
}, []);

The fallback matters: crypto.randomUUID requires a secure context, and a plain HTTP staging host would otherwise crash the checkout.


2. The server checks before it creates

The second half is the server-side lookup. Before constructing the order, search existing orders for the key:

ts
const checkoutId = form.get('checkout_id');
if (checkoutId) {
  const res = await fetch(`${base}/orders?search=${checkoutId}`, { headers: auth });
  if (res.ok) {
    const orders = await res.json();
    if (orders.length > 0) {
      return { success: true, orderId: orders[0].id, ... }; // same shape as success
    }
  }
}

On a hit, return the existing order with exactly the same response shape as a fresh success. The caller should not be able to tell that a retry occurred.


3. Persist the key with the order

When creating the order, write the key into its metadata:

ts
meta_data: checkoutId ? [{ key: '_checkout_id', value: checkoutId }] : []

This is what makes the lookup possible in the first place. The metadata is the durable link between a client attempt and a server-side side effect.


4. Clear the key at exactly the right moment

ts
if (result.success && result.orderId) {
  clearCart();
  localStorage.removeItem('wc_cart_token');
  localStorage.removeItem('wc_checkout_id');
  // redirect to payment
}

Clear the key only after confirmed success. Clearing it on a network error, or before the order is confirmed, reopens the window for a duplicate. After success, the key has done its job — and leaving it around would cause a later unrelated checkout to be deduplicated into the old order.


5. What this pattern does not solve

Be honest about the boundaries:

  • A search-then-create race between two truly concurrent requests with the same key is still possible unless the backend enforces uniqueness on _checkout_id. Add that constraint if your platform supports it.
  • The key is client-generated, so a malicious client can supply any value. Treat it as a deduplication token, not a security credential.
  • If the search fails transiently and you proceed to create, you may still create a duplicate. Fail closed on lookup errors if the stakes are high.

6. Defense in depth

LayerWithout idempotencyWith idempotency key
Double clickTwo ordersOne order, second returns first
Network retryTwo ordersDeduped by key
Two tabsTwo ordersSame stored key
Failure pathUnclear stateKey retained for safe retry
Backend guaranteeNoneMetadata + unique constraint

How to make order creation idempotent

  1. Generate one key per checkout and persist it client-side.
  2. Send it with every order submission.
  3. Search for an existing order with that key before creating.
  4. Return the existing order on a hit, in the same response shape.
  5. Clear the key only after confirmed success.

Frequently asked questions

Is disabling the submit button enough? No. It improves UX but does not handle network retries, timeouts or a second tab. Idempotency is a server-side guarantee.

Should the key be a UUID? A UUID is a good default, but you need a fallback for non-secure contexts where crypto.randomUUID is unavailable.

Can a user abuse the key? They can choose values, but that only affects their own deduplication. Never treat a client key as authorization.

What if two requests with the same key arrive simultaneously? Only a backend uniqueness constraint on the key can fully prevent that. The application-level check is a strong practical mitigation.


Key takeaways

  • Assume at-least-once delivery; make order creation idempotent.
  • Generate the key once per checkout, not per attempt.
  • Store it in both the client and the order metadata.
  • Return the original result on a key hit.
  • Clear the key only after confirmed success.

Summary

You cannot stop users and networks from retrying. You can make retries harmless. One key, one lookup and one rule about when to clear it turn a double-charge bug into a non-event.


References

  • Stripe API documentation — idempotent requests.
  • IETF draft — the Idempotency-Key HTTP header field.
  • MDN Web Docs — crypto.randomUUID().

Got something you're building?