29 KiB
Health App architecture specification
Status: complete proposed design, 2026-10-13; not an implementation or production certification. The user's clarification authorizes evaluating all topologies and documenting necessary US-16 revisions. Original requirements remain unchanged. Traceability explicitly records the resulting installation incompatibilities.
1. Selection and boundaries
Select a modular monolith: one Health App HTTPS application process, one PostgreSQL database with module-owned schemas, and an installation utility that runs only during administration. Keep API/access, Profile, Observations, Analytics, Overview and Guidance as logical modules. They communicate through typed in-process interfaces, never internal HTTP or another module's repository. There is no broker, periodic calculation worker, identity server, response cache, or generated-assessment store.
The system provides the prototype backend. Patient and professional clients are external; a frontend, device integration and production clinical service are outside this assignment. Pre-created synthetic accounts and predefined many-to-many assignments remain. Account registration, recovery, MFA, refresh tokens, assignment administration, professional writes, medication advice and emergency access remain excluded.
This choice is conditional on a modest interactive workload and no independent feature deployment requirement after the user's clarification. No throughput, availability SLA or energy saving has been established. Consolidation sacrifices process isolation and independent scaling. Decisions compares feasible alternatives without assuming that existing services are inherently unsuitable.
Editable views: context, components, domain, classes, ownership, deployment, sequences.
2. Components and dependency rules
| Module | Responsibility and public internal interface | Data ownership |
|---|---|---|
| API/access | HTTPS endpoints; credential verification/token validation; normalized identity; actual-owner and assignment policies; response mapping. AccessPolicy.authorize(identity, operation, actualPatient) |
External account/assignment configuration and persistent token-protection keys; no health tables |
| Profile | Create initial profile and account association atomically; find by account/ID; update permitted profile information. ProfileQueries, ProfileCommands |
profile.patient, including account association |
| Observations | Record, retrieve, latest, inclusive selected history, partial correction and deletion; context lifecycle and validation. ObservationQueries, ObservationCommands |
observations.observation including its owned context |
| Analytics | On-demand numerical insights and three separate metric trends; context evidence, reference applicability and explanatory limitations. AnalyticsQueries, SummaryPolicy, TrendPolicy, ClinicalPolicy |
Transient derived values only; versioned non-patient reference content supplied by Guidance |
| Overview | Compose profile, latest overall observation and selected-period insight; preserve distinct bases and absence reasons. OverviewQueries |
Transient overview only |
| Guidance | Public ordered measurement instructions; reviewed applicability, source/date and unavailable states; reference catalog for clinical interpretation | Versioned reviewed guidance/reference bundle, no patient information |
| Infrastructure | Transaction/read-snapshot coordinator, module-specific persistence adapters, secret/key loading, error/logging boundary | Connection pool and lifecycle; never decides patient access or clinical meaning |
| Installation utility | Dependency detection, configuration, secrets/certificates, database/schema migration, systemd registration, verification | Protected administrative installation material; no continuously running service |
API/access invokes module facades. AccessPolicy uses ProfileQueries to resolve patient-account association and ObservationQueries to resolve actual observation owner. Observations uses ProfileQueries for existence. Analytics uses ObservationQueries for one selected series and Guidance's reference catalog. Overview invokes ProfileQueries, ObservationQueries and AnalyticsQueries within one read snapshot. Modules cannot call back into API routing. This dependency graph is acyclic; access checks are the caller's responsibility, and every externally reachable operation must pass the API/access boundary. Internal query facades accept a trusted, request-scoped authorized patient context issued by AccessPolicy, except the narrowly scoped owner-resolution/profile-association operations used by that policy itself. These lookup operations never directly produce an external response.
Do not share mutable domain objects across modules. Internal read models are immutable values; contracts carry patient ID, period, selections, counts and provenance where relevant. A common transport contract vocabulary does not grant persistence access. Module domain entities and repositories remain private. Transaction coordination is infrastructure shared by participating adapters, not permission for Analytics or Overview to run SQL against health schemas.
3. Domain and invariants
An Account has a stable account ID, credential hash and trusted Patient or HealthcareProfessional role. A Patient account has zero profiles before creation and exactly one afterwards. A PatientProfile contains generated UUID, account ID, required name and birth date, optional contact information, original creation and update instants. Its account association is immutable. Predefined Assignment associates one professional account with one patient ID; professionals and patients may each have many assignments. Assignments can refer to currently missing patient information and confer no writes.
A BloodPressureObservation belongs to exactly one patient and has UUID, measurement instant, immutable original recording instant, current systolic/diastolic values in mmHg, pulse in beats/minute, original context text, note and one owned MeasurementContext. The required numerical values are positive; no new clinical plausibility ceiling is imposed. Context has no independent identity or lifecycle. Its independent categories are Setting {Home, Clinic, Other, Unknown} and Activity {AtRest, DuringActivity, AfterActivity, Unknown}; optional details are rest duration with unit, body position, measured arm, device, cuff and circumstances. Missing details remain unknown. Partial context, after-activity measurements and historical free text remain valid. Categories never arise by inference from text or similar readings. Conflicting category/text evidence is preserved and exposed in interpretation.
Period is two inclusive measurement instants; equal bounds are valid, reversed bounds invalid. Offset-bearing times normalize to UTC; offset-free input denotes UTC independent of machine timezone. Preserve this existing documented interpretation. Wire examples may omit the offset, but consumers must use this rule. Birth date is a calendar date, not an instant.
ContextSelection has optional setting and activity predicates. Omission means unrestricted; explicit Unknown matches unknown only; supplied dimensions combine with AND. Unsupported categories are rejected. The same selection semantics apply to history, insights, trends and the overview's insight.
HealthInsight, TrendAssessment and HealthOverview are request-derived values without persisted identifiers. A trend owns exactly three MetricAssessments, one per measurement, and ComparabilityEvidence. Each metric records unit, descriptive levels, available direction/variation, explicit unavailable reasons, applicable reference and interpretation/hint. ClinicalReference includes scope, applicability prerequisites, operators/values, source URL and review date; it is distinct from an individual treatment target. MeasurementGuidance has ordered instructions, applicability, sources and review date; it never certifies compliance or changes an observation.
4. Public contracts and access
Retain the observable REST/JSON routes and semantics documented in Docs/AsBuiltArchitecture/software-architecture.md §4 as a compatibility target, without inspecting source. Authentication, field validation and error/absence behaviour remain as specified by the functional stories. No internal service-key endpoints are exposed. /by-account is an internal interface only.
| Endpoint | Contract / result |
|---|---|
POST /api/authentication/login |
accountId/password → time-limited bearer identity/role; generic invalid-credential rejection |
GET /api/measurement-guidance |
optional setting/activity → ordered sourced guidance or explained unavailability; public |
GET /api/professionals/me/patients |
own predefined assignment IDs, including empty list; professional only |
POST /api/patients |
name/dateOfBirth/contactInfo → generated profile; identity derives solely from authenticated Patient account |
GET /api/patients/me, GET /api/patients/{patientId} |
associated/authorized profile or absent |
PUT /api/patients/{patientId} |
required name, optional contactInfo; preserve ID, account, birth date and original creation time |
POST /api/patients/{patientId}/observations |
timestamp, three positive measured values, optional context/text/note → assigned ID and retrievable observation |
GET /api/observations/{observationId} |
current observation including saved/unknown context after actual-owner authorization |
PUT /api/observations/{observationId} |
all three positive numerical values; preserve other fields |
PATCH /api/observations/{observationId} |
partial numeric/context/text/note correction; omitted ≠ cleared; invalid request changes nothing |
DELETE /api/observations/{observationId} |
delete observation and owned context; preserve all other observations |
GET /api/patients/{patientId}/observations/latest |
latest overall with its own context; none explicitly absent |
GET /api/patients/{patientId}/observations |
from/to and optional selection → full ascending history; empty array and applied-selection metadata |
GET /api/patients/{patientId}/insights |
from/to and selection → means/extrema/count/context explanation or insufficient-data result |
GET /api/patients/{patientId}/trends |
same selection → three metric results with supported descriptions and explicitly unavailable parts |
GET /api/patients/{patientId}/overview |
profile, nullable latest overall, nullable insight selected by period/context; no trend |
Use the existing field vocabulary (measurementContext, setting, activityCondition, preparation fields, context, note, from, to) and enum tokens above. History carries applied selections in the documented X-Measurement-Setting and X-Activity-Condition headers; insight/trend/overview carry their basis in response values. Preserve existing response field names documented by the input class diagrams when implementing adapters; conceptual types here are not a rename mandate.
PATCH omits untouched values. Explicit null clears optional details/text; clearing a category makes Unknown. Null entire structured context clears its structured details, preserving legacy text and numerical values. Required numerical fields cannot be cleared. Reject unsupported fields/categories and invalid values before atomic application. No observation patient reassignment is supported. All ID-based actions establish the actual persisted owner; a caller-supplied patient ID cannot override it.
5. Interactions and consistency
Login validates credentials with an established framework password-hashing facility and issues a framework-protected opaque bearer ticket. Choose a configurable 30-minute default lifetime as a design parameter, with standard expiry validation and no custom cryptography. Ticket scope is this application, contains stable account/role and issue/expiry information, and contains neither health data nor assignments/ownership. Persist compatible token-protection keys through restart. No refresh mechanism is added. Credential verification occurs at login; token validation and access policy run for every protected request. Provider replacement maps validated identity to the same stable application account and role; no automatic insecure fallback.
Creation validates name/birth date and writes profile plus account ID in one database transaction/record, with a unique non-null account constraint. A uniqueness race returns existing-profile conflict. Success follows durable commit only. Interrupted uncommitted creation rolls back; retry creates one accessible profile. Lost success response leads to existing-profile result on retry and recovery through /patients/me. No distributed saga or separate association write is needed.
A protected patient-ID request resolves account association or professional assignment before retrieval. An observation-ID request first resolves actual owner internally, then checks association/assignment, then accesses that owner-scoped observation. The lookup is never serialized externally before authorization. For mutation use one transaction with row locking: recheck owner, validate full proposed change, apply only specified fields, commit. Concurrent disjoint patches preserve one another; concurrent same-field valid updates serialize with the last committed update taking effect. Original recording time and patient association never change. Successful deletion removes the row/context; subsequent requests beginning after commit cannot include it.
Record validates input and confirms an existing authorized profile inside the write transaction. Profile deletion is outside scope. Latest sorts descending by (measurement instant, original recording instant, UUID bytes); choose greatest lexicographic unsigned 16-byte UUID as the final documented tie rule. History sorts ascending measurement instant then ascending UUID bytes; filtering occurs before calculation. UUID ordering has no trend meaning.
For insights/trends, capture current authorized selected observations in one repeatable-read snapshot. For overview, access-policy ownership resolution, profile, latest and selected series all participate in the same read snapshot; latest remains global for the patient, unrestricted by insight period/context. Retrieve selected series once, derive insight in memory, and preserve mixed/unknown explanations. For observation-ID reads authorize and retrieve within a snapshot. Configuration/assignment snapshot is fixed for the request. End the database transaction once required immutable source values have been captured, before numerical evaluation and JSON transmission, to avoid holding snapshots during client transfer.
Freshness means each new request sees commits completed before its snapshot starts; a concurrent later commit is visible on the next request. No claim of observing writes after a request's snapshot is made. There is no asynchronous replication lag or cached derived result. Snapshot composition is a deliberate improvement over baseline interleaved reads, not a new user requirement.
6. Calculation and clinical-content contracts
Numerical insight uses all eligible raw observations: arithmetic means for the three metrics; systolic/diastolic minima and maxima; final two-decimal half-up means with no intermediate rounding. One observation suffices, zero reports no insight. Unknown context never prevents numerical calculation, but never matches a known selection. Include count, patient, normalized period, selections and explanation of differing/unknown conditions. The halfway example gives 120.13 for seven 120s and one 121; three values 120,120,121 give 120.33.
TrendPolicy is separate from ClinicalPolicy so a missing clinical rule does not suppress supported numerical descriptions. The architectural method contract is deterministic and versioned: levels/extrema and observed variation retain every raw value; temporal analysis groups equal measurement instants reproducibly and considers the full ordered series, including intermediate changes and reversals. At least two distinct instants are required for temporal direction. An overall tendency cannot conceal reversal or excursions. Exactly one or equal-time-only data can still support descriptive levels/variation but no invented direction. Mathematical formula choice is an implementation decision, not an energy optimization or an inherited baseline constraint; its method documentation must state timestamp weighting, sufficiency, assumptions and reproducible examples before acceptance. No recording/retrieval ordering or final UUID tie determines trend direction.
ComparabilityEvidence records supported similarities, known differences, missing relevant details and category/narrative conflicts. Matching broad categories or values never proves identical preparation. ClinicalPolicy evaluates each clinical claim's prerequisites independently: missing irrelevant optional details do not suppress supported reference comparison; unknown setting/rest or conflicting evidence blocks claims depending on those facts. It must disclose unresolved narrative meaning rather than treating failure to recognize a phrase as evidence of consistency. Recognized contradictory descriptions, including the US-11 exercise example, are explicitly identified. General narrative understanding is an implementation/validation risk, not silently promised by a finite keyword detector.
Use a versioned, reviewed Danish/European content bundle, not live clinical-site calls per request. Each clinical rule records metric, context prerequisites, reference values/operators, source, review date and allowed inference. All potentially favourable/concerning development statements require an applicable documented rule; falling values, limited variation or similar endpoints alone never establish health. When unsupported, return CannotInterpret with reasons while retaining numerical information. Three measurements can differ in interpretation and are never forced into one good/bad label. Do not diagnose, invent clinical stability thresholds, advise medication changes or equate reference thresholds with personal targets.
Guidance is ordered and sourced, distinguishing home and clinic applicability. Its content contract covers preparation/rest, validated equipment/cuff, posture/arm position, stillness, repeat readings/timing, recording actual conditions and device-reported pulse limitations. It distinguishes a planned home-monitoring protocol from a single recorded observation. Numeric guidance must derive from the identified source. Unknown setting is labelled without saving a default. After-activity readings remain recordable and are never relabelled as resting. Viewing or declining guidance neither writes nor blocks valid submissions. Unavailable verified content yields an explanation, never authoritative invented instructions. This architecture does not supply new medical thresholds; content review remains an implementation acceptance dependency.
7. Storage, ownership and resource behaviour
Use one PostgreSQL database, profile and observations schemas and one migration version per module. Profile owns its patient row; Observations owns its observation row with flattened context details. UUID patient reference is enforced by a database foreign key with deletion restricted; no cross-module SQL joins are used by application modules. This physical integration intentionally replaces separate-database ownership and requires the US-16 revision.
Database constraints enforce identifiers, unique account association, positive values, valid categories and required measurement/original recording times. Store instants with unambiguous UTC normalization; physical timestamp type may preserve legacy UTC-clock encoding if required for compatibility. Preserve IDs, original recording instants, values and text when importing baseline data; never infer missing context. Reject or quarantine ambiguous orphan references during a future migration rather than attaching them to another patient. No migration is performed in this assignment.
One runtime DB role has only necessary read/write rights in both health schemas, no administrative or DDL rights. Separate schema migration owners are used only during installation/upgrades. Schema ownership is a maintainability boundary, not runtime security isolation: an application process compromise can reach both schemas. Repositories enforce module ownership by dependency structure. Credentials/hashes/assignments and token keys are protected external files; they do not require an extra account or session database. Guidance/reference content is immutable versioned application content, with review metadata.
Use a bounded connection pool shared by request transactions; pool capacity and concurrent-request limits are deployment parameters, not an invented workload number. Index patient plus measurement instant/original recording/ID for latest/history. Evaluate additional context indexes only when observed workload justifies their storage/write footprint. No polling, precomputation, materialized clinical views or response cache is selected. Cache only immutable public content through versioned metadata; never patient data, authorization decisions or assignments across requests. Request-local reuse of an already captured value is permitted within its snapshot.
History remains complete: no silent truncation, undocumented default period or pagination change. Capture all matching immutable data required by the request; bounded admission and cancellation protect resources. Very large histories are a known memory/CPU risk; future pagination must preserve full selection and require an explicit contract decision. CPU-heavy assessment admission must not exhaust authentication or public-guidance handling; separate logical concurrency budgets are allowed without extra worker processes.
8. Security and failures
The HTTPS API edge is the sole public trust boundary. There are no externally reachable internal module endpoints or gateway-service credentials. Untrusted headers never establish account, role or authorization. Policies use normalized identity and actual patient ownership. Public exceptions are only login and general guidance. Professional reads require predefined assignment; professional writes/profile creation and patient-only use of professional operations are rejected before mutation. Missing/invalid/expired authentication returns no protected data. A profile-less Patient can log in and create its initial profile, but receives unavailable information for other own-data requests without acquiring another patient's identity.
Choose established ASP.NET Core authentication/policy integration as a retained design choice for prototype suitability, without prescribing package versions. TLS certificate/key material and token keys are externally provisioned, protected by service-account/root permissions and excluded from logs/repository. Pin the intended application trust scope and reject forged tickets. For remote DB placement require verified encrypted DB transport and certificate-name validation; local DB connections use OS/network access restrictions and dedicated credentials. Only the app's configured DB endpoint is reachable from its account; clients cannot reach it.
| Condition | Public outcome / integrity rule |
|---|---|
| Invalid login; missing/invalid/expired ticket | 401, generic credential failure; no protected result/write |
| Professional write or forbidden role operation | 403; no mutation |
| Other patient's resource/unassigned patient | Uniform unavailable 404 without existence/context disclosure |
| Authorized missing profile/observation/latest | 404 absent information; no fabricated entity |
| Invalid category/value/body/reversed period | 400 with safe validation explanation; atomic no-change |
| Duplicate initial profile | 409 existing-profile result; immutable association |
| Empty history / no insight / insufficient trend | 200 empty history; 404 no insight; 200 trend with explicit unavailable parts |
| Empty overview insight/latest | 200 profile plus nullable parts and explained absence; missing profile 404 |
| DB unavailable, transaction failure, required content invalid | Fail closed; 503 dependency unavailable or 500 unexpected failure; no success before durable write; no false empty-data result |
| Deadline reached before response / cancelled request | 504 where a response remains possible; abort otherwise; rollback uncommitted work |
| Unsupported verified guidance | Explained unavailability; no unverified clinical instructions |
| Overload | 503 with retry indication; do not silently drop selected observations |
No automatic mutation retry follows an ambiguous commit: clients may recover profile creation as above; observation-create retries can duplicate a reading because no requirement promises idempotency. Read failures may be retried by the caller; there is no background retry storm. Cancellation propagates through transaction and module work. Log correlation ID, operation and sanitized failure; omit credentials/tokens/health payloads and avoid logging identifying route values. Patient responses and login use no-store; public content can use versioned caching. Failures after response start cannot become a replacement error body.
9. Deployment and installation
Default: one supported Linux host with systemd, one dedicated Health App application identity/process and one PostgreSQL server. DB may be local or on a separately configured host; the same application executable and public API work in either layout. Application modules are neither independently installed nor separately addressable. Containers, Kubernetes, autoscaling and extra gateway/proxy processes are unnecessary for the default. Separate DB placement can increase network and idle cost but may improve database administration or resource sharing.
The administrative installer preflights host support and settings; detects/installs runtime and required PostgreSQL dependency when local persistence is selected; provisions the database/schemas, least-privilege roles and generated credentials; generates or accepts HTTPS certificate/key material and relevant trust; writes protected configuration; runs versioned migrations; registers/enables/starts one systemd application unit; verifies PID, HTTPS, configured database and representative synthetic profile/observation/overview flows. It explicitly demonstrates stop/restart without stopping PostgreSQL. A remote DB choice must not unnecessarily install a local server. Normal installation requires no manual database, secret or certificate creation. Distributed application microservice installation is not offered.
Configuration includes listener, HTTPS endpoint, DB host/credentials, keys, accounts, predefined assignments, token lifetime, content versions and concurrency/deadline limits. A generated prototype professional with no assignments is valid; an assigned workflow requires predefined fixture configuration, not a new management API. Prototype certificates can later be replaced by trusted supplied material. Client trust must be established separately; do not disable certificate validation.
Report failed stage precisely and retain protected diagnostics; do not claim transactional installation rollback. Preflight refuses accidental overwrite. A future upgrade plan must back up health data and keys, apply compatible schema changes with the app stopped or explicitly coordinated, and validate integrity before switching. Backup retention, recovery objectives and HA are unresolved production concerns. No always-on provisioning daemon is added. Readiness distinguishes usable DB/content/key configuration from process liveness without publishing patient data. One process outage stops all modules, but public guidance can still work during DB-only outages.
10. Design limits and acceptance
Energy hypotheses explains anticipated mechanisms and counter-effects; CPU, memory and latency are not energy measurements. Consolidation alone does not guarantee lower host energy, particularly on an always-on underutilized machine. Independent scaling becomes attractive if analytics load dominates or isolation becomes mandatory; module interfaces support an intentional later extraction, not a promised zero-cost switch.
Architecture verification covers source requirement/criterion mapping, model/diagram agreement, ownership, security and error paths. It does not execute the application or establish clinical validity. Implementation acceptance must document reproducible mathematical methods, review clinical rule applicability and narrative-conflict handling, exercise access and concurrency scenarios, and validate the selected native deployment. The proposed architecture is complete; these are future implementation obligations, not missing architecture artefacts.