Agentic Trading Index

Idempotency and retries for automated order placement

A trading terminal showing order status, illustrating idempotency and retries in automated order placement
Photo by panumas nikhomkhai on Pexels

One operator gets a timeout after submitting a 100-share buy order and immediately sends the same request again. The other treats the result as unknown, checks the broker's order records and finds the first order working. The first call can leave 200 shares exposed.

The second costs time and a status lookup, but avoids doubling the position. That difference is the practical problem behind idempotency and retries.

A network timeout says the client did not receive a response. It does not say the venue rejected the order. Build recovery around that uncertainty, not around the assumption that a failed HTTP call means a failed trade.

Why a timeout is not a rejection

An order request can reach the broker, pass validation and enter the market before the response is lost. A retry can then create a second live order. Conversely, a connection error before any request bytes leave the client may be safe to retry. Many client libraries do not make that distinction easy to observe, so start with a conservative rule: once submission may have reached the server, mark the intent as unknown and reconcile it.

Separate transport status from order status. A 200 response may confirm receipt, not a fill.

A 4xx response usually needs a specific fix, such as correcting a tick size or available quantity, rather than another attempt. A 429 should respect the response's Retry-After value where supplied. A 5xx can still follow an accepted order, so it is not proof that resubmission is safe.

Idempotency only works if the receiving API implements it. A client-generated key has no protective effect by itself.

Check whether the broker accepts a key or client order ID, what scope it uses, how long it retains the value, and whether reusing a key with a changed payload is rejected. Treat those details as endpoint-specific behaviour, not a general API guarantee.

Define one order intent, not one HTTP call

Create a durable intent before sending anything. Give it a unique ID and store the account, instrument, side, quantity, order type, limit price and time-in-force. Use that ID as the idempotency key or client order ID if supported. Retries of the same intent reuse the key and an identical payload. A genuinely new trading decision gets a new intent and key.

Record separate states such as prepared, submitted, acknowledged, unknown, partially filled, filled, cancelled and rejected. Persist the transition and broker identifiers. On a process restart, reload unresolved intents before generating fresh orders. This stops a restart from turning an uncertain request into an untracked duplicate.

Do not treat an order key as permission to replay forever. Some APIs retain keys for a limited period, and some only deduplicate within an account or endpoint. If the retention window has passed, or the response is unclear, query open orders and recent executions before deciding what to do. If the API offers no reliable lookup or deduplication, use a smaller order size, a strict exposure cap and a manual or delayed recovery path.

Amendments and cancellations need their own rules. An amendment may replace an order or create a new version, depending on the API. A cancel request can race with a fill. Store the request ID and then confirm the resulting order state; do not infer that a cancel succeeded from a successful HTTP response alone.

Run this week's retry audit

Use these steps against a sandbox or a controlled paper environment. Test the same code path that will send live orders. A paper trading environment for agent workflows can help exercise restart and recovery logic without risking capital, but verify the broker's own key and lookup semantics separately.

  1. Inventory every order-writing call. Record the endpoint, timeout settings, retry middleware, idempotency support and lookup route. Include submit, amend and cancel calls. Check whether a shared HTTP client retries POST requests automatically.
  2. Write down the intent schema. Confirm that the key survives process restarts and that its payload fingerprint includes every execution-relevant field. Reject accidental reuse when quantity, price or side changes.
  3. Classify responses. Make a table in code or tests for connection failure, read timeout, 429, 5xx, validation rejection, acknowledgement and partial fill. For each case, specify whether to retry, wait, query or stop. Avoid a single catch-all retry handler.
  4. Set bounded retry behaviour. Use exponential backoff with jitter for retryable reads and rate-limit responses. Typical engineering settings to test are a 0.5-2 second initial wait, a 5-30 second cap and two or three attempts. These are starting ranges, not venue guarantees. For an uncertain order submission, query first rather than applying the same schedule blindly.
  5. Inject ambiguous failures. Drop the response after the server accepts an order, delay a lookup, restart the worker between send and acknowledgement, and return a partial fill before a retry. Assert that the system does not exceed the intended remaining quantity.
  6. Check the audit trail. For each intent, be able to reconstruct request time, key, payload hash, attempt number, response, broker order ID, fills and final state. Alert on intents that remain unknown beyond your chosen threshold.

The figures below are typical engineering ranges for test planning, not promises about any broker or venue. Replace them with measured behaviour from the specific API and account configuration.

EventTypical range to testSafe handling
Connection setup0.5-2 secondsRetry only when the client can establish the request was not sent.
Order response timeout2-10 secondsMark unknown, then query by key or order history before resubmitting.
429 rate limit cooldown1-60 seconds, or the supplied Retry-After valueRespect the server delay and keep the same intent key.
Order lookup propagation100 milliseconds-5 secondsRepeat the read with bounded backoff; do not assume a missing first result means rejection.

Reconcile before resubmitting

Build one reconciliation function and use it after timeouts, restarts and ambiguous errors. Search by client order ID where possible, then compare broker order IDs, instrument, side, quantity and submission time.

Pull executions as well as open orders: a filled order will no longer appear in the open-order list. If the broker's lookup is eventually consistent, repeat the read for a bounded period before escalating.

For partial fills, calculate the unfilled remainder from confirmed executions. If the original intent was 100 shares and 35 have filled, any follow-up decision must account for 65, not resend 100.

Check whether the original order is still working before creating a replacement. Keep position limits and a per-intent maximum as independent safeguards, since reconciliation can also fail.

Measure ambiguous submissions, duplicate-order incidents, time to resolve unknown states and retries per accepted order. A rising rate of unknown states can signal a transport or broker issue even when the strategy's P&L looks normal. Alert before the system reaches its exposure limit, and stop order generation if it cannot establish the state of existing intents.

Stop doing these things:

  • Retrying every timed-out POST as if it were rejected.
  • Generating a new client order ID for each attempt at the same intent.
  • Resending the original quantity after a partial fill.
  • Marking an order failed solely because a response was missing.

Frequently Asked Questions

Should an automated trading system retry an order after a timeout?

Not until it has checked whether the order was accepted. A timeout leaves the result unknown, so query by client order ID or inspect recent orders and executions first. Retry the same intent only when the API's deduplication behaviour makes that safe.

How should an idempotency key be generated for an order?

Generate a stable, unique key for each trading intent, then persist it before submitting the request. Reuse it for retries of the identical payload, not for a new decision or a changed order. Confirm the broker's key scope and retention period.

What should a trading bot do when an order is partially filled?

Read confirmed executions and calculate the remaining quantity. Check whether the original order is still working before creating or amending another order. Never resubmit the original full quantity without accounting for fills.