The same order was submitted twice: how do we prevent duplicate submissions and overselling?
Duplicate orders and overselling are not two bugs but two faces of the same problem: one business intent executed more than once, or one execution recorded twice. Greying out the button on the front end reduces duplicates caused by an impatient double click, but it cannot stop the more common sources: network retries, repeated payment callbacks, and redelivered messages.
What actually works is a server-side pattern: every write carries a request ID that never changes, with a database unique constraint as the backstop; inventory is deducted atomically on a “a successful deduction means it is reserved” basis, with explicit release rules once reserved; every retry, callback, and manual re-submission goes through the same entry point; and a scheduled reconciliation catches what the earlier layers missed. This has a cost, and not every endpoint needs it — but any write that moves money, inventory, quota, or entitlements deserves this standard.
1. Where duplicates come from
The most common mistake when diagnosing these problems is guessing backwards from the user interface. The same “two orders were placed” can have at least six sources, and each is handled differently:
- The user clicks repeatedly or navigates back and resubmits. The submit button has no debounce, or the page gives no clear feedback after submission, so the user assumes it failed and clicks again.
- The client retries automatically. After a timeout, the SDK or front-end framework resends according to its configuration, while the server actually completed the first request successfully.
- The payment channel resends its callback. When the channel does not receive a correct acknowledgement, it notifies again; the same payment may be called back several times, and the order of arrival may be out of sequence.
- The message queue redelivers. Under at-least-once delivery, a consumer processes a message successfully but its acknowledgement is lost, so the message is delivered again.
- Several entry points run concurrently. A customer places an order in the mini program while a service agent places one on their behalf in the back office, and each entry point believes it is the first.
- Operations or scripts run twice. Bulk imports, data patches, and scheduled jobs have no re-run protection and write duplicate records.
This leads to one conclusion: idempotency belongs at the point of the write, not on a page. There can be several pages, but the write entry point must converge into one.
2. Decide first which writes need protection
Not every endpoint needs an idempotency key. Three questions settle it: will this write create a new record, consume a limited resource, or move money; can the same business intent be triggered more than once; and can a repeated execution be undone cleanly.
By that standard, queries, updates that set a field to a fixed value (where repeating gives the same result), and log reporting usually need nothing extra. Order placement, payment, refunds, coupon issuance, redemption, appointment holds, and inventory adjustments do.
Drawing the scope too wide also costs something: adding a request ID, unique index, and deduplication table to every endpoint lengthens the write path and makes troubleshooting harder. A sensible approach is to list every “limited resource” in the system first, then work backwards to the writes that affect them.
3. Four layers of defense — miss one and it leaks
Layer one: the client only reduces probability. Disabling the button after submission, loading states, and debouncing are all experience-layer measures. They make duplicates less likely but cannot guarantee anything — a user switching devices, an automatic network retry, or a direct call to the API all bypass them. Their real value is clear feedback: say it succeeded when it succeeded, and explain why it failed when it failed, rather than leaving users to guess.
Layer two: a request ID as the idempotency key. Generate a requestId when the order page is opened, and use the same one for submission and every later retry; the server builds a unique index on “user + business type + requestId”, and on an insert conflict returns the result of the first attempt instead of an error. Two details are most often got wrong: regenerating the requestId on every retry, which amounts to not doing it at all; and keeping deduplication only in application memory or a single-node cache, where it is lost on restart and not shared across instances.
Layer three: business unique constraints as the backstop. Order numbers and payment numbers are generated by server-side rules and protected by a database unique index, so one piece of business cannot become two records. For cases such as “same user, same product, same delivery details, resubmitted within a short window”, a business fingerprint can serve as a second check; on a hit, go through a confirmation flow rather than rejecting outright — a hard error makes users think it failed and try again.
Layer four: a state machine with conditional updates. Every state transition is written as an update with a precondition, for example “change to paid only when the status is pending payment”, and the affected row count is checked. Zero rows means someone else already changed it, so return the result for the current state. By contrast, “read the status, decide, then write” lets two concurrent requests pass the check at the same time, which is the most common coding cause of duplicate charges and overselling.
The four layers stack; they are not a menu of options. With a request ID but no unique constraint, a restart or cross-instance concurrency can still write two records. With a unique constraint but no request ID, a user's retry gets an error, and both experience and diagnosis get worse. Without conditional updates on state transitions, inventory can be deducted perfectly and still take effect twice.
4. Inventory: deduction, reservation, and release
The hard part of inventory is not “subtract one” but “when does it count as reserved, and when should it be returned”. There are three common approaches, suited to different situations:
| Approach | How it works | Fits | Watch out for |
|---|---|---|---|
| Conditional update | The deduction statement includes a “stock greater than or equal to quantity” condition; zero affected rows means failure | Single database, moderate concurrency | Hot products queue on the same row |
| Reserve + timeout release | Reserve on order placement, confirm on payment success, release automatically if unpaid past the deadline | Flows with payment that need to give users time | Release must be idempotent, or stock is returned twice |
| Pre-deduct + async persistence + reconciliation | Atomic deduction in the cache layer, asynchronous write to the database, periodic comparison | Flash-sale style spikes | Decide in advance which side wins when cache and database disagree |
The order of operations also has to be settled in advance. If inventory is deducted before the order is created, a failed creation must return the stock. If the order is created first and inventory deducted second, you need reservation and release, and must never end up with “the deduction failed but the order is still there”. Both orders can work; what you must avoid is doing neither — stock was never held, yet the order exists.
The release path must be idempotent too. Order timeout closure, payment failure, successful refund, and manual cancellation all trigger a return of stock; each return carries its own serial number and hits a unique constraint, otherwise the same release runs twice, stock is returned an extra time, and nothing shows on the books until a physical count.
There is also an easily overlooked boundary: how the payment channel handles timed-out orders. Typically our system closes the order, releases the stock, and tells the channel to cancel the payment; if the channel's cancellation fails, or the user completes payment at the very moment of closure, an order that is “closed but paid” appears. Such orders cannot be found by having someone scroll through records; there must be a fixed handling path — when a late payment-success notification arrives, check the order status first, and if it is closed, trigger a refund and record the reason, rather than flipping the order back to paid to grab the stock.
5. Patterns that look done but fail
- Front-end debouncing only. It does not stop automatic retries or direct calls, as noted above.
- Read then insert, with no unique index. Two concurrent requests both find nothing and both insert. There is no protection between the read and the write.
- Using an auto-increment ID as the idempotency key. Every retry gets a new ID, so it never repeats — which means it does nothing.
- Treating a distributed lock as a cure-all. If the lock expires sooner than the business operation takes, or acquiring the lock and setting the expiry are not atomic, the lock disappears before the work finishes. A lock reduces contention but cannot replace a unique constraint.
- Reporting an error when a duplicate is detected. Users see a failure and try again, producing more duplicates. Idempotency should mean “return the first result”.
- Deducting in the cache without persisting or checking. It looks fine for a while, but once the cache is lost or scaled out, the inventory no longer matches.
- Deducting without ever releasing. Unpaid orders hold stock indefinitely, and the real sellable quantity keeps shrinking.
6. Cost, boundaries, and when not to bother
None of this is free: unique indexes add write overhead, transaction scope has to be kept tight, idempotency records must be retained for a period and cleaned up regularly, and hot inventory items need extra splitting or queuing. For an internal system with very little concurrency that involves no money or quota, the full set is over-engineering.
A simpler rule of thumb: if the system collects payments from outside, issues limited quota or entitlements, or its inventory data informs business decisions, do the four layers; for purely internal tools with human-undoable data entry, database constraints and an operation trail are enough. Upgrade when the business connects to payments or starts selling externally, rather than after something goes wrong.
Retention is a real decision as well. How long to keep request-ID records depends on how long the business allows a user to retry the same transaction. Too short, and long-interval retries slip through; too long, and the deduplication table grows without bound. The usual practice is to set it by the order lifecycle and pair it with an archiving or cleanup job.
7. How to accept it
Idempotency and oversell protection cannot be verified by “clicking twice and seeing what happens”; they need dedicated cases:
- Repeated submission with the same requestId, including 10 concurrent submissions: exactly one business record, inventory deducted once, identical responses.
- Different requestIds, same business intent: blocked by a business constraint or routed to manual confirmation; no two valid orders.
- Successful submission, then network loss and a retry after recovery: the result matches the first attempt; no second order.
- Payment callback replay: the same notification pushed repeatedly and out of order; order status and entitlements take effect only once.
- Timeout closure racing with payment success: when the timeout comes first and the callback arrives later, money and inventory must still reconcile, with no paid order left in limbo.
- Concurrent grab for the last unit: successful orders equal the stock count, and the losers get a clear message.
- Fault injection: deduction succeeded but order creation failed, message redelivery, release executed twice — check that inventory and orders agree.
- Reconciliation: orders, payment transactions, and inventory movements compared daily across all three, with differences traceable to specific order numbers.
Putting these cases into the acceptance checklist is far more useful than a line in the requirements document saying “prevent duplicate submissions”.
8. These decisions belong in the design phase
In a project, each point above becomes a handful of concrete decisions: which writes need a request ID and how long it is kept; which system owns inventory, whether this system deducts it or calls an inventory service; how long before a hold is released, and who triggers the release; which entry point handles callbacks and manual re-submissions; which side is authoritative for reconciliation. If these are postponed to late development, changes ripple through APIs, table structures, and front-end flows, at a far higher cost than settling them during design.
In our custom projects, we write these into the API specification and acceptance cases during the design phase: how idempotency keys are generated and retained, who owns inventory deduction and release, the preconditions for state transitions, and the reconciliation basis and difference-handling process. What the client needs to provide is the business rules themselves — which resources are limited, how long counts as giving up, how long a duplicate window is acceptable, and who handles discrepancy records; how to implement and test that in the system is part of what we deliver. The boundaries should be stated too: the cadence of payment-channel callbacks is controlled by the channel; what we can guarantee is that a received notification takes effect only once, and that reconciliation catches missed and duplicate receipts; eventual consistency depends on reconciliation running on time, which requires operations to cooperate.
Another article on our site about appointment mini programs, bookable slots and occupancy release, discusses capacity calculation and release on rescheduling, which shares the same reasoning as inventory reservation and is worth reading side by side.
Summary
Duplicate submissions and overselling look like fast fingers, but the substance is a write path with no single basis for deciding whether it has already run. Get the request ID, the unique constraint, conditional state updates, and inventory reservation with idempotent release right, then add reconciliation as a backstop, and most problems are stopped during design and acceptance. The small remainder goes to monitoring and alerts.
Sources and notes
The methods here are an organized summary of general engineering practice, combined with our design experience on custom software and mini program projects. The article cites no third-party benchmark data or industry statistics, and gives no specific performance figures, because concurrency levels, inventory granularity, and payment channels differ so much between systems that numbers detached from a concrete setting have no reference value. The appointment mini program article mentioned above is our own site content, offered for comparison.