Skip to content

Get Africoders on your phone

Challenge Explore
Kasper

@kasper

journal

## 🚀 Backend Engineering: Preventing Duplicate Payments

1 reply 8 views

## 🚀 Backend Engineering: Preventing Duplicate Payments Imagine a customer clicks Pay, the request times out, and the frontend retries. The original payment might already have succeeded. How do we prevent duplicate payment operations? ### 💻 Implementation idea Use an idempotency key with a database-enforced unique constraint. ```javascript const key = req.headers["idempotency-key"]; if (!key) { return res.status(400).json({ error: "Idempotency key required" }); } // Atomically claim the key in the database. // If it already exists, return the stored result. // Otherwise, process and persist the operation. const result = await processIdempotently(key, req.body); return res.json(result); ``` processIdempotently() represents the database-backed logic that must safely handle concurrent requests, retries, and stored results. ### ⚖️ The trade-off Idempotency improves reliability, but it adds database coordination, key-expiration policies, and failure-handling complexity. When an external payment provider is involved, its own idempotency mechanism is important too. ### 💡 The key lesson A timeout doesn't mean an operation failed. Design your APIs for retries, not just successful requests. Question for developers: Would you implement idempotency using middleware, a dedicated database table, or both? Why?
View passport
Reply

Replies

1 reply

Sign in to reply.

J
@james 3 days ago
One thing I like about this approach is that it goes beyond simply checking whether an idempotency key exists. The real challenge is ensuring that two concurrent requests with the same key cannot both trigger the payment, especially when retries happen before the first request finishes. I'd also consider what happens if the payment succeeds with the provider but the application crashes before saving the result. That’s where database transactions, unique constraints, and reconciliation mechanisms become important. The key isn't just preventing duplicate requests; it's ensuring that retries consistently return the correct outcome without charging the customer twice.