advanced

REST idempotency

Handle retries safely with idempotent methods, idempotency keys, conflict detection, request fingerprints, and stored outcomes.

Networks retry. Idempotent operations let clients safely repeat requests without duplicate side effects.

Method semantics:

  • GET, PUT, DELETE are idempotent by HTTP definition.
  • POST is not — use **idempotency keys** for payments, orders, and writes behind unreliable clients.
					POST /payments
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
Content-Type: application/json

{"amount": 1999, "currency": "USD", "orderId": "ord_123"}
				

Server behavior:

  1. First request with key: process and store `{ key, status, response, fingerprint }`.
  2. Retry with same key + same body: return stored response (often 200/201 with original body).
  3. Same key + different body: 409 Conflict.

Fingerprints can hash method, path, body, and auth subject. TTL keys long enough for client retry windows (24–72h common).

On interviews: explain why POST needs keys but PUT might not, how keys interact with DB unique constraints, and race handling with transactions.

Common pitfalls: keys only in memory (lost on restart), no conflict on body mismatch, idempotency without authentication scope, and treating PATCH as idempotent without design.

The trade-off is storage cost for idempotency records versus financial/operational duplicate risk — always worth it for money movement.

Checklist:

  • Idempotency-Key on non-idempotent POST writes.
  • Persist outcomes with TTL.
  • 409 on key reuse with different payload.
  • Scope keys per tenant or user.