Appearance
CoachMe Technical Architecture
TypeScript-first DDD modular monolith for coach web, coach mobile, and client/personal mobile.
CoachMe should ship quickly without collapsing domain boundaries. The first implementation should be a modular monolith with explicit bounded contexts, REST contracts, offline-capable mobile apps, and self-hosted infrastructure that can split into services later when a domain earns it.
Tags: NestJS API, Next.js Web, Two Expo Apps, PostgreSQL
Product Surfaces
Each app gets its own UX shell, but all apps share contracts, identity, permissions, domain rules, and design tokens where practical.
Coach Web App
Full desktop-optimized coaching workspace for dense workflows, reporting, review, template building, and operations.
- Next.js App Router.
- Server Components for data-heavy pages.
- Client Components for drag-and-drop builders, chat, media, and charts.
Coach Mobile App
Separate Expo app for launch-scope coach operations, review, messaging, client context, nutrition review, risk signals, and lightweight actions.
- Task inbox, client review, messaging, nutrition review, progress, and risk signals.
- Lightweight actions for daily coach operations.
- SQLite-backed snapshots, message queue, and upload queue.
Client / Personal Mobile App
Separate Expo app for onboarding, Today view, workouts, meals, check-ins, progress, messaging, reminders, motivation, and personal workspace execution where enabled.
- Offline workout logging.
- Daily task completion and sync.
- Arabic/English, RTL, dark mode, and accessibility from the start.
Frameworks & Monorepo
The codebase should use one TypeScript ecosystem while keeping platform UI and domain implementation cleanly separated.
| Layer | Choice | Responsibility |
|---|---|---|
| Backend | NestJS modular monolith | REST API, OpenAPI contracts, workers, scheduled jobs, DDD application services. |
| Web | Next.js App Router | Coach/admin workspace, dashboards, builders, reports, settings, operations. |
| Mobile | Expo React Native | Separate coach and client store apps sharing mobile infrastructure packages. |
| API contracts | REST + OpenAPI | Typed client generation, regression tests, portable integration surface. |
| Toolchain | pnpm 10 + Turborepo | Monorepo dependency management, task orchestration, codegen, migration commands, and CI command shape. |
| Observability | Pino + OpenTelemetry metrics + Grafana Alloy/Cloud + Sentry | Launch logs, metrics, errors/crashes, synthetics, dashboards, and alerts. Integration approves providers, Environment owns topology, and Toolchain owns packages, builds, and source maps. |
Application Packages
apps/api: NestJS API and workers.apps/web: coach/admin web app.apps/mobile-coach: coach iOS/Android app.apps/mobile-client: client iOS/Android app.
Shared Packages
packages/domain: primitives, value objects, shared constants.packages/contracts: OpenAPI-generated clients and DTOs following the Toolchain Contract.packages/mobile-core: auth session, API client, sync, push, RTL.packages/ui-webandpackages/ui-mobile: platform design systems.
DDD Bounded Contexts
Each context owns its domain model, application use cases, persistence adapters, API controllers, events, and tests.
| Context | Responsibilities |
|---|---|
| IdentityAccess | Users, auth identities, sessions, provider adapters, roles, invitations, and account linking. |
| CoachClientManagement | Coach-client relationships, profiles, status, notes, goals, milestones, measurements, and segmentation. |
| Forms | Questionnaire templates, form versions, assignments, schedules, submissions, and review tasks. |
| ProgramsAndExercise | Exercise provider integration, coach-created custom exercises, program templates, assigned programs, workout structure, alternatives, effort targets, progression rules. |
| DailyExecution | Today view, task generation, quick logs, workout session logs, set-level RPE/RIR, meal completion, adherence events, offline sync. |
| Nutrition | Versioned meal plans, nutrient target sets, food portions, supplement schedules, optional timing constraints, daily intake logs, nutrition templates, and meal swap requests. |
| Communication | Conversations, messages, replies, reactions, GIFs, read receipts, voice notes, attachments, push notifications. |
| ProgressAnalytics | Charts, adherence scoring, PR detection, effort trends, progress comparisons, trend detection, weekly recaps, business analytics. |
| Billing & Integrations | Future bounded context for Post-V1 payments, subscriptions, receipts, referrals, wearables, email, calendar, video calls, and cloud storage. |
Domain reference
Use the Domain Model Map as the growing visual reference for bounded-context ownership, aggregate roots, entities, value objects, events, and cross-context relations.
Data & Infrastructure
Self-host the core runtime while allowing approved external APIs for identity handshakes, exercise content, app-store push delivery, and messaging media. Every external provider and operator-controlled application integration follows the selection, data, credential, cache, failure, and evidence rules in the Integration Register.
PostgreSQL Source Of Truth
Use normalized tables for core aggregates and transactions. Use jsonb only where the shape is intentionally flexible: form answers, provider metadata, and versioned template snapshots.
Drizzle ORM
Use Drizzle for SQL-first schema, migrations, and repository implementations. Keep business rules in domain/application layers, not ORM models.
Record Lifecycle
Each feature technical page must decide lifecycle behavior per table under the Privacy And Retention authority. Use soft delete for aggregate roots and independently managed business records, status timestamps for meaningful relationships, and append-only retention or archival for audit, legal, security, and outbox records.
Redis + BullMQ
Use queues for notifications, reminders, media processing, weekly recaps, provider sync, PDF-to-template jobs, and outbox processing. Backend event publishing follows the Event and Outbox Standard.
MinIO Object Storage
Store photos, videos, voice notes, PDFs, receipts, generated assets, and resources through signed URLs. Store metadata and permissions in PostgreSQL.
Environment ownership
Environment setup details are owned by the Environment Runbook.
Offline & Sync
Mobile offline behavior is a first-class design constraint because clients train in weak-signal gyms and coaches may draft changes on mobile.
Client Mobile SQLite
- Assigned Today data cache.
- Offline workout session logs.
- Pending check-in/form submissions.
- Local outbox with retry and idempotency keys.
Coach Mobile SQLite
- Draft program and form edits.
- Client snapshots for review.
- Message and media upload queue.
- Conflict handling for drafts before publishing.
Conflict default
Server wins for published plans/forms; mobile drafts can be resumed and resubmitted; workout logs, set-level effort readings, and check-ins merge by stable client-generated IDs.
Auth & Access
Identity provider mechanics are separated from CoachMe business identity, role, and relationship rules.
Identity Stack
Use Keycloak as the self-hosted identity base. Store CoachMe-owned User, Coach, Client, CoachClientRelationship, and AuthIdentity records in PostgreSQL.
Provider Adapters
Implement Google, Apple, and Telegram login behind one provider port so registration, login, and onboarding flows do not depend on provider-specific branching. WhatsApp and Telegram messaging are delivery channels for invitations and one-time codes, not login providers, and sit behind their own transport adapter. Provider selection, conditional status, credential boundaries, and launch evidence follow the Integration Register.
Invitation Links
Client registration starts from app-owned invitation records with active, expired, consumed, and revoked states. A provider login alone never creates a coach-client relationship.
Authorization
Enforce role and relationship access in application use cases and API guards. Row-level security can be added later as defense in depth.
Internal Build Sequence For Public V1
Sequence the build around the core coaching loop before business operations and heavier integrations.
- Foundation: monorepo, auth, PostgreSQL, OpenAPI, shared mobile core, localization/RTL, deployment.
- Identity/onboarding: coach registration, client invitation validation, client onboarding, role-based sessions.
- Coach operations: web and coach mobile dashboard, task inbox, client profiles, status, goals, notes, messaging, progress review, and nutrition review.
- Forms: reusable builder on coach web, assignment/scheduling, client mobile submission, and coach mobile review/lightweight actions.
- Programs/exercise: provider adapter, templates, coach web builder, client workout snapshots, effort targets, and coach mobile review/lightweight actions.
- Daily execution: client Today view, quick logs, offline workout logging, RPE/RIR capture, sync.
- Nutrition: nutrient target sets, meal plan snapshots, macro/micro logs, supplements, hydration, and meal swap requests.
- Progress: measurements, photos, charts, adherence, PRs, effort trends, weekly recap.
- Post-V1: full coach mobile builder parity, full Priority view, payments, gamification, wearables, calendar, email, cloud integrations, comprehensive food database, business analytics, and AI/program adaptation.
Testing Strategy
Test at domain, API, contract, and product-flow levels so the three app surfaces remain consistent.
Backend Tests
- Domain unit tests for aggregate rules and use cases.
- Domain unit tests for effort validation, workout log corrections, and PR detection.
- Domain unit tests for nutrient calculations, target variance, plan versioning, and supplement adherence.
- Integration tests with PostgreSQL, Redis, MinIO, and outbox processing following Event and Outbox Standard retry and idempotency rules.
- Security tests for invitations, relationship access, signed URLs, and role-specific routes.
Client Tests
- OpenAPI contract tests for web, coach mobile, and client mobile.
- Playwright tests for coach web builders and dashboards.
- Mobile E2E tests for both Expo apps: auth, nutrition logging, offline sync, uploads, RTL, and push flows.
Feature Technical Pages
These grouped folders are ready for the next pass. Links are shown as planned until each feature page is created.
Domain Reference
- Workflow state map — authority
- Roles and permissions — authority
- Privacy and retention — authority
- API contract standard — authority
- Event and outbox standard — authority
- Offline sync protocol — authority
- Environment runbook — authority
- Toolchain contract — authority
- Integration register — authority
- Observability plan — authority
- Domain model map — ready
- Feature page template — ready contributor template in
site/.templates/feature-page.md
Authentication
- Coach login and registration — ready
- Client invitation link validation — ready
- Client login during onboarding — ready
- Extensible authentication providers — ready
Client Management
- Detailed profiles — ready
- Measurements and photo timeline — ready
- Questionnaire builder — ready
- Onboarding workflow — ready
Coach Workflow
- Coach task inbox — ready
- Client risk flags — ready
- Priority view — ready
Workout Programs
- Exercise library — ready
- YMove exercise integration — ready
- Program builder — ready
- Workout logging — ready
- PR and RPE/RIR tracking — ready
Mobile Experience
- Today view — ready
- Quick-log daily tasks — ready
- Offline workout mode — ready
- Accessibility and dark mode — ready
Nutrition
- Macro and micronutrient tracking — ready
- Meal plan builder — ready
- Supplement schedule — ready
- Meal swap requests — ready
Communication
- In-app messaging — ready
- Voice notes — ready
- Media and form attachments — ready
- Push notifications — ready
Analytics, Payments, Integrations
- Adherence scoring — planned
- Progress charts and comparisons — planned
- Billing and receipts — planned
- Wearables, calendar, email, storage — planned