Implementing Idempotency Patterns

1. Understanding Idempotent Operations

HTTP MethodIdempotentSafe
GETYesYes
PUTYesNo
DELETEYesNo
POSTNo (default)No
PATCHConditionalNo

2. Implementing Idempotency Keys

Example: Idempotency-Key middleware

@PostMapping("/payments")
public PaymentResponse charge(
        @RequestHeader("Idempotency-Key") String key,
        @RequestBody PaymentRequest req) {
    return idempotencyStore.computeIfAbsent(key,
            () -> paymentSvc.execute(req),
            Duration.ofHours(24));
}
PropertyDetail
Key formatClient-generated UUID per logical op
Storage TTL24h-7d typical (Stripe = 24h)
ConflictSame key, different body → 409

3. Implementing Deduplication Strategies

StrategyMechanism
Message ID setTrack processed IDs in Redis/RDBMS
Bloom filterProbabilistic, space-efficient
Content hashSHA-256 of payload
Sequence numbersPer-producer monotonic
Window-basedTime-bounded dedup window

4. Handling Retries with Idempotency

PatternDetail
Same idempotency key on retryServer returns cached response
Exponential backoff + jitterAvoid thundering herd
Bounded attempts3-5 with circuit breaker
Distinguish retriable5xx/timeouts retry; 4xx do not

5. Implementing Idempotent APIs

TechniqueDetail
Natural keysUse business id (orderNumber)
Conditional headersIf-Match, If-None-Match
PUT for createClient-supplied id
Idempotency-Key headerStripe convention

6. Understanding Natural vs Artificial Idempotency

Natural

  • Inherent to operation (set value to X)
  • No extra state needed
  • Examples: PUT, DELETE by id

Artificial

  • Added via key + dedup store
  • Requires storage and TTL
  • Examples: payment charge, send email

7. Implementing Idempotency Token Storage

StoreTrade-offs
Redis (TTL keys)Fast; eviction risk
RDBMS tableDurable; slower
DynamoDB TTL itemsManaged expiry; cost per op
Distributed cache + DB fallbackHybrid for hot/cold

8. Handling State Management for Idempotency

StateAction
In progressBlock / return 409 conflict
CompletedReturn cached result
FailedAllow retry with same key
ExpiredTreat as new

9. Implementing Time-Based Deduplication

ApproachDetail
Sliding windowLast N minutes deduped
Tumbling windowPer fixed interval
WatermarkDrop events older than threshold

10. Understanding Idempotency Trade-offs

ProCon
Safe retriesStorage overhead per request
Simpler error handlingTTL boundary edge cases
Enables exactly-once semanticsRequires client cooperation