Idempotency and Distributed Locks

Distributed systems often retry operations because networks and services can fail. Idempotency ensures that processing the same logical operation more than once does not produce unintended duplicate effects.

Distributed locks can coordinate work across multiple processes, but they must be designed carefully around expiration, ownership, failure, and clock assumptions.

Idempotency-Key Concept
const key = req.headers['idempotency-key'];

if (!key) {
  return res.status(400).json({ error: 'Idempotency-Key required' });
}

const existing = await store.get(key);
if (existing) {
  return res.status(existing.status).json(existing.body);
}

const result = await createPayment(req.body);
await store.set(key, result, { ttl: 86400 });

res.status(201).json(result);
💡 The idempotency key lets repeated requests return the original result instead of creating duplicate side effects.
Key Takeaways
  • Idempotency is critical when clients or infrastructure may retry requests.
  • Use unique operation identifiers for side-effecting workflows.
  • Distributed locks require careful failure and expiration handling.
Knowledge Check

What problem does an idempotency key help solve?