Performing the same operation many times has the same result as performing it once.
✗ Without it
User taps pay
↓
Network stalls, no feedback
↓
User taps again
↓
Server handles it twice
↓
Charged twice
✓ With it
User taps pay
↓
Network stalls, auto-retry
↓
Same idempotency key
↓
Server sees it was already handled
↓
Return prior result, charged once
Why you must consider it
Networks are unreliable: after a timeout the client does not know whether the server processed the request, so it retries. Users also double-tap. “The same request arrives more than once” is normal, not exceptional.
Naturally idempotent: GET (read), PUT (full replace), DELETE (delete).
Naturally not idempotent: POST (create, pay, transfer).
How to do it
🔀 What happens when the same request is retried twice
Client
Server
Database
1POST /orders (Idempotency-Key: abc)
2Write order + record key=abc
3Success
4Response lost (network blip)
5Retry: same key=abc
6Does key=abc already exist?
7Yes, return the prior result
8Return the order (no duplicate create)
🧭 How the server handles a request with an idempotency key
📥Request received
↓
Has Idempotency-Key?
NoTreat as a normal request (duplicate risk)
↓
Has this key been handled?
YesReturn the prior result directly
↓
Run the business logic and store key + resultDB unique index backs concurrent writes
↓
Return the result
The client generates a unique Idempotency-Key (e.g. a UUID) for each “intent to act”, and reuses it on retry.
The server checks first: has this key been handled?
Handled → return the prior result.
Not handled → execute, and record the result together with the key.
Use a database unique index so the key cannot be written twice under concurrency (this is the last line of defense).
Component comparison
Idempotency key + unique index
Hand-rolledOpen sourceOpsLow
The client sends a unique Idempotency-Key with each operation; the server stores it in the database with a unique index, and returns the previous result directly when a duplicate arrives.
Best forEndpoints that must execute exactly once, such as payments, orders, and transfers.
Avoid whenThe endpoint is naturally idempotent already (such as replacing a whole resource by ID), so this is unnecessary.
Pros
The unique constraint is the backstop, so concurrent duplicates are blocked too
It shares the business transaction, so you do not record a key without the write
No extra service is needed: the database itself blocks the duplicate
Cons
There is no ready-made library, so reading, storing, and returning the old result are yours
Expired keys must be cleaned up regularly, or the table keeps growing
When the same key arrives with different content, you should usually return an error
Redis dedup key
Self-hosted open sourceOpen sourceOpsMedium
On receiving a request, first write an expiring "processing" marker to Redis (SET NX); continue only if the write succeeds, and a failed write means a duplicate request.
Best forProjects that already have Redis and want to block most short-window duplicate submissions first.
Avoid whenMoney is involved and Redis is the only layer of protection; combine it with a database unique constraint.
Pros
It stays in memory and is fast, and it does not use a connection to the primary database
Expiry is built in, so you do not write a cleanup job
It is good at blocking repeated submits that arrive in a short window
Cons
Data can be lost or can expire, so it cannot be the last line of defense
A crash halfway through leaves a processing marker behind
If you do not already have Redis, you have to deploy one more service
Unique constraint on a business field
Built into the frameworkOpsLow
Instead of inventing an idempotency key, put a database unique constraint on something already unique in the business (such as a payment transaction ID or order number), so duplicate inserts are rejected by the database.
Best forHandling payment callbacks, third-party pushes, and other cases where the sender already provides a unique number.
Avoid whenThe request has no naturally unique number; in that case the client should provide an idempotency key.
Pros
Simplest to implement, just add one unique index
A natural last line of defense that does not depend on application code being correct
Fits receiving third-party callbacks (the other party's transaction ID is the unique identifier)
Cons
Only prevents duplicate creation; it cannot return the full previous response as-is
Requires a reliable unique business field, and is unusable without one
Unique conflicts must be caught and turned into a friendly response, otherwise users see a 500
State machine / conditional update
Hand-rolledOpen sourceOpsLow
Give data such as orders a status (pending payment, paid) and include a condition on update (only "pending payment" may become "paid"), so a repeated request is naturally ineffective because the status no longer matches.
Best forBusiness with clear state changes, such as order payment, approval flows, and refunds.
Avoid whenThe operation creates new data, so there is no "previous state" to check.
Pros
Also guarantees the correctness of the business flow, not just duplicate prevention
A single conditional UPDATE statement is enough, with no extra storage
A repeated request affects 0 rows, which is safe
Cons
Only fits business with clear state transitions, not "create" operations
A poor state design leaves holes or dead states
You must use the affected row count to decide success, which is easy to get wrong
Checklist
All create / pay / transfer endpoints support Idempotency-Key
The database has a unique constraint on that key
Duplicate requests return the first result, not an error
Keys have an expiry / cleanup policy (e.g. keep for 24 hours)