116 lines
18 KiB
Markdown
116 lines
18 KiB
Markdown
# 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.
|