05 · Platform Architecture
Boring where it can be, rigorous where it must be
One deployable Next.js application on Vercel, one Postgres database, and a guarded AI coach that can explain anything in the curriculum but can never touch an account. Compliance (an audit archive, PII minimization, the education-only boundary) is built in from the first commit rather than added before the broker partner’s due diligence.
≈$0.04
Blended LLM cost per conversation
Fast tier ~70% of turns, reasoning tier ~30%, at list prices
Source≥98%
Launch gate on advice-bait
Correct refusal-and-redirect rate before beta
The whole system on one page
System diagram
The MVP is a modular monolith: a single Next.js codebase whose domain modules (auth, content, learning, practice, coach, broker, billing) talk through typed interfaces and share one Postgres database. For a team of two to four engineers this is the fastest design that still splits cleanly later. The coach or the broker adapter can move to its own service when load or a partner’s isolation requirements call for it, and no code outside the module has to change.
Four rules the diagram encodes
- The coach cannot trade. There is no edge from the coach to the broker adapter. That rules out OWASP LLM06 (excessive agency) and keeps the partner’s Reg BI obligations from attaching to our AI.[22][3]
- Partners hold the sensitive PII. SSNs, ID images and bank numbers go straight to the broker’s CIP and to Plaid processor tokens. We store partner account IDs.[9][16]
- The audit trail is its own system. Observability tools rotate data; the WORM archive does not.[5]
- Every vendor sits behind a port. Broker, model provider, market data and KYC each have an interface, so swapping vendors is a contract question and not a rewrite.
What is deliberately absent
- No Kubernetes, no microservices, no event bus at MVP. Vercel functions plus Postgres cover the first 100k MAU.
- No separate vector database. pgvector in Neon handles a curriculum of a few thousand chunks easily, and keeps embeddings joined to lesson versions.
- No real-time quotes in Phase 1. Simulated or delayed data avoids a market-data redistribution licence until real money is involved.
- No self-hosted models. At MVP scale the operations work costs more than the token savings.[21]
Evidence, not slides
What the prototype already proves
The prototype is not a Figma file. Several pieces are production patterns running on Vercel today, and the rest are honestly labeled. The table separates the two so the founding team knows exactly what carries forward.
| Capability | Status | How it works today | What production adds |
|---|---|---|---|
| Email OTP sign-in | Real | A 6-digit code is emailed. The client holds a token containing an HMAC-SHA256 over email, code and expiry. Verification uses a constant-time comparison and fails closed when the signing secret is missing. No database is needed. | Passkeys and MFA through Clerk or Better Auth, server-side sessions that can be revoked, and step-up auth for money movement in Phase 2. |
| Stateless session tokens | Real | After verification the server issues a 5-minute notify token and a 24-hour session token, each HMAC-signed with a distinct purpose prefix so one cannot be replayed as the other. | Revocation (stateless tokens cannot be revoked before expiry), key rotation, and device binding. |
| Lead capture to CRM | Real | Verified emails are upserted to Attio, with first-touch lead source set only on create. Failures are logged and swallowed so sign-in never breaks. | Consent records, plus double opt-in for the newsletter under GDPR. |
| Guarded AI coach | Real | Input classifier (advice-seeking, personal data, off-topic) → keyword retrieval over the 11 vetted lessons → model call through Vercel AI Gateway with education-only instructions → lesson citations → a scripted fallback if the model is unavailable. Gated by the session token and rate-limited at the Vercel firewall. | Hybrid vector + keyword retrieval, an output checker, the WORM audit write, the eval harness in CI, and model-tier routing. |
| Market data | Simulated by design | A seeded random walk per ticker (geometric, with drift and volatility per asset) produces the same 252-day history on every visit and is labeled as simulated. Demos are reproducible and no data licence is needed. | Keep simulation for drawdown scenarios. Add delayed real data for the practice portfolio, and a licensed feed only when real money arrives. |
| Curriculum | Real content, illustrative review | 4 tracks and 11 lessons, each with cards, a quiz, an optional practice action and a reviewedBy version stamp. The stamps model the workflow. A credentialed reviewer has not yet signed the content off. | Contracted CFP®/CFA® reviewers, a CMS with LessonVersion history, and re-indexing on publish. |
| Persistence, progress, billing | Not built | The prototype has no database. Nothing a visitor does after sign-in is stored server-side. | Neon Postgres, the data model below, and Stripe Billing. |
| Content studio pipeline | UI demonstration | Shows the brief → AI draft → SME edit → compliance review → publish flow as an interface. | Real roles, sign-off records and version diffs stored as LessonVersion rows. |
Recommended stack
Picks, reasons, and the escape hatch for each
| Layer | Pick | Why this one | Alternative / revisit when |
|---|---|---|---|
| App + hosting | Next.js 16 on Vercel Pro | Preview deploy per PR, firewall and AI Gateway on the same platform, $20 per deploying seat with 1 TB transfer included.[26] | Containers on Fly or AWS if function limits or cost at 100k+ MAU start to bite. |
| Database | Neon Postgres (Launch → Scale) | Serverless, scales to zero, a database branch per PR. About $15/mo small; always-on 2 CU about $347/mo.[27] | Supabase Pro if bundled auth and storage outweigh a second vendor. |
| Vector search | pgvector inside Neon | Embeddings join directly to LessonVersion rows, so a citation is a foreign key and not a guess. | A dedicated vector store above roughly a million chunks or when sub-50 ms recall becomes a requirement. |
| Auth | Clerk (or Better Auth) | Passkeys, MFA and organisations out of the box, free to 50k monthly retained users.[28] | Better Auth when B2B2C tenants need users inside our own database. |
| LLM access | Vercel AI SDK + AI Gateway | One API across providers, failover, per-request cost tracking. Models are routed by tier, not hard-coded. | Direct provider SDKs if a gateway feature lags a provider release. |
| LLM observability | Langfuse Cloud (Core → Pro) | Traces, eval datasets, prompt versions. $29/mo, then $199/mo for SOC 2 and 3-year retention.[25] | Self-host (MIT licence) if data residency requires it. |
| CMS | Sanity (or Payload) | Structured lessons that feed RAG ingestion. Sanity is free up to 20 seats and 10k documents.[30] | Payload if we want the CMS inside the Next.js app and database. |
| Video | Mux | 100k free delivery minutes a month, then $0.0008/min at 720p.[31] | YouTube unlisted for early tests only, since it offers no analytics hooks. |
| Analytics + flags | PostHog | Analytics, flags, replays and experiments in one tool. 1M events a month free.[29] | Amplitude if a growth hire insists. Not worth a second tool early. |
| Payments | Stripe Billing | Subscriptions only. Brokerage funding never touches our Stripe account. | RevenueCat once the native app ships, for store billing. |
| Errors | Sentry | Release health and source maps, with PII scrubbing configured before the first event. | — |
| Compliance automation | Drata or Vanta | SOC 2 evidence collection. About $7.5–15k/yr; a Type II audit is about $12–20k.[33][32] | Spreadsheet-driven readiness only if the partner accepts Type I alone. |
Deep dive
AI coach architecture
The coach is the product’s most valuable feature and its largest regulatory exposure. A chat interface is personal by nature, and the publisher’s exclusion protects impersonal commentary, not advice “attuned to any specific portfolio or to any client’s particular needs.”[1] Legal guidance to trading educators in 2026 warns that individualized coaching on a user’s finances or goals risks being treated as personalized advice.[2] No court has yet ruled on whether a one-to-one AI conversation can qualify as “general and regular circulation,” so the coach must stay impersonal and be able to prove it did.
| Stage | What it does | Implementation | Failure mode it prevents |
|---|---|---|---|
| 0 Gate | Auth, quotas, redaction | Session token, Vercel firewall limits, per-user daily token cap, PII redaction before any model or telemetry call | Cost-exhaustion attacks (LLM10) and PII leaking into third-party logs.[22] |
| 1 Classify | Label intent | Fast tier with a structured output schema: education, advice-seeking, personal data, tax/legal, crisis or vulnerability, injection | Advice-bait reaching the generator. Vulnerable users get routed to resources, per FCA good practice.[42] |
| 2 Retrieve | Ground the answer | Hybrid keyword + pgvector search over published LessonVersions and regulator education pages, with a score threshold | Hallucinated financial facts (LLM09). Below the threshold the coach says “I don’t know” and links to the course. |
| 3 Generate | Teach | Fast tier by default, reasoning tier for multi-step tutoring. Socratic prompting: ask before telling. | Answer-dumping. The tutor in the Harvard RCT that withheld direct answers more than doubled median learning gains.[46] |
| 4 Check | Enforce policy | Deterministic rules (ticker plus imperative, return promises, missing citation) plus a fast-tier judge. NeMo Guardrails rails where useful. | Security-specific recommendations, performance claims, unsupervised AI communications.[23][4] |
| 5 Respond | Deliver with disclosure | Streamed answer, citation chips, AI disclosure on the first turn, a disclaimer at the point of delivery | EU AI Act Article 50 (live since 2026-08-02) and the FCA’s October 2026 expectations.[38][42] |
| Audit | Prove it | Append-only write of each turn to S3 Object Lock in compliance mode, hash-chained, 3–6 years | Recordkeeping. Practitioners treat chatbot sessions as communications to be archived, and the SEC’s scope clarification is still pending.[7][6] |
Eval harness (runs in CI on every prompt or model change)
- Golden set of 300–500 prompts in five buckets: concept questions, advice-bait (“should I buy NVDA with my $5k?”), prompt injection, vulnerable-user scripts, and non-US contexts.[24]
- Scored on: refusal accuracy, groundedness (every claim traceable to a retrieved chunk), citation correctness (the cited LessonVersion actually supports the claim), tone, and reading level.
- Fairness probe: the same question asked with different implied demographics must get equivalent answers. A July 2026 study found major chatbots varied financial advice by race and gender.[45]
- Gates: ≥98% on advice-bait to ship; any regression in the advice-bait or injection buckets blocks the merge.
Red-teaming plan
- Pre-beta: an automated Promptfoo red-team across its 50+ vulnerability types, plus a manual session with counsel present.
- Quarterly: a repeat red-team, with every new jailbreak that succeeds added to the golden set.
- Production sampling: 1–2% of turns reviewed weekly by content or compliance staff, labelled in Langfuse and fed back into the evals.
- Indirect injection: lesson text, and later any linked-brokerage data, is treated as untrusted. Nothing in the prompt carries secrets or another user’s data.[22]
- Kill switch: a feature flag drops the coach to scripted-fallback mode in seconds.
Model-tier routing and cost per conversation
The coach is model-agnostic and routes by tier. The fast tier (list price about $0.10 input / $0.50 output per million tokens) handles classification, the output judge and simple Q&A. The reasoning tier ($2 / $10 per million) handles multi-step tutoring.[21] Assume a conversation of 8 turns, about 6k input tokens per turn with half served from cache, and about 500 output tokens per turn.
| Scenario | Per conversation | 1k MAU | 10k MAU | 100k MAU |
|---|---|---|---|---|
| Reasoning tier for everything | ≈ $0.09 | ~$360 | ~$3.6k | ~$36k |
| Fast tier for everything | ≈ $0.007 | ~$28 | ~$280 | ~$2.8k |
| Recommended blend (70 / 30) + guardrail passes | ≈ $0.035–0.04 | ~$150 | ~$1.5k | ~$15k |
Core data model
Fifteen entities, three sensitivity classes
Two design choices carry most of the weight. First, LessonVersion is immutable, so every coach citation and quiz attempt points to the exact text a reviewer approved. Second, AuditEvent is append-only and mirrored to the WORM archive.
| Entity | Purpose | Key fields | Class / retention |
|---|---|---|---|
| User | Identity anchor | id, email, auth_provider_id, dob_attested_18plus, region, created_at | PII · account life + 30 days |
| Profile | Self-described context | experience_level, interests, time_horizon_band (banded, never exact income) | PII, field-encrypted |
| Goal | What the user is working toward | user_id, type, target_band, horizon_years, status | PII, field-encrypted |
| Track | Curriculum grouping | id, title, level, order | Content |
| Lesson | Stable lesson identity | slug, track_id, current_version_id | Content |
| LessonVersion | Immutable reviewed text | lesson_id, semver, body, quiz, reviewer_id, compliance_signoff_at, embedding | Content · kept forever |
| Attempt | Quiz and practice results | user_id, lesson_version_id, score, item_results, next_review_at | Learning data |
| CoachSession | A conversation | user_id, started_at, model_policy_version, channel | Communication · 3–6 yrs |
| CoachTurn | One exchange | session_id, redacted_prompt, classifier_label, output, checker_verdicts, model, tokens, cost | Communication · WORM 3–6 yrs |
| CitationRef | What grounded an answer | turn_id, lesson_version_id, chunk_id, score | Communication · WORM |
| PracticePortfolio | Paper account | user_id, cash, scenario_id, created_at | Learning data |
| PracticeOrder | Simulated trade | portfolio_id, symbol, side, qty, sim_price, sim_time | Learning data |
| BrokerAccount | Pointer to the partner (Phase 2) | user_id, partner, partner_account_id, status. No SSN, no bank numbers | Regulated · partner is the system of record |
| Subscription | Entitlements | user_id, stripe_customer_id, plan, status, period_end | Financial · per tax counsel |
| AuditEvent | Who did what | actor, action, entity, before_hash, after_hash, prev_event_hash | Append-only · WORM |
Integration matrix
Broker, data and identity partners
| Vendor | Role | Geography | Sandbox | Pricing signal | Our take |
|---|---|---|---|---|---|
| Alpaca Broker API | FINRA/SIPC broker-dealer API: stocks, ETFs, fractional shares, KYC-as-a-service, funding | US + 30–40 countries; Alpaca Europe for EU | Yes: full sandbox, free paper trading | Usage-based, custom; commission-free for the end user[10] | Default rail. The same API serves Phase 1 simulation and Phase 2 accounts. |
| DriveWealth | API-first brokerage, fractional US equities, Plaid funding | Global, strong in APAC/LatAm | Partner sandbox (not publicly verified) | Not public[11] | Second source; worth it if international users matter early. |
| Apex Fintech (AscendOS) | Clearing, custody, OMS, direct indexing | US | Partner sandbox | Enterprise, not public[12] | Built for scale; too heavy for the MVP. |
| Atomic Invest | Self-directed plus managed portfolios (RIA) and direct indexing | US | Not verified | Not public[13] | Fast route to Phase 3 managed portfolios without becoming an RIA. |
| Upvest | EU investment API: stocks, ETFs, funds, pensions | EU + UK | Partner sandbox (not publicly verified) | Not public; raised $125M in March 2026[14] | EU-native alternative to Alpaca Europe. |
| SnapTrade | Connect the user’s existing brokerage (read, some trading) | Mostly US/CA | Free tier | $1–2 per connected user per month; Launch $100/mo base[15] | Phase 1.5: “explain my portfolio,” kept impersonal. |
| Alpaca Market Data | Quotes and history | US | Free IEX tier | Free → Algo Trader Plus $99/mo[18] | Paper-trading data in Phase 1. |
| Massive (ex-Polygon) | Equities and options data | US | Free basic | $0 / $29 / $79 / $199 per month[17] | Display to end users needs a business redistribution licence (quote). |
| Persona / Sumsub | KYC, AML screening | Global | Yes | Persona from $250/mo for 500 checks; Sumsub $1.35–1.85 per check[20][19] | Only if the partner accepts our CIP, or for fraud controls. |
| Plaid | Bank linking via processor tokens | US/CA | Plaid Sandbox | Per-Item subscription, not public | Bank details stay with the broker.[16] |
Controls by phase
Security and compliance controls
| Area | Phase 1 · Education | Phase 2 · Invest | Phase 3 · Advice / scale |
|---|---|---|---|
| Assurance | SOC 2 readiness from month 2; Type I by month 6[32] | Type II observation window running before partner signature | Annual Type II; pen test; vendor reviews |
| Infosec program | GLBA Safeguards baseline: named owner, written program, MFA, encryption, access logs[34] | Breach of 500+ consumers reported to the FTC within 30 days[35] | Incident-response retainer; tabletop exercises twice a year |
| Encryption | TLS everywhere; AES-256 at rest; KMS envelope field encryption for DOB, goals, profile | Partner API keys in a secrets manager, scoped and rotated, egress allow-listed | Customer-managed keys for B2B2C tenants that require them |
| PII minimization | Banded profile fields; redaction before LLM and telemetry | No SSN, ID images or bank numbers stored; Plaid processor tokens[16] | Data-protection impact assessments for each new use |
| Recordkeeping | Every coach turn in WORM storage (S3 Object Lock, compliance mode), 3-year minimum | Partner-grade archive aligned to 17a-4(b)(4)[5] | 5 years for an RIA under Rule 204-2[8] |
| AI disclosure | AI disclosure on the first turn (EU Article 50, in force)[38]; disclaimer at the point of delivery[42] | Coach templates reviewed as retail communications by the partner[4] | ESMA: disclose AI use and keep records of AI changes[41] |
| AI claims | Marketing copy says what the AI is and what it is grounded in. No AI-picked returns.[43] | Partner review of AI-related marketing | Marketing Rule substantiation file |
| Age and privacy | 18+ only, which sidesteps amended COPPA (in force 2026-04-22)[37]; GDPR/CCPA privacy policy | CCPA ADMT obligations from 2027-01-01 if any significant automated decisions are made[36] | Annex III review before 2027-12-02 if the coach grades or gates learners in the EU[39][40] |
| Account security | Passkeys or MFA; rate limits; bot protection | Step-up auth on funding changes, device binding, velocity limits | IA AML program before 2028-01-01 if RIA[44] |
Run cost
Monthly cost at 1k, 10k and 100k MAU
| Item | 1k MAU | 10k MAU | 100k MAU |
|---|---|---|---|
| Vercel Pro (seats + usage) | $20 | $40–100 | $300–1,000 |
| Neon Postgres | $0–20 | $50–150 | $350–800 |
| Clerk | $0 | $0–25 | $25–1,000 |
| PostHog | $0 | $0–100 | $300–800 |
| Sanity / Payload | $0 | $15–45 | $45–150 |
| Mux (≈30 min per MAU per month) | $0 | $160 | $2,400 |
| LLM (70/30 blend) | ~$150 | ~$1,500 | ~$15,000 |
| Langfuse | $0–29 | $29–199 | $199–500 |
| Market data (display licence) | $0–99 | $200–2,000 (quote) | $2,000+ (quote) |
| KYC (Phase 2, 5% of MAU onboarding a month) | Persona $250 minimum | ~$750 | ~$7,500 |
| Compliance platform + audit (amortized) | ~$1,500–2,500 | ~$1,500–2,500 | same + pen test |
| Total (rough) | ~$2–3k | ~$5–7k | ~$30–40k |
Build vs buy
Where our engineering time goes
| Capability | Decision | Reasoning |
|---|---|---|
| Brokerage, custody, clearing | Partner (Alpaca default) | Becoming a broker-dealer is a multi-year licensing project. Partners run CIP, custody and confirmations. |
| KYC / AML | Partner, vendor only if allowed | The partner’s program is mandatory unless it approves ours. |
| Auth | Buy (Clerk) or adopt (Better Auth) | Passkeys, MFA and session security are solved problems. |
| CMS | Buy (Sanity) or adopt (Payload) | Editors need a real UI. We build only the publish → embed → re-index hook. |
| AI coach pipeline | Build | This is the product and the compliance moat. Classifier, retrieval, checker, policy and evals are ours, on bought primitives (gateway, pgvector, Langfuse). |
| Curriculum + mastery model | Build | The learning path, spaced-review scheduling and practice actions are what differentiates us. |
| Practice engine | Build | A simple ledger plus drawdown scenarios. Simulating risk is the point, and no vendor sells that as a teaching tool. |
| Audit archive | Assemble | S3 Object Lock plus a hash chain and a small writer. Days of work, not a vendor contract. |
| Analytics, errors, billing | Buy | PostHog, Sentry, Stripe. No differentiation in building any of them. |
Architecture Decision Records
The first ten ADRs
Each one becomes a one-page markdown record in the repository with context, the decision, its consequences, and what would make us revisit it.
| ADR | Decision | Rationale |
|---|---|---|
| 001 | Modular monolith on Next.js + Vercel | Fastest delivery for a small team. Module boundaries allow later extraction without a rewrite. |
| 002 | Postgres (Neon) is the system of record; pgvector for retrieval | One database, branch per PR, citations as foreign keys. No second datastore to secure. |
| 003 | The coach answers only from published LessonVersions and regulator education pages, and cites or declines | Keeps output impersonal and traceable, the core of the publisher’s-exclusion posture.[1] |
| 004 | The coach has no tools that read or write brokerage accounts or orders | Removes excessive-agency risk and Reg BI exposure for the partner.[22][3] |
| 005 | Models are accessed through the AI Gateway with fast / reasoning tier routing | No vendor lock-in, failover, a cost ceiling per conversation. |
| 006 | Every coach turn is written to a WORM archive, separate from observability | Cheap now and expensive to retrofit. The SEC’s 17a-4 scope clarification is still pending.[6] |
| 007 | The education-only policy is enforced in code and tested in CI | Classifier, output checker and golden set. A policy that only lives in a prompt is a hope, not a control. |
| 008 | Brokerage sits behind a BrokerPort interface, with Alpaca as the first adapter | Sandbox now, live in Phase 2, with DriveWealth or Upvest as drop-in alternatives. |
| 009 | We never store SSNs, ID images or bank account numbers | Partner-hosted KYC and Plaid processor tokens keep GLBA, GDPR and CCPA exposure small. |
| 010 | 18+ only at launch, with self-attested date of birth at sign-up | Avoids amended-COPPA obligations and brokerage age-of-majority issues. A teen product needs a custodial partner.[37] |
Sources
- [1]Lowe v. SEC, 472 U.S. 181 (1985)
- [2]Gordon Rees: Legal compliance for financial publishers and trading educators (Jan 2026)
- [3]Reg BI explained: individually tailored communications
- [4]FINRA 2210 FAQ on AI-generated communications
- [5]SEC 17a-4 and AI recordkeeping
- [6]Business Law Today: AI prompts and responses, records or not? (Jun 2026)
- [7]Duane Morris: AI and broker-dealer compliance (Jul 2026)
- [8]SEC Rule 204-2 books and records
- [9]Alpaca Broker API docs (KYC/CIP responsibilities, EU)
- [10]Open Banking Tracker: Alpaca embedded finance
- [11]DriveWealth selected by OnePay (Oct 2025)
- [12]Embedded Finance Index: Apex Fintech Solutions
- [13]Open Banking Expo: Atomic raises $30M
- [14]Tech.eu: Upvest raises $125M (Mar 2026)
- [15]SnapTrade pricing
- [16]Plaid processor tokens with DriveWealth
- [17]Massive (formerly Polygon.io) plans
- [18]Alpaca Market Data API
- [19]Identity verification pricing (Sumsub, Onfido)
- [20]KYC pricing in the US (Persona)
- [21]Anthropic API list pricing
- [22]OWASP Top 10 for LLM Applications (2025)
- [23]NVIDIA NeMo Guardrails
- [24]Promptfoo red-teaming for LLM apps
- [25]Langfuse pricing (2026)
- [26]Vercel pricing breakdown
- [27]Neon pricing after the Databricks acquisition
- [28]Clerk pricing guide
- [29]PostHog pricing
- [30]Sanity vs Payload vs Strapi pricing (2026)
- [31]Mux pricing
- [32]SOC 2 audit cost
- [33]SOC 2 software pricing comparison (Drata, Vanta)
- [34]GLBA Safeguards Rule requirements
- [35]GLBA breach notification (FTC, 500+ consumers, 30 days)
- [36]CPPA finalizes ADMT, risk assessment and audit regulations
- [37]COPPA rule amendment compliance deadline
- [38]Cooley: EU AI Act transparency obligations take effect 2 Aug 2026
- [39]Digital Omnibus: high-risk obligations moved to 2027-12-02
- [40]Usercentrics: Annex III education uses and Article 50
- [41]ESMA public statement on AI and investment services (2024)
- [42]FCA good and poor practice for AI disclaimers (Oct 2026)
- [43]SEC AI-washing enforcement, FY2025 review
- [44]FinCEN postpones investment-adviser AML rule to 2028
- [45]OECD.AI incident: chatbots give inconsistent financial advice (Jul 2026)
- [46]Kestin et al. 2025: AI tutoring RCT (Scientific Reports)