Architecture is proposed and there are also alternative architectures proposed

This commit is contained in:
Steffen committed 2026-10-14 00:38:08 +02:00
1 parent ccf9041183
commit 3426236c6c
24 files changed
+2516

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
# Energy-conscious architectural suggestions
2026-10-13. Separate exploratory supplement requested by the user after reviewing the modular-monolith proposal. **Keeping microservices is a valid option.** Lower energy use does not require consolidating all application functionality into one process.
These suggestions do not replace the selected [architecture proposal](../ArchitectureProposal/README.md), alter original requirements, or authorize implementation. The user's request explicitly authorizes this separate folder. Application source was not inspected or changed.
| Document | Purpose |
| --- | --- |
| [Suggestions and alternatives](energy-with-independent-services.md) | Nine architectural options, mechanisms, assumptions, counter-effects and a suggested sequence of decisions |
| [Energy recommendation](energy-recommendation.md) | Leading candidate, expected ranking, rationale, assumptions and conditions that could reverse the recommendation |
| [Behaviour and compatibility](requirements-and-compatibility.md) | Requirement safeguards, original US-16 compatibility, freshness/security constraints and unresolved questions |
| [Editable service topologies](diagrams/service-topology-options.drawio) | Five-service deployment with preserved routing; optional direct internal routing with explicit trust boundaries |
| [Validation](validation.md) | Documentation, diagram, links and preservation checks; evidence limits |
The most conservative candidate retains the existing five independent services and gateway-routed communication, colocates services where suitable, uses one PostgreSQL server with **two separately owned databases/credentials**, and improves architectural resource management and request reuse. A more invasive candidate retains five processes but changes internal routing; it requires explicit communication/trust-design revisions. Conditional caching and selective scaling have workload-dependent trade-offs.
The earlier monolith selection was based on architectural simplicity and plausible overhead reduction under a modest-workload assumption. It did **not** establish that a monolith consumes the least energy. These suggestions explain how independent services could address the same overheads and when their isolation or selective scaling could be advantageous.
No energy saving is measured or quantified. No benchmark procedure, application code, deployment configuration, compiler tuning or replacement mathematical algorithm is supplied. Authentication, current data, context, clinical interpretation and complete results remain binding.
@@ -0,0 +1,133 @@
<?xml version='1.0' encoding='utf-8'?>
<mxfile host="app.diagrams.net" type="device" compressed="false">
<diagram id="A" name="A — five independent processes, colocated deployment">
<mxGraphModel grid="1" gridSize="10" page="1" pageWidth="1700" pageHeight="1250">
<root>
<mxCell id="0" />
<mxCell id="1" parent="0" />
<mxCell id="title" value="A — preserve processes, routing and separately owned databases" style="text;html=0;fontSize=25;align=left;" vertex="1" parent="1">
<mxGeometry as="geometry" x="40" y="20" width="1600" height="60" />
</mxCell>
<mxCell id="client" value="External client&#10;HTTPS login / authorized APIs" style="rounded=0;whiteSpace=wrap;html=0;fontSize=15;fillColor=#e8f0fe;strokeColor=#355070;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="630" y="100" width="390" height="100" />
</mxCell>
<mxCell id="host" value="One suitably sized Linux host&#10;Independent systemd units/configuration; same remote-capable HTTPS interfaces" style="rounded=0;whiteSpace=wrap;html=0;fontSize=14;fillColor=#fff6df;strokeColor=#b28725;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="40" y="240" width="1600" height="100" />
</mxCell>
<mxCell id="gateway" value="Gateway process&#10;Authentication + authorization&#10;Original internal routing retained" style="rounded=0;whiteSpace=wrap;html=0;fontSize=15;fillColor=#e8f0fe;strokeColor=#355070;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="630" y="390" width="390" height="145" />
</mxCell>
<mxCell id="profile" value="Profile process&#10;Own Profile DB credentials&#10;Atomic profile/account association" style="rounded=0;whiteSpace=wrap;html=0;fontSize=15;fillColor=#e8f0fe;strokeColor=#355070;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="40" y="600" width="370" height="155" />
</mxCell>
<mxCell id="obs" value="Observation process&#10;Own Observation DB credentials&#10;Context / current source data" style="rounded=0;whiteSpace=wrap;html=0;fontSize=15;fillColor=#e8f0fe;strokeColor=#355070;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="450" y="600" width="370" height="155" />
</mxCell>
<mxCell id="insights" value="Insights process&#10;Current numerical insights/trends&#10;No database or stored results" style="rounded=0;whiteSpace=wrap;html=0;fontSize=15;fillColor=#e8f0fe;strokeColor=#355070;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="860" y="600" width="370" height="155" />
</mxCell>
<mxCell id="overview" value="Overview process&#10;Profile + latest + selected insight&#10;No database or stored results" style="rounded=0;whiteSpace=wrap;html=0;fontSize=15;fillColor=#e8f0fe;strokeColor=#355070;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="1270" y="600" width="370" height="155" />
</mxCell>
<mxCell id="pg" value="One PostgreSQL server&#10;Two independent databases and identities&#10;No shared clinical repository" style="shape=cylinder3;whiteSpace=wrap;html=0;fontSize=14;fillColor=#f1e8fa;strokeColor=#76558d;spacing=14;" vertex="1" parent="1">
<mxGeometry as="geometry" x="40" y="830" width="580" height="140" />
</mxCell>
<mxCell id="rules" value="Placement changes only: all five processes remain independent.&#10;Gateway-routed calls and separate DB ownership remain.&#10;Colocation may release physical capacity only if that capacity was actually duplicated.&#10;Bounded pools and safe request-local GET reuse are optional resource/call refinements." style="rounded=0;whiteSpace=wrap;html=0;fontSize=14;fillColor=#fff6df;strokeColor=#b28725;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="700" y="830" width="940" height="140" />
</mxCell>
<mxCell id="e0" value="HTTPS" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="client" target="gateway">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="e1" value="HTTPS / service credentials" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="gateway" target="profile">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="e2" value="HTTPS / service credentials" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="gateway" target="obs">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="e3" value="HTTPS / service credentials" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="gateway" target="insights">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="e4" value="HTTPS / service credentials" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="gateway" target="overview">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="e5" value="Profile DB only" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="profile" target="pg">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="e6" value="Observation DB only" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="obs" target="pg">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="foot" value="Internal callbacks still use Gateway: Observation → Profile; Insights → Observation; Overview → Profile/latest/insight. These callback routes are retained, not direct arrows between application services. One PostgreSQL server is already permitted by US-16. Five VMs sharing a host may have little additional physical consolidation benefit." style="rounded=0;whiteSpace=wrap;html=0;fontSize=14;fillColor=#fff6df;strokeColor=#b28725;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="40" y="1040" width="1600" height="130" />
</mxCell>
</root>
</mxGraphModel>
</diagram>
<diagram id="B" name="B — five independent processes, optional direct private calls">
<mxGraphModel grid="1" gridSize="10" page="1" pageWidth="1700" pageHeight="1250">
<root>
<mxCell id="0" />
<mxCell id="1" parent="0" />
<mxCell id="title" value="B — retain service processes; revise internal routing and trust" style="text;html=0;fontSize=25;align=left;" vertex="1" parent="1">
<mxGeometry as="geometry" x="40" y="20" width="1600" height="60" />
</mxCell>
<mxCell id="client" value="External client&#10;Only public Gateway is reachable" style="rounded=0;whiteSpace=wrap;html=0;fontSize=15;fillColor=#e8f0fe;strokeColor=#355070;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="680" y="110" width="340" height="100" />
</mxCell>
<mxCell id="gateway" value="Gateway process&#10;Login / current authorization&#10;Issue request-scoped trusted delegation&#10;Never trust client identity headers" style="rounded=0;whiteSpace=wrap;html=0;fontSize=15;fillColor=#e8f0fe;strokeColor=#355070;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="680" y="285" width="340" height="160" />
</mxCell>
<mxCell id="profile" value="Profile process&#10;Private authenticated HTTPS API&#10;Own Profile DB" style="rounded=0;whiteSpace=wrap;html=0;fontSize=15;fillColor=#e8f0fe;strokeColor=#355070;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="50" y="570" width="340" height="155" />
</mxCell>
<mxCell id="obs" value="Observation process&#10;Private authenticated HTTPS API&#10;Own Observation DB&#10;Current period/context selection" style="rounded=0;whiteSpace=wrap;html=0;fontSize=15;fillColor=#e8f0fe;strokeColor=#355070;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="460" y="570" width="340" height="155" />
</mxCell>
<mxCell id="insights" value="Insights process&#10;Private authenticated HTTPS API&#10;Current calculation / no result DB" style="rounded=0;whiteSpace=wrap;html=0;fontSize=15;fillColor=#e8f0fe;strokeColor=#355070;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="870" y="570" width="340" height="155" />
</mxCell>
<mxCell id="overview" value="Overview process&#10;Private authenticated HTTPS API&#10;Compose available parts / no DB" style="rounded=0;whiteSpace=wrap;html=0;fontSize=15;fillColor=#e8f0fe;strokeColor=#355070;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="1280" y="570" width="340" height="155" />
</mxCell>
<mxCell id="e0" value="HTTPS client request" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="client" target="gateway">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="public0" value="Authorized dispatch" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="gateway" target="profile">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="public1" value="Authorized dispatch" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="gateway" target="obs">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="public2" value="Authorized dispatch" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="gateway" target="insights">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="public3" value="Authorized dispatch" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="gateway" target="overview">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="dep1" value="Private patient-existence read" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="obs" target="profile">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="dep2" value="Private selected-series read" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="insights" target="obs">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="dep3" value="Private profile read" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="overview" target="profile">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="dep4" value="Private latest overall read" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="overview" target="obs">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="dep5" value="Private selected insight" style="edgeStyle=orthogonalEdgeStyle;html=0;endArrow=open;fontSize=13;labelBackgroundColor=#ffffff;" edge="1" parent="1" source="overview" target="insights">
<mxGeometry as="geometry" relative="1" />
</mxCell>
<mxCell id="security" value="Required trust boundary&#10;Verified HTTPS + generated service identity/credential&#10;Operation allowlist + Gateway-issued request-scoped patient/action/audience delegation&#10;Receiver validates scope and actual resource owner; no client bypass&#10;No custom cryptography; no new service mesh required" style="rounded=0;whiteSpace=wrap;html=0;fontSize=14;fillColor=#fff6df;strokeColor=#b28725;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="40" y="840" width="790" height="180" />
</mxCell>
<mxCell id="compat" value="Design status&#10;All five processes and two DB owners remain independent.&#10;Private endpoints support colocated or separate-host placement.&#10;Original gateway-routed communication changes; record AC-16-H/trust revisions.&#10;Additional authentication/delegation work can offset the saved hop." style="rounded=0;whiteSpace=wrap;html=0;fontSize=14;fillColor=#fff6df;strokeColor=#b28725;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="890" y="840" width="750" height="180" />
</mxCell>
<mxCell id="foot" value="This is an exploratory topology, not an approved implementation/trust specification or a measured energy improvement. Scope authentication remains per current external request. Independent service reads do not automatically provide a cross-service snapshot. No result cache, broker, cross-service SQL access or extra database is implied." style="rounded=0;whiteSpace=wrap;html=0;fontSize=14;fillColor=#fff6df;strokeColor=#b28725;spacing=12;" vertex="1" parent="1">
<mxGeometry as="geometry" x="40" y="1070" width="1600" height="130" />
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>
@@ -0,0 +1,62 @@
# Recommendation: the most likely lowest-energy Health App architecture
2026-10-13. This recommendation compares the modular-monolith proposal with the service-preserving suggestions. It is a reasoned prediction for the documented prototype, **not an established energy result**.
## Recommendation and scope
My leading candidate is an **efficient modular monolith on one suitably sized Linux host with PostgreSQL**. Combine the topology with bounded connection pooling, request-local reuse of current source data and on-demand calculations. Retain explicit module responsibilities, private persistence adapters, secure authorization and the complete required results.
The nine suggestions in this folder are mostly complementary architectural changes, rather than nine mutually exclusive complete architectures. Several apply to both a monolith and independent services. The meaningful comparison is therefore between complete combinations under equivalent behaviour, data, workload and hosting assumptions.
This recommendation follows the previously authorized freedom to reconsider topology. It requires the [US-16 revisions](../ArchitectureProposal/us16-revision.md) already documented in the proposal. It does not claim to satisfy original independent-feature installation requirements or authorize implementation. The main [architecture specification](../ArchitectureProposal/software-architecture.md) remains authoritative.
## Assumptions behind the prediction
Assume modest, intermittent interactive use with synthetic patient data; profile and observation operations plus current insights/trends/overviews; no demonstrated need for independent feature scaling, separate deployment teams or mandatory process isolation. Assume one host can accommodate the application and database with appropriate operating headroom. Workload volume, history size, query repetition, hardware power response and physical host sharing remain unknown.
The predicted advantage concerns total operational energy for equivalent useful work over equivalent periods, including idle operation. Fewer requests, incomplete results, stale assessments or weaker access protection cannot count as improvements. CPU utilization, memory, latency and throughput alone do not establish lower energy consumption.
## Why this is the leading candidate
| Architectural characteristic | Expected energy mechanism | Qualification |
| --- | --- | --- |
| One application runtime | Avoids duplicating application runtime, listener and housekeeping resources across five feature processes | Runtime footprint does not translate directly into a known energy saving; fixed host power may dominate |
| In-process module calls | Removes internal HTTP handling, serialization and TLS work, including gateway callback detours | External HTTPS and database communication remain; efficient colocated services may have a small marginal communication cost |
| Direct request composition through module interfaces | Captures current source values and reuses them within an authorized request, avoiding redundant retrieval where possible | This benefit can also be designed into microservices; do not attribute every avoided read exclusively to consolidation |
| Bounded shared connection management | Reuses database sessions and avoids duplicating unbounded per-service resource budgets | Idle pooled connections and contention still cost resources; efficiently bounded service pools may achieve similar benefits |
| On-demand calculations without an added broker/cache server/worker | Avoids extra resident components and unsolicited background work | The documented baseline already calculates on demand without these components, so this is a retained advantage over more elaborate variants, not a new saving against that baseline |
| One appropriately sized physical deployment | May avoid powering separate underused application/database hosts | If all five services already share the same host/PostgreSQL server, physical consolidation supplies no additional advantage |
The strongest rationale is that this combination removes internal communication and duplicated application-runtime overhead without adding coordination machinery for a workload that does not yet justify it. Simpler deployment and transactions also support correctness and maintainability, although those benefits are not energy measurements.
Physical hosting deserves separate attention. Static power and energy proportionality mean software work and host energy need not move in direct proportion. The [Green Software Foundation's energy-efficiency guidance](https://learn.greensoftware.foundation/energy-efficiency/) describes those mechanisms. Applying them to this Health App is an inference; the guidance does not demonstrate that this application's monolith beats its microservices.
## Expected ranking under these assumptions
| Expected position | Complete candidate | Reason and uncertainty |
| --- | --- | --- |
| 1 | Efficient modular monolith; one app host with local PostgreSQL; bounded pooling, request reuse, current on-demand results | Removes internal application-network calls and multiple runtime footprints. Leading candidate with limited confidence |
| 2 | Efficient colocated independent services; one suitable host and PostgreSQL server, two owned databases; bounded pools and safe duplicate-read removal | Retains process isolation and independent installation while addressing physical overhead and repeated work. Could be close to, or outperform, the monolith depending on resource behaviour |
| 3 | Independent services distributed across several dedicated, continuously powered hosts | Likely higher idle infrastructure cost at modest demand. This prediction does not apply automatically when those services instead share existing physical capacity or a more efficient hosting platform |
This is an ordinal prediction, not a quantified ranking. It does not prescribe adding idle hosts to the service alternative, overprovisioning either candidate or comparing different security/result guarantees. Equal software behaviour on different hardware can also change the ordering.
## Conditions that could change the recommendation
**Heavy, uneven analytics demand:** Independent services can scale only Insights while leaving lightly used features small. A monolith may replicate the whole application to handle that load. If the avoided replication exceeds service communication and coordination overhead, service separation could use less energy.
**Frequent repeated expensive queries:** Source-revision-validated result reuse could avoid repeated data transfer and calculation. It can apply to either architecture. A cached service design could outperform an uncached monolith, but that would not prove that service boundaries caused the difference. Cache memory, source revision checks, invalidation correctness and query repetition determine whether the mechanism is worthwhile.
**Different physical hosting:** Five services on an already shared host may have little avoidable infrastructure overhead. Conversely, a dedicated oversized monolith host can be wasteful. Remote shared database capacity may be preferable to another mostly idle local server. Physical host count and suitability matter more than deployment labels alone.
**Resource contention or isolation needs:** A shared process may experience contention or require excess headroom that isolated services avoid. Mandatory independent deployment/fault isolation can also make services the more suitable architecture even if a small energy penalty remains. The recommendation must continue to respect security, correctness and operational requirements.
**Acceptable intermittent activation:** Hosting that can remove unused capacity may favour independently activated services for some workloads. Cold starts, dependency activation, availability and platform overhead require an explicit design decision; no scale-to-zero benefit is assumed here.
## Practical recommendation
For the current clarified architecture assignment, retain the efficient modular monolith as the **most plausible lowest-energy candidate**, while recording the efficient colocated five-service design as the strongest alternative. Confidence in the qualitative mechanisms is greater than confidence in the final energy ranking, because workload and hardware evidence are absent.
If preserving original service installation/isolation is important, choose [Candidate A from the suggestions](energy-with-independent-services.md): it addresses several energy mechanisms without a runtime merger and requires fewer structural changes than direct-call delegation or distributed caching. Do not introduce brokers, cache servers, orchestration platforms or additional replicas solely on the assumption that they will save energy.
No universal winner, numerical saving or energy measurement procedure is claimed. Current information supports a conditional recommendation; it does not establish actual consumption. Application code, original inputs and the architecture proposal remain unchanged by this document.
@@ -0,0 +1,115 @@
# Reducing energy use while retaining independent services
Yes: process consolidation is one architectural lever among several. Physical deployment, repeated work, communication paths, connection lifecycles, data movement and scaling can all influence energy use while service boundaries remain intact. The choices below are **Health App design hypotheses**, not evidence of savings or a new implementation specification.
The documented baseline has five independent processes, gateway-routed internal calls, two separately owned PostgreSQL databases, on-demand Insights and Overview without stored results, and pre-created account/assignment configuration. Generated DB connections disable pooling, and observation-ID authorization reads the observation before the forwarded operation reads it again. These findings come from [as-built documentation](../Docs/AsBuiltArchitecture/software-architecture.md), especially §§2, 5, 7–9; application source was not opened. Runtime HTTP-client reuse already exists, so it is not assumed to be a missing feature.
## 1. Consolidate physical placement while keeping five processes
**Design:** Run Gateway, Profile, Observation, Insights and Overview as separate systemd services on one suitably sized host, or on fewer hosts than a fully distributed installation. Keep their configured HTTPS interfaces, independent management and service identities. Use the same binaries/interfaces for separate-machine deployments.
**Mechanism:** Fewer dedicated physical machines may remove avoidable idle server and network overhead while retaining deployment/process boundaries. Static power and energy proportionality make physical placement a different issue from application-process count. The [Green Software Foundation energy-efficiency guidance](https://learn.greensoftware.foundation/energy-efficiency/) explains this relationship; applying it to Health App is an architectural hypothesis.
**Assumptions/dependencies:** Services fit with operating headroom; physical consolidation actually reduces powered capacity or enables resource sharing. This is already allowed by original US-16; no monolith or shared process is needed.
**Counter-effects:** Five VMs may already share one physical machine, and moving them may remove no host. A permanently powered host may consume similar idle energy despite less software work. Resource contention, larger peaks and a shared host failure domain can reduce the benefit. Maximum utilization is not a design target when it harms responsiveness or correctness.
## 2. Share the PostgreSQL server, preserve database ownership
**Design:** One PostgreSQL server hosts a Profile database and an Observation database, each with its own credentials and restricted rights. Insights and Overview receive no database. Persistent services still access only their own data.
**Mechanism:** Potentially avoid duplicating database-server/background resource footprints or dedicated DB hosts without merging databases or ownership. Original [US-16 addendum](../Docs/Requirements/us16-addendum) explicitly allows this arrangement.
**Assumptions/dependencies:** The starting deployment actually uses multiple PostgreSQL servers or hosts, and their workloads can safely share capacity.
**Counter-effects:** If the baseline already uses one PostgreSQL instance, there is no new server-consolidation benefit. Shared maintenance/I/O and host failure affect both owners. Separate databases do not make the server a distributed-transaction or cross-service snapshot mechanism. Never justify direct cross-database reads as an energy shortcut.
## 3. Bound and reuse connections and concurrent work
**Design:** Give Profile and Observation bounded application-side connection pools, preserving separate DB identities; place an overall connection budget across services/replicas. Maintain reusable authenticated HTTPS connections for internal requests rather than provisioning a separate proxy or pooler by default. Bound admitted expensive analytics work independently from lightweight operations; propagate cancellation and deadlines.
**Mechanism:** Reusing database sessions may avoid repeated establishment/authentication work. A bounded budget limits unnecessary connection/process/resource growth and wasted work after callers cancel. PostgreSQL documents that its connection limit affects resource sizing, including shared memory. That supports the need for a resource budget, **not a claim of lower energy**. [PostgreSQL connection settings](https://www.postgresql.org/docs/current/runtime-config-connection.html).
**Assumptions/dependencies:** Repeated DB establishment or excessive concurrency is meaningful in the actual deployment; pooled sessions preserve transaction cleanup and separate credentials. The documented generated `Pooling=false` makes DB lifecycle management a concrete candidate. Existing HTTP-client reuse must be considered rather than counted as a new saving.
**Counter-effects:** Idle pooled connections consume resources; multiplying per-service pools by replicas can inflate the total. Too small a pool or overly strict admission increases waiting. An external pooler adds its own process and failure/configuration boundary; use only if that extra component has a justified role. These are architectural budgets/lifecycles, not prescribed tuning numbers or code-level optimizations.
## 4. Remove duplicate reads within an authorized operation
**Design:** For a specific observation GET, the Gateway already retrieves a protected observation to establish its actual owner. After successful authorization, it can return that same validated upstream representation rather than fetching the observation again. Buffer it privately until the policy decision; unauthorized callers never receive any part of it. Preserve response/context fields and safe error/absence semantics.
Keep the reuse limited to that request. A PATCH/DELETE still needs an owner-scoped, atomic mutation at Observation; reusing a GET body does not establish that a write succeeded. Current immutable patient association makes ownership stable, but deletion and correction can race with a read as in any defined read snapshot.
**Mechanism:** Avoid one upstream call, one DB read and duplicate serialization for the affected GET. This is request-local reuse, not cross-request caching of health data or authorization.
**Assumptions/dependencies:** The owner lookup returns the full required observation representation, as documented; it is compatible with the external representation. Gateway can preserve status/headers without exposing data before authorization.
**Counter-effects:** Buffering consumes memory and can require different response handling. A metadata-only owner endpoint can reduce payload for write authorization, but adding it changes an internal interface and does not remove the mutation's required DB work. Reusing Profile data across nested Overview callbacks would need explicit bounded request-context design; do not assume ordinary HTTP callbacks share request memory.
## 5. Reduce unnecessary data movement through purpose-specific contracts
**Design:** Keep period, patient and context selection at Observation, the source owner. Offer narrowly scoped internal read representations only where the consumer's complete functional needs are known. Index supported patient/time access paths at the owned datastore. Preserve full public history and context retrieval contracts.
For numerical insight, a compact internal response could contain current count, exact sums, BP extrema and **complete context evidence needed for its explanation**, all from one source snapshot. Insights still owns final rounding/result interpretation. This changes the responsibility for numerical aggregation and internal contracts; it must be recorded rather than disguised as a harmless transport change. For trends, retain all timestamps/readings and relevant context/narrative evidence needed by the full-period method; endpoint values or averages are insufficient.
**Mechanism:** Fewer unnecessary rows/fields/bytes may reduce DB reads, serialization, transfer and downstream materialization. Removing redundant work does not require removing process boundaries.
**Assumptions/dependencies:** Relevant histories/payloads are large enough, and the new contract reproduces every required result under equal data. Patient/time indexing is missing in the documented baseline; index usefulness remains workload dependent.
**Counter-effects:** Computation may simply move to the database; aggregate queries and indexes add CPU, writes, storage and maintenance. Extra internal contracts increase maintenance. Do not drop notes/conflicts, Unknown categories or preparation evidence. Do not silently cap history, substitute a selected-period latest for latest overall, or invent a new trend formula. Protocol replacement/compression is not presumed to save energy; retain existing HTTPS/JSON unless a separate justified contract decision is made.
## 6. Shorten internal routes without merging services
**Design:** Keep clients entering through Gateway. Let authenticated Overview call Profile, Observation and Insights directly on private HTTPS interfaces; let Insights read selected history directly from Observation and Observation verify patient existence with Profile. The same five independently runnable processes and separate DB owners remain.
**Mechanism:** Remove gateway forwarding on internal legs, potentially reducing extra routing, serialization/HTTP handling and Gateway load. For example, an insight's internal source path changes from `Insights → Gateway → Observation` to `Insights → Observation`.
**Assumptions/dependencies:** The extra hop is significant. Provide explicit source-side service authentication, operation allowlists and request-scoped authorization delegation. This revises the existing gateway-routed communication design and original AC-16-H interpretation; user topology freedom permits exploring it, but this document does not activate it.
**Security boundary:** Each source verifies the receiving endpoint's TLS identity and the calling service's generated credentials or equivalent established service-authentication mechanism. A trusted Gateway-issued authorization scope must be bound to the current request, patient, permitted read/action and intended service; receivers reject mismatched scope and resolve actual ownership for ID-addressed resources. Use established framework protection rather than custom cryptography. Never treat a client header, correlation ID or a service credential alone as proof of a user's patient entitlement. No public backend route may bypass this control. Scope/transport/credential distribution is part of a future complete trust design, not an optional afterthought.
**Counter-effects:** More trust relationships, backend checks, delegated context and certificate/credential distribution can outweigh the saved hop. Gateway becomes less of an internal bottleneck, but no cross-service atomic snapshot appears automatically. A service mesh would add sidecars/listeners and operational overhead; it is not required merely to permit these direct calls. [Microsoft's communication guidance](https://learn.microsoft.com/en-us/dotnet/architecture/microservices/architect-microservice-container-applications/communication-in-microservice-architecture) discusses synchronous dependencies and consistency trade-offs; the Health App routing proposal and energy expectation are our inference.
## 7. Introduce freshness-safe reuse only when repetition justifies it
**Design:** Start with public, immutable reviewed guidance/reference content, whose versions and applicability are explicit. The baseline already loads static content, so an internal memory cache may add no benefit; external conditional/public caching may avoid repeated transfers without exposing patients.
For expensive repeated clinical-data calculations, an optional bounded **in-memory** Insights cache can use source-certified per-patient observation revision plus patient, normalized period, context selection, method version and reference-content version. Observation increments its revision atomically on every record, numeric/context correction, clearing and deletion. The source provides revision and selected data from the same consistent read when data is needed. Each request still authenticates/authorizes and validates the current source revision; failure to establish current state fails rather than serving an unverified result. A matching current revision allows reuse; a changed revision forces calculation from current selected data. Clinical/account/assignment updates must not be bypassed by cache hits.
**Mechanism:** Potentially avoid repeated full-series retrieval/calculation while retaining immediate post-commit freshness for subsequent requests. This is useful only when saved repeated work exceeds revision checks, cache management and memory overhead.
**Assumptions/dependencies:** Repeated identical expensive queries are common, methods/content are versioned, and source revision is correct and transactional. Every replica follows the same validation rule; request-time snapshot semantics are explicit. Cached results are protected internal derived health data, not public HTTP cache entries.
**Counter-effects:** High write rates/low repetition yield few hits. Revision updates/checks, retained memory and extra contracts cost work. Requests concurrent with a write see their documented source-read point, not future data. A TTL alone or eventual invalidation event does not satisfy freshness; asynchronous replicas must not return stale latest results. No Redis/broker/persisted result store is necessary for this candidate, and none is proposed by default. Baseline no-cache architecture would need an explicit revision; no-persistence and original internal contract expectations remain recorded.
## 8. Scale only the services that need capacity
**Design:** Retain independent services and allocate additional instances only to a saturated feature, such as expensive Insights reads, instead of cloning the entire application. Keep source ownership/current reads and per-request access checks. Scale back redundant capacity when acceptable; preserve stable endpoint discovery and compatible service credentials.
**Mechanism:** Under skewed demand, selective scaling can avoid replicating lightly used Gateway/Profile/Observation/Overview work. This is a genuine architectural advantage independent services can have over whole-application replication.
**Assumptions/dependencies:** The load is sufficiently uneven and high to justify replicas, routing and coordination. Sufficient DB capacity exists; replica pools are included in a global budget.
**Counter-effects:** Additional instances/load balancers/controllers cost idle resources and may amplify source load. Adding Kubernetes or an autoscaling control plane for a small prototype can be counterproductive. Full scale-to-zero introduces cold starts, dependency activation and availability complications; it is conditional on an explicit responsiveness/hosting decision, not the default. Scaling is not automatically lower energy just because throughput rises.
## 9. Keep unsolicited and failed work bounded
**Design:** Retain on-demand calculations and transient provisioning, rather than adding periodic summary recalculation, continuous content polling or a resident provisioning service. Where background administrative work becomes necessary, schedule only genuinely deferrable work without delaying user-visible record/read/correction/deletion semantics. Use propagated cancellation, bounded read retries/deadlines and fail-closed dependency errors; do not repeatedly retry an ambiguous write.
**Mechanism:** Avoid work no user requested and limit amplification during cancellations/outages. The baseline already has no broker/periodic calculation worker, so preserving that absence is not an additional saving relative to it.
**Assumptions/dependencies:** No acceptance criterion requires real-time push/background computation; the current synchronous model remains appropriate.
**Counter-effects:** Repeated on-demand computations may cost more than a correct cache under highly repetitive load. Overly aggressive deadlines/retries can cause failures or repeated client work. Replacing synchronous current results with eventual projections creates freshness problems; a broker's cost is not justified by the word “asynchronous.” Moving work to a lower-carbon time/location may affect emissions without reducing energy, and is a separate objective.
## Suggested architectural path
| Candidate | Composition | Why consider it | Remaining trade-offs |
| --- | --- | --- | --- |
| A — Conservative independent services | Five processes, original gateway routing, one suitable host where possible, one PostgreSQL server/two DB owners; bounded pools/admission; safe request-local GET reuse | Addresses physical/resource/repeated-work overhead with minimal structural change; original independent-installation capability remains | Duplicate runtimes and internal network paths remain; host contention and pooled idle resources |
| B — Independent services with direct internal calls | A plus explicit private direct dependency APIs and scoped authorization delegation | Addresses gateway detours while preserving independent runtime/DB boundaries | Revises communication/trust design; credential/delegation complexity; independent failures remain |
| C — Workload-adaptive independent services | A or B plus only justified source-revision reuse/selective replicas | May be advantageous for repeated expensive queries or skewed feature demand | Highest correctness/coordination overhead; unsuitable as a default for an unknown small workload |
For this prototype, **Candidate A is a reasonable alternative to evaluate before a runtime merger** if retaining services is valuable. Establish physical placement and documented resource lifecycles first; then remove avoidable repeated reads. Consider B when gateway detours matter, and C when the workload actually needs its extra machinery. This ordering expresses reversibility, requirement compatibility and complexity, not a measured ranking of energy savings.
Combining mechanisms does not mean their savings add: colocation may already remove much network/host overhead; pooling, compact contracts and caching can address overlapping work. A monolith may still be appropriate for simplicity, while an efficient service deployment may outperform it under different load/hosting assumptions. Current documentation provides no universal energy winner.
@@ -0,0 +1,40 @@
# Requirement safeguards and compatibility
This is a suggestion register, not a replacement architecture. Binding behaviours remain the [common requirements](../Docs/Requirements/00-common-requirements.md) and US-01–US-15. Original [US-16](<../Docs/Requirements/US16 easy installation and deployment installer.txt>) and its [addendum](../Docs/Requirements/us16-addendum) are assessed explicitly; earlier user clarification allows topology alternatives to be documented with necessary revision.
## Constraints every candidate preserves
| Behaviour | Architectural safeguard |
| --- | --- |
| US-01/02/03 account/profile lifecycle and retrieval | Atomic durable association, uniqueness and retry/recovery remain Profile-owned; no cross-service association cache replaces the source of truth |
| US-04/05/06 record/read/latest and context | Positive required values/time; actual existing patient; saved independent categories/text/details; latest uses measurement/original recording/deterministic tie, independent of context suitability |
| US-07 and shared periods/selections | Full inclusive patient history, equal bounds valid/reversed rejected, ascending measurement order, AND selected dimensions, Unknown distinct from omission; no silent truncation or default exclusions |
| US-08/09 updates/deletion | Atomic validation/mutation; omitted values preserved, clear makes Unknown; source revision (if added) changes in the same transaction; later source reads exclude deleted values/context |
| US-10 arithmetic insight | Exact raw contributions/count, three means with final half-up two decimals, BP extrema and one/zero sufficiency; mixed/unknown context visible. Aggregate transfer must preserve these obligations |
| US-11 trends | Full-period timestamp evidence, intermediate excursions/reversals, distinct-time sufficiency, separate metrics/units, current context, applicable reviewed references and claim-specific limits; no endpoint-only shortcut or replacement formula for energy |
| US-12 overview | Latest overall remains independent of insight period/selection; profile/latest retained for no insight; distinct bases and explanations; no trend added. Independent-service composition does not promise a cross-service snapshot |
| US-13/14 authentication and authorization | Validate current request identity, ownership and assignment before any result, including cache hits; professional reads only; actual observation owner, never caller patient ID; no direct API bypass, leaked tokens or public clinical caches |
| US-15 guidance | Public sourced/reviewed/applicability-labelled guidance; no record writes/certification/defaulting/submission dependency; unsupported verified content explained |
| Deployment/security | Separate feature processes/configuration and generated protected credentials/certificates when retained; remote origins supported; HTTPS trust verified; only owners access their databases |
## Structural compatibility by suggestion
| Suggestion | Five service processes? | Original US-16 / existing design status |
| --- | --- | --- |
| 1 physical colocation | Yes | Explicitly permitted; independent units/configuration and configured remote interfaces retained |
| 2 shared PostgreSQL server/two owned DBs | Yes | Explicitly permitted; never merge databases, credentials or owners |
| 3 bounded resource/connection lifecycle | Yes | Preserves boundaries and configuration semantics; resource policy is a revisable runtime design decision |
| 4 request-local observation GET reuse | Yes | Preserves processes/ownership/public results; recorded Gateway forwarding behaviour changes. A strict requirement to preserve every original call path requires explicitly documenting this reduction |
| 5 tailored internal data contracts/source aggregates | Yes | Selection/index decisions can remain within owners. New internal APIs/source aggregation change contracts or responsibilities and require corresponding architecture/AC-16-H reconciliation; not asserted fully compatible |
| 6 direct private service calls | Yes | Original gateway-routed design changes; AC-16-H communication-path interpretation and deployment/trust documentation require revision. Same service installability and separate DB ownership remain |
| 7 revision-validated memory result cache | Yes | Preserves current functional results if its transactional revision contract holds. Changes baseline no-cache/on-demand mechanism; internal metadata contracts/persistence fields require explicit revision. No generated-result database is required |
| 8 selective replicas / conditional activation | Yes | Optional runtime topology; per-service management retained. Added routing/credentials/global budgets require design; scale-to-zero is unresolved pending responsiveness/host constraints |
| 9 bounded/on-demand work | Yes | Retains baseline on-demand/no-worker behaviour. Any new deferral must leave synchronous acceptance semantics intact |
Candidate A is compatible with the central independent-service/deployment constraints; request-local reuse is an optional refinement with its call-path delta identified. Candidates B/C require more significant recorded changes. None introduces direct SQL access by Insights/Overview or claims separate DBs give atomic multi-service reads.
## Decisions still dependent on deployment/workload
Physical host sharing and idle power response determine whether colocation releases any powered capacity. History size and repeated query patterns determine whether compact contracts/cache reuse pay for their complexity. Uneven load and isolation needs determine whether selective service scaling offers an advantage. Token/service trust, scope lifetime and cache revision contracts must be fully specified before implementing B/C. Availability and cold-start tolerance must be clarified before scale-to-zero. No numerical workload, savings, pool sizes or automatic-scaling thresholds are invented.
External sources in the suggestions support general mechanisms and architectural concerns, not a Health App energy result. No changes to clinical guidance/reference values, original requirements, source or deployment configuration are made.
+19
View File
@@ -0,0 +1,19 @@
# Suggestion-document verification
Completed 2026-10-13. This folder is an exploratory supplement requested by the user, not a second completed implementation architecture or a replacement of `ArchitectureProposal/`.
The README, nine-option architectural discussion, requirement/compatibility register, this validation record and editable two-page topology diagram are present. Each option identifies its proposed change, energy mechanism, assumptions/dependencies and possible counter-effects. Baseline mechanisms already present are distinguished from possible new improvements. Candidate A preserves five-process installation and separate DB ownership; communication, contract, cache and activation changes are explicitly conditional/revision-requiring.
The compatibility review covers US-01–US-15/common behavioural safeguards and original US-16 installation/ownership semantics. It specifically checks actual-owner authorization before request-local read reuse, no professional writes, complete history/context, current corrections/deletions, source-certified cache revision, clinical-method independence and latest-overall versus selected-insight distinction. Suggestions do not invent clinical thresholds, silently drop data, add an unneeded broker, or claim multi-service snapshot consistency.
Primary external guidance was consulted for energy proportionality/static power, PostgreSQL connection resource sizing and microservice communication/consistency concerns. Links are attached to the relevant discussion. Those sources do not establish Health App energy savings; application-specific mechanisms and priorities are explicitly inferences/hypotheses. No numerical savings or energy measurement procedure is specified.
Diagram verification parsed native uncompressed Draw.io XML with **2 pages, 21 editable vertices and 17 connectors**. Cell IDs are unique, all connector endpoints resolve, dimensions are positive, peer boxes do not overlap and font-metric estimates found no vertex label overflow. No raster-only diagram content is embedded. Draw.io GUI import/rendering/round-trip and automatic connector-label placement were not exercised; the GUI/CLI remains unavailable.
Local Markdown file links and balanced fences were checked after all files were created. A SHA-256 comparison confirms all **81 existing `Docs/` and `ArchitectureProposal/` files remain unchanged**. Existing proposal documents and original sources were not edited; new repository work is confined to `ArchitectureSuggestions/`. No application source was inspected or modified, and no application tests or installer were run. Temporary documentation checks were outside the repository.
Open workload, physical hosting, availability, query repetition and isolation questions remain assumptions, not blockers for this exploratory discussion. Direct-call delegation, source revision/cache metadata, compact aggregate contracts and conditional activation require detailed design before implementation. The completed deliverable is a documented menu of architectural alternatives with safeguards and editable topology sketches.
## Recommendation supplement
The [energy recommendation](energy-recommendation.md) records the efficient modular monolith as the leading candidate under modest/intermittent workload assumptions, with efficient colocated independent services as the strongest alternative. It distinguishes complementary changes from complete architectures, existing baseline behaviour from new benefits, and physical consolidation from process consolidation. The expected ranking explicitly accounts for hosting, repeated queries, selective scaling, contention and original US-16 incompatibility. It states limited confidence and makes no measured or quantified saving claim. Local links and input/proposal preservation were checked again after adding it; no existing diagrams or application artefacts changed.