Idempotency & retries

Networks fail mid-request. Idempotency lets you retry safely without ever charging twice.

How it works

  • Pass an idem key (any unique string per logical payment) on money-moving calls like /partner/stk.

  • We record the key. A repeat with the same key returns the original result instead of creating a new charge.

  • Use a new key for each genuinely new payment; reuse the key only when retrying the same one.

Safe-retry pattern

Node.js

const idem = `${orderId}:${attempt}`;   // stable per payment
for (let i = 0; i < 3; i++) {
  const res = await stk({ payer_msisdn, amount, reference, idem });
  if (res.ok) return res.data;             // same charge on every retry
  await sleep(500 * 2 ** i);               // backoff on timeout / 5xx
}

Python

idem = f"{order_id}:{attempt}"
for i in range(3):
    res = stk(payer_msisdn, amount, reference, idem)
    if res.ok:
        return res.data
    time.sleep(0.5 * 2 ** i)

Webhooks are idempotent too

Deliveries can repeat. Always key your webhook handler on charge_ref / TransID so re-processing is a no-op.

Was this page helpful?