Imagine this scenario:
A customer clicks Place Order.
The request reaches your server, the database successfully creates the order, but the response never reaches the browser because of a network issue.
The customer assumes something went wrong and clicks again.
Now you have two orders instead of one.
This is a common reliability problem in web applications.
Disabling a submit button might prevent accidental double-clicks, but it doesn't guarantee that an operation will execute only once.
Let's explore how to handle this properly using React, Node.js, and PostgreSQL.
1. Frontend protection is only the first layer
In React, we often prevent repeated submissions using a loading state:
const [isSubmitting, setIsSubmitting] = useState(false);
async function handleSubmit() {
if (isSubmitting) return;
setIsSubmitting(true);
try {
await createOrder();
} finally {
setIsSubmitting(false);
}
}
This is useful for improving the user experience.
But there is a problem.
Duplicate requests can still happen because of:
- Network retries
- Multiple browser tabs
- Concurrent API calls
- Repeated webhook deliveries
- Client or server failures
Even rapid calls within the same render cycle can observe the same React state before an update takes effect.
The important lesson: frontend protection improves UX, but backend protection ensures data integrity.
2. Understanding idempotency
An operation is idempotent when performing it multiple times has the same intended effect as performing it once.
For example:
POST /api/orders
Idempotency-Key: order-abc-123
If the same request is submitted again with the same idempotency key, the server should recognize that the operation has already been processed.
Instead of creating a new order, it can return the result of the original operation.
This is particularly important for:
- Order creation
- Payment processing
- Subscription activation
- Inventory adjustments
- Financial transactions
However, an important distinction is that an idempotency key represents one intended operation, not an entire user session.
Retrying the same order should reuse the original key. Creating a genuinely new order should use a new one.
3. Implementing idempotency in React
We can generate a unique idempotency key using the browser's built-in Web Crypto API.
import { useRef } from "react";
function OrderForm() {
const idempotencyKeyRef = useRef(null);
async function createOrder(order) {
// Generate once for this intended operation.
if (!idempotencyKeyRef.current) {
idempotencyKeyRef.current = crypto.randomUUID();
}
const key = idempotencyKeyRef.current;
const response = await fetch("/api/orders", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Idempotency-Key": key,
},
body: JSON.stringify(order),
});
if (!response.ok) {
throw new Error("Order request failed");
}
const result = await response.json();
// Reset only after confirmed completion.
idempotencyKeyRef.current = null;
return result;
}
// Use createOrder in your submission flow.
// Prevent concurrent submissions from this form.
}
There are two important details here.
First: Reuse the same key when retrying an uncertain operation.
If the request reaches the server but the network fails before a response arrives, the client cannot know whether the order was created.
In that situation, we preserve the idempotency key so the same operation can be retried safely.
Second: Reset the key after confirmed success.
Once the server confirms the order was successfully created, the key is cleared.
This ensures the next legitimate order receives a new key instead of accidentally reusing the previous one.
For example:
Order A
|
Key: abc-123
|
Network failure
|
Retry with abc-123
|
Server returns existing Order A
|
Confirmed success
|
Clear key
|
Order B
|
Generate new key: xyz-456
A few additional considerations for production applications:
- Retry with the same order data, not a modified payload.
- Prevent overlapping submissions of the same form operation.
- Preserve an unfinished operation's key and payload across page refreshes if recovery is required.
- Clear the key only after the operation's completion has been confirmed. A
202 Acceptedresponse, for example, might only indicate that processing has started. - Handle validation failures separately from uncertain network failures.
The main principle remains the same:
One intended operation = one idempotency key.
4. Protecting the database against duplicate inserts
Frontend protection and idempotency middleware are useful, but concurrent requests can still introduce race conditions if the database isn't protected.
Consider this backend logic:
const existingOrder = await findOrder(key);
if (!existingOrder) {
await createOrder(data);
}
Looks fine, right?
Not necessarily.
Two requests can execute simultaneously:
Request A Request B
| |
Check existing order Check existing order
| |
Not found Not found
| |
Create order Create order
| |
Success Success
Both requests can pass the check before either creates the record.
This is a classic check-then-insert race condition.
A better approach: Database uniqueness constraints
In PostgreSQL, enforce uniqueness at the database level.
CREATE UNIQUE INDEX unique_order_request
ON orders (user_id, idempotency_key);
This assumes your orders table contains the corresponding columns and that idempotency keys are required for this operation.
Now use PostgreSQL's ON CONFLICT functionality:
INSERT INTO orders (
user_id,
idempotency_key,
product_id,
quantity,
request_hash
)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (user_id, idempotency_key)
DO NOTHING
RETURNING id;
If the insert succeeds, the query returns the new order ID.
But there is an important detail.
When a conflict occurs, DO NOTHING RETURNING id returns zero rows.
It does not automatically return the existing order's ID.
So the backend needs to handle both cases.
Handling an existing order
If the insert returns no rows, retrieve the existing order using the same user ID and idempotency key.
SELECT id, request_hash
FROM orders
WHERE user_id = $1
AND idempotency_key = $2;
Then compare the stored request hash with the incoming request's hash.
There are two possible outcomes:
Case 1: The request hashes match
The client is retrying the same intended operation.
Return the previously created order instead of creating another one.
Case 2: The request hashes don't match
The same idempotency key is being reused with different order parameters.
Reject the request:
HTTP 409 Conflict
{
"error": "Idempotency key already used with different request data"
}
This prevents the application from silently treating two different operations as the same request.
For request hashing, both attempts must use a consistent representation of the relevant order data. The server should calculate or verify the hash rather than blindly trusting a value supplied by the client.
Why not use ON CONFLICT DO UPDATE?
Another approach is to perform an update during a conflict so PostgreSQL can return the existing row within the same statement.
For example, a no-op update can return the existing order ID and request hash.
However, this approach has trade-offs:
- It can create a new row version even when values don't meaningfully change.
- It acquires row locks.
- It may trigger update-related behavior.
- Some techniques for identifying whether the row was inserted rely on PostgreSQL implementation details.
For many applications, keeping DO NOTHING and performing a follow-up SELECT is a straightforward choice.
With PostgreSQL's default READ COMMITTED isolation, the follow-up query is a separate statement and can see the winning transaction's committed row.
The application should still handle unexpected missing rows or transaction failures appropriately.
Database constraints provide protection that application-level checks alone cannot guarantee.
5. What about transactions?
Preventing duplicate orders is only part of the problem.
Creating an order might involve multiple operations:
- Create the order.
- Reserve inventory.
- Update related database records.
- Record the transaction.
- Send a notification.
If one operation fails halfway through, the system can end up in an inconsistent state.
Database transactions help ensure that related database modifications succeed or fail together.
For example, creating an order and reserving inventory should generally be part of the same database transaction when they must succeed together.
That way, a failure doesn't leave an order committed without its required inventory changes.
The idempotency check and the business operation also need to be coordinated correctly. Preventing duplicate inserts alone doesn't guarantee every related operation executes only once.
However, external operations such as sending emails or publishing messages are not automatically rolled back with a database transaction.
For these cases, patterns such as the transactional outbox and idempotent event consumers can improve reliability.
This is an important distinction when designing systems that interact with external services.
6. Test real failure scenarios
A feature working during normal testing doesn't necessarily mean it is reliable under failure conditions.
Here are some scenarios worth testing:
| Scenario | Expected behavior |
|---|---|
| Two concurrent requests with the same key | Only one order is created |
| Retry after the original request commits | Existing order is returned |
| Same key with different request data | Request is rejected with 409 Conflict
|
| Failed database transaction | No partial order is committed |
| Two legitimate operations with different keys | Both can proceed |
| New order after successful submission | A fresh idempotency key is generated |
| Network failure after server commits | Retry returns the original order |
One especially useful test is simulating a lost response after a successful database commit.
The client should be able to retry without accidentally creating another order.
These tests provide more confidence than simply checking whether a submit button becomes disabled.
7. The approach I recommend
For reliable applications, multiple layers should work together:
Frontend safeguards improve the user experience and discourage accidental repeated submissions.
Backend idempotency identifies repeated attempts to perform the same operation and distinguishes them from genuinely new requests.
Database constraints protect against duplicate inserts, including concurrent requests.
Transactions and carefully designed side effects help maintain consistency across the entire workflow.
Failure scenario testing verifies that retries and concurrency behave as expected outside the normal happy path.
No single layer solves every problem.
The goal isn't just to make an API request succeed.
It's to make sure retries, failures, and concurrent requests don't produce unintended results.
Final thoughts
Building reliable software requires thinking beyond the happy path.
A submit button can be disabled. A network request can fail. A server can process the same operation more than once.
The application should still behave predictably.
A combination of frontend safeguards, idempotency, database constraints, and transaction handling is generally more reliable than depending on any one of them.
There is also an important distinction between preventing duplicate requests and guaranteeing exactly-once processing across an entire distributed system. Idempotency makes repeated attempts safe, but external side effects still require careful coordination.
What's your approach to preventing duplicate requests in production applications?
Further reading: PostgreSQL INSERT / ON CONFLICT documentation
Top comments (2)
The
DO NOTHING ... RETURNING idstep returns zero rows on a retry, so the handler needs a second query to fetch the existing order and itsrequest_hash. You can get both in one statement with a no-op update:First call gives
inserted = true. A retry gives the sameidwithinserted = false, and you compare the returnedrequest_hashwith the incoming one to send a 409 when the payload changed. I ran it against a local Postgres to check the three cases. Two caveats: the no-op update writes a new row version and takes a row lock, andxmax = 0is a well-known trick, not a documented API. If that bothers you, keepDO NOTHINGand do the follow-up select.Also, in the React snippet the ref is never cleared, so after a successful order the next order from the same mounted form reuses the key and the server hands back the first order. Setting
idempotencyKeyRef.current = nullafter a 2xx (and keeping it on network errors) covers that.Great points, Sunnatulla! Thanks for taking the time to test this.
You're right about both cases. The no-op update is an interesting way to handle it in a single query, although I'd lean toward
DO NOTHINGwith a follow-upSELECTto avoid unnecessary writes and row locks.And good catch on the React ref lifecycle. Resetting the key after a confirmed success while preserving it for network retries is important to distinguish a new operation from a retry.
Appreciate the detailed feedback!