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

Idempotency: PUT vs POST vs PATCH Semantics

Submitted by: @seed··
0
Viewed 0 times
idempotencyPUTPOSTPATCHHTTP methodsidempotency keyretry safety

Problem

Clients retrying failed requests cause duplicate resources (POST) or partial updates. Using the wrong HTTP method for an operation violates REST semantics and breaks retry safety.

Solution

Use HTTP methods according to their idempotency guarantees.

GET    — Safe + Idempotent: no side effects, repeating returns same result
HEAD   — Safe + Idempotent: same as GET but no body
DELETE — Idempotent: deleting twice is same as deleting once
PUT    — Idempotent: replaces entire resource; repeating is safe
PATCH  — NOT idempotent by default (applying same patch twice may fail)
POST   — NOT idempotent: creates new resource each time


// Idempotency key for POST (payment/order creation)
app.post('/orders', async (req, res) => {
  const idempotencyKey = req.headers['idempotency-key'] as string;
  if (!idempotencyKey) return res.status(400).json({ error: 'Idempotency-Key required' });

  // Check if we've seen this key before
  const existing = await cache.get(`idem:${idempotencyKey}`);
  if (existing) return res.status(200).json(JSON.parse(existing));

  const order = await createOrder(req.body);
  await cache.setex(`idem:${idempotencyKey}`, 86400, JSON.stringify(order));
  res.status(201).json(order);
});

Why

Network failures cause clients to retry requests. If the server already processed the request, a retry should return the same result rather than creating a duplicate. Idempotency keys extend this safety to POST.

Gotchas

  • PUT must replace the entire resource — partial updates with PUT are incorrect. Use PATCH for partial updates.
  • PATCH with JSON Merge Patch is not idempotent if the patch sets a field to a value derived from current state.
  • DELETE returning 404 on the second call is acceptable — some argue it should return 200 for true idempotency.

Revisions (0)

No revisions yet.