Design a Governed AI Agent for Automated Trade Execution
System DesignModel answerLast updated
Design a safety-first, ML-driven order generation system with deterministic validation gates, idempotent execution, and a fully replayable audit trail.
Context
A large asset management firm runs hundreds of investment strategies across equities, futures, and FX derivatives. Each strategy has a target allocation that drifts over time as markets move. You are asked to design an AI-driven rebalancing agent that continuously monitors these drift signals and alpha model outputs, then proposes corrective trades.
Because ML and LLM-based systems can produce unreliable outputs under unusual market conditions, no model-generated trade instruction may reach an execution venue directly. Every proposed order must clear a sequence of deterministic rule checks and, where warranted, receive explicit human sign-off before anything is routed.
Functional Requirements
- Proposal engine: Consume target weights, live positions, cash balances, and market feeds to produce structured trade proposals: instrument, side, quantity, notional, and order type.
- Governance pipeline: Every proposal must pass through, in order:
- A freshness check verifying that prices and positions have not moved beyond tolerance since the proposal was generated.
- Entitlement and mandate checks: restricted instruments, leverage ceilings, sector concentration caps.
- Hard pre-trade risk checks: value-at-risk limits, drawdown caps, liquidity constraints.
- An escalation layer routing large or sensitive orders to a human approval workflow.
- Execution with exactly-once semantics: Proposals that clear all gates must be routed without duplicates even under retries or partial failures.
- Immutable audit trail: Every event — proposal, tool call, check outcome, human decision, fill — must be stored in a way that allows full reconstruction of what happened and why.
Non-Functional Requirements
- Scale: ~5,000 active strategies, up to 100,000 candidate orders per rebalancing window.
- Latency: Under 500 ms end-to-end for automated paths; sub-second dashboard updates for human reviewers.
- Isolation: No cross-strategy information leakage. Proprietary signals must stay within their owning strategy pod.
What Your Answer Should Cover
- Component architecture: How the agent, state store, governance engine, and order router fit together, and why those boundaries exist.
- Typed data model: What the proposal and validation records look like as structured schemas (not free-form text).
- Validation sequence: The ordered checks between proposal generation and execution, and the rationale for that ordering.
- Concurrency and freshness: How the system handles race conditions when market data changes between when a proposal is generated and when it is approved.
- Exactly-once routing: The mechanism that prevents duplicate orders under retries or node failures.
- Audit and replay: How the event log is structured so that any past decision can be reconstructed offline.
- Security and isolation: How the system prevents alpha leakage and keeps execution credentials away from the model layer.
Hints
Hint 1
Start by drawing a strict privilege boundary: the agent can read state and write proposals, but it should hold zero execution credentials. Ask yourself what would happen if the model were compromised or hallucinated a large order.
Hint 2
The freshness check is not just 'is the data recent?' — it needs to compare the exact snapshot version the model used against the current version and compute actual drift in bps. A stale-but-within-tolerance proposal should be re-priced and allowed through; only genuinely stale proposals should be rejected.
Hint 3
Exactly-once execution in a distributed system is really idempotent at-least-once. Make the order ID deterministic (hash of plan ID and leg index), use an outbox pattern to durably record the routing intent before sending to the venue, and rely on the venue rejecting duplicate client order IDs.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify Scope and Size the Problem
Before drawing boxes, pin down numbers — they determine where the hard problems actually are.
Volume and throughput: 5,000 strategies with up to 100,000 candidate orders per 10-minute rebalancing window works out to roughly 170 orders/s average, with bursts of 2–5k/s when many strategies fire on the same signal. Design the governance pipeline for 5k/s peak validation throughput, parallelized across independent strategies.
Latency budget (automated path, 500 ms p99):
| Stage | Allocation |
|---|---|
| Schema validation + freshness check | 20 ms |
| Mandate and entitlement rules | 30 ms |
| Incremental pre-trade risk | 200 ms |
| Escalation decision + durable persist | 50 ms |
| EMS routing | 100 ms |
| Headroom | ~100 ms |
LLM generation time sits upstream of this clock and runs asynchronously.
Audit volume: ~10 events per order at ~2 KB each produces roughly 2 GB per window. Storage is cheap; integrity is not. The hard requirement is hash-chained, tamper-evident records with WORM-backed archival (SEC 17a-4 / MiFID II mandates 5–7 year retention).
Key clarifications to raise in an interview:
- Are baskets atomic (all legs or none) or best-effort?
- What are the four-eyes rules for human approvals?
- What drift tolerance applies per asset class?
2. Architecture: Strict Privilege Separation
The central design principle: the agent is a proposal generator with zero execution privileges. It holds no venue credentials. Its only output is a typed, validated message dropped onto a queue.
Market data / positions / alpha feeds
│
▼
State Store (versioned snapshots — Redis hot, OMS as source of truth)
│
▼
Agent Proposal Engine (LLM orchestrates deterministic optimizer tools;
read-only access to State Store)
│ RebalancePlan (Protobuf)
▼
Governance Gateway (stateless, deterministic workers — no ML)
schema → freshness → mandate → risk → escalation policy
│ │
auto-approved Human Approval Service
▼ │
Order Router (only component with EMS creds) ◄┘
│
EMS ──► fills ──► State Store
│
Every arrow also writes to ──► Append-only, hash-chained Event Log
│
WORM object store (archive)
The LLM reasons over context and selects tools; quantities come from a deterministic optimizer (e.g., a convex rebalancer given target weights). Free-form LLM output is never parsed for action — only the structured tool outputs feed the proposal.
3. Data Model
message CandidateOrder {
string order_id = 1; // deterministic: hash(plan_id, leg_index)
string portfolio_id = 2;
string instrument_id = 3; // FIGI — never free-text
Side side = 4;
Decimal quantity = 5;
OrderType type = 6;
Decimal limit_px = 7;
}
message RebalancePlan {
string plan_id = 1;
string pod_id = 2;
repeated CandidateOrder legs = 3;
BasketPolicy basket_policy = 4; // ATOMIC | BEST_EFFORT | GROUPED
StateVersions basis = 5; // position_ver, cash_ver, md_ver per instrument
ProvenanceHashes provenance = 6; // model_hash, prompt_hash, tool_output_hashes
string rationale = 7; // display only — never parsed
}
order_id being deterministic is what makes exactly-once semantics possible. basis is what makes the freshness check precise.
Event log types (append-only, partitioned by plan_id, each carrying prev_hash):
PlanProposed → ToolCallRecorded → CheckEvaluated → EscalationRequested → HumanDecision (signed) → OrderRouted → ExecutionAck / Fill / PlanInvalidated
Full prompts and context are stored encrypted in a content-addressed blob store and referenced by hash — this keeps the event log small while preserving full reconstructability.
4. Validation Pipeline (cheapest checks first)
-
Schema and sanity. Known instrument ID, positive quantity, correct lot size, price within a collar of last trade, no duplicate legs. Reject immediately on any violation.
-
Freshness check. Compare the
basissnapshot versions embedded in the plan against current versions. If they differ, compute actual drift in bps. Within tolerance: re-price and continue. Outside tolerance: reject asSTALEand request regeneration. This guards against a proposal acting on a market picture that no longer exists. -
Entitlement and mandate. Does this pod own the portfolio and have permission to trade this asset class? Check restricted lists, leverage ceiling, and sector/issuer/country concentration caps — evaluated on the post-trade portfolio, not the current one.
-
Hard risk. Incremental VaR from precomputed factor exposures (marginal contributions, no full revaluation per order), drawdown cap, liquidity limit (% of ADV, days-to-liquidate), and concentration. Risk is assessed on the basket's net effect, not leg by leg — otherwise a split basket can pass individually but breach jointly.
-
Escalation. Escalate if notional exceeds $10M, size exceeds 5% ADV, instrument is novel, or model confidence is below threshold. The default is escalate-or-deny, never silently allow. Human decisions are recorded with the approver's identity, timestamp, and the exact snapshot version they reviewed.
Strategies are independent — their checks run in parallel. Within a single strategy, evaluation is serialized.
5. Concurrency, Freshness, and Exactly-Once Execution
Optimistic concurrency for approval. Authorization commits an APPROVED status only if position_ver in the state store still matches the basis version in the plan. If it has moved, the plan is rejected and re-queued. For market data, strict version equality is impractical (prices tick constantly), so a bps-tolerance comparison is used instead.
Headroom reservation. On approval, atomically reserve risk budget (gross exposure, VaR headroom) per portfolio. This prevents two concurrently approved baskets from jointly breaching a limit that each individually clears. Reservations are released on fill, cancellation, or TTL expiry.
Exactly-once via outbox pattern. True exactly-once is not achievable across a network boundary; the practical equivalent is idempotent at-least-once:
order_idis deterministic and is used as the FIXClOrdID.- The router writes an
OrderRoutedevent with a unique constraint onorder_idbefore sending to the venue — this is the outbox. - On retry or restart, the router reconciles by querying EMS order status before resending.
- The EMS rejects any duplicate
ClOrdID, so even if a message is sent twice, only one order is created.
6. Security and Information Barriers
- The agent reads only the state for its own pod; cross-pod reads require explicit, logged entitlement grants.
- The order router is the only component with EMS credentials. The agent layer has no path to them.
- Proprietary model weights and alpha signals never leave the pod's compute boundary; only their hashes appear in the audit log.
- Human approval dashboards show only the fields necessary for a decision — not raw position data that could reveal another strategy's intent.
Common Mistakes to Avoid
- Letting the LLM parse its own output for action. Always interpose a schema parser; the rationale field is display-only.
- Running risk checks leg by leg. A basket's net effect can breach limits even when each leg passes individually.
- Using wall-clock time for freshness instead of data versions. A version number is unambiguous; a timestamp is not.
- Treating human approval as the last safety gate. Approvals should also be time-limited and bound to a snapshot version — an approval from 10 minutes ago on stale positions is not safe.