Design a Multi-Agent AI Chat Platform for Financial Services
System DesignModel answerLast updated
Design a scalable and secure backend system for an LLM-powered multi-agent financial assistant with real-time streaming, conversation persistence, and strict compliance controls.
Design the backend architecture for an enterprise financial assistant platform powered by Large Language Models (LLMs) and specialized autonomous agents.
Context & Requirements
Users interact with a chat interface to ask complex financial questions, review market data, generate financial models, and analyze internal corporate filings. The platform must handle agent orchestration behind the scenes while maintaining real-time responsiveness and strict financial compliance.
Core Functional Requirements
- Interactive Chat & Streaming: Process user messages and stream assistant responses with low initial token latency.
- Context & State Management: Maintain session state, allow conversation resumption/branching, and manage context token limits efficiently.
- Multi-Agent Orchestration: Route incoming user requests across autonomous agents (e.g., Query Planner, RAG Retriever, Deterministic Calculator, Compliance Checker, and Final Synthesizer).
- Tool Execution Gateway: Securely execute internal database queries, third-party financial API calls, and code execution sandboxes.
- Auditing & Compliance: Provide deterministic audit trails, strict PII/MNPI (Material Non-Public Information) filtering, and enforcement of document access control lists (ACLs).
Non-Functional Requirements
- Scale: Support 50,000 active users, 5,000 peak concurrent active sessions, with a system load of ~20 incoming user messages per second (fanning out to ~200 agent/LLM calls per second).
- Latency: Time-to-first-token (TTFT) should be under 1.5 seconds for direct queries; multi-step analytical workflows must stream intermediate status events.
- Reliability & Isolation: 99.9% uptime. System state must persist across worker node crashes. Zero cross-tenant data leaks.
Describe the system architecture, API schemas, data models, worker orchestration flow, and strategies for handling failure and security.
Hints
Hint 1
Decouple the initial message ingestion HTTP request from the long-lived response stream. Consider how persistent run IDs allow client reconnects without re-triggering model generation.
Hint 2
LLMs frequently struggle with precise financial arithmetic. How can your agent framework delegate math operations to a sandboxed execution engine?
Hint 3
How do you enforce fine-grained access control (ACLs) when performing vector similarity searches across confidential financial documents?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture Overview
The system uses an asynchronous, event-driven microservices architecture. Client message submission is decoupled from real-time response streaming to guarantee delivery and support network reconnection.
+-------------------+
| Client Web/App |
+---------+---------+
|
(HTTPS / SSE)
v
+-------------------+
| API Gateway | (Auth, Rate Limiting, Tenant AuthZ)
+---------+---------+
|
+----------------+----------------+
| |
v v
+--------------------+ +--------------------+
| Session Service | | Streaming Engine |
+----------+---------+ +----------+---------+
| ^
(Persist Msg / Run) | (Tail Events)
v |
+--------------------+ +--------------------+
| PostgreSQL DB | | Redis Streams |
+--------------------+ +----------+---------+
| ^
(Enqueue Event) |
v |
+--------------------------------------------+---------+
| Workflow Engine |
| (e.g., Temporal Workers / Kafka) |
+--+-------------------+--------------------+----------+
| | |
v v v
+-------+ +---------------+ +---------------+
|Planner| | Retrieval/RAG | | Tool Gateway |
+---+---+ +-------+-------+ +-------+-------+
| | |
+------------------+--------------------+
|
v
+---------------------+
| LLM Gateway |
| (Fallback/Budgets) |
+---------------------+
1. API Design
Post Message (Submit Input)
- Method:
POST /v1/conversations/{conversation_id}/messages - Headers:
X-Tenant-ID,X-Idempotency-Key - Payload:
{ "client_message_id": "msg_uuid_9876", "content": "Calculate the year-over-year revenue growth for ACME Corp from the latest 10-K and compare it with current market consensus.", "attachments": [{"document_id": "doc_123", "type": "pdf"}] } - Response:
202 Accepted{ "run_id": "run_00123", "status": "queued", "created_at": 1700000000 }
Stream Execution Output (SSE)
- Method:
GET /v1/runs/{run_id}/stream - Headers:
Last-Event-ID(for reconnects) - Output Event Stream:
id: seq_1 event: status data: {"step": "planning", "message": "Analyzing request and determining required data..."} id: seq_2 event: status data: {"step": "retrieval", "message": "Fetching 10-K filings for ACME Corp..."} id: seq_3 event: token data: {"delta": "Based on the "} id: seq_4 event: citation data: {"doc_id": "doc_123", "page": 42, "snippet": "2023 Revenue was $1.2B..."} id: seq_5 event: done data: {"total_tokens": 420, "execution_time_ms": 1820}
2. Data Storage & Schema Design
Relational Schema (PostgreSQL)
CREATE TABLE conversations (
conversation_id UUID PRIMARY KEY,
tenant_id VARCHAR(64) NOT NULL,
user_id VARCHAR(64) NOT NULL,
title VARCHAR(255),
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
) PARTITION BY HASH (tenant_id);
CREATE TABLE messages (
message_id UUID PRIMARY KEY,
conversation_id UUID REFERENCES conversations(conversation_id),
parent_message_id UUID NULL, -- Enables thread branching/edits
role VARCHAR(16) NOT NULL, -- 'user', 'assistant', 'system', 'tool'
content TEXT NOT NULL, -- Encrypted at rest (AES-256)
token_count INT,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE agent_runs (
run_id UUID PRIMARY KEY,
message_id UUID REFERENCES messages(message_id),
status VARCHAR(32) NOT NULL, -- 'queued', 'running', 'completed', 'failed'
execution_dag JSONB,
total_cost_usd NUMERIC(10, 6),
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE run_steps (
step_id UUID PRIMARY KEY,
run_id UUID REFERENCES agent_runs(run_id),
agent_type VARCHAR(32) NOT NULL, -- 'planner', 'rag', 'calculator', 'compliance'
input_payload JSONB,
output_payload JSONB,
latency_ms INT,
created_at TIMESTAMPTZ DEFAULT NOW()
);
In-Memory Buffering (Redis)
- Key:
run:stream:{run_id} - Type: Redis Stream
- TTL: 1 Hour
- Usage: Intermediary message bus between backend agent workers and client SSE streaming connection pods.
3. Multi-Agent Orchestration Flow
User Input
│
▼
[1. Planner Agent] ──(Generates DAG)──► [2. RAG Retriever] ──┐
│ │
▼ │
[3. Tool Executor] │
(Python Sandbox / API)│
│ │
▼ │
[4. Synthesizer] ◄────┘
│
▼
[5. Compliance Guard]
│
▼
Stream Token
- Planner Agent: Uses a fast, deterministic instruction model to analyze intent. It produces an execution Directed Acyclic Graph (DAG) specifying dependencies (e.g., fetch filing and market consensus concurrently, then run calculation).
- Retrieval Agent (RAG): Queries enterprise vector database using hybrid search (sparse BM25 + dense embedding vectors). Hard metadata filtering is enforced at query time using the incoming user’s security context:
tenant_id == X AND acl_groups OVERLAPS user_groups. - Calculation Agent: Financial math is offloaded to a sandboxed Python execution engine (e.g., WebAssembly or microVMs like Firecracker) to ensure $100% $ numerical accuracy instead of relying on token probability distributions.
- Synthesizer Agent: Aggregates intermediate step outputs and generates draft responses with inline citation markers.
- Compliance & Guardrail Agent: A dual-layer safety check:
- Streaming Layer: A sliding-window pattern matcher and lightweight classifier checks outgoing token chunks for PII, MNPI, and mandatory legal disclaimers. If a violation occurs, the stream is aborted immediately.
- Final Async Audit: Logs prompt-response SHA-256 hashes to write-once-read-many (WORM) storage for Regulatory Compliance (e.g., SEC/FINRA auditing).
4. Context Management & Token Optimization
- Rolling Context Window: A sliding window holds the latest user and assistant turns. When total tokens exceed a pre-allocated budget (e.g., 8,000 tokens), an asynchronous worker generates a concise structural summary of older turns and appends it to the system message block.
- Large Tool Payload Referencing: Raw JSON payloads from external financial APIs are not injected raw into subsequent prompts. Instead, they are persisted to object storage, and the model receives a structured summary and pointer reference.
- Prompt Caching: Static system prompts, safety guidelines, and base agent instructions use provider-level prompt caching (e.g., Anthropic/Azure OpenAI cache control headers) to cut latency by up to 50% and reduce token costs.
5. Security & Isolation
- Tenant Isolation: Multi-tenant data partition keys enforced at the API gateway layer. Database connections use Row Level Security (RLS) policies scoped to
tenant_id. - Zero Data Retention Contracts: External LLM calls use enterprise endpoints with explicit zero-retention guarantees, ensuring data is never used for foundation model training.
- Data Redaction: An inline regex/NER pipeline redacts sensitive data (e.g., SSNs, credit card numbers, account numbers) before tokens hit external API endpoints.
6. Resilience & Edge Cases
| Failure Scenario | Mitigation Strategy |
|---|---|
| Worker Node Crash during execution | Workflow tasks managed via Temporal/Durable Functions. Steps are checkpointed; on restart, the worker resumes execution from the exact failed step without re-running prior steps. |
| LLM Provider Outage / Rate Limit (429) | The LLM Gateway provides automatic token-bucket rate limiting and fallbacks across regions (e.g., US-East to US-West) and secondary vendors (e.g., Primary: Azure OpenAI, Secondary: Anthropic Claude). |
| SSE Connection Drop | Client reconnects using GET /v1/runs/{run_id}/stream with header Last-Event-ID: seq_X. Redis Streams replays buffered events starting from seq_X + 1. |
| Infinite Agent Execution Loop | Execution runs enforce strict constraints: maximum 5 step iterations, max wall-clock execution time of 45 seconds, and a strict per-run token cost budget limit ($0.25). |