One operator sees a 2-second timeout after submitting a market order and retries immediately. Another records the request as unresolved, checks the broker for the order, then retries only if it cannot find a match. The first favours speed; the second favours avoiding a duplicate position. Neither call is safe in every situation, but the difference exposes the central problem: a client timeout is not proof that the broker rejected the order.
For software trading without a human watching, idempotency and retries are a question of controlling uncertainty across two systems. The client can lose a response after the broker accepts an order.
A connection can fail before the request arrives. The broker can accept an order but delay its status update. A reliable execution service must distinguish those states instead of treating every error as permission to send again.
Model the uncertain outcome before choosing a retry
When an HTTP request times out, the client usually knows only that it did not receive a complete response. The order may be absent, accepted, rejected, partially filled, or filled with the acknowledgement still in transit. Retrying a non-idempotent order request can turn one intended trade into two live orders.
There is no general exactly-once guarantee across a trading client, network and broker. A client can make its own processing idempotent, and a broker may offer request deduplication, but neither removes every failure between systems.
Treat order submission as a state machine with an explicit uncertain state. Do not convert uncertainty into failure just to simplify the code.
A useful distinction is between an order intent and an API attempt. The intent describes what the strategy means to do: instrument, side, quantity, order type, limit price and a strategy decision identifier. An attempt is one delivery of that intent to the broker. A retry should normally reuse the original intent and its deduplication identifier, not create a fresh order identity.
- Known rejection: the broker returned a definitive rejection. Correct the cause or stop; do not blindly repeat the same invalid request.
- Known acceptance: the broker returned an order ID. Track that order, including partial fills and later state changes.
- Unknown outcome: the connection failed or response was ambiguous. Reconcile before submitting another order.
- Known absence: a sufficiently reliable broker query shows no matching order. Retry only under a bounded policy.
HTTP status alone is not enough to classify an outcome. A 4xx response often means the broker rejected the request, but rate limits, authentication failures and gateway responses need different handling.
A 5xx response can occur after the broker has already accepted an order. Read the broker's error semantics, log its request or correlation IDs, and preserve the raw response for diagnosis.
Choose an idempotency boundary that matches the order
Use broker keys or client order IDs where the API enforces them
A broker idempotency key can make repeated submissions of the same request return the original result rather than create another order. A client order ID can serve a similar role if the broker enforces uniqueness and supports lookup by that ID.
These mechanisms are valuable, but their guarantees are specific to the API. Check whether deduplication applies across accounts, endpoints, sessions and restarts, and how long the broker retains the key.
Generate the identifier once when the strategy commits an intent. Persist it before the network call, and reuse it for every retry of that intent. Do not generate a new UUID for each attempt. If the same key is sent with a changed quantity or price, the broker may reject the request, return the first result, or behave according to its own rules. Keep a payload hash alongside the identifier so the client can detect accidental changes locally.
Client order IDs are not universal protection. Some APIs accept them but do not enforce uniqueness; others scope uniqueness narrowly or allow reuse after a session ends.
Verify the behaviour with tests and documentation. If the broker does not guarantee deduplication, a client order ID still helps reconciliation, but it cannot by itself make a retry safe.
Persist intent and attempts separately
Write the intended order to durable storage before sending it. A useful record includes the strategy decision ID, account, instrument, side, quantity, order type, prices, client order ID, payload hash, creation time and current state. Store each network attempt separately, with its start time, response or exception, and correlation ID if available.
This separation handles process restarts. If a worker crashes after sending the request but before recording the response, it can reload the unresolved intent and query the broker. It should not reconstruct a fresh order from the strategy's current signal, since that signal may have changed. An outbox pattern can make saving an intent and scheduling its delivery atomic inside the client's database, although it cannot make the broker call part of that database transaction.
Set a uniqueness constraint on the internal intent ID and, where appropriate, on the client order ID within the broker's documented scope. Make strategy decisions that deliberately create another order use a new intent ID. For example, a later rebalance or a new entry after a completed exit is not a retry, even if the instrument and side match an earlier order.
Compare retry and recovery strategies
Choose how to handle an ambiguous submission
The approaches below solve different parts of the problem. The figures are typical operating ranges or commonly encountered API behaviours, not guarantees. Confirm broker-specific limits, especially key retention and client order ID uniqueness, before relying on them in live trading.
| Approach | Duplicate protection | Typical range or limitation |
|---|---|---|
| Broker idempotency key | Broker deduplicates repeated requests using the same key | Retention may range from hours to several days; confirm the documented window |
| Client order ID | Broker may reject or identify duplicate IDs | Uniqueness scope varies by account, session or endpoint; some APIs do not enforce it |
| Query before retry | Finds an accepted order before another submission | Initial wait of 0.5 to 2 seconds, then polling every 1 to 5 seconds is a common starting point |
| Bounded backoff | Reduces request bursts, but does not deduplicate orders on its own | Intervals often start around 250 milliseconds and cap between 2 and 5 seconds |
| Manual or automated hold | Prevents a second order while the outcome remains unknown | Can hold exposure unresolved for seconds or minutes if broker data is delayed |
A broker key is the strongest option when its semantics are clear and the key remains valid for the whole recovery window. Query-before-retry is a useful fallback, but it depends on the order endpoint being searchable and the broker's data being current. If the query is eventually consistent, an empty result immediately after a timeout does not prove that no order exists.
Some systems combine the two: submit with a stable key, then query by key or client order ID if the response is lost. This is usually safer than choosing either mechanism alone. A delayed or stale query should leave the intent unresolved rather than trigger a rapid second submission.
Bound retries by state, time and risk
Use exponential backoff with jitter for transient transport errors and rate limits. A common starting policy is a short first delay, then increasing delays capped at a few seconds. Jitter helps prevent a fleet of workers from retrying together after an outage. Backoff controls load; it does not make an order request idempotent.
Give each intent a retry budget and a deadline. For example, a service might make three to five attempts over 10 to 30 seconds for a transient error, while continuing reconciliation separately for an ambiguous submission.
These are tuning ranges, not defaults that fit every strategy. A market-making order with a short useful life may expire quickly; a slow-moving limit order may justify a longer recovery window.
Before another submission, check whether the original intent is still valid. The signal may have changed, the market may have moved beyond a slippage limit, the order may have partially filled, or the account may have reached a position cap. Do not let a retry policy turn a stale strategy decision into a fresh order.
- Classify the error as a definite rejection, a transient failure before submission, or an ambiguous outcome.
- For an ambiguous outcome, query open orders and recent order history using the strongest available identifier.
- Match the broker record against account, instrument, side, quantity, client order ID and submission time. Avoid matching on symbol alone.
- If a match exists, adopt its broker order ID and continue tracking fills. If no match exists, retry with the original intent ID only when the API's deduplication rules make that safe.
- If the result remains unclear at the deadline, hold the intent and alert or apply a pre-agreed risk policy. Do not silently create a second order.
Cancel-and-replace needs the same care. A cancel request can time out while the original order remains live or fills. Sending a replacement immediately can leave both orders executable. Confirm cancellation, inspect cumulative fills, then calculate the replacement quantity from the remaining intended exposure.
Make recovery observable before sending live orders
Log and measure the full lifecycle, not just HTTP success. Useful fields include intent ID, client order ID, broker order ID, attempt number, request timestamp, response timestamp, state transitions, fill quantity, average fill price, error class and reconciliation result. Keep identifiers stable across application restarts so an operator or recovery process can connect the records.
Track the rate of ambiguous submissions, duplicate-order detections, time to resolve an unknown state, retry counts, partial-fill corrections and broker query failures. Alert on unresolved orders that exceed the strategy's normal recovery window. A rising timeout rate or a change in the delay between submission and visibility can be a reason to stop new orders, not to increase retry volume.
Test failure paths deliberately. Drop the response after the broker accepts an order, restart the worker between submission and persistence of the acknowledgement, return a stale order query, and simulate partial fills during cancellation. The test should verify that one strategy intent does not create multiple live orders and that unresolved exposure remains visible. Paper trading can help exercise these paths; a controlled environment such as agentic trading paper trading is useful for testing the client's recovery logic before live orders, though it cannot prove a broker's exact production behaviour.
Keep a hard stop available when reconciliation is unavailable or the broker's responses contradict local state. Depending on the strategy, that may mean pausing new submissions for one account, instrument or worker, while continuing to monitor existing orders. The safe scope should be explicit in configuration, with an alert that identifies the unresolved intent and the action taken.
I would first make every order intent durable and assign it one stable client order ID before the first network call. Then I would test the lost-acknowledgement path against the broker's actual deduplication and query behaviour, and keep ambiguous orders on hold until that recovery is proven.
Frequently Asked Questions
What should a trading bot do after an order request times out?
Treat the outcome as unknown, not rejected. Query open orders and recent order history using the original client order ID or idempotency key, then retry only if the broker's response and deduplication rules support it.
Does a client order ID prevent duplicate orders?
Only if the broker enforces uniqueness in the relevant account and endpoint scope. If it does not, the ID can still help find and reconcile an order, but it cannot make a repeated submission safe by itself.
How many times should an automated trading system retry an order?
Set a bounded retry budget based on the strategy's order lifetime and the broker's rate limits. Use backoff for transient errors, but reconcile ambiguous submissions separately rather than repeating them until a retry count is reached.