← Blog'a Dön
ARCHITECTURE

What Is Idempotency? Reliable API & Payment System Design

F. Çağrı Bilgehan23 Ocak 202610 dk okuma
idempotencyapireliabilitydistributed systems

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

  1. Upsert — INSERT ON CONFLICT UPDATE
  2. Conditional Update — Check transaction ID before modifying
  3. Deduplication — Track processed message IDs

When Is Idempotency Required?

  • ✅ Payment processing | ✅ Order creation | ✅ Email sending
  • ✅ Message queue consumers | ✅ Webhook handlers

Best Practices

  1. Support idempotency keys on all POST endpoints
  2. Client generates the key (UUID)
  3. Cache results with 24-48h TTL
  4. Handle race conditions with mutex
  5. 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.

İlgili Yazılar

What Is a Message Queue? Async Communication with RabbitMQ & Kafka

Message queues explained: RabbitMQ, Apache Kafka, async architecture, pub/sub patterns, and event-driven design for scalable systems.

What Is Software Architecture? A Comprehensive Guide

What is software architecture, why does it matter, and how do you learn it? A deep dive into architectural patterns, quality attributes, and the architect's career path.