Module 6 — Reliability

Idempotency

Make operations safe to retry. Doing it twice has same effect as doing it once.

1The Elevator Button Analogy

💡 Simple Analogy
Pressing an elevator button 5 times doesn't call 5 elevators—it's the same as pressing once. The button is idempotent.

Compare to a vending machine: pressing the button twice charges you twice. Not idempotent!

2Why It Matters

In distributed systems, requests can be duplicated:

Client timeout → retry → server processed both
Network hiccup → message delivered twice
User double-clicks submit button
Queue retry after failure

Without idempotency: double charges, duplicate orders, corrupted data!

3Idempotent vs Non-Idempotent

Naturally Idempotent

  • GET: Read data
  • PUT: Set value to X
  • DELETE: Remove resource
  • Set field to value

Not Naturally Idempotent

  • POST: Create new resource
  • Increment counter
  • Add to balance
  • Send email/notification

4Making Operations Idempotent

Idempotency Key

Client sends unique ID. Server checks if already processed.

Header: Idempotency-Key: abc123 → Server stores abc123 in Redis with result

Upsert Pattern

INSERT or UPDATE based on existence. Same outcome regardless of state.

INSERT ... ON CONFLICT UPDATE

Versioning

Include version number. Only process if version matches.

UPDATE ... WHERE version = 5 → Increment version

Natural Idempotency

Design operation to be idempotent by nature.

'Set balance to $100' instead of 'Add $50'

5Implementation Example

Idempotency Key Pattern
async function processPayment(idempotencyKey, amount) {
  // Check if already processed
  const existing = await redis.get(`payment:${idempotencyKey}`);
  if (existing) {
    return JSON.parse(existing); // Return cached result
  }
  
  // Process payment
  const result = await chargeCard(amount);
  
  // Cache result (TTL 24 hours)
  await redis.setex(
    `payment:${idempotencyKey}`,
    86400,
    JSON.stringify(result)
  );
  
  return result;
}

// Same request twice → same result, charged once

6Key Takeaways

1Idempotent: doing it twice has same effect as once.
2Critical for safe retries in distributed systems.
3GET, PUT, DELETE are naturally idempotent. POST is not.
4Use idempotency keys for non-idempotent operations.
5Design APIs to be idempotent from the start.
6In interviews: explain how you'd handle duplicate payments or double-orders.