In distributed systems, networks are notoriously unreliable. A client sends a request, the server processes it successfully, but the acknowledgment gets lost in transit. The client, assuming the request failed, retries. If that request was "deduct ₹500 from this account," the user just got charged twice. This is the fundamental problem that idempotency and exactly-once processing aim to solve. They are non-negotiable concepts when designing payment gateways, order management systems, or any platform where duplicate actions have severe business consequences.
What it is and why it matters
Idempotency is a mathematical concept applied to computer science. An operation is idempotent if performing it multiple times yields the same result as performing it exactly once. In mathematical terms: f(f(x)) = f(x).
In the context of APIs, if a client makes a POST /charge request five times because of network timeouts, an idempotent API will only charge the user once and return the same successful response for the subsequent four retries.
Exactly-once processing (often called effectively-once) is the holy grail of stream processing and messaging systems like Kafka. Due to the Two Generals' Problem, true exactly-once delivery over an unreliable network is impossible. Instead, systems achieve exactly-once processing by combining at-least-once delivery (retrying until an ack is received) with idempotent consumers (ignoring duplicates).
Without these mechanisms, systems face:
- Double charging: The classic e-commerce nightmare.
- Data corruption: Duplicate records in databases skewing analytics and state.
- Cascading failures: Retries triggering downstream services multiple times, multiplying the load.
How it works
The most common way to implement idempotency in web services is via an Idempotency Key. This is a unique identifier (usually a UUID) generated by the client and sent as an HTTP header (e.g., Idempotency-Key: <uuid>).
The server uses this key to track the lifecycle of the request. When a request arrives, the server checks if it has seen this key before.
Handling the "In-Progress" state
Notice the IN_PROGRESS state in the diagram. If the client retries while the first request is still being processed, the server must not start a second parallel process. It should either block and wait for the first to finish, or return a 409 Conflict indicating a concurrent request is being handled.
Here is how you might implement a robust idempotent payment processor. Notice how we use atomic database operations to prevent race conditions.
import hashlib
import json
from enum import Enum
class Status(Enum):
IN_PROGRESS = "IN_PROGRESS"
SUCCESS = "SUCCESS"
FAILED = "FAILED"
def process_payment(request_payload, idempotency_key, db):
payload_hash = hashlib.sha256(json.dumps(request_payload).encode()).hexdigest()
# 1. Try to insert atomically (fails if key already exists)
# In SQL: INSERT INTO idempotency_keys (key, hash, status) VALUES (...) ON CONFLICT DO NOTHING
inserted = db.insert_if_not_exists(
key=idempotency_key,
hash=payload_hash,
status=Status.IN_PROGRESS
)
if not inserted:
# Key exists, fetch the existing record
record = db.get(idempotency_key)
# Security check: Ensure the payload hasn't changed on retry
if record.hash != payload_hash:
raise Exception("400 Bad Request: Payload mismatch for idempotency key")
if record.status == Status.IN_PROGRESS:
raise Exception("409 Conflict: Request already in progress")
# Return cached response if already completed
return record.response
# 2. Process the actual business logic
try:
response = call_bank_api(request_payload)
db.update(idempotency_key, status=Status.SUCCESS, response=response)
return response
except Exception as e:
# On failure, we might allow retries by deleting the key or marking it FAILED
db.update(idempotency_key, status=Status.FAILED, error=str(e))
raiseThe main strategies compared
Different layers of your system require different approaches to idempotency. Here is how the most common strategies compare:
| Strategy | Layer | How it works | Best for |
|---|---|---|---|
| API Idempotency Keys | Gateway / App | Client sends a UUID header. Server tracks state (In-Progress, Success) in a fast store like Redis or a DB. | Public-facing APIs (e.g., Stripe, Razorpay). Protects against client retries. |
| Database Constraints | Storage | Using UNIQUE constraints on specific columns (e.g., transaction_id). | Final line of defense. Ensures data integrity even if app-level logic fails. |
| Kafka Exactly-Once | Messaging / Stream | Producers attach a Producer ID (PID) and sequence number. Brokers deduplicate based on this. | Internal microservice communication, stream processing, event-driven architectures. |
| Event Sourcing | Architecture | State is built by applying an append-only log of events. Deduplication happens during projection. | Complex financial systems, audit-heavy domains. |
Trade-offs and failure modes
Implementing idempotency introduces complexity. You must balance correctness with performance and storage costs.
1. Storage Overhead and TTL
You cannot store idempotency keys forever; your database would grow infinitely. You must define a Time-To-Live (TTL).
- Trade-off: If the TTL is too short (e.g., 1 hour), a client retrying after 2 hours will bypass the idempotency check and trigger a duplicate action.
- Standard practice: Stripe keeps idempotency keys for 24 hours. For critical UPI systems, transaction IDs might be kept in hot storage for 30 days and archived thereafter.
2. The "Database Crash" Failure Mode
What happens if your server successfully calls the downstream bank API, but crashes before it can update the idempotency record to SUCCESS?
When the client retries, the server sees the state as IN_PROGRESS (or it timed out and reverted to FAILED), and might attempt the bank call again.
- Solution: The downstream system (the bank) also needs to be idempotent. You must pass your internal transaction ID to the bank so they can deduplicate on their end.
3. Latency
Checking an idempotency key requires a database read/write before executing business logic.
- Trade-off: Using Redis adds <5ms latency but risks data loss if Redis crashes before persisting to disk. Using PostgreSQL adds 10-30ms but guarantees ACID compliance. Financial systems almost always prefer the relational database approach.
How it shows up in real systems
Stripe API
Stripe popularized the Idempotency-Key HTTP header. If you send a POST /v1/charges request, Stripe saves the resulting status code and body. If you retry with the same key, Stripe intercepts the request at the API gateway layer and returns the saved response without hitting their core payment engines.
Apache Kafka
Kafka achieves exactly-once semantics (EOS) using a combination of idempotent producers and transactional APIs. When enable.idempotence=true is set, the producer assigns a unique Producer ID (PID) and a sequence number to every message. The Kafka broker keeps track of the largest sequence number it has successfully committed for that PID. If a network error causes the producer to resend a message with an already-committed sequence number, the broker silently drops the duplicate.
UPI Payments (India)
When you scan a QR code on PhonePe or GPay, a unique Transaction ID is generated. If your internet drops while the payment is processing and you hit "Retry", the app doesn't create a new transaction. It queries the NPCI (National Payments Corporation of India) using the exact same Transaction ID to check the status. This is why you rarely get double-charged even on spotty 4G networks.
Interview questions
1. How do you handle two identical requests arriving at the exact same millisecond?
Model Answer: A simple "read-then-write" approach will cause a race condition. Both requests will read that the key doesn't exist, and both will process the payment. To fix this, we must rely on the database's atomic guarantees. We can use a UNIQUE constraint on the idempotency key column and perform an INSERT ... ON CONFLICT (or catch the Unique Constraint Violation exception). The first request succeeds and proceeds; the second request fails the insert and is forced to wait or return a 409 Conflict.
2. Is Kafka's "exactly-once" really exactly-once?
Model Answer: Mathematically, exactly-once delivery over a network is impossible due to the Two Generals' Problem. What Kafka provides is effectively-once processing. It guarantees that even if a message is delivered multiple times (at-least-once delivery), the state of the system will only be updated once, thanks to idempotent producers and transactional consumers.
3. Which HTTP methods are idempotent by default?
Model Answer: According to the HTTP specification, GET, PUT, DELETE, HEAD, and OPTIONS are idempotent.
GETretrieves data without changing state.PUTreplaces a resource entirely (updating a user's name to "Rahul" ten times leaves the name as "Rahul").DELETEremoves a resource (deleting user ID 5 ten times results in user ID 5 being gone).POSTis not idempotent, as it typically creates a new resource. This is why idempotency keys are primarily used withPOSTrequests.
4. Where should you store idempotency keys: Redis or a relational database?
Model Answer: It depends on the criticality of the data. For non-critical actions (like sending a push notification), Redis is excellent because it's fast and supports automatic TTLs. For financial transactions, a relational database (like PostgreSQL or MySQL) is preferred. You want the idempotency record and the actual transaction record to be committed in the same ACID transaction to prevent inconsistent states if the system crashes midway.
5. What happens if a client reuses an idempotency key with a different request payload?
Model Answer: The system should reject the request. If a client sends a request to transfer ₹100 with key ABC, and later sends a request to transfer ₹5000 with the same key ABC, returning the cached success response of the ₹100 transfer would be a massive security flaw. We should hash the request payload and store the hash alongside the idempotency key. On retry, we compare the hashes and return a 400 Bad Request if they don't match.