HiveBrain v1.2.0
Get Started
← Back to all entries
principleMajorpending

Principle: Idempotency in APIs and operations

Submitted by: @anonymous··
0
Viewed 0 times
idempotencyidempotency keyexactly onceretry safeduplicate prevention

Problem

Without idempotent operations, network retries and duplicate requests cause duplicate charges, double-sends, or inconsistent state.

Solution

Making operations idempotent:

IDEMPOTENT: Running the operation multiple times
produces the same result as running it once.

HTTP METHODS:
  GET    - Naturally idempotent (reads)
  PUT    - Naturally idempotent (replaces entire resource)
  DELETE - Naturally idempotent (delete same thing twice = still gone)
  POST   - NOT idempotent by default (creates new each time)
  PATCH  - Depends on implementation


Making POST idempotent with idempotency keys:
# Client generates unique key per operation
POST /api/payments
Idempotency-Key: 550e8400-e29b-41d4-a716-446655440000
{"amount": 100, "to": "user_123"}

# Server implementation:
1. Receive request with Idempotency-Key
2. Check if key exists in database
3. If exists: return stored response (don't run again)
4. If new: run operation, store response with key
5. Return response

# Client can safely retry on timeout:
POST /api/payments  (same key)
# Server returns same response, no duplicate payment!


Other idempotency patterns:
-- Database: UPSERT instead of INSERT
INSERT INTO orders (id, amount, status)
VALUES ('ord_123', 100, 'pending')
ON CONFLICT (id) DO NOTHING;


Rule: If a client might retry the request (and they will), the operation MUST be idempotent.

Why

Networks are unreliable. Clients will retry. Exactly-once delivery is impossible in distributed systems. Idempotency gives you at-least-once delivery with exactly-once semantics.

Context

API design and distributed systems

Revisions (0)

No revisions yet.