What Is Idempotency? Reliable API Design
Does double-clicking the payment button charge twice? Does a retry after a network error create a duplicate order? Idempotency ensures repeating the same operation is safe.
Definition
An operation is idempotent if calling it multiple times with the same input produces the same result.
HTTP Method Idempotency
| Method | Idempotent | Notes | |--------|-----------|-------| | GET | ✅ | Reads data | | PUT | ✅ | Full resource update | | DELETE | ✅ | Already deleted = no-op | | POST | ❌ | May create duplicates |
Idempotency Keys
Make POST requests idempotent with a unique key:
// Client
fetch('/api/payments', {
headers: { 'Idempotency-Key': 'pay_abc123' },
body: JSON.stringify({ amount: 1500 })
});
// Server
async function processPayment(req) {
const key = req.headers['idempotency-key'];
const existing = await redis.get(`idempotency:${key}`);
if (existing) return JSON.parse(existing); // Return same result
const result = await paymentGateway.charge(req.body);
await redis.set(`idempotency:${key}`, JSON.stringify(result), 'EX', 86400);
return result;
}
Idempotent Patterns
- Upsert — INSERT ON CONFLICT UPDATE
- Conditional Update — Check transaction ID before modifying
- Deduplication — Track processed message IDs
When Is Idempotency Required?
- ✅ Payment processing | ✅ Order creation | ✅ Email sending
- ✅ Message queue consumers | ✅ Webhook handlers
Best Practices
- Support idempotency keys on all POST endpoints
- Client generates the key (UUID)
- Cache results with 24-48h TTL
- Handle race conditions with mutex
- Log duplicate requests for monitoring
Conclusion
Idempotency is fundamental to distributed system reliability. Network failures, retries, and double-clicks are inevitable — your system must handle them safely.
Learn idempotency and API design on LabLudus.