Skip to content

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.

LayerChoiceResponsibility
BackendNestJS modular monolithREST API, OpenAPI contracts, workers, scheduled jobs, DDD application services.
WebNext.js App RouterCoach/admin workspace, dashboards, builders, reports, settings, operations.
MobileExpo React NativeSeparate coach and client store apps sharing mobile infrastructure packages.
API contractsREST + OpenAPITyped client generation, regression tests, portable integration surface.
Toolchainpnpm 10 + TurborepoMonorepo dependency management, task orchestration, codegen, migration commands, and CI command shape.
ObservabilityPino + OpenTelemetry metrics + Grafana Alloy/Cloud + SentryLaunch 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-web and packages/ui-mobile: platform design systems.

DDD Bounded Contexts

Each context owns its domain model, application use cases, persistence adapters, API controllers, events, and tests.

ContextResponsibilities
IdentityAccessUsers, auth identities, sessions, provider adapters, roles, invitations, and account linking.
CoachClientManagementCoach-client relationships, profiles, status, notes, goals, milestones, measurements, and segmentation.
FormsQuestionnaire templates, form versions, assignments, schedules, submissions, and review tasks.
ProgramsAndExerciseExercise provider integration, coach-created custom exercises, program templates, assigned programs, workout structure, alternatives, effort targets, progression rules.
DailyExecutionToday view, task generation, quick logs, workout session logs, set-level RPE/RIR, meal completion, adherence events, offline sync.
NutritionVersioned meal plans, nutrient target sets, food portions, supplement schedules, optional timing constraints, daily intake logs, nutrition templates, and meal swap requests.
CommunicationConversations, messages, replies, reactions, GIFs, read receipts, voice notes, attachments, push notifications.
ProgressAnalyticsCharts, adherence scoring, PR detection, effort trends, progress comparisons, trend detection, weekly recaps, business analytics.
Billing & IntegrationsFuture 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.

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.

  1. Foundation: monorepo, auth, PostgreSQL, OpenAPI, shared mobile core, localization/RTL, deployment.
  2. Identity/onboarding: coach registration, client invitation validation, client onboarding, role-based sessions.
  3. Coach operations: web and coach mobile dashboard, task inbox, client profiles, status, goals, notes, messaging, progress review, and nutrition review.
  4. Forms: reusable builder on coach web, assignment/scheduling, client mobile submission, and coach mobile review/lightweight actions.
  5. Programs/exercise: provider adapter, templates, coach web builder, client workout snapshots, effort targets, and coach mobile review/lightweight actions.
  6. Daily execution: client Today view, quick logs, offline workout logging, RPE/RIR capture, sync.
  7. Nutrition: nutrient target sets, meal plan snapshots, macro/micro logs, supplements, hydration, and meal swap requests.
  8. Progress: measurements, photos, charts, adherence, PRs, effort trends, weekly recap.
  9. 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

Authentication

Client Management

Coach Workflow

Workout Programs

Mobile Experience

Nutrition

Communication

Analytics, Payments, Integrations

  • Adherence scoring — planned
  • Progress charts and comparisons — planned
  • Billing and receipts — planned
  • Wearables, calendar, email, storage — planned

CoachMe internal planning documentation.