## 🚀 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);
```
View passport
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?