Design a Permission-Gated Agentic Research Assistant
System DesignModel answerLast updated
Architect an LLM-powered agent for internal analysts that enforces row-level access control, supports durable multi-step workflows, and gates consequential actions behind human approval.
Scenario
Your team is building an AI research assistant for analysts at a regulated financial firm. Analysts type natural language questions like "How do my fixed-income positions compare to the benchmark on a risk-adjusted basis?" The agent interprets the request, selects the right tools, fetches data, and returns a synthesized answer.
Unlike a simple chatbot, the agent can also trigger downstream actions such as requesting a portfolio rebalance. This creates two distinct classes of behavior that must be handled very differently.
What You Need to Design
1. Authorization boundaries The system serves analysts with different roles, desk assignments, and information-barrier restrictions. The LLM must never be the component that decides what a user is allowed to see. Describe how entitlement checks are enforced outside the model, and how you prevent personally identifiable information (client names, account numbers) from appearing in model context.
2. Orchestration Explain how the agent manages tool discovery (which tools are available to a given user), multi-step planning, parallel execution, and loop termination. The system must survive process crashes mid-workflow without re-issuing external API calls.
3. Consequential actions Draw a clear boundary between read-only queries (market data lookups, performance calculations) and actions with real-world effect (submitting a rebalance to an order management system). Define the full lifecycle of a consequential action from the moment the model proposes it to the moment it executes.
4. Audit logging Every step must be logged for regulatory review. Describe the data model for these logs, covering what fields are captured, how immutability is enforced, and how long records must be retained.
Constraints
- 500 analysts, roughly 5,000 requests per day, with a sharp spike at market open
- Read-only queries must complete in under 5 seconds end-to-end
- A crashed or restarted process must be able to resume from its last completed step
- Consequential actions above a certain notional threshold require a second approver
Deliverables
Provide a high-level architecture diagram or description, then address each of the four areas above. Discuss trade-offs and failure modes rather than just the happy path.
Hints
Hint 1
Start by sizing the problem. 5,000 requests/day sounds large, but convert it to peak QPS first — the numbers change your architectural choices significantly.
Hint 2
The hardest constraint is not latency or throughput; it is that the model must never be trusted as a security decision-maker. Work out where authorization checks live and who holds credentials before designing the data flow.
Hint 3
Think about what 'durable' means for an LLM workflow. If the orchestrator crashes after a tool call returns but before the result is saved, what happens on replay? How do you prevent a rebalance proposal from being re-submitted to the OMS?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Size the Problem First
5,000 requests/day is roughly 0.06 QPS on average. A conservative 10x peak at market open brings that to about 1 QPS. If each request involves four or five LLM turns and four or five tool calls, peak load is around 10 model calls per second — well within what a small stateless fleet handles. The binding constraints are latency, correctness, and compliance, not raw throughput.
Latency budget for read-only queries (target: under 5 s):
- Each LLM turn runs 1–1.5 s, so the design can afford at most two or three turns.
- Tool calls run in parallel; a typical data API responds in 200–400 ms.
- Orchestration overhead is tens of milliseconds.
- Streaming partial output to the UI buys perceived responsiveness.
Audit volume: Roughly 20 events per request at ~10 KB each is about 1 GB/day, or ~2.5 TB over a seven-year retention window (the SEC 17a-4 standard). Storage is cheap; the real requirements are immutability and queryability.
Clarifying questions worth asking: Is a rebalance executed directly or staged to an OMS for review? What is the entitlement source of truth — a central IAM system, account-level ACLs, or information-barrier groups? Does "audit the model's reasoning" mean the visible output only, or a hidden chain-of-thought too?
2. High-Level Architecture
Analyst UI ──(SSO/OIDC)──► API Gateway ──► Agent Orchestrator (durable workflow)
│
┌───────────────────────────────┼──────────────────────┐
▼ ▼ ▼
LLM Gateway Tool Executor + PEP Approval Service
(prompt assembly, (schema validation, (HITL, cryptographic
redaction, logging) OBO token, OPA policy, signature check)
row-level filter) │
│ ▼
Market Data / Portfolio / OMS / Trading
Risk services (row-level ACL)
All components ──► Audit Event Bus ──► Append-only WORM store
Tool registry: Tools are stored with a JSON schema, a classification (READ or CONSEQUENTIAL), required permission scopes, and a data-sensitivity label. At session start, the orchestrator filters the registry by the analyst's roles. A tool the user cannot invoke is never included in the model's context window — there is nothing to jailbreak.
Orchestration loop: Each analyst request maps to one durable workflow (Temporal works well here). The loop is: plan → validate and dispatch tool calls in parallel → observe results → respond or plan again. Hard caps prevent runaway loops: a maximum step count (e.g., 6), a token budget, and a wall-clock deadline tied to the latency SLA.
Durability: When a workflow restarts after a crash, the engine replays its event history. Completed activities return their recorded results rather than re-executing, so downstream APIs are not called twice and the LLM is not re-sampled (re-sampling would change the decision path). Every external call also carries an idempotency key in the form workflow_id:activity_seq to cover the narrow window where a call succeeded but the result was not yet persisted.
3. Enforcing Authorization Without Exposing PII
The core principle: the model proposes; deterministic code decides. The model is never a security boundary.
Identity is injected, not chosen. Tool schemas contain no user_id parameter. The executor performs an OAuth on-behalf-of token exchange and calls downstream services with a short-lived, scoped token. The model cannot choose whose data to fetch.
Pre-execution policy check. Before running any tool, the executor asks the policy decision point (OPA or Cedar) a question such as: "Can user U invoke get_holdings on account handle A?" The policy covers account ACLs, desk restrictions, and information barriers. The default answer is deny.
Row-level filtering as defense in depth. Data services enforce their own row-level security using the user's token. The executor also strips disallowed rows or fields from the response before the result enters the prompt, so a misconfigured upstream service cannot leak data through.
PII tokenization. Client names and account numbers are replaced with opaque handles (ACCT_7f3a, CLIENT_19c2) before anything enters model context. The handle vault maps a handle back to its real value only for the session's user, and only after an entitlement check at render time. The model can reason about "ACCT_7f3a is 40% tech-sector exposure" without ever seeing the underlying identity. Handles are scoped per session, so a handle copied from another context resolves to nothing.
4. Lifecycle of a Consequential Action
The model can only draft a proposal. It has no tool that directly submits an order.
-
Propose. The model calls
propose_rebalance(portfolio_handle, target_weights, constraints). The executor validates inputs, runs pre-trade compliance (position limits, restricted-list check, concentration rules), computes concrete orders, and persists an immutableProposalrecord containing the canonical JSON payload and its SHA-256 hash. It returns aproposal_idand a human-readable diff to the model. -
Pause. The workflow suspends on a durable signal with a 15-minute expiry. No compute is consumed while waiting, and the state survives restarts.
-
Approve. The analyst sees a diff of current vs. proposed positions, estimated transaction cost, and risk impact. They sign
{proposal_hash, proposal_id, nonce, expiry}with a hardware-backed key (WebAuthn/FIDO2). Above a notional threshold, a second distinct approver must sign. -
Execute. The executor verifies: the signature is cryptographically valid; the signer holds trade authority on that account; the hash matches the stored payload (preventing the model from altering the action post-approval); the nonce is fresh and the approval has not expired; prices have not drifted beyond a tolerance. If prices have moved too far, the proposal is re-priced and returned for re-approval. Only then does the executor submit to the OMS using the idempotency key.
-
Observe. The execution result is returned to the model as a read-only observation so it can summarize the outcome. The model cannot trigger further orders from this signal.
5. Audit Data Model
One append-only row per event, immutable after write:
AuditEvent {
event_id UUID
workflow_id UUID -- one per analyst request
seq INT -- monotonically increasing within workflow
ts TIMESTAMP -- UTC, NTP-synced
actor { user_id, session_id, impersonated_by }
event_type ENUM(USER_PROMPT, LLM_REQUEST, LLM_RESPONSE,
TOOL_CALL, POLICY_DECISION, TOOL_RESULT,
PROPOSAL, APPROVAL, EXECUTION, ERROR)
model_meta { model_name, version, temperature, template_version }
tool_meta { tool_name, tool_version, args_hash }
policy_outcome { decision, policy_version, matched_rules[] }
payload_ref STRING -- pointer to encrypted blob in object store
prev_hash STRING -- SHA-256 of previous event; chains integrity
signature STRING -- signed by audit service private key
}
Immutability: Events are written to an append-only store (S3 Object Lock in COMPLIANCE mode, or equivalent). Each event hashes the previous one, producing a tamper-evident chain. The audit service holds the signing key in an HSM; its key usage is itself logged.
Retention: Seven years minimum to satisfy SEC 17a-4 and FINRA requirements. At ~1 GB/day this is about 2.5 TB — manageable and inexpensive in cold storage.
Queryability: A secondary index (e.g., a data warehouse projection) supports compliance queries like "show all tool calls by user U on account A in the last 90 days" without touching the write path.
Common Mistakes to Avoid
- Trusting the model to filter data. Prompt instructions like "only return data the user is authorized to see" are not a security control.
- Skipping idempotency keys. Crashes in the gap between a successful external call and its result being persisted cause duplicate orders without them.
- Logging only the final answer. Regulators often want the full reasoning chain, not just the output.
- Flat approval UX. Showing a wall of JSON to an approver means they rubber-stamp it. A diff view with risk impact is what actually enables informed human oversight.