Fitrace · Architecture

How Fitrace is built

A strength-training app for iPhone, built with Expo and React Native, talking to a TypeScript serverless backend on AWS. Clerk handles sign-in, RevenueCat handles subscriptions, and the AI features (FitraceAI chat, scanning, form checks) call Claude or OpenAI from the server only. Workouts can go to Strava and Apple Health.

Expo SDK 58 React Native 0.88 · React 19.3 Clerk RevenueCat API Gateway HTTP API Lambda × 60 · Node 24 · arm64 DynamoDB single table S3 (private) Claude Haiku 5.5 AWS CDK v2 ap-southeast-2 (Sydney)

Overview

The phone does the work a person sees: logging sets, timers, plans, charts, reminders. It keeps a workout in progress on the device so logging never waits for the network, and it reads Apple Health and the calendar itself, without sending them to the server. Everything that must be trusted or kept (accounts, plans, workout history, photos, saved chats, subscriptions, AI calls, Strava) goes through one HTTPS API, where every request is checked against the signed-in user before anything is read or written.

Connections

Every service outside Fitrace's own code, which side talks to it, and what crosses. "Phone" means the app talks to it directly; "server" means only a Lambda does.

ServiceWho talks to itWhat it's forWhat crossesKeys
Clerkphone ⇄ Clerk
server → Clerk
Sign-in (Apple, Google, email code) and the API's tokens; deleting a loginEmail, name, sign-in. The server only calls Clerk to delete a login when an account is deletedPublishable key in the app (public); secret key in Secrets Manager (DELETE /me only)
Anthropic (Claude)server → AnthropicEvery AI feature today: Claude Haiku 5.5The user's message, recent chat, training context, memory; scan photos and form-check frames, sent once, not stored by FitraceSecrets Manager, AI Lambdas only
OpenAIserver → OpenAIEnabled as a second provider; any feature can switch to it with a config changeSame as above when switched on; store: falseSecrets Manager, AI Lambdas only
RevenueCatphone ⇄ RevenueCat
RevenueCat → server
server → RevenueCat
Subscriptions through Apple In-App PurchaseThe Clerk user id and purchases. RevenueCat's webhook tells the server; the server re-reads the customer from RevenueCat before changing a tierPublic appl_… key in the app; secret API key and the webhook's Authorization value in Secrets Manager
Apple App Storephone ⇄ ApplePayment, through RevenueCat's SDKHandled by Apple and RevenueCat; Fitrace never sees card detailsNone in Fitrace
Stravaphone → Strava sign-in
server → Strava
Posting finished workouts as Weight Training (one way: nothing is read back)The workout's name, time, length and sets. Strava's tokens stay on the server, never on the phoneClient id in config (public); client secret in Secrets Manager
Apple Healthphone ⇄ HealthSaving workouts and weight; reading weight, height, steps and activityStays on the phone. Weight and height go into the user's Fitrace profile; steps and activity never leave the phoneNone (iOS permission)
iPhone Calendarphone → Calendar"When can I train?": FitraceAI and check-ins plan around busy timesBusy times only (start and end, never names, people or places), sent with a chat message and not storedNone (iOS permission)
Locationphone → serverOptional: answers that depend on where you areApproximate area (about 1 km) with a chat message, only when Location is on; never stored or loggedNone (iOS permission)
Expo (EAS)phone ⇄ ExpoBuilds and TestFlight submission; over-the-air updates (EAS Update); performance monitoring (EAS Observe)Updates: JavaScript and assets down to the phone. Observe: start and screen timings and JS errors, with an anonymous per-install id, from TestFlight and App Store buildsNone in the app
Google Fontsthis page onlyGeist on this documentation pageNothing from the app (the app bundles its fonts)None

No analytics or crash-reporting SDKs that could receive user content. EAS Observe sends timings and error names only, never what a user typed.

AWS services

Everything is defined in AWS CDK v2 (TypeScript) in backend/infra; nothing is set up by hand. Region: ap-southeast-2 (Sydney), apart from this documentation site's certificate, which CloudFront needs in us-east-1.

ServiceWhat Fitrace uses it forHow it's set up
API Gateway (HTTP API)The one public API the app callsClerk JWT authorizer as the default on every route; the only public route is RevenueCat's webhook, which checks its own secret. CORS; $default stage with throttling (dev 20 req/s, burst 40; prod 50, burst 100); 30-second integration limit
AWS LambdaAll server logic: one function per route (60)Node.js 24, arm64 (Graviton), ESM bundles built by esbuild via NodejsFunction; 512 MB, 10 s by default (AI routes and the webhook up to 29 s; uploads and Strava 15–25 s); its own log group each
Amazon DynamoDBAll app dataSingle table Fitrace-<stage>, on-demand billing, PK/SK, TTL on expiresAt (AI counters, chats unused for 30 days), point-in-time recovery (35 days); prod also has deletion protection and is retained if the stack is removed. A stream (old images) is enabled but has no consumer yet
Amazon S3Photos: exercise catalogue images and users' own photosOne private media bucket: all public access blocked, S3-managed encryption, HTTPS only; files reach the phone only through signed links that expire
AWS Secrets ManagerThird-party keys the server needsfitrace/<stage>/ anthropic-api-key, openai-api-key, clerk-secret-key, strava-client-secret, and two for RevenueCat (its API key and the webhook's Authorization value). CDK creates each with a placeholder; the real value is set once with the CLI. Read at runtime, cached in memory, readable only by the functions that need them
AWS Systems Manager (Parameter Store)Tier limits that change without a deploy/fitrace/<stage>/tier-limits: JSON overrides of the built-in Free, Pro and Max limits, set with npm run tier:limits
Amazon CloudWatchLogs, AI metrics, the AI dashboard and alarmsStructured JSON logs (Powertools Logger), kept 1 week in dev and 3 months in prod; error names only, never tokens, links or user content. Each AI call records its tokens and outcome as metrics; a dashboard shows them, with alarms for daily tokens (2 million), failures (5 in 15 minutes) and slow calls (25 s). The alarms don't notify anyone yet
AWS X-RayTracingActive tracing on every function
AWS IAMPermissionsA role per function, scoped to the table and to the bucket prefixes it needs (e.g. read catalog/*, or get/put/delete under users/*), and to only the secrets it uses
AWS Certificate ManagerHTTPS for the custom hostnamesDNS-validated certificates for the API domain (regional) and this docs site (us-east-1, for CloudFront)
Amazon Route 53DNSAlias records in the dev.fitrace.ai, api.fitrace.ai and docs.fitrace.ai zones, which fitrace.ai's DNS (Cloudflare) delegates to Route 53; the old names in the shared pyutasane.com zone
Amazon CloudFrontServes this documentation pageA private S3 bucket behind CloudFront (Origin Access Control), HTTPS only, at docs.fitrace.ai
AWS CloudFormation / CDKDeploymentsStacks Fitrace-Data-<stage> (table and bucket) and Fitrace-Api-<stage> (API, functions, secrets, dashboard), plus Fitrace-Docs for this page

Mobile app

Expo SDK 58 (React Native 0.88, React 19.3 with the React Compiler), TypeScript strict, Expo Router with typed routes. It runs in Expo Go for day-to-day work; development, TestFlight and App Store builds add what Expo Go can't do (native Sign in with Apple, the Live Activity, Apple Health, purchases, dictation, Strava).

Structure

  • app/: routes only, kept thin. Groups for signed out (auth) and the signed-in app (app), guarded with Stack.Protected.
  • src/features/<feature>/: screens, hooks and pure logic with tests (workout, plans, train, today, progress, body, exercises, scan, form check, chat, personalization, check-ins, calendar, health, Strava, subscription, themes, settings…).
  • src/components/: shared UI, one component per file.
  • src/theme/: every colour, spacing, radius and text style. Monochrome, light and dark, Geist, tabular numbers; colour themes on paid plans.
  • src/lib/api/: the useApi client, ApiError and the response types.

Navigation

  • A bottom tab bar: Today · Train · Progress, with FitraceAI's round button at the end. FitraceAI is its own tab: the chat as a page, with saved chats and folders in a drawer.
  • A workout bar above the tab bar while a workout is running.
  • Full-screen stacks for the live workout logger, Scan a program or a machine, Check form, the exercise library, plan editing, body stats, progress photos, settings, connections (Apple Health, Calendar, Strava) and the subscription screens.

Data on the phone

  • TanStack Query for all server data. No ad hoc fetches in screens.
  • The workout in progress lives in an on-device store (AsyncStorage). Logging, finishing and discarding work offline; an outbox syncs to the API in order when the network is back.
  • Chats are saved on the server (since 10 Nov); the phone shows them a page at a time.
  • Settings that are only about this phone (Apple Health, calendar choices, check-ins, step goal) stay on the phone.
  • Exercise photos are cached by exercise (memory and disk) so lists show them at once.

Native features

  • Sign in: @clerk/expo, session token in the Keychain (expo-secure-store); native Sign in with Apple, Google OAuth, email code.
  • Live Activity: the current exercise and rest timer on the Lock Screen and Dynamic Island (expo-widgets, @expo/ui).
  • Notifications: local only (expo-notifications): the rest timer and FitraceAI check-ins, written on the phone from templates. No push server.
  • Apple Health (@kingstinct/react-native-healthkit), Calendar (expo-calendar), Location (expo-location), Dictation (expo-speech-recognition, on the phone where the iPhone supports it).
  • Photos and video: camera and library (expo-image-picker), shrunk on the phone before upload (expo-image-manipulator); form-check videos become still frames on the phone (expo-video-thumbnails), so no video is uploaded.
  • Purchases: react-native-purchases (RevenueCat). Strava sign-in: expo-web-browser.
  • Over-the-air updates (expo-updates) and performance monitoring (expo-observe).

Only EXPO_PUBLIC_* values (the API URL, Clerk's publishable key, RevenueCat's public key) are built into the app, and those are public by design.

A request, end to end

  1. The user signs in with Clerk. The session token is kept in the device's secure storage.
  2. For each call, useApi() asks Clerk for a fresh JWT from the api template: audience fitrace-api, a 60-second lifetime, signed by Clerk.
  3. API Gateway's JWT authorizer checks the signature against Clerk's published keys, plus the issuer, audience and expiry. Anything wrong is a 401, and no Lambda runs.
  4. The route's Lambda takes the user id only from the verified sub claim, never from the body or the URL. It validates the body with a strict zod schema (unknown keys such as userId are refused).
  5. It reads or writes only that user's partition in DynamoDB (USER#<sub>), or their own folder in S3 (users/<sub>/). For a paid AI feature it first checks the user's tier and takes one from their allowance, atomically.
  6. Errors come back in one shape: { "error": { "code", "message" } }. The app maps them to plain messages, including offline, limit and "not in your plan" states.

API

60 routes. All but RevenueCat's webhook are behind the Clerk JWT authorizer. Code lives in backend/services/<domain>/ as handlers, commands (writes) and queries (reads); each route has its own Lambda.

DomainRoutesNotes
AccountGET · PATCH · DELETE /me · GET /me/subscription · PUT /me/testingProfile, setup answers and settings (created on first call); the tier, limits and today's usage; testers only (a list on the server) can switch their own plan or turn limits off. Delete disconnects Strava, then removes every item in the user's partition, every file under their folder and their Clerk login
MemoryGET · PUT · DELETE /me/memoryWhat FitraceAI remembers about the user, which they can read, edit or clear
Exercise catalogueGET /exercises · GET /exercises/{id} · GET /exercises/thumbnails876 exercises from free-exercise-db, imported by a script; signed photo links
Your exercisesGET · POST /custom-exercises · PATCH · DELETE /custom-exercises/{id} · PUT · DELETE /custom-exercises/{id}/photo · POST /custom-exercises/resolve · POST /custom-exercises/suggestExercises a user makes, private to them, with an optional photo; matching names from FitraceAI's workout cards; "Fill in with AI"
PlansGET · POST /plans · GET · PUT · DELETE /plans/{id}Up to 20 plans of 1–7 days in rotation; days carry sections, sets, rest, notes and sides
WorkoutsPOST · GET /workouts · GET /workouts/active · GET · PUT · DELETE /workouts/{id} · POST /workouts/{id}/finishIds made on the phone (UUIDv7) so a workout can start offline; revisions guard against stale saves; finishing records stats and each exercise's last performance
ProgressGET /progress · GET /exercise-historyReduced history for charts, streaks and muscle breakdown; per-exercise history
BodyGET /body · PUT /body/{date}Body measurements by day
Progress photosGET · POST /progress-photos · DELETE /progress-photos/{id}JPEG only, private, signed links
FitraceAI chatPOST /chatOne training answer; saves the question and reply to the chat
Saved chatsGET · POST /chats · PATCH · DELETE /chats/{id} · GET /chats/{id}/messages · POST /chats/import · POST · PATCH · DELETE /chat-folders(/{id})Chats and folders (one level deep, up to 100); a chat unused for 30 days is deleted; import moved chats kept on the phone before 10 Nov
ScanningPOST /scan · POST /scan/fix · POST /scan/machineA program from a photo, typed fixes to it, and "which machine is this?"
Form checkPOST /form-check · POST /form-check/identifyTechnique tips from a set's still frames; suggests which exercise a video shows
SubscriptionsPOST /me/subscription/sync · POST /webhooks/revenuecatThe phone asks for a sync after a purchase; RevenueCat's webhook (public, checked with its own secret) reports renewals, cancellations and refunds
StravaGET · POST · PUT · DELETE /me/strava · POST /workouts/{id}/stravaConnect, auto-post on or off, disconnect (revokes at Strava), and post one finished workout

Shared code in backend/services/common: auth (the verified sub), the HTTP wrapper and errors, DynamoDB and S3 clients, key builders, the AI layer (one function for every provider), tiers and AI allowances, secrets.

Data

One DynamoDB table with a generic PK / SK. Everything a user owns sits in their own partition, so a single query reads it and nothing can reach across users by accident. Every key is built in one place (common/keys.ts).

ItemPKSKNotes
ProfileUSER#<sub>PROFILEName, units, time zone, setup answers, current plan, default rest
MemoryUSER#<sub>MEMORYWhat FitraceAI remembers; written every few messages, editable by the user
SubscriptionUSER#<sub>SUBSCRIPTIONThe tier and where it came from (App Store via RevenueCat, or early access); sandbox purchases marked
PlanUSER#<sub>PLAN#<uuid>Days, exercises, sets in one item; when each day was last done
WorkoutUSER#<sub>WORKOUT#<uuidv7>Sorted by start time; in progress or completed, with stats
Active workoutUSER#<sub>ACTIVE_WORKOUTPoints at the one workout in progress
Last performanceUSER#<sub>LAST#<exerciseId>Last sets and best set, for "Last: 60 kg × 8" and suggestions
Body entryUSER#<sub>BODY#<metric>#<day>Weight, body fat, waist…
Progress photoUSER#<sub>PHOTO#<uuid>Details; the image is in S3
Custom exerciseUSER#<sub>CUSTOM_EXERCISE#custom-<uuid>Up to 300; deleting hides it so history keeps its name
Exercise aliasUSER#<sub>EXERCISE_ALIAS#<name>A name from FitraceAI's workout cards and the exercise it was matched to
Chat folderUSER#<sub>CHATFOLDER#<id>Name and parent (one level deep)
ChatUSER#<sub>CHAT#<id>Title, folder, last used; deleted by TTL after 30 days unused
Chat messageUSER#<sub>MSG#<chatId>#<time>#…One message, in time order; goes with its chat
AI allowanceUSER#<sub>QUOTA#<kind>#<day or week>Atomic counter per feature (chat, photo scans, form checks, suggestions, AI fill-ins) in the user's own day or week; removed by TTL
Strava connectionUSER#<sub>STRAVAAthlete, tokens (never returned to the app or logged), auto-post setting
Strava postUSER#<sub>STRAVA_POST#<workoutId>The activity a workout became; holds a short claim while a post is under way so it can't be posted twice at once
Catalogue exerciseCATALOGEXERCISE#<id>Shared and read-only to the API
Catalogue versionCATALOGMETAWhich import is live

Recovery: point-in-time recovery on both stages. In prod the table also has deletion protection and is kept if its stack is deleted. The catalogue can be rebuilt any time with the import script; user data only exists in the table.

Photos and media

Prefix in the media bucketWhatWho can touch it
catalog/exercises/<id>/Exercise photos as WebP (720px and 240px thumbnails)Written by the import script; API functions can only read
users/<sub>/progress-photos/Progress photos (JPEG full size and thumbnail)Only that user's requests; upload, list and delete functions
users/<sub>/custom-exercises/<id>/Photos of a user's own exercises (a new key for each upload)Only that user's requests; deleted with the exercise
  • The bucket is private. The phone gets signed GET links (about an hour) and refreshes them before they expire.
  • Photos are shrunk on the phone before upload, so the server never decodes images; it only checks the file is a JPEG.
  • Photos scanned for a program or a machine, and form-check frames, are sent once to the AI provider and never stored.
  • Deleting the account deletes everything under users/<sub>/.

AI features

Every AI call goes through one function on the server (createStructuredResponse in common/ai.ts), with an adapter per provider: Anthropic's Messages API and OpenAI's Responses API (store: false), both with plain fetch. Each feature's provider and model come from its Lambda's environment, set per stage in backend/infra/config.ts, so switching is a config change and a deploy, not a code change. Today every feature runs on Claude Haiku 5.5; OpenAI stays enabled as a second provider. Answers are structured JSON, checked on the server before the app sees them. Keys never reach the phone.

FitraceAI chat POST /chat

  • A guard call first decides whether the message is about training; the answer must also mark itself on topic. Either says no: fixed copy, never the model's words.
  • The answer gets the user's training context from their own partition only (profile, plans, recent workouts, exercise names), their memory, the chat's recent messages, and, if they allowed it, their busy times, local time and approximate area.
  • Answers can include a workout card the user can start. The chat can't change data by itself.
  • Every few messages a small call updates FitraceAI's memory; the user sees and can edit it in Personalization.

Scanning POST /scan · /scan/fix · /scan/machine

  • A photo of a board, sheet or screenshot is read into a strict routine (days, sections, exercises, targets).
  • The server clamps every number to plan limits, merges repeats and matches names to the catalogue (name → alias → same words → careful fuzzy match). Anything unmatched becomes the user's own exercise, only when they save or start.
  • "Ask to fix…" applies typed corrections; a machine scan names the machine and its exercises.

Form check POST /form-check · /identify

  • The phone turns the video into still frames; only the frames are sent, once, and not stored.
  • Tips on one set's technique. A separate call suggests which exercise the video shows.

Limits and cost

  • Every paid call first takes one from the user's allowance for their tier, atomically, in their own day or week.
  • CloudWatch records each call's tokens and outcome; a dashboard and alarms watch daily tokens, failures and slow calls.
  • Strava data is never given to the AI (Strava's API terms forbid it, and nothing is read from Strava anyway).

Plans and payments

Three tiers: Free, Pro and Max. Plans, the logger and progress are free; the tiers differ in how much FitraceAI a user gets, plus colour themes on paid plans.

AllowanceFreeProMax
FitraceAI messages a day52040
Photo scans a day (programs and machines)3510
Form checks a week1510
  1. The phone buys through RevenueCat's SDK (Apple In-App Purchase), logged in to RevenueCat with the Clerk user id.
  2. After a purchase the phone calls POST /me/subscription/sync; RevenueCat's webhook also reports renewals, cancellations and refunds.
  3. Either way, the server asks RevenueCat for the customer itself and writes the tier to SUBSCRIPTION. The phone's word is never taken.
  4. Every limited route reads the tier on the server. The numbers above are the defaults; they can be changed without a deploy in Parameter Store.

Security

Who you are

  • Authorisation always happens on the server, from the verified sub claim. The app never sends a user id the server trusts.
  • Every route except RevenueCat's webhook requires a valid Clerk token with the fitrace-api audience; tokens last 60 seconds. The webhook checks its Authorization header in constant time against a secret, then re-reads the customer from RevenueCat.
  • Strict request schemas refuse unknown fields such as userId or planId.

What a function can do

  • One IAM role per function: read-only routes can only read the table; photo routes only touch users/*; only AI routes can read AI keys, only Strava routes and account deletion the Strava secret. Infrastructure tests check this.
  • Custom exercise ids start with custom- and must belong to the caller before a plan or workout can use them.
  • API throttling per stage; tier allowances on paid AI calls.

Secrets and logs

  • Keys in Secrets Manager, set once by hand with the CLI (never in code, templates or the app). .env files are never committed.
  • Third-party tokens (Strava) are kept on the server and never returned to the app.
  • Logs carry error names, never tokens, keys, signed links or user content.

Data at rest and in transit

  • HTTPS everywhere (the bucket refuses plain HTTP).
  • S3 and DynamoDB encrypted at rest; the bucket blocks all public access.
  • Account deletion disconnects Strava, then removes the user's items, files and Clerk login.
  • Apple Health data, steps and calendar details stay on the phone.

Environments and delivery

StageAPIStacksData safety
devhttps://api.dev.fitrace.aiFitrace-Data-dev, Fitrace-Api-devPITR; can be torn down and rebuilt
prodhttps://api.fitrace.aiFitrace-Data-prod, Fitrace-Api-prodPITR, deletion protection, retained on stack removal. Not deployed yet: waits for Clerk's production instance and a Fitrace-owned Strava app

Repository

  • apps/mobile: the Expo app.
  • backend/services: Lambda code by domain.
  • backend/infra: the CDK app (stacks, route constructs, Lambda defaults, stage config).
  • docs/: the build spec (the source of truth for screens, copy, routes and data), the backend runbook, the AI and chat notes, and this page.
  • scripts/: smoke test, Clerk setup, brand assets.

Checks and releases

  • npm run check: typecheck, lint and tests in all three packages (Jest with jest-expo for the app, ts-jest for backend and infra, CDK assertions).
  • npm run deploy: CDK deploy to prod, only when asked (npm run deploy:dev for dev). Then npm run smoke, an end-to-end test against the deployed API with a temporary Clerk test user.
  • npm run testflight: an EAS production build, submitted to TestFlight.
  • npm run update: an over-the-air update (EAS Update) for JavaScript-only changes, to builds with the same native code (runtime version by fingerprint). Anything native needs a new build.
  • Work happens on branches, merged to main after a passing check (and smoke test, for the backend).