Implementing Idempotency Logic

1. Understanding Idempotent Operations

ConceptDetail
DefinitionSame effect regardless of repeats
Naturally idempotentGET, DELETE, PUT
Needs keyPOST creating resource
Why criticalNetwork retries, at-least-once delivery

2. Implementing Idempotency Key Validation

ValidationDetail
HeaderIdempotency-Key
FormatUUID or opaque ≤ 255 chars
Required forPOST mutations
Reject ifEmpty / malformed

3. Implementing Idempotency Key Storage

FieldDetail
keyUnique by (tenant, key, route)
request_hashDetect mismatched body reuse
statusin_progress / completed
responseCached response payload
created_at, expires_atTTL (24h typical)

4. Implementing Idempotent POST Handler

Example: Handler flow

public Response handle(String key, Request req) {
    var hash = sha256(req.canonicalJson());
    var existing = store.findByKey(key);
    if (existing.isPresent()) {
        if (!existing.get().requestHash().equals(hash))
            throw new ConflictException("idempotency key reused with different body");
        if (existing.get().status() == IN_PROGRESS) throw new ConflictException("in flight");
        return existing.get().response();  // replay
    }
    store.save(new Entry(key, hash, IN_PROGRESS));
    var resp = doWork(req);
    store.complete(key, resp);
    return resp;
}

5. Implementing Response Caching

AspectDetail
CachedStatus code, headers, body
StorageRedis with TTL
ReplayIdentical to original
IndicateAdd header Idempotent-Replayed: true

6. Implementing Retry-Safe Operations

StrategyDetail
Upsert by natural keyINSERT ... ON CONFLICT
Idempotency key in DBUnique constraint
Compensating actionDetect duplicate and reverse

7. Implementing Idempotency Token Expiration

TTLUse Case
24 hoursGeneral API
7 daysPayments (Stripe)
After expiryTreat as new request

8. Implementing Natural Idempotency

PatternExample
Set statePUT user.status = "active"
Check then actIf not exists, create
Unique business keyorder_number constraint

9. Handling Concurrent Idempotent Requests

MechanismDetail
Insert with unique constraintFirst wins; others see existing
Distributed lockSET NX in Redis
Status flagReturn 409 if in_progress

10. Implementing Idempotency Audit Trail

LogDetail
key + actorWho used the key
replay countDetect retry storms
conflict eventsDifferent body for same key

11. Implementing Idempotency Middleware

Example: Spring filter

public class IdempotencyFilter extends OncePerRequestFilter {
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) {
        if (!"POST".equals(req.getMethod())) { chain.doFilter(req, res); return; }
        var key = req.getHeader("Idempotency-Key");
        if (key == null) { chain.doFilter(req, res); return; }
        // ... wrap response, check store, replay or proceed
    }
}

12. Implementing Payment Idempotency

PracticeDetail
Mandatory keyReject without one
Long TTL≥ 24h, often 7 days
Provider idempotencyForward to Stripe/PayPal idempotency-key
Audit immutableNever overwrite payment records