Backend Hosts & Services Architecture
1. Architectural Paradigm: The Modular Monolith
Section titled “1. Architectural Paradigm: The Modular Monolith”The backend of the GERCIA Platform is engineered as a high-performance Modular Monolith targeting .NET 10 (C# 14). Rather than prematurely distributing domain logic into independently deployed microservices—which introduces distributed transaction overhead, network latency, and operational complexity—the platform organizes domains into strictly bounded modules within a single monorepo and execution boundary.
High-Level Architecture & Layered Boundaries
Section titled “High-Level Architecture & Layered Boundaries”flowchart TD
subgraph PresentationLayer ["Decoupled Presentation Clients (apps/)"]
WEB_SPA["@gercia/app (apps/app)<br>Angular 22 SPA • PrimeNG 22 • Tailwind v4<br>Hosted on Cloudflare Pages (app.gercia.com.br • app.gercia.vet.br)"]
MOBILE_APP["GERCIA Care (apps/mobile - Roadmap)<br>Kotlin Multiplatform (SwiftUI & Compose)<br>Push-to-Sign & Wearable Telemetry"]
end
subgraph HostsLayer ["Backend Orchestration Host (dotnet/src/Hosts/)"]
direction LR
SERVER["Gercia.Server<br>(REST Gateway, OpenIddict STS, MCP AI & Migrations)"]
end
subgraph BusinessLayer ["Isolated Domain Verticals (Health/, Veterinary/ & Operations/)"]
direction LR
CLINICAL["Gercia.Clinical<br>(schema: clinical)"]
DENTAL["Gercia.Dental<br>(schema: dental)"]
PHARMACY["Gercia.Pharmacy<br>(schema: pharmacy)"]
VET["Gercia.Veterinary<br>(schema: veterinary)"]
OPS["Gercia.Operations<br>(schema: operations)"]
end
subgraph PlatformLayer ["Universal SaaS Engine (Foundation/)"]
CORE["Gercia.Core<br>(Multitenancy, Postgres RLS, Master Identity, Audit, AES-256)"]
BB["Gercia.BuildingBlocks<br>(Universal DDD Primitives, ValueObject, IUnitOfWork)"]
end
subgraph DatabaseLayer ["Google Cloud SQL for PostgreSQL (Database: gercia)"]
subgraph Schemas ["Sovereign Schemas Segregation"]
S_CORE[("core<br>SaaS Foundation & IAM")]
S_CLINICAL[("clinical<br>Medical & EHR Records")]
S_DENTAL[("dental<br>Odontograms & Periodontics")]
S_PHARMACY[("pharmacy<br>Formulas & Orders")]
S_VET[("veterinary<br>Animal Health & MAPA")]
S_OPS[("operations<br>Billing & Subscriptions")]
S_AI[("ai<br>Agents & Vector Embeddings")]
S_EXT[("extensions<br>pgcrypto, uuid-ossp, pgvector")]
end
end
WEB_SPA -- "HTTPS / OAuth 2.1 (PKCE)" --> SERVER
MOBILE_APP -- "HTTPS / OAuth 2.1 (PKCE)" --> SERVER
SERVER --> CLINICAL
SERVER --> DENTAL
SERVER --> PHARMACY
SERVER --> VET
SERVER --> OPS
CLINICAL --> CORE
DENTAL --> CORE
PHARMACY --> CORE
VET --> CORE
OPS --> CORE
CORE --> BB
CORE -.->|"Identity & Auditing"| S_CORE
CLINICAL -.->|"Tenant RLS"| S_CLINICAL
DENTAL -.->|"Tenant RLS"| S_DENTAL
PHARMACY -.->|"Tenant RLS"| S_PHARMACY
VET -.->|"Tenant RLS"| S_VET
OPS -.->|"Tenant RLS"| S_OPS
SERVER -.->|"MCP / pgvector"| S_AI
Consolidated Single Database with 8-Schema Segregation
Section titled “Consolidated Single Database with 8-Schema Segregation”The platform persistence tier is consolidated into a single PostgreSQL database catalog named gercia on managed Google Cloud SQL for PostgreSQL, eliminating physical database fragmentation. Isolation between domains is enforced through PostgreSQL schemas and kernel-level Row-Level Security (RLS):
core: Universal SaaS engine, multi-tenancy (tenants,branches), master civil identity, user credentials (users,user_logins), roles, distributed audit log (core.audit_history), and OpenIddict STS security tables.clinical: Healthcare Clinical vertical bounded context (patients, medical charts, healthcare professionals, consultations, insurance carriers, ICD/CID records).dental: Healthcare Dental / Odontology vertical bounded context (visual Odontograms [ISO 3950 / FDI], periodontal charting, procedure plans, and dental compounding).pharmacy: Healthcare Compounding Pharmacy vertical bounded context (galenic formulations, active pharmaceutical ingredients, compounding orders, cleanroom weighing logs conforming to ANVISA RDC 67/2007).veterinary: Sovereign Veterinary vertical bounded context (tutor/legal owner records, multi-species patient profiles, species-based ponderal dosing [mg/kg], and MAPA/SIPEAGRO regulatory traceability).operations: Platform management and SaaS backoffice (corporate contracts, multi-tenant subscription plans, billing cycles, invoice tracking).ai: Dedicated workspace for artificial intelligence and MCP agent runtimes (conversation history, tool execution telemetry, and vector embeddings viapgvectorfor semantic search).extensions: Isolated home for all PostgreSQL engine extensions (pgcrypto,uuid-ossp,pgvector,pg_stat_monitor), keeping the defaultpublicschema unpolluted and secure.
Direct C# Application Services over Third-Party Dispatchers
Section titled “Direct C# Application Services over Third-Party Dispatchers”To maintain zero-overhead in-memory throughput, direct code navigation, and compile-time verification, the platform rejects mediator dispatch libraries (such as MediatR). Instead, orchestration occurs via Pure C# Application Services:
- Zero-Reflection Overhead: Application services are registered directly in the native .NET Dependency Injection container (
Microsoft.Extensions.DependencyInjection), guaranteeing zero reflection cost at runtime. - Deterministic Navigation (F12): Developers and static analysis tools can navigate directly from presentation endpoints to service definitions and domain aggregates without runtime handler scanning.
- Compile-Time Safety: Incompatible parameters, missing return types, or contract mismatches fail immediately during compilation rather than failing silently at runtime.
2. The Unified Cloud Server Host (Gercia.Server)
Section titled “2. The Unified Cloud Server Host (Gercia.Server)”The platform consolidates all server-side cloud workloads into a single, high-performance orchestration host: dotnet/src/Hosts/Gercia.Server. It is containerized into a minimal, rootless Microsoft Azure Linux Distroless image deployed to Google Cloud Platform:
| Host Project | Primary Responsibilities | Network Domain | Max Connection Pool | Hosting Target |
|---|---|---|---|---|
Gercia.Server |
Universal Cloud Server executing REST API, OpenIddict STS (RFC 8693 Token Exchange, Argon2id, TOTP), Model Context Protocol (MCP) AI endpoints (/mcp), and pre-deploy database migrations (--migrate). |
api.gercia.com.brmcp.gercia.com.br |
80 connections |
Google Cloud Run Service (Web) & Cloud Run Job (DDL Migrations) |
Decoupled Presentation Layer & Authentication
Section titled “Decoupled Presentation Layer & Authentication”All human presentation is decoupled from .NET hosts into specialized frontend clients:
@gercia/app(apps/app): Built with Angular 22, PrimeNG 22, and Tailwind CSS v4, deployed statically to Cloudflare Pages. It authenticates withGercia.Servervia OAuth 2.1 Authorization Code Flow with PKCE (OpenIddict). Claims within the signed JWT determine role-based view permissions across Clinical, Dental, Pharmacy, Veterinary, and Operations routes.GERCIA Care(apps/mobile): Native Kotlin Multiplatform client for iOS and Android, communicating via HTTPS REST and short-polling / Server-Sent Events.
Distroless Container Health Checks (--health)
Section titled “Distroless Container Health Checks (--health)”All production containers run on Distroless Azure Linux runtime images. Because distroless containers intentionally strip out shell interpreters (sh, bash) and diagnostic tools (curl, wget) to minimize security attack surfaces, traditional shell probes fail.
Every host application implements an internal CLI health check argument at startup:
if (args.Contains("--health")){ using var client = new HttpClient(); var response = await client.GetAsync("http://localhost:8080/health"); Environment.Exit(response.IsSuccessStatusCode ? 0 : 1);}Google Cloud Run and container runtimes verify host liveness directly via HTTP probes (GET /health), while developer environments can invoke dotnet run -- --health.
3. Strict Dependency & Monorepo Boundaries
Section titled “3. Strict Dependency & Monorepo Boundaries”To preserve architectural integrity, reference boundaries are enforced at the .csproj level:
[Gercia.BuildingBlocks] <-- The absolute foundation. Has ZERO project references. ▲[Gercia.Core] <-- SaaS engine. References BuildingBlocks only. ▲[Business Modules] <-- Health/Clinical, Health/Dental, Health/Pharmacy, Veterinary, Operations. (Clinical ⊘ Dental ⊘ Pharmacy ⊘ Veterinary ⊘ Operations) <-- ZERO cross-module references permitted between verticals. ▲[Orchestration Host] <-- Gercia.Server. References Business Modules + Core. ▲[Clients & Edges] <-- Web SPA, Mobile App, Edge Hub. ZERO domain references (Network API only).Architectural Rules
Section titled “Architectural Rules”- Isolation of Business Verticals:
Gercia.Clinical,Gercia.Dental,Gercia.Pharmacy,Gercia.Veterinary, andGercia.Operationsmust never reference each other. Inter-domain workflows (such as a clinic sending a digital prescription to a compounding pharmacy) are orchestrated via shared contracts inGercia.Coreor asynchronous integration events. - Network-Only Clients: Frontend applications (
@gercia/app), mobile clients (GERCIA Care), and workstation hardware daemons (Gercia.Edge) must never reference domain libraries, entities, or DbContexts. They consume the platform exclusively through sovereign REST endpoints or local Edge loopback APIs. - Domain Purity: Domain entity assemblies must not reference UI frameworks, database ORM packages outside EF Core abstractions, or presentation libraries.
4. Domain-Driven Design (DDD) & Transactional Unit of Work
Section titled “4. Domain-Driven Design (DDD) & Transactional Unit of Work”Every business vertical implements DDD tactical patterns derived from Gercia.BuildingBlocks:
Rich Domain Models & Aggregate Invariants
Section titled “Rich Domain Models & Aggregate Invariants”- Encapsulated State: Aggregates and Entities protect their invariants. Properties use
privateorinternalsetters. State transitions occur exclusively through expressive behavioral methods (e.g.,ApprovePrescription(),UpdateDosingMetric(),MarkCompoundingOrderReady()). - Value Object Immutability: Structural concepts without individual identity (e.g.,
Address,Money,DosageMetric,FormulaUnit) inherit fromValueObjectand are 100% immutable. - Domain Events (
IDomainEvent): Business side effects are expressed as domain events raised inside aggregate roots and published during transaction commit.
Transactional Unit of Work (IUnitOfWork)
Section titled “Transactional Unit of Work (IUnitOfWork)”Database persistence across business modules is governed by the IUnitOfWork pattern implemented natively by GerciaDbContext (which maps and manages all schemas in the unified gercia database):
sequenceDiagram
autonumber
participant AppService as "Application Service"
participant Aggregate as "Domain Aggregate Root"
participant UoW as "GerciaDbContext (IUnitOfWork)"
participant Interceptor as "Audit & SoftDelete Interceptor"
participant Postgres as "PostgreSQL (RLS Enforced)"
participant Outbox as "Transactional Outbox"
AppService->>Aggregate: ExecuteBusinessAction(command)
Aggregate->>Aggregate: Validate Domain Invariants
Aggregate->>Aggregate: Raise DomainEvent(event)
AppService->>UoW: SaveChangesAsync(cancellationToken)
UoW->>Interceptor: Intercept Modified & Deleted Entities
Interceptor->>Interceptor: Calculate JSON Diff (core.audit_history)
Interceptor->>Interceptor: Apply SoftDelete (is_deleted = true)
UoW->>Outbox: Stage Domain Events to Outbox Table
UoW->>Postgres: Atomic COMMIT (Postgres RLS Session Active)
Postgres-->>UoW: Transaction Succeeded
UoW-->>AppService: Return Result DTO
5. Two-Tier Validation Architecture
Section titled “5. Two-Tier Validation Architecture”The platform separates structural input sanitation from semantic domain invariants into two distinct validation tiers:
flowchart LR
subgraph Tier1 ["Tier 1: Application & Input Validation"]
direction TB
REQ["HTTP Request (JSON Payload)"]
FV["FluentValidation DTO Validator<br>(Cpf, Cnpj, Required, Length, Format)"]
REQ --> FV
end
subgraph Tier2 ["Tier 2: Domain Invariant Protection"]
direction TB
AGG["Domain Aggregate Behavioral Method"]
RULE["Pure C# Domain Invariant Rules<br>(IBusinessRule, CheckRule, State Transitions)"]
AGG --> RULE
end
FV -->|"Valid DTO Passed to Service"| AGG
- Tier 1 — FluentValidation (Application Layer): Validates input payloads, string lengths, mandatory presence, regex patterns, and document formatting (
.Cpf(),.Cnpj()). In the frontend client (@gercia/app), reactive forms with AngularReactiveFormsModulemirror these structural validations to provide instant user feedback before network transmission. - Tier 2 — Pure C# Domain Rules (Domain Layer): Validates business preconditions, status state machines, and regulatory invariants using
IBusinessRuleandCheckRule(). Domain invariants do not depend on external validation libraries and cannot be bypassed.
6. API Contracts & TypeScript Model Synchronization
Section titled “6. API Contracts & TypeScript Model Synchronization”With the decoupling of the presentation tier into an Angular 22 Single Page Application (@gercia/app), contract synchronization is maintained through strict schema standards:
- OpenAPI 3.1 & Scalar Documentation:
Gercia.Servergenerates strongly typed OpenAPI specifications directly from C# record DTOs and Minimal API endpoints. - TypeScript Synchronization: Frontend models in
apps/app/src/app/core/models/map 1:1 to backend DTOs, ensuring compile-time type safety across API requests and responses. - Zero Leaks: Internal domain aggregates and database entities are never serialized directly to clients; API responses use dedicated, versioned response DTOs.
7. Secrets Management & Connection Pooling
Section titled “7. Secrets Management & Connection Pooling”Runtime secrets and database connection strings are never committed to source control or plain text configuration files:
- Google Secret Manager (GSM): Hosts hydrate configuration dynamically at startup via environment-suffixed GSM keys (
CONNECTION_STRING_SERVER_PRD/STG,CONNECTION_STRING_MIGRATOR_PRD/STG,GOOGLE_CLIENT_ID_OPS,GOOGLE_CLIENT_SECRET_OPS, andGERCIA_APP_ENCRYPTION_KEY). - Npgsql Programmatic Enrichment: Connection strings are enriched in-memory with strict pool sizes (
MaxPoolSize=80for Server,10for ephemeral migrator jobs), UTC timezone locks, and socket timeouts. - Database Transport Security (TLS 1.3) & Reactive Password Rotation: Database connections strictly enforce TLS 1.3 encryption (
SslMode=Require) over isolated private VPC networking with SCRAM-SHA-256 authentication. Zero-downtime credential rotation is handled via Npgsql’sUsePeriodicPasswordProvider, updating credentials every 15 minutes without requiring container restarts.