DEV Community

Cover image for Engineering Out Duplicate Charges: Idempotency, State, and Reconciliation
Jarrod Wright for Chargebacks911

Posted on AI-assisted

Engineering Out Duplicate Charges: Idempotency, State, and Reconciliation

Most chargeback advice is aimed at operations teams: write clearer descriptors, answer the phone, refund quickly. One category is mostly an engineering problem, though: the duplicate charge.

A customer who is billed twice for one order has a legitimate complaint. Card networks treat it as a processing error. Visa, for example, has a dispute condition for duplicate processing. These disputes are usually not worth fighting because the customer is right. The only good strategy is to make sure the second charge never happens, and to catch it yourself before the cardholder does.

The broader operational checklist is covered in this guide to preventing Visa disputes, which recommends reviewing transaction logs so each sale is submitted only once. This article looks at how to enforce that rule in code.

Where duplicate charges actually come from

Duplicates rarely come from one obvious bug. They come from retries that are reasonable on their own but unsafe together.

Source What happens
Client double-submit The user clicks Pay twice, or the mobile app retries on a flaky network.
Client timeout + retry The browser gives up after 30s, but the server finished the charge. The user tries again.
Server-to-PSP timeout Your backend calls the payment provider, the socket times out, and you retry. The first request had already succeeded.
At-least-once queues A job worker crashes after charging but before acking. The message is redelivered.
Webhook redelivery A payment succeeded webhook arrives twice and each copy triggers a capture or fulfillment step.
Batch resubmission A POS or batch file is re-sent after a partial failure, and settled items go through again.

All of these share one root cause: a network failure leaves the caller unsure whether the operation happened. The fix is to make retries safe, not to stop retrying.

Layer 1: Derive the idempotency key from intent

Many payment provider APIs accept an idempotency key, often sent as an Idempotency-Key HTTP header. The IETF HTTPAPI working group has a draft standardizing this header. The provider stores the first response for that key and returns it on repeats instead of charging again.

The common mistake is generating the key per request:

# WRONG: every retry gets a fresh key, so every retry is a new charge
key = str(uuid.uuid4())
psp.charge(amount, card, idempotency_key=key)
Enter fullscreen mode Exit fullscreen mode

The key must identify the business intent, not the HTTP attempt. Derive it from data that is stable across retries:

def charge_key(order_id: str, attempt_group: int) -> str:
    # attempt_group increments only when the user deliberately
    # retries with a new card or amount after a decline
    return f'order:{order_id}:charge:{attempt_group}'
Enter fullscreen mode Exit fullscreen mode

If the user's card is declined and they enter a new card, that is a new intent, so increment attempt_group. If the network dropped, it is the same intent, so reuse the key.

Also check how long your provider keeps idempotency keys. Retention windows are finite. A retry that happens days later, for example from a stuck queue, may not be protected by the provider at all. That is why you need the next layer.

Layer 2: Own the state locally

Never rely only on the provider for deduplication. Keep a payment record with a database-enforced uniqueness constraint and an explicit state machine.

CREATE TABLE payment_attempts (
  id              BIGSERIAL PRIMARY KEY,
  order_id        TEXT NOT NULL,
  idempotency_key TEXT NOT NULL UNIQUE,
  amount_minor    BIGINT NOT NULL,
  currency        CHAR(3) NOT NULL,
  state           TEXT NOT NULL CHECK (state IN
                   ('pending','authorized','captured','failed','unknown')),
  psp_reference   TEXT,
  created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- At most one successful capture per order
CREATE UNIQUE INDEX one_capture_per_order
  ON payment_attempts (order_id) WHERE state = 'captured';
Enter fullscreen mode Exit fullscreen mode

The partial unique index is the important part. Even if application logic fails, the database will reject a second captured row for the same order.

The charge flow then looks like this:

def charge_order(order, attempt_group):
    key = charge_key(order.id, attempt_group)

    row = db.insert_or_get(
        'payment_attempts',
        idempotency_key=key, order_id=order.id,
        amount_minor=order.total_minor, currency=order.currency,
        state='pending')

    if row.state in ('authorized', 'captured'):
        return row                      # already done, return the same result
    if row.state == 'unknown':
        return resolve_unknown(row)     # never fire blind

    try:
        resp = psp.authorize(order.total_minor, order.currency,
                             idempotency_key=key, timeout=20)
    except (Timeout, ConnectionError):
        db.update(row.id, state='unknown')
        return resolve_unknown(row)

    db.update(row.id, state='authorized' if resp.ok else 'failed',
              psp_reference=resp.reference)
    return db.get(row.id)
Enter fullscreen mode Exit fullscreen mode

The unknown state is the whole point

When a call times out, you do not know whether the money moved. Treating that as failed and letting the user retry with a new key is exactly how duplicates happen.

resolve_unknown should either retry with the same key, which is safe while the provider still remembers it, or look up the transaction using your own reference, such as the order ID in metadata. Only mark the attempt failed once you have confirmed it.

Layer 3: Make webhook handlers idempotent

Webhooks are typically delivered at least once. Your handler must accept the same event twice without side effects.

def handle_event(event):
    with db.transaction():
        inserted = db.execute(
            'INSERT INTO processed_events (event_id) VALUES (%s) '
            'ON CONFLICT DO NOTHING', [event.id]).rowcount
        if not inserted:
            return 200          # already handled
        apply_event(event)       # state transition, same transaction
    return 200
Enter fullscreen mode Exit fullscreen mode

Recording the event ID and applying the state change in one transaction matters. If you mark the event processed and then crash before applying it, you lose the event. If you apply it and then crash before marking it, you apply it twice.

Also make apply_event a guarded state transition, for example UPDATE ... SET state='captured' WHERE id=%s AND state='authorized', so out-of-order events cannot move a payment backward.

Layer 4: Reconcile against settlement data

Prevention will not be perfect. A legacy integration, a manual terminal entry, or a resubmitted batch can still get through. Reconciliation is your detection layer, and it should run before the cardholder's statement arrives.

Pull the provider's settlement or transaction report daily and compare it to your ledger:

def find_suspected_duplicates(settled, window_hours=48):
    groups = defaultdict(list)
    for txn in settled:
        # card_fingerprint: a provider token for the card, never the PAN
        groups[(txn.card_fingerprint, txn.amount_minor, txn.currency)].append(txn)

    flagged = []
    for txns in groups.values():
        txns.sort(key=lambda t: t.settled_at)
        for a, b in zip(txns, txns[1:]):
            close = (b.settled_at - a.settled_at) <= timedelta(hours=window_hours)
            same_order = a.order_id and a.order_id == b.order_id
            if same_order or (close and not b.order_id):
                flagged.append((a, b))
    return flagged
Enter fullscreen mode Exit fullscreen mode

Two checks are useful:

  1. Hard duplicates: two settled charges linked to the same order ID. This is almost always a bug, so auto-refund the second one and alert.
  2. Soft duplicates: same card, same amount, close together, with no distinct order behind the second charge. Send these to human review, since repeat purchases are legitimate.

Also check for orphans, meaning settled charges with no matching ledger row. Orphans often come from timeouts your system recorded as failures.

Decision table: what to do on each outcome

Outcome of charge call Local state Safe action
2xx, approved authorized Proceed to fulfillment
2xx, declined failed Allow retry with new attempt_group
4xx validation error failed Fix input; new intent if amount or card changes
409 / idempotency conflict unchanged Another request with this key is in flight or used different params; do not retry with a new key
Timeout / connection reset unknown Retry same key or look up by reference
5xx unknown Same as timeout; never treat as failure

Common mistakes and how to catch them

  • Random keys per attempt. Grep for UUID generation near charge calls. Keys should come from order data.
  • Treating timeouts as declines. Search your code for exception handlers around provider calls that set state to failed.
  • Disabling the Pay button as the only protection. That helps the UX, but a client-side guard is not a server-side guarantee.
  • Webhook handlers that fulfill without checking state. Send the same event twice in a test.
  • Capturing in two places. For example, both a webhook and a shipping job call capture. Pick one owner for the capture transition.

Tests worth writing

def test_timeout_then_retry_charges_once(fake_psp):
    fake_psp.succeed_then_timeout()        # charge lands, response is lost
    with pytest.raises(PaymentPending):
        charge_order(order, attempt_group=1)
    charge_order(order, attempt_group=1)   # user retries
    assert fake_psp.successful_charges(order.id) == 1

def test_concurrent_submits_charge_once(fake_psp):
    run_in_parallel(lambda: charge_order(order, 1), n=10)
    assert fake_psp.successful_charges(order.id) == 1
Enter fullscreen mode Exit fullscreen mode

The concurrency test often exposes read-then-insert races that a unique constraint would have prevented.

Summary

Duplicate charges come from ambiguity after failures, not from a single bug. Use four layers: intent-derived idempotency keys, a local state machine with database constraints, idempotent webhook handling, and daily reconciliation against settlement data. Together they turn "check your transaction logs" into a guarantee you can test.

Top comments (0)