Architecture Philosophy

CAHS handles data that is deeply personal — mood states, private thoughts, unsent letters, and crisis disclosures. The architecture must treat privacy as a first-class constraint, not an afterthought. Every system design decision should be evaluated through the question: "If this system were breached, what would the worst case look like?" Design to minimize that worst case.

The architecture must scale without requiring a complete rewrite. Many startups make Phase 1 decisions that create Phase 3 problems. The recommended stack is deliberately chosen for longevity and hiring ease — widely-adopted technologies with mature ecosystems, not bleeding-edge choices that trade hiring difficulty for marginal performance gains.

Build for offline-first. The most emotionally charged moments — when someone needs to journal at 2am, or read a comfort piece on a flight — often happen without reliable internet. Content should be cached locally. Journal entries should write to local storage first and sync when connectivity returns.


Tech Stack Recommendation

Each technology choice is evaluated against three criteria: privacy posture, developer ecosystem (hiring ease), and long-term viability. This is not an exhaustive list — it covers every architectural layer that will be touched in Phase 1 through Phase 3.

Mobile & Web Clients
Layer Choice Why Alternatives Considered
Mobile Application React Native (Expo) Cross-platform iOS + Android from one codebase. Expo managed workflow removes native build complexity. Expo Go enables rapid testing. Large, well-documented hiring pool. Flutter (faster rendering, smaller team hiring pool); Native Swift/Kotlin (best performance, 2× development cost)
Web Application Next.js 14+ (App Router) SEO-critical for content discoverability. React ecosystem compatibility with mobile codebase. Server Components reduce client-side JS. Strong hiring pool. Remix; Nuxt (Vue)
Backend & Data
Layer Choice Why Alternatives Considered
Backend API NestJS (TypeScript) Opinionated structure prevents architectural drift as team scales. TypeScript end-to-end. Excellent dependency injection. Decorator-based controllers feel clean and self-documenting. Express (too minimal, requires strict architectural discipline); FastAPI (Python — breaks TypeScript end-to-end)
Database (primary) PostgreSQL ACID compliance for sensitive data. Row-Level Security (RLS) for multi-tenant data isolation. Excellent JSON support where needed. Full-text search available natively. MySQL (weaker RLS); MongoDB (inappropriate for relational wellbeing data — mood + journal + user relationships are inherently relational)
Database Hosting Supabase Managed PostgreSQL + Auth + Storage + Realtime out of the box. Built-in Row Level Security. Excellent developer experience. Auth handles OAuth (Apple, Google) without additional services. AWS RDS (more control, more ops overhead); PlanetScale (MySQL, weaker for RLS)
Authentication Supabase Auth Handles Apple Sign In (required for App Store), Google OAuth, email/password, and magic links. No additional auth service needed. Cost included in Supabase plan. Auth0 (more cost at scale); Clerk (good DX, different pricing model)
Cache / Session Redis (Upstash serverless) Fast session store. Content cache for daily quote and reflection. Rate limiting. Queue for notification scheduling. Serverless billing model suits Phase 1 traffic patterns. Memcached (less flexible); no cache (unacceptable latency for daily content delivery)
File Storage Supabase Storage (S3-compatible) Audio files (Phase 2+), profile images, community content images. Consistent with existing infrastructure. RLS policies extend to storage buckets. AWS S3 directly (more configuration); Cloudinary (expensive at scale, image transformation is overkill for Phase 1)
Notifications & Communication
Layer Choice Why Alternatives Considered
Push Notifications Expo Push → APNs / FCM Expo handles the complexity of APNs + FCM token management. Single API surface for both platforms. Integrates directly with Expo managed workflow. OneSignal (good but adds vendor dependency); direct APNs/FCM (more control, significantly more setup)
Transactional Email Resend Beautiful transactional email. React Email for templates — stays in TypeScript ecosystem. Simple, clean API. Generous free tier for Phase 1. SendGrid (more enterprise, heavier setup); Postmark (good but more expensive at volume)
Analytics, Payments & Observability
Layer Choice Why Alternatives Considered
Analytics PostHog Privacy-respecting. Open source option available for self-hosting. Excellent session recording for UX research. Feature flags built in. Data stays under your control. Mixpanel (expensive at scale); Amplitude (excellent but costly); Firebase Analytics (less control, data goes to Google)
Payments Stripe + RevenueCat Stripe is industry standard for web and direct billing. In-app purchase must go through Apple/Google IAP — RevenueCat bridges Stripe and IAP into a single subscription management layer. RevenueCat alone (excellent for mobile IAP but weaker for web billing)
Error Tracking Sentry Industry standard. Works across React Native and Next.js. Source maps for production debugging. Generous free tier covers Phase 1 volume. Datadog (expensive for Phase 1); Rollbar (good, less widespread)
Uptime Monitoring Uptime Robot Inexpensive for basic uptime monitoring. 50 monitors on the free plan. Sufficient for Phase 1 alerting. Upgrade to PagerDuty at Phase 3. PagerDuty (Phase 3+, overkill for Phase 1); Datadog (full observability, Phase 3+)
AI Features (Phase 3+) Anthropic Claude API Best-in-class emotional intelligence and nuance for sensitive wellbeing contexts. Highly controllable via system prompts. Constitutional AI training reduces risk of harmful outputs. claude-sonnet for complex tasks, claude-haiku for latency-sensitive paths. OpenAI GPT-4 (good, less nuance for emotional contexts); Gemini (emerging, less established for this use case)

System Architecture Diagram

The following diagram describes the high-level component relationships. All client traffic passes through the API Gateway before reaching the application server. Background workers operate independently of the request cycle to handle scheduled and async work.

CLIENT LAYER
┌──────────────────────────┐   ┌──────────────────────────┐
│  Mobile App              │   │  Web App                 │
│  (React Native / Expo)   │   │  (Next.js 14 App Router) │
│                          │   │                          │
│  • Offline-first storage │   │  • Server Components     │
│  • Local journal cache   │   │  • SEO for content       │
│  • Push token management │   │  • Public content routes │
└────────────┬─────────────┘   └────────────┬─────────────┘
             │                               │
             └───────────────┬───────────────┘
                             │  HTTPS only / HSTS
                             ▼
EDGE LAYER
┌─────────────────────────────────────────────────────────┐
│  API Gateway + Rate Limiter                             │
│  (Redis-backed: 100 req/min per user,                   │
│   10 req/min for write endpoints)                       │
└──────────────────────────┬──────────────────────────────┘
                           │
                           ▼
APPLICATION LAYER
┌─────────────────────────────────────────────────────────┐
│  NestJS API Server (TypeScript)                         │
│                                                         │
│  Modules: Auth │ Journal │ Mood │ Content │ Community   │
│           Subscription │ Notifications │ Admin          │
└──────────┬──────────────┬────────────────┬──────────────┘
           │              │                │
           ▼              ▼                ▼
DATA LAYER
┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐
│ Supabase DB  │  │ Redis Cache  │  │ Supabase Storage     │
│ (PostgreSQL) │  │ (Upstash)    │  │ (S3-compatible)      │
│              │  │              │  │                      │
│ • RLS active │  │ • Session    │  │ • Audio files (P2+)  │
│ • AES-256    │  │ • Daily      │  │ • Profile images     │
│   encrypted  │  │   content    │  │ • Community assets   │
│   journals   │  │ • Rate limit │  │                      │
└──────┬───────┘  └──────────────┘  └──────────────────────┘
       │
       ▼
┌──────────────┐
│ Supabase     │
│ Auth         │
│              │
│ • Apple Sign │
│   In         │
│ • Google     │
│   OAuth      │
│ • Email /    │
│   Magic Link │
└──────────────┘

BACKGROUND WORKERS
┌──────────────────────────────────────────────────────────┐
│  NestJS Worker: Notification Queue                       │
│    → Expo Push Service → APNs (iOS) / FCM (Android)     │
│                                                          │
│  NestJS Worker: Email Queue                              │
│    → Resend API → Transactional email delivery           │
│                                                          │
│  NestJS Cron: Daily Content Scheduler                    │
│    → Selects and caches daily quote + reflection         │
│    → Updates Redis cache at 00:00 UTC                    │
│                                                          │
│  AI Service (Phase 3+)                                   │
│    → Anthropic Claude API (claude-sonnet / claude-haiku) │
│    → Journaling prompts, emotional insights              │
└──────────────────────────────────────────────────────────┘

External providers: Stripe (billing) · RevenueCat (IAP) · PostHog (analytics) · Sentry (errors)
      

Data Architecture — Sensitive Data Handling

Every piece of data in CAHS carries a different risk profile. This section documents how each sensitive data type is stored, accessed, and protected. Decisions here are binding — they should be revisited only when there is a clear user-facing or compliance need.

Journal Entries

Mood Check-in Data

Listening Room Messages (Phase 4)

Design Tension: Zero-Knowledge Encryption

True zero-knowledge architecture — where CAHS literally cannot read journal content under any circumstance — is the gold standard for user trust. However, it also makes full-text search within journals impossible, prevents any AI features from touching journal content, complicates password recovery, and adds significant implementation complexity. The recommendation: implement application-layer encryption from day 1 (CAHS staff cannot access content without a court order and the user's key), with a documented upgrade path to zero-knowledge if user research demonstrates it matters to retention. Do not let perfect be the enemy of good privacy.


Database Schema — Key Tables

The following describes the primary tables in the PostgreSQL schema. All tables include created_at (timestamp with time zone, default now()) and are protected by Row Level Security policies unless noted. Fields marked _encrypted store AES-256 ciphertext.

users
iduuid PRIMARY KEY
created_attimestamptz DEFAULT now()
first_nametext
email_encryptedtext-- AES-256, searchable via email_hash
email_hashtext UNIQUE-- SHA-256 for lookup without decryption
timezonetext-- IANA timezone string
onboarding_reasontext-- selected during onboarding flow
subscription_statustext-- 'free' | 'trialing' | 'active' | 'past_due' | 'canceled'
subscription_tiertext-- 'free' | 'founding' | 'premium'
journal_entries
iduuid PRIMARY KEY
user_iduuid REFERENCES users(id) ON DELETE CASCADE
created_attimestamptz DEFAULT now()
updated_attimestamptz DEFAULT now()
titletext-- nullable; user-set or auto-generated
body_encryptedtext NOT NULL-- AES-256 ciphertext
word_countinteger-- stored at write time, not derived from encrypted body
prompt_iduuid REFERENCES content_pieces(id)-- nullable
tagstext[]-- user-set tags (not derived from encrypted content)
mood_at_timetext-- nullable; mood state captured at write time
mood_checkins
iduuid PRIMARY KEY
user_iduuid REFERENCES users(id) ON DELETE CASCADE
checked_attimestamptz DEFAULT now()
mood_statetext-- enum: 'peaceful' | 'okay' | 'unsettled' | 'heavy' | 'overwhelmed'
note_encryptedtext-- nullable; brief note encrypted at rest
streak_dayinteger-- current streak count at time of check-in
content_pieces
iduuid PRIMARY KEY
typetext-- 'quote' | 'reflection' | 'poem' | 'essay' | 'story' | 'letter' | 'lesson'
titletext
bodytext NOT NULL-- plaintext; editorial content, not user data
authortext
tagstext[]
published_attimestamptz
is_dailyboolean DEFAULT false
scheduled_fordate-- nullable; date this piece is scheduled as the daily feature
community_submissions
iduuid PRIMARY KEY
user_iduuid REFERENCES users(id) ON DELETE SET NULL
titletext NOT NULL
bodytext NOT NULL
categorytext
statustext DEFAULT 'pending'-- 'pending' | 'approved' | 'rejected'
pen_nametext-- nullable; user-chosen display name for this submission
reviewed_attimestamptz
reviewer_notetext-- internal only; never surfaced to user
unsent_letters
iduuid PRIMARY KEY
user_iduuid REFERENCES users(id) ON DELETE CASCADE
addressed_totext-- nullable; e.g. "Mum", "Younger me" — not a real address
body_encryptedtext NOT NULL
created_attimestamptz DEFAULT now()
statustext DEFAULT 'active'-- 'active' | 'archived' | 'released'
subscriptions
iduuid PRIMARY KEY
user_iduuid REFERENCES users(id) ON DELETE CASCADE UNIQUE
stripe_customer_idtext
stripe_subscription_idtext
tiertext-- 'founding' | 'premium'
statustext-- mirrors Stripe status: 'active' | 'trialing' | 'past_due' | 'canceled'
created_attimestamptz DEFAULT now()
current_period_endtimestamptz

API Design Principles

The API is the contract between the clients and the server. Conventions here are binding from day 1 — changing them later requires versioning coordination across mobile releases which cannot be force-updated.


Security Architecture

Security at CAHS is not a checklist — it is a design posture. The following controls are non-negotiable and must be in place before any production traffic is accepted.

Transport Security HTTPS only. HSTS enabled with a minimum max-age of one year. No HTTP fallback.
Content Security Policy Strict CSP headers on all web responses. script-src 'self'. No inline scripts in production.
Input Validation All API endpoints use class-validator in NestJS. Requests that fail validation are rejected at the DTO layer before reaching business logic.
SQL Injection Prevented by Supabase parameterized queries throughout. Raw SQL is only used in migrations and is code-reviewed separately.
XSS Prevention React's default escaping in web app. Content Security Policy as a second layer. Markdown rendered via a sanitizing library — no raw HTML from user input.
CSRF Protection Same-site cookies (SameSite=Strict). No cookie-based auth on the API — JWT in Authorization header only.
Row Level Security All Supabase tables have RLS enabled. Users can only read and write their own data. Admin access via a separate service-role key, never exposed to client.
Secret Management Environment variables via Railway / Vercel env management. Secrets never committed to version control. Automated scanning via git-secrets pre-commit hook.
Dependency Scanning GitHub Dependabot enabled for all repositories. Critical and high severity advisories require patch within 48 hours before next deploy.
Rate Limiting Redis-backed rate limiting per authenticated user and per IP address. Applied at the API Gateway layer before requests reach NestJS.

Infrastructure & Deployment

Phase 1 — Simple, Low Cost (0–10K users)
  • API Server: Railway — simple deployment from GitHub, $20–50/month on hobby plan. Zero DevOps overhead.
  • Database: Supabase free tier graduating to Supabase Pro ($25/month) at ~1,000 active users.
  • Cache: Upstash Redis — serverless billing, ~$5–10/month at Phase 1 traffic.
  • Mobile builds: Expo EAS Build — managed build pipeline for iOS and Android. Removes the need for a macOS build machine for iOS.
  • Web: Vercel — free tier covers Phase 1. Automatic deployments from GitHub main branch.
  • Email: Resend free tier (3,000 emails/month) — covers Phase 1 transactional volume.
  • Total estimated infra cost: ~$50–100/month
Phase 2–3 — Scaling Up (10K–1M users)
  • API Server: Railway Pro → AWS ECS (Fargate) or Render for horizontal scaling. Multiple API instances behind a load balancer.
  • Database: Supabase Pro → Supabase Business → AWS RDS with read replicas for content queries at high read volume.
  • Cache: Dedicated Upstash Redis cluster with persistence enabled for session data.
  • CDN: Cloudflare for static assets, content caching, and DDoS protection.
  • Monitoring: Datadog (Phase 3+) for full observability — APM, logs, infrastructure metrics.
  • Total estimated infra cost: $300–5,000/month depending on scale band

Scalability Projections

User Scale Architecture Notes Est. Monthly Infra Cost
0 – 10K Supabase Free → Pro. Railway Hobby. Upstash serverless Redis. Single API instance. Vercel free web hosting. ~$50 / mo
10K – 100K Supabase Pro. Railway Pro with autoscaling. Dedicated Redis instance. Cloudflare CDN for content delivery. PostHog cloud. ~$300–500 / mo
100K – 1M Supabase Business or AWS RDS. Horizontal API scaling (multiple instances). Dedicated Redis cluster. Datadog observability. Background worker fleet. ~$2,000–5,000 / mo
1M+ Custom PostgreSQL cluster or managed cloud DB. Global CDN for content. Multi-region consideration for latency. Dedicated SRE function. ~$15,000+ / mo
Principle: Don't Optimize for Scale You Don't Have

Every week of over-engineering is a week not spent building the product. The Supabase + Railway stack will comfortably serve 50,000 users without modification. Build for today's scale, document the upgrade path clearly, and scale when the problem actually exists. The biggest risk in Phase 1 is not performance — it is product-market fit. An over-engineered system that no one uses is worse than a simple system that people love.