2 min read
· The MariPay teamImagine your server sends a payment request and the connection drops before the response arrives. Did the payment get created? You cannot tell. If you retry blindly you might charge the customer twice; if you do nothing you might not charge them at all. Idempotency keys solve exactly this.
What an idempotency key is
It is a unique string you generate for one logical operation, such as paying invoice 42, and send in the Idempotency-Key header. The first time we see a key, we perform the operation and remember the result. If the same key arrives again, we return that stored result instead of doing the work a second time.
How to generate and use them
- Use a UUID, or a stable string you can rebuild such as order-42-attempt-1.
- Create the key once, before the first attempt, and store it with your order.
- Reuse the same key on every retry of that same operation.
- Use a new key for a genuinely new operation, like a second payment attempt the customer chose to make.
// one key per logical payment, saved with the order
const key = order.paymentKey ?? crypto.randomUUID()
await db.orders.update(order.id, { paymentKey: key })
async function createPayment() {
return fetch("https://api.maripay.com/api/v1/payments", {
method: "POST",
headers: {
Authorization: "Bearer " + process.env.MARIPAY_SECRET,
"Idempotency-Key": key,
"Content-Type": "application/json",
},
body: JSON.stringify({ amount: order.amount, currency: "UGX", reference: order.id }),
})
}Retrying safely
With a key in place, a retry becomes harmless. If the first request actually succeeded, the retry returns the same payment. If it never arrived, the retry creates it. Either way you end up with exactly one payment, so you can retry on timeouts and network errors without fear.
Common mistakes
- Generating a fresh key on every retry, which defeats the purpose.
- Reusing one key for different amounts or customers. Keys are per operation.
- Skipping the key on writes. MariPay requires it on payment, order and refund creation for this reason.
Idempotency protects your calls to us. Your webhook handler needs the same care in the other direction, because we may deliver an event more than once. Key it on the payment id.
Ready to try it?
Create a free account, grab your sandbox keys and take a test payment in minutes. No verification needed to start testing.