Skip to content

Execution

How idempotency prevents duplicate crypto workflow orders

A worked duplicate-delivery example and intent-record worksheet show where exchange client IDs help and where durable workflow state is needed.

Ivory tokens approach a lime-accented gate while one token sits in a recessed socket, illustrating duplicate workflow detection.
Illustration for execution; examples in this article are educational.

Idempotency in a crypto trading workflow means that processing the same trading intent again does not create another order or repeat another side effect. It requires a stable intent identity, a durable record of what happened and exchange-specific recovery rules. Reusing an API client order ID alone does not establish that guarantee.

A duplicated webhook, two workers handling the same candle close or a restart after a lost response can all repeat work. The useful design question is whether each repetition returns to the original decision record before it can change the account.

This guide explains a workflow design pattern for operators and builders. The examples are hypothetical, and the exchange documentation establishes only the venue behavior cited. It does not establish that KLINEO or another platform implements the whole pattern.

Decide what counts as the same intent

An event, a trading intent and an order attempt need separate identities.

An event is an occurrence such as a specific candle close. An intent is the resulting approved action, such as one entry for that occurrence. An attempt is one interaction with the exchange. A transport retry can create another attempt while remaining attached to the same intent.

For a candle-driven strategy, an intent record might identify the account, live or test environment, market, instrument, original candle-close time, strategy revision and entry slot. Capture that revision when the event first enters the workflow. Redelivering an older event must retrieve its original record; deploying a new revision must not silently turn that replay into a fresh entry.

The candle-close trigger contract establishes which completed bar starts an evaluation. Intent identity then determines whether the resulting action is new work or a repetition.

Do not use the time a worker receives the message as the event identity. Every redelivery has a different arrival time. Conversely, identical order parameters do not prove duplication: two scheduled purchases on different days can legitimately buy the same quantity at the same limit price.

AWS describes the general approach of using an explicit request identifier and rejecting changed parameters under that identifier in its guide to making retries safe with idempotent APIs. Applying it to trading requires defining the business intent before constructing an exchange request.

Keep an identity record before submission

Use the following worksheet when assessing a workflow. It is a suggested record, not an exchange API schema.

Record itemQuestion it should answer
Event identity and intent keyWhich occurrence and approved action does this belong to?
Account, venue, environment and productWhere may the action change exposure?
Frozen economic parametersWhat symbol, side, quantity, order type and price constraints were approved?
Action identityIs this an entry, protective order, cancellation or journal update?
Current state and attempt historyHas submission started, and is the exchange result known?
Client and exchange order identitiesHow can the original order be found?
Fill evidence and observation timeWhat execution has been confirmed, and how current is that evidence?

Store the economic parameters or a reliably comparable representation alongside the intent. If the same key arrives with a different quantity, stop and resolve the mismatch. A price or quantity change needs an explicit amendment or new decision with its own authorization. Transport fields such as a fresh authentication timestamp can change without changing the approved economic intent.

Where a person must authorize the action, the human-approval worksheet makes the exact quantity, account and expiry inspectable. Idempotency preserves that decision rather than supplying permission by itself.

The record must survive a process restart. A flag held only in memory disappears precisely when recovery needs it.

Three deliveries should still represent one purchase

Consider a hypothetical spot workflow authorized to buy 250 USDT of an asset for each qualifying candle. Assume every purchase fills fully. Fees and price movement are excluded so the example isolates duplicate execution.

The event for one candle is delivered three times: the initial delivery, a retry after an acknowledgement is lost and a delayed replay after a worker restarts.

DeliveryWorkflow observationRequired handling
First copy of candle ANo record existsCreate and claim one intent, then begin its approved execution path.
Retry of candle AThe record shows submission with an unknown resultRecover that attempt; do not create another entry.
Late replay of candle AThe record shows a completed 250 USDT purchaseReturn or reference the recorded outcome.
First copy of qualifying candle BA genuinely different occurrence arrivesEvaluate a new 250 USDT intent under current limits.

With independent purchases for all three copies of candle A, gross spending would be 3 × 250 = 750 USDT. With the intended behavior, candle A produces 250 USDT of spending. If candle B separately qualifies and is approved, the two distinct intents total 250 + 250 = 500 USDT.

Suppressing candle B because its order looks identical would be the opposite error: merging separate decisions. The identity must distinguish legitimate repetition from redelivery.

Two workers can both pass a simple check

“Check whether the key exists, then insert it” leaves a race if two workers perform the check before either inserts. Use a storage operation that atomically creates or claims the unique intent, with only the successful owner permitted to advance it.

A unique record still does not make a local database transaction and a remote exchange submission one indivisible operation. A worker can send the order, lose the response and crash before saving the exchange order ID. The next worker needs a persisted client identity and an unresolved submission state to investigate.

A timed-out ownership lease is not evidence that the earlier worker never submitted. Prevent an expired owner from advancing local state again, and treat a previous wire attempt as potentially effective until reconciled. Design and test this boundary with the actual venue adapter; no generic database flag supplies an end-to-end execution guarantee.

Exchange client IDs are part of the evidence

Binance Spot documents newClientOrderId as unique among open orders and permits another order with that ID when the previous one is filled. Replaying a completed purchase can therefore create fresh exposure even with the same identifier. The workflow needs its own completed-intent record. See Binance Spot new-order parameters.

Bybit specifies a unique orderLinkId of no more than 36 characters. It also describes placement acknowledgement as asynchronous and directs users to the WebSocket stream to confirm status. These are Bybit order-placement rules, not a universal promise that a repeated create call returns the first result.

When an outcome is uncertain, preserve the original identity and query supported order and execution records. Binance explicitly says that a processing timeout can leave execution unknown and calls for a status query if the result has not appeared in the user data stream. See Binance general REST API information.

The order timeout reconciliation guide covers that recovery process. A missing open-order row is insufficient evidence that the original intent never traded.

Give each side effect its own lifecycle

One successful entry does not mean every downstream step finished. A stop order, journal write and notification have different identities and completion evidence. Restarting the entire workflow because a notification failed must not repeat the entry.

Record each action against the parent intent. Deduplicate execution events using the provider's identifiers and documented semantics, and reconcile cumulative fills when appropriate. The WebSocket recovery guide explains why counting repeated status messages as new trades corrupts accounting.

Keep an intent's evidence long enough to cover the workflow's actual replay and recovery horizon. If an old event arrives after its record has been deleted, the system can mistake it for new work. Define retention and event-expiry policies together, and block stale signals from opening new exposure. Expiring a signal must not discard the duty to resolve an order already submitted.

Test duplicate handling as an account-state outcome

In a controlled environment, replay one event concurrently, restart after submission but before saving the response, replay it after the order fills and send the same key with changed quantity. Also test a legitimate new occurrence with identical economic parameters.

Inspect the resulting intent records, exchange orders and fills. A green workflow status cannot prove that only the approved exposure exists. Compare the actual state with the expected one in the paper-trading validation process, then verify venue-specific behavior separately before live use.

Idempotency does not validate the trading signal or make an unwanted first order harmless. It makes repetition accountable to the original decision. The practical acceptance criterion is one explained outcome per approved intent, with unresolved execution kept visible until the evidence supports a resolution.

Keep the context with the example.

Each worked example is illustrative, with its sources and assumptions in the article. Read our editorial standards for authorship, verification and corrections.