Technical Design TD-0009 — Fitness service and app¶
| Field | Value |
|---|---|
| ID | TD-0009 |
| Title | Fitness: workouts, routines, body tracking, weekly plan, reminders |
| Status | Draft |
| Owner | Kostas Alexopoulos |
| Audience | contributors |
| Created | 2026-10-30 |
| Last Updated | 2026-10-30 |
| Related | PRD-006, Fitness user stories, ADR-0017 background jobs |
1. Summary¶
Add a loryth-fitness microservice and a /fitness app in the web client. The service owns the exercise library, workouts, routines, body measurements, weight goals, the weekly plan, and reminders. Nutrition data stays in Grocery; the web app composes both. A fitness worker evaluates reminders on a schedule and creates in-app notifications.
2. Context and Problem Statement¶
Grocery already records meals, quick meals, and dietary goals (/api/v1/grocery/nutrition/*, /api/v1/grocery/quick-meal). Journal already models activity_ref items whose source of truth is "the owning service (e.g. fitness tracker)". No service owns training or body data.
2.1 Goals¶
- One place for training records, plan, and body progress, following the platform's service conventions exactly (layered architecture, SQL migrations, integration tests, gateway wiring).
- Fast set logging: one request per set change, no page reload.
- Reminders without a new scheduler dependency.
2.2 Out of Scope¶
Meal storage, imperial units, device imports, mobile screens, journal activity_ref writes.
2.3 Assumptions and Constraints¶
- The API derives
user_idfrom the signed-in user; callers send no user ID. The platform's caller checks remain a separate hardening task; every repository query must still filter byuser_id. - Python 3.13, PEP 695 generics, no
Optional, noAny. - Timestamps are
TIMESTAMPTZ; dates for "today" are computed from a client-supplied IANA timezone, as Journal's day projection does.
3. Design Overview¶
3.1 Key Components¶
| Component | Purpose |
|---|---|
loryth-fitness API | FastAPI service on port 8000 behind /api/v1/fitness/* |
loryth-fitness worker | TaskScheduler cron job that fires due reminders through the Notifications API |
PostgreSQL fitness database | Own role and database, migrations v00–v05 |
Web app /fitness | Section-bar app: Today, Train, Exercises, Body, Plan, Nutrition |
| Grocery nutrition hooks | Reused as-is for the Nutrition section and the Today macro bar |
3.2 Architecture¶
graph LR
Web[/fitness web app/] -->|/api/v1/fitness| API[loryth-fitness-api]
Web -->|/api/v1/grocery/nutrition| Grocery[loryth-grocery-api]
API --> DB[(fitness db)]
Worker[loryth-fitness-worker] --> DB
Worker -->|POST /notifications| Notif[loryth-notifications-api] 4. Domain Model (DDD)¶
Bounded context: Fitness (loryth.fitness). All aggregates are owned by a single user (user_id); there is no space scoping in v1.
4.1 Ubiquitous language¶
| Term | Definition |
|---|---|
| Exercise | A named movement with a category and a measurement kind that decides what a set records. Library exercises have no owner; user exercises have user_id. |
| Workout | One training session: started_at, optional ended_at, status, ordered WorkoutExercise children, each with ordered WorkoutSet children. |
| Set | One performed unit: reps, weight, duration, distance (subset by kind), completed. |
| Routine | A reusable workout template with RoutineExercise targets. |
| WeeklyPlan | The user's single plan: PlannedSession children (weekday, routine, optional time). |
| BodyMeasurement | A dated record of weight and optional body-fat and girths. |
| WeightGoal | Start weight, target weight, target date; one active per user. |
| Reminder | Kind, label, local time, weekdays, timezone, enabled, last_fired_on. |
| Today | Read model for a date and timezone: planned sessions, workouts, latest measurement, goal progress, due reminders. |
4.2 Aggregates¶
Exercise (aggregate root, table exercise)¶
| Column | Type | Notes |
|---|---|---|
id, uuid, created_at, updated_at | BaseAggregate | |
user_id | UUID NULL | NULL = built-in library entry |
name | VARCHAR(128) | unique per owner: partial unique index on (user_id, lower(name)) where user_id IS NOT NULL, and on lower(name) where user_id IS NULL |
category | enum exercise_category: strength, cardio, mobility, other | |
measurement | enum exercise_measurement: reps_weight, reps_only, duration, distance_duration | |
muscle_groups | JSONB list of strings | e.g. ["quads","glutes"] |
notes | TEXT NULL | |
is_archived | BOOLEAN default false |
Invariants: built-in exercises (user_id IS NULL) cannot be edited or archived through the API (409). Archiving hides from pickers but keeps history.
Workout (aggregate root, table workout)¶
| Column | Type | Notes |
|---|---|---|
user_id | UUID | indexed with started_at |
title | VARCHAR(128) NULL | defaults to routine name or "Workout" in the UI |
routine_id | BIGINT FK routine.id ON DELETE SET NULL | |
status | enum workout_status: in_progress, completed | |
started_at | TIMESTAMPTZ | |
ended_at | TIMESTAMPTZ NULL | required when completed |
perceived_effort | SMALLINT NULL | 1–10 |
notes | TEXT NULL |
Children, both BaseEntity + AuditMixin, cascade all, delete-orphan, lazy="selectin":
- WorkoutExercise (
workout_exercise):workout_idFK CASCADE,exercise_idFKexercise.idON DELETE RESTRICT,exercise_nameVARCHAR(128) snapshot,measurementsnapshot enum,positionINT,notesTEXT NULL. Unique(workout_id, position). - WorkoutSet (
workout_set):workout_exercise_idFK CASCADE,positionINT,repsINT NULL,weight_kgNUMERIC(6,2) NULL,duration_secondsINT NULL,distance_mNUMERIC(9,1) NULL,completedBOOLEAN default false,is_warmupBOOLEAN default false. Unique(workout_exercise_id, position).
Invariants: at most one in_progress workout per user (partial unique index on user_id where status = 'in_progress'); ended_at >= started_at; set fields allowed by the exercise's measurement kind only (validated in the service, others stored NULL); perceived_effort in 1..10.
Domain events (outbox, no consumer in v1): WorkoutCompletedEvent(workout_uuid, user_id, started_at, ended_at).
Routine (aggregate root, table routine)¶
user_id, name VARCHAR(128) (unique per user, case-insensitive), description TEXT NULL, is_archived BOOLEAN. Child RoutineExercise (routine_exercise): exercise_id FK RESTRICT, position, target_sets SMALLINT, target_reps INT NULL, target_weight_kg NUMERIC(6,2) NULL, target_duration_seconds INT NULL, target_distance_m NUMERIC(9,1) NULL, rest_seconds INT NULL, notes TEXT NULL.
WorkoutService.start_from_routine copies each routine exercise into a WorkoutExercise and creates target_sets uncompleted WorkoutSets carrying the targets.
WeeklyPlan (aggregate root, table weekly_plan)¶
One row per user (user_id unique), created on first access. Child PlannedSession (planned_session): weekday SMALLINT 0=Monday..6, routine_id FK CASCADE, time_of_day TIME NULL, label VARCHAR(128) NULL, position. Unique (weekly_plan_id, weekday, position).
BodyMeasurement (aggregate root, table body_measurement)¶
user_id, measured_at TIMESTAMPTZ, weight_kg NUMERIC(5,2), body_fat_pct NUMERIC(4,1) NULL, waist_cm, chest_cm, hips_cm NUMERIC(5,1) NULL, notes TEXT NULL. Index (user_id, measured_at DESC).
WeightGoal (aggregate root, table weight_goal)¶
user_id, start_weight_kg, target_weight_kg NUMERIC(5,2), start_date, target_date DATE, status enum weight_goal_status: active, achieved, abandoned, achieved_at TIMESTAMPTZ NULL. Partial unique index on user_id where status = 'active'. target_date > start_date.
GoalService.progress(user_id, tz) returns: latest weight, change so far, remaining, percent (clamped 0..100), required kg/week from today, observed kg/week from a linear fit over measurements in the last 28 days (NULL with fewer than two points). Logging a measurement at or past the target (direction-aware) marks the goal achieved. Progress weights and weekly rates are rounded to two decimals; percent is rounded to one decimal.
Reminder (aggregate root, table reminder)¶
user_id, kind enum reminder_kind: workout, meal, weigh_in, custom, label VARCHAR(128), time_of_day TIME, weekdays SMALLINT bitmask (bit 0 = Monday), timezone VARCHAR(64) IANA, enabled BOOLEAN, last_fired_on DATE NULL.
Firing rule (worker, every minute): for each enabled reminder, compute local now in timezone; if today's weekday bit is set, time_of_day <= local time, and last_fired_on < local date (or NULL), create an IN_APP notification (category ACTIVITY) via the Notifications API and set last_fired_on = local date in the same transaction before the HTTP call commits. A failed notification call logs and leaves last_fired_on unset so the next tick retries. Rows are selected FOR UPDATE SKIP LOCKED so two workers never double-fire.
4.3 Read models¶
- Today (
TodayService.summary(user_id, date, tz)): planned sessions for the weekday with acompleted_workout_idwhen a workout with thatroutine_idended on that local date; workouts whosestarted_atfalls on the local date; the in-progress workout if any; latest measurement; goal progress; reminders due that weekday withsatisfiedcomputed as described in PRD-006 §3.4 (meal satisfaction is computed in the web app from Grocery data; the API returnssatisfied: nullfor meal reminders). - Exercise history (
HistoryService): sets grouped by workout, best set (maxweight_kg, then reps; max distance; max duration by kind), Epley e1RMweight × (1 + reps/30)forreps_weight, and a per-workout best series for the chart. - Week (
PlanService.week(user_id, week_start, tz)): planned vs completed per day, adherencecompleted/planned. The web app labels each session Done whencompleted_workout_idis set, Missed when its date precedes the browser's local date, and Planned otherwise. Today uses the same labels.
No projection tables in v1; the queries are indexed and per-user.
5. API¶
All routes under the service root, exposed by the gateway at /api/v1/fitness. Responses use SuccessResponse[T]; lists use PageModel where paginated. user_id is a required query parameter on GET/DELETE and a body field on POST/PUT/PATCH (Grocery convention).
| Method | Path | Purpose |
|---|---|---|
| GET | /exercises?user_id&q&category&include_archived | Library + user exercises |
| POST | /exercises | Create user exercise |
| GET / PATCH / DELETE | /exercises/{uuid} | Read, edit, archive (DELETE archives; 409 for built-in) |
| GET | /exercises/{uuid}/history?user_id&limit | History read model |
| GET | /workouts?user_id&from&to&status | Paginated list, newest first |
| POST | /workouts | Start ad hoc (started_at optional) |
| POST | /workouts/from-routine | {user_id, routine_id} |
| GET / PATCH / DELETE | /workouts/{uuid} | Read full workout; patch title/notes/effort/started_at/ended_at |
| POST | /workouts/{uuid}/finish | {user_id, perceived_effort?, notes?, ended_at?} |
| POST | /workouts/{uuid}/exercises | Add exercise {user_id, exercise_id, position?} |
| PATCH / DELETE | /workouts/{uuid}/exercises/{we_uuid} | Reorder, notes, remove |
| POST | /workouts/{uuid}/exercises/{we_uuid}/sets | Add set (copies previous when body is empty) |
| PATCH / DELETE | /workouts/{uuid}/exercises/{we_uuid}/sets/{set_uuid} | Edit values / completed, remove |
| POST | /workouts/{uuid}/save-as-routine | {user_id, name} |
| GET / POST | /routines | List (archived excluded by default), create with exercises |
| GET / PUT / DELETE | /routines/{uuid} | Read, replace exercises, archive |
| GET | /plan?user_id | Weekly plan with sessions |
| PUT | /plan | Replace all planned sessions |
| GET | /plan/week?user_id&week_start&tz | Week adherence read model |
| GET / POST | /measurements | List (paginated, from/to), create |
| PATCH / DELETE | /measurements/{uuid} | Edit, delete |
| GET | /goal?user_id | Active goal with progress, 404 when none |
| PUT | /goal | Create or replace active goal |
| POST | /goal/abandon | {user_id} |
| GET / POST | /reminders | List, create |
| PATCH / DELETE | /reminders/{uuid} | Edit (including enabled), delete |
| GET | /today?user_id&date&tz | Today read model |
| GET | /health | Health check |
Errors: NotFound → 404, duplicate names → 409, in-progress workout exists → 409 with the existing workout uuid in detail, validation → 422.
6. Service Layout¶
server/services/loryth-fitness/
migrations/
v00-setup.sql # uuid-ossp, outbox tables (copy Journal v00)
v01-exercise.sql # enums + exercise + library seed (~24 rows)
v02-workout.sql # workout, workout_exercise, workout_set
v03-routine-plan.sql # routine, routine_exercise, weekly_plan, planned_session
v04-body.sql # body_measurement, weight_goal
v05-reminder.sql # reminder
src/loryth/fitness/
api/app.py # FastAPI app, RequestIdMiddleware, DbContext scope middleware
api/<area>/{router,schema}.py # exercises, workouts, routines, plan, body, reminders, today
config/{context,infrastructure}.py
domain/<area>/ # aggregate, children, enums, exceptions, dto, repository
domain/*_service.py # ExerciseService, WorkoutService, RoutineService, PlanService,
# BodyService, GoalService, ReminderService, TodayService, HistoryService
domain/notification_gateway.py # httpx client for Notifications API (LORYTH_NOTIFICATIONS_URL)
worker/cli.py # TaskScheduler cron "* * * * *" -> ReminderService.fire_due()
tests/conftest.py, tests/api/test_*.py, tests/stubs.py (notification gateway stub)
Dockerfile, Makefile, pyproject.toml, mkdocs.yml, CLAUDE.md, docs/
Copy the Journal service scaffolding (Makefile, Dockerfile, pyproject, conftest) and rename. The worker needs no RabbitMQ in v1; keep the outbox tables and EventConsumer wiring so events can be bridged later, mirroring Journal's worker.
7. Platform Wiring¶
| File | Change |
|---|---|
docker/postgres/init-databases.sh | add fitness to SERVICES |
docker-compose.yml | x-db-fitness-env anchor, DB_PASSWORD_FITNESS on postgres and migrations, loryth-fitness-api and loryth-fitness-worker (profile workers, LORYTH_NOTIFICATIONS_URL=http://loryth-notifications-api:8000), gateway depends_on |
docker/migrations/Dockerfile, run-migrations.sh | copy and run fitness migrations |
docker/nginx/templates/default.conf.template | fitness_backend upstream and /api/v1/fitness location |
docker/tests/compose.py, test_gateway.py | add fitness to the service lists |
.env.example, .env.server.example | DB_PASSWORD_FITNESS |
docs/mkdocs.yml | PRD-006, user stories, TD-0009, service docs include |
CLAUDE.md (root), .claude/rules/infrastructure.md | list the fitness database and service |
Deployment note for an existing installation: init-databases.sh only runs on an empty PostgreSQL volume. On snoopy the fitness role and database must be created by hand with the same statements before the migration job runs, including CREATE EXTENSION "uuid-ossp" in the new database.
8. Web App¶
ui/packages/app/src/modules/fitness/
FitnessLayout.tsx, FitnessNav.tsx, FitnessNav.css.ts, sections.ts # mirror grocery
api/{fitness-api.ts,types.ts,queries.ts} # customFetch + TanStack Query, keys under ['fitness', ...]
today/TodayPage.tsx # /fitness
train/{WorkoutsPage,WorkoutPage,RoutinesPage,RoutineFormPage}.tsx
exercises/{ExercisesPage,ExercisePage}.tsx
body/{BodyPage,MeasurementDialog,GoalDialog}.tsx
plan/{PlanPage,ReminderDialog}.tsx
nutrition/NutritionPage.tsx # uses useDietaryGoal/useDailyMeals from @loryth-ui/api and grocery's MacroBars
components/{SetRow,ExercisePicker,WorkoutCard,GoalCard,WeightChart,...}.tsx
index.ts
Routes (in App.tsx): /fitness (Today), /fitness/workouts, /fitness/workouts/:workoutId (focused screen, section strip and phone bar hidden), /fitness/routines, /fitness/routines/new, /fitness/routines/:routineId/edit, /fitness/exercises, /fitness/exercises/:exerciseId, /fitness/body, /fitness/plan, /fitness/nutrition. Navigation: Fitness with the Dumbbell Lucide icon and its sections are declared in shell/navigation/apps.ts, with its title in routeTitles.
Sections: Today /fitness, Train /fitness/workouts (also /fitness/routines), Exercises, Body, Plan, Nutrition. Reuse @/components/workspace primitives (PageHeader, Panel, Field, FormDialog, Notice) and @loryth-ui/web components; styles in vanilla-extract with tokens only.
Set logging: optimistic updates on the workout query; each set change is one PATCH; "Add set" POSTs an empty body and the server copies the previous set.
Tests: Vitest + MSW for TodayPage (empty and populated), WorkoutPage set logging, BodyPage goal progress; Storybook stories for Today and Workout mirroring stories/journal.
9. Testing¶
- Service: testcontainers integration tests per router (
tests/api/test_exercises.py,test_workouts.py,test_routines.py,test_plan.py,test_body.py,test_reminders.py,test_today.py), function-based,cleanup_dbautouse. Reminder firing is tested throughReminderService.fire_due(now)with a stub notification gateway. - Docker tests pick up the new service through the shared lists.
- Web: the Vitest suites above;
pnpm typecheckandpnpm lintclean.
10. Error Handling and Edge Cases¶
- Starting a workout while one is in progress returns 409 with the existing uuid; the UI offers Resume.
- Deleting an exercise that has history archives it instead (RESTRICT FK).
- Deleting a routine removes its planned sessions (CASCADE) and nulls
workout.routine_id. - Reminder timezones are validated with
zoneinfo; invalid → 422. - Measurement
measured_atin the future → 422. - Goal with
target_weight_kg == start_weight_kg→ 422.
11. Follow-ups¶
- Journal
activity_refitem on workout completion (consumeWorkoutCompletedEvent). - Dashboard widget "This week's training".
- Mobile screens from the shared contracts.
- Unit preferences.
12. Implementation clarifications¶
- The repeat-set POST takes
user_idin the query so its body can be exactly{}. Other writes carryuser_idin the body. API resource references are UUIDs. - Notifications uses its existing singular
POST /notification/route and a newfitness-remindertemplate. The gateway sendsin_app/activityenum values and a reminder/local-date idempotency key. This also covers a worker crash after notification creation but before the Fitness transaction commits. - The outbox consumer is configured but inactive until a bridge exists. Completion events remain in the event log; the v1 worker only schedules reminders.
- Routine DELETE archives the routine and removes its planned sessions while retaining workout references.
- Grocery groups meal logs by UTC day. Fitness reuses the existing nutrition hooks for adjacent UTC dates, then filters the browser's local day for macros. The same fetched meals cover reminder windows that cross midnight.
- Body chart ranges read all measurement pages. The measurement list stays paginated and includes older records independently of the selected chart range.
- Fitness uses the Journal template's mypy 1.19 series (
<1.20) and installs croniter stubs. Newer mypy versions currently report two errors in the shared DI plan builder. This range keeps Fitness aligned with Journal until those shared types are updated.