API Reliability: Scenario-Based Questions
79. How do you design idempotent APIs, and why are they important?
Idempotency means that multiple identical requests produce the same effect. This is critical for reliability, especially in network retries, payment APIs, and distributed systems.
π Why Idempotency Matters
- Prevents accidental duplication (e.g., duplicate charges).
- Enables safe retries in case of timeouts or client failures.
- Improves user experience and consistency in distributed environments.
π§± Idempotency in HTTP
- GET, HEAD, PUT, DELETE are naturally idempotent.
- POST is not, but can be made idempotent with proper design.
π§ Techniques to Achieve Idempotency
- Use an
Idempotency-Key
header for POST requests. - Store keys + outcomes in a database/cache for deduplication.
- Ensure side effects (writes, emails, etc.) only occur once.
π¦ Examples
- Stripe API: Requires
Idempotency-Key
for payments to avoid double charges. - Create User: Return existing user if same email is sent twice.
β Best Practices
- Expire idempotency keys after a safe window (e.g., 24h).
- Document idempotency behavior in API docs.
- Return consistent response structure across identical retries.
- Log and monitor for duplicate key usage.
π« Common Pitfalls
- Storing partial results on first failure and retrying without validation.
- Confusing client retries vs retry logic in downstream services.
- Not persisting key outcomes β causing duplicate effects if server restarts.
π Final Insight
Idempotency adds safety and predictability to APIs. Itβs a design discipline that enables better retries, user experience, and system resilience β especially under load or failure.