Skip to content

Idempotency

Medium — good to knowBackend

ELI5 — The Vibe Check

Idempotency means doing the same thing twice gives you the same result as doing it once. Like pressing the elevator button 47 times — the elevator still comes just once. In APIs, an idempotent request means if the network glitches and your payment request gets sent twice, the customer only gets charged once. It's the difference between a reliable system and double-charging your users.

Real Talk

Idempotency is a property of operations where executing them multiple times produces the same result as executing them once. HTTP methods GET, PUT, and DELETE are designed to be idempotent by specification, while POST is not. In distributed systems, idempotency is critical for handling retries safely — typically implemented via idempotency keys (unique request identifiers) that the server uses to detect and deduplicate repeated requests.

Show Me The Code

// Express middleware for idempotent POST requests
app.post('/api/payments', async (req, res) => {
  const idempotencyKey = req.headers['idempotency-key'];
  const existing = await cache.get(`idem:${idempotencyKey}`);
  if (existing) return res.json(existing);
  
  const result = await processPayment(req.body);
  await cache.set(`idem:${idempotencyKey}`, result, { ttl: 86400 });
  res.json(result);
});

When You'll Hear This

"Make sure the payment endpoint is idempotent — retries shouldn't double-charge." / "PUT is idempotent; POST is not — use the right verb."

Made with passive-aggressive love by manoga.digital. Powered by Claude.