Idempotency

A new idempotency key on every retry is a double charge

Your worker dies halfway through a charge. The retry library fires again. Whether that customer gets billed once or twice comes down to one string. Derive it from your own order or cycle ID, never from a UUID minted per retry, and put a second guard in the handler for the webhooks that follow. This is the idempotency material from chapters 4, 7 and 5.

An idempotency key is a unique string a client sends with a request that changes something, so the server can recognize a retry of that request and return the original result instead of doing the work twice. In payments, the work is moving money, which is why every major processor API takes one.

An idempotent API is one where sending the same request twice has the same effect as sending it once. HTTP gives you some of that for free: GET, HEAD, PUT, DELETE and OPTIONS are idempotent by definition, and POST and PATCH aren't. Creating a charge is a POST. The key is how a POST earns a property it doesn't have. There's an IETF draft to standardize an Idempotency-Key header for any HTTP API, though MDN still marks it experimental.

Here's how Stripe's API v1 handles keys, from its API reference:

QuestionStripe API v1
Where the key goesIdempotency-Key header, on POST requests
Maximum length255 characters
What a retry gets backThe saved status code and body of the first request, 500 errors included
Same key, different parametersAn error, not a second charge
Validation failure or a concurrent conflictNothing is saved, so the retry is safe
How long a key lastsIt can be pruned once it's 24 hours old, and after that the same key is a new request
GET and DELETENo effect, they're already idempotent

The 24-hour row is the one that bites. A retry queue that sits on a failed renewal for two days isn't protected by the key anymore, so the code behind it needs its own guard. That's the third excerpt below.

2. Implement Idempotency

The same payment might arrive multiple times due to network issues:

def charge_card(order_id, amount, payment_method_id):
    # Use order_id to prevent double charging
    idempotency_key = f"charge_order_{order_id}"

    return stripe.PaymentIntent.create(
        amount=amount,
        currency='usd',
        payment_method=payment_method_id,
        confirm=True,
        automatic_payment_methods={'enabled': True, 'allow_redirects': 'never'},
        idempotency_key=idempotency_key  # Stripe won't double-charge
    )

Idempotency is what keeps a retried request from charging the same card twice. Always send an idempotency key. Most payment providers support them natively, but implement the check at your application level too.

The mistake, and the one-line fix. From chapter 7.

1. Always Use Idempotency Keys

Every mutating call to your processor (charge creation, subscription creation, refund, plan change) takes an idempotency key. Use it. The key should be deterministic from your domain identifier (the order ID, the subscription event ID), not a fresh UUID every retry. If you generate a new key on each retry, the API treats every call as new and you double-charge.

# WRONG - each retry creates a new charge
def renew(subscription):
    return stripe.Charge.create(
        amount=subscription.amount,
        customer=subscription.customer_id,
        idempotency_key=str(uuid.uuid4()),  # NEW KEY EVERY CALL
    )

# RIGHT - retries are deduplicated
def renew(subscription, cycle_number):
    return stripe.Charge.create(
        amount=subscription.amount,
        customer=subscription.customer_id,
        idempotency_key=f"sub_{subscription.id}_renew_{cycle_number}",
    )

The processor will return the original response on subsequent calls with the same key, even across retries spanning hours. This is the single most important pattern for not double-charging customers when your network blips, your worker dies mid-call, or your retry library is misconfigured. Idempotency-key TTLs are usually 24 hours (Stripe) to indefinite (Adyen) - check your provider.

Implementation: src/examples/7-subscriptions-recurring-billing/subscription_testing.py

The provider key covers the request you send. This covers the webhook that comes back. From chapter 5.

4. Handle Idempotency

Idempotency matters because webhooks get delivered more than once, and your handler has to be fine with that:

def fulfill_order(order_id):
    with transaction.atomic():
        order = Order.objects.select_for_update().get(id=order_id)

        if order.status == 'fulfilled':
            return  # Already processed this webhook

        # Fulfill the order
        order.status = 'fulfilled'
        order.fulfilled_at = datetime.now()
        order.save()

        # Send confirmation email, etc.
        send_order_confirmation(order)

Idempotency is non-negotiable in payment systems. Payment providers will retry webhooks, network issues can cause duplicate deliveries, and race conditions can trigger multiple handlers. Every webhook handler and payment operation must be safe to execute multiple times with the same result.

Questions

What is an idempotency key?

A unique string a client sends with a request that changes something, so the server can recognize a retry of that request and return the original result instead of doing the work twice.

What is an idempotent API?

One where sending the same request twice has the same effect as sending it once. GET, HEAD, PUT, DELETE and OPTIONS are idempotent by definition. POST and PATCH aren't, which is why payment APIs take an idempotency key on them.

Should an idempotency key be a UUID?

A UUID works if you generate it once per operation and store it with the order, which is what Stripe's docs suggest. The bug is a fresh UUID on every retry: the API sees a new key, treats the call as new, and charges again. Deriving the key from your own order or billing-cycle ID skips the storage step. Keep personal data such as email addresses out of it.

How long does Stripe keep an idempotency key?

Stripe can prune a key once it's at least 24 hours old, and a request that reuses a pruned key is treated as new. Don't rely on the key alone for retries that can wait longer than a day.

Do I still need deduplication if I send idempotency keys?

Yes. The key protects the request you send. The webhook that comes back is a separate delivery that providers send at least once, so the handler that fulfills the order needs its own check, like the locked status check in the chapter 5 excerpt.

What the book adds

What chapters 4, 7 and 39 add

  • Key TTLs per provider, 24 hours to indefinite
  • Atomic claims, so two workers cannot race
  • The idempotency store in Redis and Postgres
  • Grace periods when a renewal fails
  • Retry backoff that does not stampede

30-day money-back · Instant PDF and EPUB

All 42 chapters