Idempotency in system design interviews

An operation is idempotent when running it twice leaves the system in the same state as running it once. In a system design interview it is the answer to one recurring question: a client timed out and retried, or a queue delivered a message again, so how do you stop the work from happening twice?

By Published 10 min read

1. What idempotency means

The word comes from mathematics, where a function f is idempotent if applying it to its own output changes nothing: f(f(x)) = f(x). Rounding a number is an everyday case. In distributed systems the definition is about side effects on the server, not about the reply. Deleting order 42 twice leaves order 42 deleted, so the operation is idempotent, even though the second call may return "not found" instead of "deleted".

Two nearby words get mixed up with it. A safe operation changes nothing at all (a read). A retry is the act of sending again. Idempotency is the property that makes a retry harmless.

2. Why interviewers keep asking

Every remote call has three outcomes, not two: it worked, it failed, or you do not know. The third case is the one that matters. A request can reach the server, change the database and then lose its response to a dropped connection or a timeout. The client cannot tell that apart from a request that never arrived, so the only sensible move is to try again. Message brokers make the same trade on purpose: they redeliver anything not acknowledged, which means a consumer can see one message several times. Interviewers bring up idempotency to check whether you know this and have a concrete plan for it, especially in designs where a duplicate costs money or trust.

3. Idempotent by nature, and not

Common operations and whether repeating them is harmless
OperationIdempotent?Why
Set a user's email to a given valueYesThe second write stores the same value
Increment a counter by 5NoEach repeat adds another 5
Delete a record by its IDYesAfter the first call, there is nothing left to remove
Create an order with a server-generated IDNoEach call creates a new row with a new ID
Create an order with an ID the client choseYes, if the ID is uniqueThe second insert hits the unique constraint and can return the existing order
Add an item to a cartNoTwo clicks can mean two items
Mark an invoice as paidYesA state change to a fixed target state
Send an email or a push notificationNoEach attempt reaches the user again
Call a payment provider to charge a cardOnly with the provider's idempotency keyWithout it, a retry can charge again
Common operations and whether repeating them is harmless. Scroll sideways on a small screen.

HTTP builds the idea into its method definitions. The HTTP semantics standard (RFC 9110) defines GET, HEAD, OPTIONS, PUT and DELETE as idempotent, while POST and PATCH carry no such promise. That is a statement about what servers are expected to do, not a property the protocol enforces, so an API that deletes something on GET or appends on PUT breaks the contract that proxies and clients rely on when they retry.

4. How an idempotency key works

For operations that are not naturally idempotent, the client attaches a unique key to each logical operation, usually a random UUID created when the user presses the button, and sends the same key on every retry of that operation. Many payment and commerce APIs accept such a key in a request header; an IETF draft proposes a standard Idempotency-Key header, and vendors document their own rules for it.

  1. Claim the key atomicallyInsert the key into a table with a unique constraint, together with a hash of the request body and the status "in progress". Only one attempt can win the insert, even if two retries arrive at the same moment.
  2. Do the workPerform the effect. If it lives in the same database, do it in the same transaction that marks the key done, so the key and the effect commit or fail together.
  3. Store the responseSave the status code and body against the key, then return them.
  4. Replay on a retryWhen the key already exists and is done, return the stored response without running the work again.
  5. Reject misuseIf the key exists but the request hash differs, the client reused a key for a different operation: refuse with an error instead of guessing. If the key is still in progress, tell the client to retry shortly.
  6. Expire old keysDelete keys after a window long enough to cover every realistic retry (hours to days, depending on the product), and give in-progress keys a lease so a crashed attempt does not block retries forever.
import hashlib, json, sqlite3

db = sqlite3.connect(":memory:", isolation_level=None)
db.execute("""CREATE TABLE idempotency_keys (
  key TEXT PRIMARY KEY, request_hash TEXT NOT NULL,
  status TEXT NOT NULL, response TEXT)""")
db.execute("CREATE TABLE transfers (id INTEGER PRIMARY KEY, amount INTEGER)")

def fingerprint(body):
    return hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()

def handle(key, body):
    h = fingerprint(body)
    try:  # claim the key: the PRIMARY KEY makes this atomic
        db.execute("INSERT INTO idempotency_keys VALUES (?, ?, 'in_progress', NULL)", (key, h))
    except sqlite3.IntegrityError:
        stored_hash, status, response = db.execute(
            "SELECT request_hash, status, response FROM idempotency_keys WHERE key = ?", (key,)).fetchone()
        if stored_hash != h:
            return 422, {"error": "key reused with a different request"}
        if status == "in_progress":
            return 409, {"error": "original request still running, retry later"}
        return 200, json.loads(response)           # replay, no second effect
    db.execute("BEGIN")
    cur = db.execute("INSERT INTO transfers (amount) VALUES (?)", (body["amount"],))
    response = {"transfer_id": cur.lastrowid, "amount": body["amount"]}
    db.execute("UPDATE idempotency_keys SET status = 'done', response = ? WHERE key = ?",
               (json.dumps(response), key))
    db.execute("COMMIT")
    return 201, response

print(handle("k-1", {"amount": 40}))   # (201, {'transfer_id': 1, 'amount': 40})
print(handle("k-1", {"amount": 40}))   # (200, {'transfer_id': 1, 'amount': 40}) replayed
print(handle("k-1", {"amount": 99}))   # (422, ...) same key, different body
A minimal idempotency-key handler with SQLite in memory (run with python3)

The sketch claims the key outside the transaction that does the work, which keeps it short but leaves one gap: a crash between the claim and the commit strands the key as in progress. Production versions close it with a lease timestamp on the claim, or by claiming and working inside one transaction when both tables share a database.

5. Idempotent consumers for queues and events

Brokers such as Kafka, SQS and RabbitMQ are usually run with at-least-once delivery: a consumer that crashes after doing the work but before acknowledging will see the message again. Some offer exactly-once features inside their own boundary, but the moment a consumer writes to an outside database or calls another service, duplicates are back on the table. Two ways to handle them:

  • A processed-messages table. Record the message ID in the same database transaction as the effect. A redelivered message fails the unique insert, and the consumer acknowledges it without repeating the work.
  • Make the effect itself repeatable. Write "order 7 is shipped" rather than "ship one more"; upsert by a natural key; apply an update only if the stored version is older than the event's version, which also discards events that arrive out of order.

The producer side has a twin problem: a service that updates its database and then publishes an event can crash between the two. The transactional outbox pattern writes the event into the same database transaction and publishes it afterwards, at least once, which is exactly why consumers must deduplicate. The payment system walk-through uses both halves.

6. Making writes safe without a key table

Techniques that make a repeated write harmless
TechniqueHow it worksGood fit
Client-generated IDsThe client picks the primary key (a UUID) before the first attempt; a retry collides with the unique constraint and returns the existing rowCreating orders, posts, uploads
Conditional writesUpdate only if the current version or state matches what the client read (compare-and-set)State machines, inventory, profile edits
Absolute values instead of deltasSend "quantity = 3" or "status = shipped", not "add one" or "advance one step"Settings, status flags, counters you can recompute
Upserts on a natural keyInsert or update by a key that identifies the real-world thing, such as (user_id, date)Daily rollups, read models, search indexes
Deterministic job IDsDerive the ID from the input (for example a hash of the file and the step), so re-running a step overwrites the same outputBatch pipelines, schedulers
Techniques that make a repeated write harmless. Scroll sideways on a small screen.

7. Sizing the key store and choosing the window

write requests carrying keys:  1,000 a second
keys a day:                    1,000 x 86,400        = 86.4 million
bytes per row:                 key + hash + small stored response, about 500 bytes
one day of keys:               86.4 million x 500 B   = about 43 GB
retention of 24 hours:         about 43 GB live, before replication and indexes
Rough size of an idempotency key table (all inputs are assumptions)

The window is a product decision as much as a storage one. It must outlast the longest retry the client will attempt, including a mobile app that comes back online the next morning. Too short, and a late retry runs twice; too long, and the table grows and old keys block legitimate reuse. Keep the key next to the data it protects when you can, because a key store in a different database cannot commit atomically with the effect.

8. How it shows up in common prompts

Where duplicates hurt in well-known walk-throughs
PromptThe duplicate to preventUsual answer
Payment systemCharging a card twice after a timeoutOne key from the client through to the payment provider, plus a ledger written once
Ticket bookingTwo bookings from one double-clickA client-generated booking ID and a conditional seat claim
Notification systemThe same push sent twice by a redelivered eventDeterministic delivery IDs and an idempotency check at each hop
Job schedulerA job run twice after a worker is presumed deadIdempotent job steps, plus fencing so a stale worker cannot commit
URL shortenerTwo short codes for one retried createAccept a client key, or return the existing code for the same long URL if the product wants that
Where duplicates hurt in well-known walk-throughs. Scroll sideways on a small screen.

9. Interview questions on idempotency

Questions to rehearse and what a strong answer covers
QuestionWhat a strong answer covers
Why can't we just guarantee exactly-once delivery?A lost response looks the same as a lost request; at-least-once plus idempotent handling gives an exactly-once effect
Is PUT idempotent? Is POST?By HTTP's definition PUT is and POST is not; what matters is whether your handler honors that
Where does the idempotency key come from?The client, once per user intent, reused on every retry of that intent
Two retries with the same key arrive at once. What happens?An atomic claim with a unique constraint lets one win; the other gets "in progress" or waits
What if the same key comes with a different body?Reject it; silently replaying the old response hides a client bug
How long do you keep keys?Longer than the longest retry; tie it to the client's retry policy and the storage estimate
How does a queue consumer avoid double processing?Dedupe table in the same transaction, or a repeatable effect such as a versioned upsert
Your service calls a third party that has no idempotency support. Now what?Record intent first, query the third party's state before retrying, and reconcile anything left ambiguous
Questions to rehearse and what a strong answer covers. Scroll sideways on a small screen.

10. Mistakes to avoid

  • Generating the key on the server. A key created per request changes on every retry and protects nothing.
  • A check-then-insert race. Reading "does the key exist?" and then inserting lets two concurrent retries both pass the check. Use the unique constraint.
  • Caching only successes. If the first attempt failed with a validation error, replaying that error is usually right; retrying a deterministic failure just fails again.
  • Forgetting downstream calls. Your endpoint can be idempotent while the email or charge it triggers is not. Pass a derived key along, or dedupe at the next hop.
  • Retrying with no backoff. Idempotency makes retries safe, not free. Use exponential backoff with jitter and a retry budget.

11. How to talk about it in the interview

  • Name the moment duplicates appear: a client timeout, a load balancer retry, a broker redelivery.
  • Say which operations are already safe and which need a key or a dedupe record.
  • Describe the key's life in one breath: client-generated, atomically claimed, response stored, replayed, expired.
  • Close the loop on downstream effects and on what the user sees while a result is unknown.

Fictional example

Handling a retried money transfer in a wallet app
Interviewer
The app sends a transfer, the request times out, and the app retries. What stops the money moving twice?
Candidate
The app creates a transfer key when the user confirms, and every retry carries the same key. The service inserts that key into a table with a unique constraint before doing anything, so only one attempt can proceed.
Candidate
The debit, the credit and marking the key as done happen in one transaction, and I store the response on the key. A retry that finds a finished key gets that same response back, so the user sees one transfer.
Interviewer
What if the retry arrives while the first attempt is still running?
Candidate
It sees the key in progress and gets a "try again shortly" reply. The in-progress claim has a lease of a few seconds, so a crashed attempt does not lock the key forever.

Rehearsing retry questions with Natively

Idempotency questions tend to arrive as a chain: timeout, then concurrent retries, then the downstream call. A good drill is to have a friend play interviewer and push down that chain while Natively runs on your computer. It transcribes both voices as you talk and can draft a suggested answer to the latest question, so you can check whether you mentioned the atomic claim or the key's expiry. Ask it for a sequence diagram of a retried request and it draws one inside the answer. After the session the transcript and notes stay on your machine, which makes it easy to find the follow-up where your explanation got vague.

Questions people ask

What is idempotency in system design?

An operation is idempotent when performing it several times has the same effect on the system as performing it once. It matters because networks and message queues deliver requests at least once, so clients retry and consumers see duplicates. Idempotent handling turns those repeats into a single effect.

How does an idempotency key work?

The client creates a unique key for one user action and sends it with every retry of that action. The server claims the key atomically with a unique constraint, does the work, stores the response on the key and replays that response to any retry. Keys are expired after a window longer than the client's longest retry.

Which HTTP methods are idempotent?

The HTTP semantics standard, RFC 9110, defines GET, HEAD, OPTIONS, PUT and DELETE as idempotent; POST and PATCH are not. The definition describes what servers should do, so an API is only idempotent in practice if its handlers honor it.

Is exactly-once delivery possible?

Not over an unreliable network in general, because a request that succeeded but lost its response looks the same to the sender as one that never arrived. Systems get an exactly-once effect instead: deliver at least once and make the handling idempotent, with keys or deduplication records.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP