A brass mechanical stamp pressing a single seal onto a paper envelope on a workbench, representing a donation processed exactly once

Stripe Idempotency Keys: Build Donations That Never Double-Charge

•12 min read

A donor clicks "Give $50", the spinner hangs, they click again, and your server retries a request that timed out. Did you charge them once, twice or not at all? This deep dive shows how to use Stripe idempotency keys, together with your own database constraints and webhook deduplication, to build a donation flow that never double-charges and never loses a gift. The patterns apply to any payment provider; the examples use Stripe because its idempotency rules are well documented.

If you are still deciding which platform or form to use, start with our guide on how to accept donations online with an 8-step GivingTuesday checklist. This article picks up where that one stops: the engineering underneath the button.

Where duplicate donations come from

Duplicates are rarely caused by one bug. They come from several places that each look harmless on their own:

  • The double click. The donor submits twice before the first response arrives, or presses back and resubmits.
  • Client retries. A mobile connection drops, and your front end (or a fetch wrapper) retries automatically.
  • Server retries. Your backend calls the payment API, the call times out, and you do not know whether the charge was created.
  • Webhook redelivery. Design as if every event can arrive more than once and in any order, because your handler can fail after the provider sent it.
  • Scheduled job reruns. A monthly recurring-donation job crashes halfway, gets restarted, and walks the same list of donors again.

An idempotency key solves only the third problem cleanly. The other four need your own data model. That is the main trade-off to understand: the provider's idempotency is a safety net for a single API call, not a design for your whole system.

How Stripe idempotency keys actually behave

Read the Stripe idempotent requests reference before you write any code, because several details change how you should design retries:

  • Stripe saves the status code and body of the first request made with a key, whether it succeeded or failed, and later requests with the same key return that same result, including 500 errors.
  • Keys can be removed once they are at least 24 hours old; if you reuse a key after that, Stripe treats it as a new request.
  • Results are saved only after the endpoint starts executing. If parameters fail validation, or the request conflicts with another one running at the same time, nothing is saved and you can retry.
  • In API v1, all POST requests accept idempotency keys; sending one on GET or DELETE has no effect.

The newer API v2 overview recommends a UUID as the key, notes that Stripe generates one automatically if you do not provide it, and says all POST and DELETE v2 requests accept keys.

Two design consequences follow. First, because a 500 is replayed for the same key, blindly retrying with the same key after a server error does not give you a second chance; you must check what actually happened and decide whether a new attempt is needed. Second, because keys expire, they cannot protect a monthly job that reruns days later. Your database has to do that.

The data model: one row per donation attempt

Model the donation attempt as a first-class record that exists before you call the payment provider. Its unique constraints are what make the system idempotent end to end.

CREATE TABLE donation_attempts (
  id                 uuid PRIMARY KEY,
  idempotency_key    text NOT NULL UNIQUE,      -- generated when the form renders
  donor_email        text NOT NULL,
  campaign_id        text NOT NULL,
  amount_minor       bigint NOT NULL CHECK (amount_minor > 0),
  currency           char(3) NOT NULL,
  status             text NOT NULL DEFAULT 'created',
  payment_intent_id  text UNIQUE,
  created_at         timestamptz NOT NULL DEFAULT now(),
  updated_at         timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE processed_events (
  event_id     text PRIMARY KEY,                -- provider event id
  received_at  timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE recurring_charges (
  plan_id     uuid NOT NULL,
  period      text NOT NULL,                     -- e.g. '2025-12'
  attempt_id  uuid NOT NULL REFERENCES donation_attempts(id),
  PRIMARY KEY (plan_id, period)
);

Keep status as an explicit state machine: created, processing, requires_action, succeeded, failed, refunded. Allowed transitions live in code, and a transition that is not allowed is ignored and logged, not applied.

Generating and scoping the key

The most common mistake is choosing the wrong scope for the key. A key per donor or per session is too broad: a donor who wants to give twice, on purpose, gets blocked or, worse, gets the first donation's result. A random key per HTTP request is too narrow: it does nothing against the double click.

The right scope is one key per donation attempt:

  1. When the form renders, generate a UUID and keep it in the form state.
  2. Send it with every submission of that form, including automatic retries.
  3. If the donor changes the amount, currency or frequency, generate a new UUID. A different donation is a different attempt.
  4. On the server, derive the provider key from your attempt id (for example donation:<attempt_id>) instead of forwarding the browser value directly. That way a malicious client cannot reuse someone else's key namespace.

Creating the attempt and the PaymentIntent

app.post("/donations", async (req, res) => {
  const clientKey = req.header("Idempotency-Key");
  if (!isUuid(clientKey)) return res.status(400).json({ error: "missing key" });
  const input = validateDonation(req.body); // amount_minor, currency, campaign, email

  // 1. Insert the attempt, or find the one this key already created
  let attempt = await db.oneOrNone(
    `INSERT INTO donation_attempts
       (id, idempotency_key, donor_email, campaign_id, amount_minor, currency)
     VALUES ($1, $2, $3, $4, $5, $6)
     ON CONFLICT (idempotency_key) DO NOTHING
     RETURNING *`,
    [uuid(), clientKey, input.email, input.campaignId, input.amountMinor, input.currency]
  );
  attempt ??= await db.one(
    "SELECT * FROM donation_attempts WHERE idempotency_key = $1", [clientKey]
  );

  // 2. Same key, different payload: refuse instead of guessing
  if (attempt.amount_minor !== input.amountMinor || attempt.currency !== input.currency) {
    return res.status(409).json({ error: "key reused with different donation" });
  }

  // 3. Create (or replay) the PaymentIntent with a key derived from the attempt
  const intent = await stripe.paymentIntents.create(
    {
      amount: attempt.amount_minor,
      currency: attempt.currency.toLowerCase(),
      metadata: { attempt_id: attempt.id, campaign_id: attempt.campaign_id },
    },
    { idempotencyKey: `donation:${attempt.id}` }
  );

  await db.none(
    `UPDATE donation_attempts
        SET payment_intent_id = $1, status = 'processing', updated_at = now()
      WHERE id = $2 AND payment_intent_id IS NULL`,
    [intent.id, attempt.id]
  );

  res.json({ clientSecret: intent.client_secret });
});

Notice the layers. The unique constraint absorbs double clicks and client retries. The provider key absorbs server retries within its retention window. The attempt_id in metadata lets you match any provider object back to your row, even if your UPDATE never ran.

Do not mark the donation as paid in this endpoint. The front end confirms the payment, and the result arrives by webhook.

Webhook handling: deduplicate in the same transaction

The webhook is the source of truth for "the money moved". Verify the signature, then record the event id and apply the state change in one database transaction. If the transaction rolls back, the event id is not stored and the redelivery will be processed normally.

app.post("/webhooks/stripe", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    event = stripe.webhooks.constructEvent(
      req.body, req.header("stripe-signature"), process.env.STRIPE_WEBHOOK_SECRET
    );
  } catch {
    return res.status(400).end();
  }

  await db.tx(async (t) => {
    const fresh = await t.oneOrNone(
      `INSERT INTO processed_events (event_id) VALUES ($1)
       ON CONFLICT DO NOTHING RETURNING event_id`,
      [event.id]
    );
    if (!fresh) return; // already handled

    if (event.type === "payment_intent.succeeded") {
      const pi = event.data.object;
      await t.none(
        `UPDATE donation_attempts SET status = 'succeeded', updated_at = now()
          WHERE payment_intent_id = $1 AND status IN ('created', 'processing', 'requires_action')`,
        [pi.id]
      );
      await t.none(
        "INSERT INTO outbox (kind, ref) VALUES ('donation_receipt', $1)", [pi.id]
      );
    }
    // handle payment_intent.payment_failed, charge.refunded, etc.
  });

  res.status(200).end();
});

Two details matter here:

  • Guarded transitions. The WHERE status IN (...) clause means a late payment_failed event cannot overwrite a succeeded donation. Out-of-order delivery becomes harmless.
  • Outbox for side effects. Sending the receipt or thank-you email inside the transaction is a trap: the email goes out, the commit fails, and the retry sends it again. Write an outbox row and let a worker send it, along with slow work such as CRM sync.

Recurring donations: the database is the guard

For monthly giving you can let the provider's subscription engine bill donors, or run your own scheduler that charges saved payment methods. Provider subscriptions remove most of this problem; your own scheduler gives you control over dates, amounts and retries, but you own the idempotency.

If you run your own job, claim the period in your database before charging:

for plan in plans_due(period):
    attempt_id = new_uuid()
    claimed = INSERT INTO recurring_charges (plan_id, period, attempt_id)
              VALUES (plan.id, period, attempt_id)
              ON CONFLICT DO NOTHING
    if not claimed:
        continue                    # charged or in progress in an earlier run
    create donation_attempt(attempt_id, plan)
    create PaymentIntent(off_session, idempotencyKey = "recurring:" + plan.id + ":" + period)

The composite primary key on (plan_id, period) keeps working when the job reruns a week later, long after the provider key may have been pruned.

Failure handling: timeouts and 500s

When the call to create a PaymentIntent fails, classify the failure before retrying:

  1. Network timeout, no response. Retry with the same key. If the first request reached the provider, you get its result; if not, the request runs now.
  2. Conflict with a concurrent request using the same key. Nothing was saved for that key, so retrying with backoff is safe.
  3. 5xx returned. The same key will replay the same error. Look up whether a PaymentIntent exists for this attempt (search by the attempt_id metadata or wait for the reconciliation job). Only if none exists, issue a new provider key such as donation:<attempt_id>:2.
  4. Validation error (4xx). Do not retry. Fix the input and show the donor a clear message.

Then run a reconciliation job, for example hourly, that lists recent payments from the provider and compares them with donation_attempts. Anything paid at the provider but not succeeded locally is a missed webhook; anything processing for too long needs a look.

Idempotency does not stop card testing

Public donation forms with no login are attractive to fraudsters who validate stolen cards with small charges. Idempotency keys do nothing here, because every test uses a new card and a new attempt. A write-up on Stripe card testing attacks points out that, according to Stripe, card testers can use a publishable key to retry a large number of payments, and that these runs usually have a very different country distribution from normal traffic.

Practical defenses that fit the design above:

  • Create attempts only through your server endpoint, with rate limits per IP, per email and per device fingerprint.
  • Add a challenge (CAPTCHA or similar) that activates when the attempt rate rises, so normal donors are not penalized.
  • Set a sensible minimum amount for your campaign; very small amounts are typical of testing.
  • Alert on the ratio of failed to created attempts per hour, not just on revenue.

If your donation flow lives inside a larger product, such as a direct-selling company's store and back office, these controls belong in the same payment layer as everything else. That is the kind of system we design in our custom software development work.

Implementation checklist

  • One donation_attempts row per attempt, created before any provider call.
  • Unique constraint on the client idempotency key; 409 when the payload differs.
  • Provider key derived from your attempt id, not from user input.
  • attempt_id stored in provider metadata.
  • Webhook signature verified on the raw body.
  • Event id inserted and state updated in one transaction.
  • Guarded state transitions that ignore out-of-order events.
  • Outbox for receipts, emails and CRM sync.
  • (plan_id, period) primary key for recurring charges.
  • Retry policy that treats timeouts, conflicts, 5xx and 4xx differently.
  • Scheduled reconciliation against the provider.
  • Rate limits and failure-rate alerts against card testing.

Common mistakes

  • Generating the key on every request. It looks idempotent and protects nothing.
  • Marking donations paid from the browser redirect. The redirect can be lost or forged; the webhook is authoritative.
  • Sending emails inside the webhook transaction. Duplicated receipts are the visible symptom.
  • Using floats for money. Integer minor units only.
  • Testing only the happy path. Kill the process between the provider call and the UPDATE, replay webhooks twice and out of order, and confirm the totals still match.

A donation page is also a web page: speed, form design and accessibility all affect how many donors finish. If you need help on that side, see our website design and development services.

Frequently asked questions

Do I still need my own idempotency if I use Stripe Checkout?

Yes, for the parts you own. A hosted checkout handles the card form, but you still receive webhooks that can be redelivered, and you still create receipts, CRM records and campaign totals. Deduplicate events by id and guard your state transitions.

How long should I keep processed webhook event ids?

At least as long as the provider may redeliver an event, plus a safety margin. Keeping them indefinitely is a reasonable default, since one short row per event is cheap; if you prune, do it with a scheduled job and document the window.

Should the idempotency key come from the client or the server?

Both have a role. The client-generated UUID identifies the donor's intent and absorbs double clicks and retries. The server derives the key it sends to the provider from its own attempt id, so the outbound key is never under user control.

Comments

No comments yet. Be the first to share what you think.

Leave a comment

It is never published.