Idempotency is Critical
Make operations safe to retry. Essential for distributed systems, retries, at-least-once delivery.
In distributed systems, messages/requests can be duplicated:
Problem: Without idempotency, retries create duplicates!
Solution: Idempotency - Make operations safe to retry!
An idempotent operation is one that produces the same result when executed multiple times with the same input. In other words, calling it once has the same effect as calling it N times.
In distributed systems, operations can be retried due to network failures, timeouts, or system crashes. Without idempotency, retries can cause:
Idempotency makes operations safe to retry - if a request is retried, it produces the same result as the first attempt, preventing duplicates and ensuring consistency.
f(f(x)) = f(x)
Calling the function twice = calling once.
Idempotent Operations:
GET /users/123 - Always returns same userPUT /users/123 - Replaces user (same result)DELETE /users/123 - Deletes user (same result if already deleted)SET balance = 100 - Sets to 100 (same result)Non-Idempotent Operations:
POST /orders - Creates new order each timebalance = balance + 50 - Adds 50 each timesend_email() - Sends email each timeClient provides unique key. Server checks if seen before.
How it works:
Ensures message processed exactly once.
For multiple servers, use shared storage (Redis/Database):
Always provide idempotency keys for mutating operations:
POST /ordersIdempotency-Key: abc123-xyz789Content-Type: application/json
{ "user_id": 456, "amount": 99.99 }Client generates unique key:
Cache results with keys:
Always check key before processing:
Design operations to be idempotent:
Idempotency is Critical
Make operations safe to retry. Essential for distributed systems, retries, at-least-once delivery.
Idempotency Keys
Use unique keys to detect duplicates. Check before processing. Cache results. Return cached on duplicate.
Exactly-Once
Exactly-once requires idempotency + deduplication. Track processed messages. Use distributed storage for multiple servers.
Store Results
Cache successful results with keys. Don’t cache failures. Set TTL. Check before processing.