SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • What is an API?
  • API Styles
  • Idempotency
  • Data Formats
  • REST, GraphQL, gRPC
  • Pagination, Filtering and Sorting
  • API Versioning
  • Error Handling and Status Codes
  • OpenAPI / Swagger
  • Bulk APIs and File Upload
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/API Design

Idempotency

Doing the same request twice should not charge the customer twice.

⏱ 13 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

An operation is idempotent if doing it once or many times gives the same final result.

  • On a flaky network, clients retry. Retries are only safe if the operation is idempotent.
  • Reading, setting a value and deleting are naturally idempotent. “Add ₹100” or “create an order” are not.
  • For those, we add an idempotency key: the server remembers it and does the work only once.

02Concept: What is it?

Idempotent comes from maths: f(f(x)) = f(x). In APIs it means: sending the same request again does not change the result any further.

Idempotent
Safe to repeat
  • “Set the light to ON”
  • “Set my name to Ravi”
  • “Delete order 42”
  • Pressing the elevator call button again
Not idempotent
Repeat = extra effect
  • “Toggle the light”
  • “Add ₹100 to my balance”
  • “Create a new order”
  • Pressing “Pay” twice
🧠Idempotent is about the final state
The reply may differ. The first DELETE returns 204 and the second returns 404. But in both cases the order is gone. The state is the same, so DELETE is idempotent.

Safe vs idempotent

A safe method does not change anything at all (GET). Every safe method is idempotent. But some idempotent methods (PUT, DELETE) do change data, so they are not safe.

03Real-Life Example

🍵The lift button and the vending machine
In a lift, you press the “5” button. Pressing it again does nothing new: you still go to floor 5. Idempotent. At a vending machine, each press of “buy tea” gives another tea and takes more money. Not idempotent.
The lost reply problem
📱Appno reply, so retry
→↓pay ₹100 (1st)
💳Servercharged ₹100
←reply LOST ✖
→↓pay ₹100 (retry)
💳Servercharged ₹100 again!
The payment worked, but the reply got lost. The app does not know, so it tries again.
Everyday
API
Lift button pressed twice
PUT or DELETE sent twice
Vending machine pressed twice
POST sent twice
A ticket number on your receipt
Idempotency key
Shop checks the ticket: “already served”
Server finds the key and returns the saved reply

04Why Do We Need It?

Networks fail. Timeouts happen. The client often cannot know whether its request worked. The only safe move is to retry. Idempotency makes that retry safe.

📶Flaky networks
Mobile users lose signal mid-request.
🖱️Double clicks
Users tap “Pay” twice when the page is slow.
🔁Automatic retries
Clients, load balancers and queues retry on their own.
💸Money safety
Charging twice destroys trust.
📦At-least-once delivery
Queues and webhooks may deliver a message more than once.
🧘Calm systems
You can retry freely without fear.
If something can be retried, it should be safe to retry.

05Where Do We Use It?

💳Payments
Never charge twice for one order.
🛒Order creation
One tap, one order.
📧Sending email / SMS
One reset email, not five.
📬Message consumers
A handler may see the same message twice.
🪝Webhook receivers
Senders retry, so receivers see repeats.
🏦Money transfers
A transfer must not run twice.

HTTP methods and idempotency

MethodMeaningSafe?Idempotent?
GETReadYesYes
HEAD / OPTIONSRead info onlyYesYes
PUTReplace with this valueNoYes
DELETERemoveNoYes
PATCHChange a partNoDepends (“set x=5” yes, “add 5” no)
POSTCreate / run an actionNoNo (add a key to make it so)

06Types / Parts / How It Works

Three ways to make an operation safe to repeat

1. Natural
📝Set, do not addPUT /users/7 {name:"Ravi"}
Design the call so repeats do not matter.
2. Idempotency key
🔑Same key, same resultIdempotency-Key: abc-123
Server remembers the key and the reply.
3. Unique rule
🧱Database blocks duplicatesUNIQUE(order_id)
The second insert is rejected.

How an idempotency key works

Server logic with a key
  1. 1
    Client makes a unique key
    A random UUID, made once per user action, not once per try.
  2. 2
    Client sends the request with the key
    Header: Idempotency-Key: 7f3c-…
  3. 3
    Server looks up the key
    In a fast store (Redis, or a database table).
  4. 4
    New key → do the work, save the reply
    Store key + result atomically (in one step).
  5. 5
    Seen key → return the saved reply
    Do NOT run the work again.
  6. 6
    Same key, different body → reject
    Return 422 / 409: the key is being reused wrongly.
This idea is used by many payment APIs, for example Stripe-style APIs (general idea).
Client Lookup First time Repeat Misuse
VisualizerCharge once or twice?Double-click Pay with the key OFF, then ON. Then compare HTTP methods below.
Idempotency key
📱Shop appsends nothing extra
→↓POST /pay ₹100
💳Payment serverremembers nothing
→↓balance
🏦₹1000started with ₹1000
Press a button to send a payment.
Order number
1
one order = one payment
Payments taken
0
for 0 orders paid
Balance
₹1000
Try Double-click with the key OFF. Then turn the key ON, press New order, and try again.
Which HTTP methods are safe to repeat?
PUT /users/7 { name: Ravi }
send #1 → 200 name set to Ravi
Idempotent. Sets the whole thing to a value. Setting it again gives the same result.

07How to Use It / Steps / Implementation

  1. 1
    Choose idempotent methods when you can
    Prefer PUT (“set to this value”) over POST (“add this”).
  2. 2
    For POST, accept an Idempotency-Key header
    The client makes the key once per user action and reuses it on every retry.
  3. 3
    Check the key first
    Look it up before doing any work.
  4. 4
    Do the work and save the key together
    Use one database transaction, so a crash cannot leave the key saved without the result, or the result without the key.
  5. 5
    Return the saved reply on repeats
    Same status code and body as the first time.
  6. 6
    Keep keys for a limited time
    For example 24 hours. Then delete them to save space.
  7. 7
    Handle two requests at the same time
    Lock the key, or use a UNIQUE index, so only one wins.
Example
POST /payments
Idempotency-Key: 7f3c9a2e-1d4b-4a8e-9c11-5b0e6a3d2f10
Content-Type: application/json

{ "orderId": "A-1001", "amount": 100, "currency": "INR" }

--- 1st call:  201 Created  { "paymentId": "p_55", "status": "paid" }
--- retry:     201 Created  { "paymentId": "p_55", "status": "paid" }   (same, no new charge)
Server idea in pseudocode
def pay(key, body):
    saved = store.get(key)
    if saved:
        if saved.request_hash != hash(body):
            return 422                   # key reused with a different request
        return saved.response            # repeat: no new charge
    with transaction():
        result = charge_card(body)
        store.put(key, hash(body), result)
    return result

08Key Terms to Know

TermMeaning in easy words
IdempotentDoing it many times has the same final effect as doing it once
Safe methodA method that changes nothing (like GET)
RetrySending the same request again after a failure or timeout
Idempotency keyA unique id sent with a request so the server can spot repeats
At-least-onceA message will arrive once or more, so duplicates are possible
Exactly-once effectDuplicates may arrive, but the result happens only once (done with idempotency)
DeduplicationFinding and ignoring repeats
UUIDA long random id that is unique in practice
TTLHow long a stored key is kept before it is deleted
BackoffWaiting longer between each retry, so a struggling server can recover

09Pros, Cons and Trade-offs

✅ Pros
  • Retries become safe
  • No double charges or double orders
  • Works well with queues and webhooks
  • Clients can be simple: “just retry”
⚠️ Cons
  • Server must store keys and replies (storage and cost)
  • Extra code and a lookup on each call
  • Races: two same-key calls at once need locking
  • Keys expire, so very late retries may run again
ChoiceWe gainWe lose
Natural idempotency (PUT, set)No extra storage, simpleNot always possible (“add to balance”)
Idempotency keyWorks for any POSTStorage, lookup, expiry rules
Unique database ruleStrong guaranteeOnly blocks duplicate rows; the error must be handled
No idempotencyLeast workDuplicates and angry users

10Common Problems and Mistakes

Common mistakes

  1. Making a new key on every retry. Then the server sees a different key and charges again. The key belongs to the user action, not the try.
  2. Saving the key after the work, outside one transaction. A crash in between loses the key and the retry runs again.
  3. Ignoring parallel requests. Two requests with the same key at once can both pass the check. Use a lock or a UNIQUE index.
  4. Returning a different reply on repeats. Return the same status and body.
  5. Using POST for “set to” actions. Prefer PUT, which is idempotent by design.
  6. Retrying non-idempotent calls automatically in a client or gateway without a key.
🏁Race
Two same-key calls arrive together.
⌛Key expired
A retry after the TTL looks like a new request.
🧩Partial work
Charge done, email not sent. Plan each step.
🧾Key misuse
Same key with a different body must be rejected.

11Real-World Examples

💳Payment APIs
Many payment providers let you send an Idempotency-Key on payment calls (general idea).
☁️Cloud APIs
Create-resource calls often accept a client token so a retry does not create two.
📬Queue consumers
At-least-once queues mean the consumer must handle repeats.
🪝Webhook receivers
Store each event id and skip ids you have already handled.
🏦UPI-style transfers
A reference id per transaction stops the same transfer running twice (general idea).
🗂️Database upserts
“Insert or update” by a unique id makes repeats harmless.
Mini case: a flaky mobile network
📱Appkey = K1
→↓pay (K1)
💳Servernew key: charge
←reply lost
→↓retry (K1)
💳ServerK1 seen: send saved reply
With a key, the retry is safe. The customer is charged once.

12Related Topics to Read Next

What is an API?→

The basics of requests and responses.

API Styles→

Why retries and repeats happen in each style.

Delivery Semantics→

At-least-once delivery is the reason consumers need idempotency.

Message Queues→

Queues can deliver the same message twice.

Webhooks→

Senders retry, so receivers must handle repeats.

Rate Limiting→

Another guard against too many repeated calls.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Idempotent: same final result whether you do it once or many times.
  • ✔Why: retries are needed on bad networks, and retries must be safe.
  • ✔Naturally idempotent: GET, PUT, DELETE. Not: POST.
  • ✔Fix for POST: an Idempotency-Key that the client makes once per action.
  • ✔Server: look up key, do work and save result in one transaction, return the saved reply on repeats.
  • ✔Watch: races, key expiry, same key with a different body.
  • ✔One line: “Make it safe to try again.”
← Previous
API Styles
Next →
Data Formats