• System Design
  • πŸ” Idempotency in API Design: A Must-Know Concept

    In distributed systems, one truth stands above all:

    πŸ‘‰ Failures will happen. Retries are inevitable.

    But here’s the real challenge:

    What happens when the same request is executed multiple times?

    • Duplicate payments
    • Multiple orders
    • Inconsistent state

    This is where idempotency becomes a critical concept in API design.


    🧠 What is Idempotency?

    An operation is idempotent if:

    Performing it multiple times produces the same result as performing it once.


    🧾 Simple Example

    DELETE /users/123
    
    • First call β†’ deletes user
    • Second call β†’ user already deleted

    πŸ‘‰ Result is the same: user does not exist

    βœ” This is idempotent


    ❌ Non-Idempotent Example

    POST /orders
    
    • First call β†’ creates order #1001
    • Second call β†’ creates order #1002

    πŸ‘‰ Duplicate orders = big problem


    πŸ”₯ Why Idempotency Matters in Real Systems

    In production, retries happen due to:

    • Network timeouts
    • Service failures
    • Client retries
    • Load balancer retries

    Tools like NGINX or AWS Elastic Load Balancer may retry requests automatically.

    πŸ‘‰ Without idempotency, retries can corrupt your data.


    ⚠️ Real-World Failures

    πŸ’Έ Duplicate Payments

    A payment request is retried:

    POST /payments
    

    πŸ‘‰ Without idempotency:

    • Customer gets charged twice

    πŸ›’ Duplicate Orders

    User clicks β€œBuy” multiple times:

    πŸ‘‰ System creates multiple orders


    πŸ“‰ Trading Systems

    In a trading platform:

    POST /execute-trade
    

    πŸ‘‰ Duplicate execution = real financial loss


    🧩 HTTP Methods and Idempotency

    MethodIdempotent?Why
    GETβœ… YesRead-only
    PUTβœ… YesReplaces resource
    DELETEβœ… YesRemoves resource
    POST❌ NoCreates new resource
    PATCH❌ UsuallyPartial updates

    πŸ‘‰ The biggest challenge is making POST operations idempotent.


    πŸ—οΈ How to Design Idempotent APIs

    πŸ”‘ 1. Idempotency Keys (Most Important Pattern)

    Client sends a unique key:

    POST /payments
    Idempotency-Key: abc123
    

    πŸ” How It Works

    1. Server receives request with key
    2. Stores the result (DB or cache)
    3. If same key is reused:
      • Return same response
      • Do NOT reprocess

    πŸ§ͺ Example Flow

    Client β†’ POST /payments (key=abc123)
            β†’ Payment processed
    
    Client retries β†’ same key
            β†’ Server returns cached response
    

    βœ” No duplicate payment
    βœ” Safe retries


    🧰 Implementation Strategies

    1. Database Constraint

    • Unique key per request
    • Reject duplicates

    βœ” Simple
    ❌ Doesn’t return original response


    2. Cache-Based (Best Practice)

    Use Redis:

    • Store key + response
    • Add TTL (e.g., 24 hours)

    βœ” Fast
    βœ” Scalable


    3. Hash-Based Requests

    • Generate hash from request body
    • Use as idempotency key

    βœ” Automatic
    ❌ Risk of collisions (rare but possible)


    βš™οΈ Real Backend Example

    πŸ’³ Payment API

    POST /payments
    Idempotency-Key: user123-transaction456
    

    Server logic:

    1. Check if key exists
    2. If not:
      • Process payment
      • Store response
    3. If exists:
      • Return stored response

    πŸ“Š Internal Microservices

    Even internal calls need idempotency:

    Order Service β†’ Payment Service
    

    πŸ‘‰ If retry happens, system remains consistent.


    ⚠️ Common Mistakes

    ❌ Ignoring Idempotency in Critical Flows

    • Payments
    • Orders
    • Financial transactions

    πŸ‘‰ These MUST be idempotent.


    ❌ Storing Only the Key

    πŸ‘‰ You must store:

    • Request result
    • Status
    • Response

    ❌ Infinite Storage

    πŸ‘‰ Always use TTL:

    • Prevent memory leaks
    • Clean old keys

    🧠 Design Insight

    Idempotency is not just a backend concernβ€”it’s a system-wide guarantee.

    πŸ‘‰ It works together with:

    • Retries
    • Message queues
    • Event-driven systems

    In tools like Apache Kafka, idempotency is essential to avoid duplicate event processing.


    πŸš€ Advanced Pattern: Idempotent Consumers

    In event-driven systems:

    • Messages may be delivered multiple times
    • Consumers must handle duplicates

    πŸ‘‰ Solution:

    • Track processed message IDs
    • Ignore duplicates

    πŸ’‘ Final Thoughts

    Idempotency is one of those concepts that separates mid-level engineers from senior engineers.

    Without it:

    • Systems break under retries
    • Data becomes inconsistent

    With it:

    • Systems become safe, predictable, and resilient

    πŸ‘‰ If your system handles money, orders, or critical data:

    Idempotency is not optionalβ€”it’s mandatory.

    3 mins