Agentic Trading Index

Idempotency and retries for safer automated order placement

Developer checking an automated trading dashboard while managing order idempotency and retries
Photo by Joshua Mayo on Pexels

At the end of a bad week, a developer watches a dashboard show two filled buy orders where the strategy issued one. The first request timed out.

The agent retried, and both submissions reached the broker. The position is twice the intended size; the logs say only that the first response was missing.

A timeout is an exposure event

A network timeout describes what the client knows, not what the broker did. The broker may have rejected the request, accepted it and lost the response, or filled it before the connection failed. Treating every timeout as a failed order turns an availability problem into a position-limit problem.

Exactly-once delivery cannot be guaranteed by a client alone across an unreliable network. The practical target is effectively-once execution: identify each intended order, prevent duplicate acceptance where the broker supports it, then reconcile broker state before another submission. This is a risk control, not just a way to make an API call more reliable.

Reserve buying power and exposure for the intended order before sending it. Keep that reservation while the result is unknown. Releasing it on a timeout can let another strategy order consume the same risk budget while the original is live.

Make the order intent idempotent

Create a unique client order ID for each distinct trading intent and persist it before sending the request. Reuse that same ID for retries of that intent. Do not generate a fresh ID after a timeout: that makes the retry look like a new order to a broker that deduplicates by client ID.

Store the ID with the account, instrument, side, quantity, order type, limit price and strategy decision. Enforce uniqueness in your database for the appropriate scope, usually account plus client order ID.

If the strategy changes price or quantity, record a new version or a separate cancel-and-replace action. Do not mutate the original intent silently.

Broker behaviour varies. Some APIs reject repeated IDs, some return the original order, and some only retain deduplication records for a limited period. Check the documented scope and retention window, then test the behaviour in a sandbox.

If the broker has no idempotency key, use a client order ID where available and reconcile open orders and executions before resubmitting. The Agentic Trading Index paper-trading environment, from $9.99 a month, can help exercise these failure paths before live orders are enabled.

Retry by failure class

Use a bounded policy, not a catch-all retry loop. A connection reset or timeout after sending is an unknown outcome.

Query by client ID and inspect open orders, recent executions and rejections before taking action. If the broker cannot confirm status, keep the intent in an unknown state and stop new orders that could exceed its reserved risk.

Classify responses before retrying:

  • Rate limit: honour the broker's retry-after value. Apply jitter and keep within the account's rate budget.
  • Server error or connection failure: check order status first. Retry with the same ID only where the broker's deduplication rules make that safe.
  • Validation error or insufficient buying power: do not retry unchanged. Record the rejection and let strategy or risk logic decide what happens next.
  • Authentication or permission error: stop submissions and alert an operator. Repeated attempts will not fix a disabled permission.

Exponential backoff with jitter can reduce load, but it does not resolve an unknown order state. A common starting policy for safe transient failures is a small number of attempts, such as two or three, with delays that grow from hundreds of milliseconds to a few seconds.

Set the exact limits against broker rate limits, market conditions and the strategy's time horizon. A stale order should expire or be cancelled, not be submitted late just because a retry timer fired.

Put a cost on duplicate exposure

The unwanted position can matter more than the API fee. The table gives illustrative typical market ranges for a $10,000 duplicate market order in liquid US equities under ordinary conditions.

Costs vary by broker, venue, instrument and volatility. These are not audited company results, and a fast price move can exceed them.

Cost componentTypical market rangeScope
Spread crossing to unwind$1 to $5About 1 to 5 basis points round trip on $10,000
Additional execution slippage$0 to $10About 0 to 10 basis points in ordinary liquid conditions
Explicit commissions and fees$0 to $10Indicative round-trip range; broker schedules vary

These figures exclude the market move while the excess position remains open. A 1% adverse move on $10,000 adds $100 before fees. Set a maximum unintended exposure and an escalation rule for unknown orders. A retry ceiling without an exposure ceiling is incomplete.

Keep evidence and risk controls together

For every intent, retain enough evidence to reconstruct what the agent knew and when. Record the strategy decision, client ID, payload hash, account, UTC timestamps, each attempt, broker response, status query, execution and any risk-limit decision. Keep original request data immutable; append events instead of overwriting history.

Useful controls include:

  • A pre-trade reservation that counts submitted and unknown orders against gross, net and instrument limits.
  • A kill switch that blocks new submissions without discarding the ability to query, cancel or reconcile existing orders.
  • Alerts for duplicate broker IDs, multiple broker order IDs for one intent, repeated unknown states and retry-limit breaches.
  • Retention and access controls aligned with the firm's recordkeeping policy and broker terms.

Cancellation also has races. A cancel request can arrive after a partial or full fill, so never treat a cancel acknowledgement as proof that no position exists. Reconcile executions and remaining quantity, then update the risk reservation. For compliance review, the record should show both the order lifecycle and why the agent retried, stopped, cancelled or escalated.

Checklist before unattended release

Run failure tests against the exact broker adapter and order types intended for production. Include timeouts after request transmission, delayed acknowledgements, duplicate callbacks, partial fills, rate limiting and a broker response that arrives after the client has marked an order unknown. Confirm that the database and risk service recover consistently after a process restart.

  1. Persist a unique order intent and client ID before any network call.
  2. Prove that a retry reuses the ID and cannot increase reserved exposure.
  3. Verify broker deduplication scope, retention period and status-query behaviour.
  4. Test partial-fill, cancel and replace races, including late responses.
  5. Confirm retry limits, backoff, stale-order expiry and operator alerts.
  6. Check that an unknown order blocks conflicting exposure until reconciliation.
  7. Review an audit record from decision through final execution or rejection.

Do not enable unattended retries until these controls pass in the deployment configuration, not just in a unit test. Check the production retry ceiling for one order intent: is it 3 attempts?

Frequently Asked Questions

What does idempotency mean in automated order placement?

It means repeated requests for the same order intent do not create multiple live orders. In practice, the client reuses a stable identifier and relies on broker deduplication where available, then reconciles the broker's order and execution state.

Should an agent retry an order after a timeout?

Not until it checks whether the broker accepted the original request. Query by client order ID and inspect open orders, executions and rejections. If status remains unknown, retain the risk reservation and pause conflicting orders.

Should retries use a new client order ID?

No, retries of the same intent should normally reuse the same ID. A changed price or quantity is a new order version or a cancel-and-replace action, not a retry of the unchanged request.

How many times should an automated trading system retry?

Use a bounded number based on broker limits and strategy timing. Two or three attempts can be a starting point for safe transient failures, but unknown order status requires reconciliation rather than blind resubmission.

What should an order retry audit log contain?

Keep the intent ID, client and broker order IDs, request details or payload hash, timestamps, responses, retry reason, status queries, executions and risk decisions. Preserve events rather than overwriting earlier states so a reviewer can reconstruct the order lifecycle.