Technical Design Document

Twin CMMS Platform — System Design

Architecture, module design and technology stack for a digital-twin CMMS that reads live BACnet data from Honeywell and Johnson Controls systems, imports IFC / FBX building models, and delivers dashboards, asset & maintenance management and energy intelligence.

DocumentSystem Design (SDD)
Version0.4 Draft
Date30 Nov 2026
RelatedTwin CMMS BRD v0.5
ClassificationInternal

1Summary and key decisions

The platform is a set of containers that runs the same way on an on-premise server, a single VPS or any cloud. An on-site edge gateway reads BACnet data and streams it over MQTT. The data is normalised once, stored in PostgreSQL (business data) and ClickHouse (time-series), and served by a modular Core API to the twin, CMMS, energy and dashboard screens.

#DecisionChoiceWhy
D1Architecture styleModular monolith for business logic + separate stream workersSmall team, internal product first. Clear module boundaries, so modules can become services later.
D2Edge to platformEdge gateway polls BACnet, publishes MQTT over TLS, outbound onlyNo inbound firewall ports; 72 h buffering; same for every hosting option.
D3Event busApache Kafka (KRaft mode, no ZooKeeper)Replay, back-pressure, many consumers; Apache 2.0; one node for small installs, a cluster for HA.
D4DatabasesPostgreSQL for business data + ClickHouse for time-seriesBoth fully open source. PostgreSQL for transactions, outbox and sagas; ClickHouse for about 10× compression and fast roll-ups over billions of readings.
D5Data modelOne canonical reading; points tagged with Brick classesModules never parse vendor formats; rules work on any building.
D63DIFC / FBX converted to glTF / Fragments; Three.js + That Open EngineFast browser loading; open-source.
D7IdentityKeycloak (OIDC / SAML, MFA)Works offline on-prem; federates with Azure AD / LDAP.
D8DeploymentContainers + Helm: Docker Compose or k3s on one VPS, RKE2 on-prem cluster, any managed KubernetesOnly portable dependencies (PostgreSQL, S3 API, Kafka API, MQTT, OIDC). No cloud lock-in.
D9TenancySingle tenant now; tenant_id everywhere from day oneReady to sell later without a redesign.
D10Publishing eventsTransactional outbox + idempotent inbox (Wolverine)No lost or phantom events when a pod or broker fails.
D11Multi-step processesOrchestrated sagas with compensating actions (Wolverine)Consistency across modules and workers without distributed transactions.
D12Backend platformASP.NET Core on .NET 10 LTS (C#); Python only for BACnet edge, analytics / ML and BIM conversion; React + TypeScript front endsBest mix of performance, built-in outbox / saga support, long-term support and enterprise fit. See section 3.
D13Duplicate safetyIdempotency at every layer: stable message IDs, unique keys, inbox, Idempotency-Key on API writesAt-least-once delivery everywhere, effectively-once results. See section 8A.
D14Licensing100% open source, zero licence fees (OSI-approved licences only)No lock-in or future licence costs, including if the product is sold. Proposed default; trade-offs per component in section 3 (OD-2).

2Overall architecture

Data flows top to bottom. Controllers feed the edge gateway, the platform normalises every reading once, and all modules share the same data. Highlighted boxes are the parts we build ourselves.

Building site (OT network) one gateway per building / segment
Honeywell controllersBACnet/IP, MS/TP
JCI controllersBACnet/IP, MS/TP
Meters & IoT sensorsBACnet, Modbus, MQTT
BACnet simulatormock data, Phase 1
Edge gateway (Docker)BACnet discovery · ReadPropertyMultiple + COV · deadband · 72 h store-and-forward · MQTT publish · health heartbeat
MQTT over TLS · outbound only · port 8883 ▼
Ingestion & normalisation
Mosquitto brokerMQTT 5, device certificates
Ingest bridgeMQTT → Kafka topics
Normaliservendor adapters, units, IDs, quality
Apache Kafka (KRaft)raw · canonical · DLQ · events
canonical readings ▼
Stream workers .NET Worker Services + Python analytics
TS writer→ ClickHouse, Valkey last value
Alarm enginethresholds, BACnet events
FDD enginediagnostic rules
Analytics service (Python)baselines, forecasts, ML
Data-quality monitorstale, flatline, gaps
alarms · faults · KPIs ▼
Application layer
Core API — ASP.NET Core (.NET 10) modular monolithTwin · CMMS · Energy · Portfolio · Reports · Notifications · Admin · (Ph 2) Sustainability · Wellbeing · Space · Wolverine outbox, inbox + sagas
Live hubSignalR (WebSocket)
BIM workers (Python)IFC / FBX → glTF
Report workersPDF / Excel
read / write ▲▼
Data & identity
PostgreSQLtwin, CMMS, outbox, sagas
ClickHousereadings, roll-ups
Valkeylive values, cache
Object storage (S3 API)SeaweedFS / any S3
Keycloakusers, roles, SSO, MFA
HTTPS + WebSocket via API gateway (Traefik) ▼
Users & external systems
Web appReact, 3D twin, dashboards
Technician viewsame web app on phone / tablet
Notificationsemail, SMS, in-app
IntegrationsERP, BI, REST API, webhooks
Control stays with the BMS. Honeywell / JCI controllers keep running their own control loops. The platform only reads data (write-back is a Phase 3 option with strict safeguards), so a platform outage never stops HVAC, lighting or life-safety systems.

2ASensor-to-dashboard data flow

This is the path one sensor reading takes, from the physical sensor to the live dashboard and the trend charts. The upper lanes run left to right on site and through ingestion; the lower lanes run back to the user. Once a value reaches the platform, it appears on screen within 5 seconds (p95).

A reading reaches the dashboard within 5 s of arriving at the platform Building (OT) Edge gateway Ingestion Processing & storage Application (.NET) Browser BACnet/IP, MS/TP outbound, port 8883 write readings (batch) live, < 1 s 15-min / 1 h aggregates on request Sensor temp, kW, CO₂ 1 Controller Honeywell / JCI 2 Read RPM poll / COV 3 Filter + buffer deadband, 72 h 4 Publish MQTT 5, TLS 5 Mosquitto auth, topic ACL 6 raw.readings Kafka topic 7 Normaliser adapter, units 8 canonical readings topic 9 TS writer dedupe, COPY 10 Valkey last value 11 ClickHouse raw + roll-ups 12 Live hub SignalR push 13 Dashboard widgets, 3D twin 14 Trend API query aggregates 15 Trend charts history, compare 16 uplink down: hold, replay later bad / unmapped → DLQ Time budget 1–2 · Controller scan vendor, about 1 s 3 · Poll interval 15 s – 15 min; COV instant 4–5 · Gateway → platform < 1 s 6–9 · Ingest + normalise < 1 s 10–11 · Write + cache < 1 s 13–14 · Push to browser < 1 s

Step by step

#StepWhat happensWhere
1SensorMeasures a physical value (temperature, flow, kW, CO₂) and sends it to its controller over wiring or a field bus.Building
2ControllerHoneywell / JCI controller runs its own control loop and exposes the value as a BACnet object (e.g. analog-input:12).Building
3ReadGateway reads the object with ReadPropertyMultiple on the point's interval, or receives a COV notification when it changes.Edge gateway
4Filter + bufferApplies the deadband and heartbeat, timestamps in UTC, and writes the reading to the local SQLite buffer. If the uplink is down, readings wait (≥ 72 h) and are replayed in order.Edge gateway
5PublishBatches readings, compresses them and publishes over MQTT 5 / TLS (QoS 1) on t/{tenant}/s/{site}/gw/{id}/data.Edge gateway
6Mosquitto brokerChecks the gateway's certificate and topic permissions, then accepts the batch.Platform
7raw.readingsIngest bridge writes the batch, unchanged, to the raw.readings Kafka topic (also archived for 30 days).Platform
8NormaliserVendor adapter parses the batch; maps (gateway, device, object) to a point_id; converts units; sets quality; validates. Failures go to the dead-letter queue; unknown objects go to “discovered points”.Platform (.NET worker)
9canonical.readingsOne canonical reading per message, keyed by point_id.Platform
10TS writerConsumes canonical readings in batches and inserts them into ClickHouse, using the batch ID as the insert de-duplication token; the table also collapses duplicate (point, ts) rows (section 8A).Platform (.NET worker)
11ValkeyUpdates the last value per point and publishes a change notice.Platform
12ClickHouseStores the raw reading in a compressed column store; the roll-up job keeps the 15-min, 1-h and 1-day tables current.Platform
13Live hubSignalR hub sends the change to every browser subscribed to that point, floor or asset (at most one update per point per second).Core API (ASP.NET Core)
14DashboardReact updates the widget value, colour state and 3D twin overlay without reloading the page.Browser
15Trend APIWhen a user opens a chart, the API picks raw, 15-min or hourly data depending on the time range.Core API (ASP.NET Core)
16Trend chartsECharts draws history, period comparisons and min / max bands; export to CSV / PNG.Browser
The alarm and FDD engines read the same canonical.readings topic (step 9) in parallel, so alarms appear on the dashboard through the same live hub. That path is described in section 10.

3Technology stack and rationale

Recommended stack: ASP.NET Core on .NET 10 LTS for the platform, Python only where it is clearly the strongest tool, and React + TypeScript for the user interfaces. All components run in Linux containers without internet access, so the same build deploys on-premise, on a VPS or in any cloud.

C# / ASP.NET Core — the platform

Core API and all business modules, outbox / inbox / sagas, live updates (SignalR), jobs, and the high-volume stream workers (normaliser, TS writer, alarm and FDD engines).

Python — specialist services

BACnet edge gateway and simulator (bacpypes3), analytics and machine learning (baselines, forecasts, anomaly detection), and IFC / FBX conversion (IfcOpenShell).

TypeScript — user interfaces

One responsive React web app for every role: dashboards and the 3D twin on desktop, and a technician view for phones and tablets in the browser. No native mobile app.

Selection principles

  1. Reliability first: mature, widely used components with long-term support releases.
  2. Runs anywhere: only open protocols and portable dependencies; no cloud-specific services; works fully offline.
  3. Built-in patterns, not custom plumbing: outbox, sagas, retries, real-time push and scheduling come from proven libraries.
  4. Performance per server: handle tens of thousands of readings per second on modest hardware, which keeps on-premise costs low.
  5. Right tool per job, but few languages: two back-end languages (C#, Python) plus TypeScript for front ends.
  6. Licence-safe for resale: permissive licences (MIT / Apache / BSD) preferred; anything else flagged.
  7. Hiring and support: skills that are easy to find in India and Saudi Arabia, with strong enterprise adoption.

Why ASP.NET Core for the platform

CriterionASP.NET Core (.NET 10)NestJS (Node.js)Spring Boot (Java)FastAPI (Python)
Throughput / efficiencyVery high; compiled, async, low memoryGood; single-threaded event loopVery high; heavier memoryModerate
Outbox, inbox and sagasBuilt in via Wolverine (MIT)Custom code or smaller librariesAxon / Eventuate (heavier, some commercial)Mostly custom
Real-time pushSignalR built in, Valkey scale-outSocket.IOWebSocket / STOMPBasic WebSocket
Type safety and maintainabilityStrong static typing, mature toolingGood (TypeScript)StrongOptional typing
Long-term supportLTS: 3 years per release from MicrosoftNode LTS; framework community-ledCommercial support availableCommunity
Enterprise fit (KSA / India)Very common in government and enterprise ITCommon in start-upsVery common in large enterprisesCommon in data teams
Runs on Linux / Windows / containersYes, allYesYesYes
Analytics / MLLimited (ML.NET)LimitedLimitedBest

Result: ASP.NET Core gives the best balance for the transactional core (CMMS, twin, alarms, sagas) and for high-volume data processing. Python stays for analytics, BACnet and IFC, where its libraries are the most mature. Spring Boot would also work, but needs more memory per service and has fewer free saga options.

Full stack

Every component is open source with no licence fee. Use Docker Engine (Apache-2.0), not Docker Desktop, which needs a paid subscription for larger organisations.

LayerTechnologyLicenceWhy this choice
Edge gatewayPython 3.12 · bacpypes3 · SQLite buffer · DockerPython (PSF-2.0) · bacpypes3 (MIT) · SQLite (Public domain) · Docker Engine (Apache-2.0)Most complete open-source BACnet stack (COV, ReadRange, routing); small footprint on industrial PCs
Device messagingEclipse Mosquitto (MQTT 5)Mosquitto (EPL-2.0 / EDL-1.0)Proven, lightweight broker; X.509 client certificates and topic ACLs; active / standby pair for HA (gateways buffer during fail-over)
Event busApache Kafka (KRaft) · Kafbat UIApache Kafka (Apache-2.0) · Kafbat UI (Apache-2.0)Industry standard; no ZooKeeper needed; replay and partitions for scale; one node or a cluster
Core APIASP.NET Core 10 · Minimal APIs / controllers · EF Core 10 + NpgsqlASP.NET Core (MIT) · EF Core (MIT) · Npgsql (PostgreSQL)High performance, strong typing, first-class PostgreSQL support, LTS until Nov 2028
Outbox / inbox / sagaWolverine (MIT) with PostgreSQL persistence and Kafka transportWolverine (MIT)Transactional outbox, inbox de-duplication, saga state, retries and scheduled timeouts built in
Real-timeSignalR + Valkey backplaneSignalR (MIT) · Valkey (BSD-3)Built into ASP.NET Core; automatic fallback; scales across replicas
Jobs & timersQuartz.NET (clustered, PostgreSQL store)Quartz.NET (Apache-2.0)PPM generation, SLA timers, escalations, scheduled reports; Apache licence
Stream workers.NET Worker Services · Confluent.Kafka · ClickHouse.Client · UnitsNet.NET (MIT) · Confluent.Kafka (Apache-2.0) · ClickHouse.Client (MIT) · UnitsNet (MIT-0)Normaliser, TS writer (ClickHouse batch inserts), alarm, FDD and data-quality engines at high throughput
Analytics / MLPython · pandas, statsmodels, scikit-learn, LightGBM · FastAPI (internal)pandas, statsmodels, scikit-learn (BSD-3) · LightGBM (MIT) · FastAPI (MIT)Best ecosystem for baselines, forecasting and anomaly detection
Cross-cutting .NET librariesFluentValidation · Mapster · Polly · Serilog · OpenTelemetry · Scalar (API docs)FluentValidation (Apache-2.0) · Mapster (MIT) · Polly (BSD-3) · Serilog (Apache-2.0) · OpenTelemetry (Apache-2.0) · Scalar (MIT)Permissive licences; avoids libraries that moved to commercial licences
Business databasePostgreSQL 17 · Patroni · pgBackRestPostgreSQL (PostgreSQL) · Patroni (MIT) · pgBackRest (MIT)Twin, CMMS, outbox, sagas, audit; HA and point-in-time recovery
Time-series databaseClickHouse + ClickHouse KeeperClickHouse + Keeper (Apache-2.0)Column store built for sensor data: about 10× compression, fast aggregates, TTL retention, native Parquet / S3 archives
CacheValkey 8 (Sentinel)Valkey (BSD-3)Linux Foundation fork, Redis-compatible; live values, SignalR backplane, rate limits
Object storageSeaweedFS or any S3-compatible serviceSeaweedFS (Apache-2.0)S3 API on-premise; the same code works with any cloud S3
BIM processingPython · IfcOpenShell · web-ifc / Fragments · Assimp / ufbxIfcOpenShell (LGPL-3.0) · web-ifc (MPL-2.0) · Fragments (MIT) · Assimp (BSD-3) · ufbx (MIT / Unlicense)Most capable open IFC toolkit; FBX read without the proprietary Autodesk SDK; fast web formats for the 3D viewer
WebReact + TypeScript · Vite · MUI (RTL) · Apache ECharts · Three.js + That Open Engine · i18nextReact (MIT) · TypeScript (Apache-2.0) · Vite (MIT) · MUI Core (MIT) · ECharts (Apache-2.0) · Three.js (MIT) · That Open Engine (MIT) · i18next (MIT) · html5-qrcode (Apache-2.0)Largest UI ecosystem; strong 3D and charting; full Arabic RTL support
API contractOpenAPI 3.1 → generated TypeScript clients (Kiota / NSwag)OpenAPI spec (Apache-2.0) · Kiota (MIT) · NSwag (MIT)Front ends stay in sync with the API automatically
IdentityKeycloakKeycloak (Apache-2.0)OIDC / SAML, MFA, Azure AD / LDAP; runs offline on-prem
IngressTraefik + cert-managerTraefik (MIT) · cert-manager (Apache-2.0)Automatic TLS, routing, rate limiting on any Kubernetes or Docker host
ReportsHTML templates → Playwright for .NET (PDF) · ClosedXML (Excel)Playwright for .NET (Apache-2.0) · Chromium (BSD-3) · ClosedXML (MIT)Same templates for screen and PDF; permissive licences
TestingxUnit · Testcontainers · Playwright (E2E) · Locust (load)xUnit (Apache-2.0) · Testcontainers (MIT) · Playwright (Apache-2.0) · Locust (MIT)Real PostgreSQL / Kafka in tests; load tests against the simulator
PlatformDocker Compose · k3s · RKE2 · any managed Kubernetes · Helm · Argo CDDocker Engine / Compose (Apache-2.0) · Kubernetes, k3s, RKE2, Helm, Argo CD (Apache-2.0)One install method from a single VPS to a multi-node cluster
ObservabilityPrometheus · Alertmanager · VictoriaLogs · Jaeger · OpenTelemetry · Grafana OSSPrometheus, Alertmanager, VictoriaLogs, Jaeger, OpenTelemetry (Apache-2.0) · Grafana OSS (AGPL-3.0, unmodified)Open standards; .NET and Python both export OpenTelemetry natively
SecurityOpenBao · Trivy · OWASP ZAP · Falco (optional)OpenBao (MPL-2.0) · Trivy, OWASP ZAP, Falco (Apache-2.0)Secrets, image scanning, DAST, runtime detection
Copilot (Phase 3)Open-weight LLM served locally · pgvector · Semantic Kernel (.NET)Semantic Kernel (MIT) · pgvector (PostgreSQL) · open-weight LLM (Apache-2.0 models only)Data stays in-house; integrates with the .NET API and its permissions

Open-source licence policy

100% open source, zero licence fees. Every component uses an OSI-approved open-source licence and can be used, sold and deployed at no licence cost, now and if the product is sold later.
  • Allowed: permissive licences (MIT, Apache-2.0, BSD, PostgreSQL). Weak copyleft (LGPL, MPL, EPL) and copyleft (GPL, AGPL) only for tools used unmodified and run as separate services, so they place no obligations on our own code.
  • Not allowed: source-available licences (BSL, SSPL, RSAL, Elastic, Timescale License), "open-core" paid tiers, proprietary SDKs, and libraries that have moved to commercial licences. This is why the design uses Apache Kafka instead of Redpanda, Mosquitto instead of EMQX, ClickHouse instead of TimescaleDB's licensed features, Valkey instead of Redis, SeaweedFS instead of MinIO, OpenBao instead of HashiCorp Vault, Assimp instead of the Autodesk FBX SDK, Locust instead of k6, and Wolverine / Mapster instead of MassTransit, MediatR and AutoMapper.
  • Enforced in CI: a licence scan (OSS Review Toolkit) checks every NuGet, npm and Python dependency and container image; a disallowed licence fails the build. The approved-licence list and the component register below are reviewed every quarter.
  • Running costs that remain (not licences): servers / VPS / cloud hosting, SMS messages and domain names. No app-store accounts are needed because there is no native mobile app.

Component licence register

AreaComponentsLicenceType / use
Back endASP.NET Core, .NET, EF CoreMITPermissive
Back endWolverine (outbox, inbox, sagas)MITPermissive
Back endNpgsql · ClickHouse.Client · Confluent.Kafka clientPostgreSQL · MIT · Apache-2.0Permissive
Back endQuartz.NET · FluentValidation · Mapster · Polly · Serilog · UnitsNet · ClosedXML · ScalarApache-2.0 / MIT / BSDPermissive
PythonPython, bacpypes3, FastAPI, pandas, statsmodels, scikit-learn, LightGBMPSF / MIT / BSDPermissive
BIMIfcOpenShellLGPL-3.0Weak copyleft: used unmodified in a separate worker
BIMAssimp · ufbx · That Open Engine · web-ifc · Three.jsBSD-3 · MIT · MIT · MPL-2.0 · MITPermissive / weak copyleft (unmodified)
DataPostgreSQL · Patroni · pgBackRest · pgvectorPostgreSQL · MIT · MIT · PostgreSQLPermissive
DataClickHouse + ClickHouse KeeperApache-2.0Permissive
MessagingApache Kafka · Kafbat UIApache-2.0Permissive
MessagingEclipse MosquittoEPL-2.0 / EDL-1.0Weak copyleft: used unmodified
DataValkeyBSD-3-ClausePermissive
DataSeaweedFSApache-2.0Permissive
SecurityKeycloakApache-2.0Permissive
SecurityOpenBao (secrets)MPL-2.0Weak copyleft: used unmodified
SecurityTrivy · OWASP ZAP · gitleaks · cosign · Falco · Semgrep CEApache-2.0 / MIT / LGPL-2.1Permissive / weak copyleft (tools)
SecurityWazuh (optional SIEM)GPL-2.0Copyleft: separate tool, unmodified
PlatformKubernetes · k3s · RKE2 · Helm · Argo CD · Argo Rollouts · Traefik · cert-managerApache-2.0 / MITPermissive
ObservabilityPrometheus · Alertmanager · VictoriaLogs · Jaeger · OpenTelemetryApache-2.0Permissive
ObservabilityGrafana OSS (dashboards)AGPL-3.0Copyleft: separate ops tool, unmodified (alternative: Perses, Apache-2.0)
Front endReact · Vite · MUI Core · Apache ECharts · i18next · MapLibre GL · html5-qrcodeMIT / Apache-2.0 / BSD-3Permissive (MUI Core only, not the paid MUI X Pro / Premium)
TestingxUnit · Testcontainers · Pact · Locust · Chaos Mesh · PlaywrightApache-2.0 / MITPermissive
FeaturesOpenFeature · flagdApache-2.0Permissive
AI (Phase 3)Semantic Kernel · open-weight LLMMIT · Apache-2.0 models onlyPermissive

Open source vs licensed software: how to decide

Each component can be either free open source or licensed (commercial). Neither is always better. The comparison below sets out the trade-offs so the team can decide component by component.

Open source: advantages

  • No licence fees, now or as sites, users and servers grow
  • Product can be sold without paying royalties or OEM fees per client
  • No vendor lock-in; runs on-prem, VPS, any cloud and offline
  • Full source code: security audits, fixes and customisation are possible
  • Large communities and widely available skills

Open source: disadvantages

  • No guaranteed support SLA unless a support contract is bought
  • Our team owns installation, upgrades, tuning and security patching
  • Some enterprise features (admin consoles, geo-replication, advanced grids) are missing or need building
  • Licence-change risk: some projects have moved to restrictive licences (prefer foundation-governed projects)
  • Some clients' procurement teams prefer a named vendor to hold accountable

Licensed: advantages

  • Vendor support with SLAs and a single party accountable
  • Enterprise features ready: management UIs, replication, audit, compliance reports
  • Faster delivery for some features (advanced grids, BIM viewing, reporting designers)
  • Certifications and hardened builds that help in audits
  • Training and certified partners available

Licensed: disadvantages

  • Recurring costs per core, node, user or GB that grow with every building
  • Selling the product needs redistribution / OEM licences, adding cost to every client
  • Vendor lock-in, price increases and roadmap dependence
  • Licence audits and compliance tracking
  • Some products are cloud-only or need online activation, which conflicts with air-gapped on-prem installs
Middle path: open source with paid support. Many components can be used free and backed by an optional support contract when needed (for example commercial support for PostgreSQL, Kafka or Keycloak). This gives vendor SLAs without licence lock-in, and support can be dropped later without changing the software.

Decision criteria

QuestionPoints to open source when…Points to licensed when…
Will we sell the product?Yes: avoids per-client licence costs and redistribution limitsInternal only and a vendor allows the use case at a fair price
Team skillsTeam can run Linux, Kubernetes, PostgreSQL, KafkaSmall team without platform / DevOps experience
Support expectationsInternal SLA is acceptable, or a support contract can be addedClient contract requires a vendor-backed SLA for that component
DeploymentOn-prem, air-gapped, VPS or multi-cloudA single cloud with that vendor's managed service
Time to marketFeature is simple or the open-source tool is matureA licensed component saves months (e.g. advanced data grid)
Budget modelPrefer spending on people and hardware, not licencesPrefer predictable subscriptions over building in-house expertise

Component-by-component comparison

ComponentOpen-source optionLicensed alternativeOpen source: + / −Licensed: + / −Recommendation
Event busApache KafkaConfluent Platform; Redpanda Enterprise+ Free; industry standard; huge skills pool
− You run upgrades and tuning; admin UI is basic
+ Vendor support; management UI, tiered storage, connectors
− Per-core / node subscription; lock-in to vendor tooling
Open source; buy Kafka support only if the team lacks experience
MQTT brokerEclipse MosquittoEMQX Enterprise; HiveMQ Enterprise+ Free; very stable and light; easy to run
− No built-in clustering (active / standby only); basic dashboard
+ Clustering to millions of devices; rule engine; web console; support
− Per-connection / node pricing; licence needed per client if resold
Open source (a few hundred gateways do not need clustering)
Time-series databaseClickHouseTimescaleDB licensed features / cloud; InfluxDB Enterprise+ Free; excellent compression and speed; scales out
− Second database to operate; SQL dialect differs from PostgreSQL
+ Single PostgreSQL engine (Timescale); vendor support; managed cloud
− Licence limits on resale / hosting (Timescale License); subscription
Open source (ClickHouse)
Business databasePostgreSQLMicrosoft SQL Server; Oracle+ Free; mature; strong .NET support; no core limits
− Support from community or a third party
+ Familiar to many enterprise DBAs; vendor support; built-in tooling
− Per-core licences grow with every site; resale needs licences per client
Open source; optional commercial PostgreSQL support
CacheValkeyRedis Enterprise / Redis Software+ Free; Redis-compatible; Linux Foundation governance
− Newer brand; no vendor SLA
+ Active-active geo replication; support; modules
− Subscription; Redis's own licence changed in 2024
Open source
Object storageSeaweedFS (or any cloud S3)MinIO AIStor; NetApp / Dell object storage+ Free; S3 API; light
− Smaller community; fewer enterprise features (e.g. object lock varies)
+ Mature UI, object lock, support, appliances
− Capacity-based pricing; hardware lock-in for appliances
Open source on-prem; provider S3 in cloud
Secrets managementOpenBaoHashiCorp Vault Enterprise; cloud KMS / Key Vault+ Free; Vault-compatible API; Linux Foundation
− Younger project; community support
+ Support, HSM integration, replication, namespaces
− Expensive enterprise tiers; cloud KMS ties you to one cloud
Open source; use cloud KMS where already in a cloud
Messaging / sagas libraryWolverineNServiceBus; MassTransit v9+ Free (MIT); outbox, inbox, sagas built in
− Smaller vendor; community support
+ Very mature; commercial support; monitoring tools (ServicePulse)
− Per-endpoint / per-core licences; resale costs
Open source; NServiceBus if the team wants a support contract
Identity / SSOKeycloakMicrosoft Entra ID; Auth0 / Okta+ Free; runs offline on-prem; full SSO / MFA
− You host, patch and back it up
+ Fully managed; strong security features; easy social / enterprise logins
− Per-user monthly pricing; cloud only (no air-gapped install)
Open source; federate to the client's Entra ID / AD when they have one
BMS gatewayPython bacpypes3 gatewayTridium Niagara (JACE / Supervisor); commercial BACnet stacks+ Free; full control; small hardware
− We build and maintain the BACnet logic
+ Proven with Honeywell / JCI; drivers for many protocols; integrator ecosystem
− Licence per device / point count; annual maintenance; vendor tooling
Open source gateway; consider Niagara only if the site already has it
3D / BIM viewerThree.js + That Open Engine + IfcOpenShellAutodesk Platform Services (APS) Viewer; xeokit commercial+ Free; works offline; full control of UI
− More development effort for large models
+ Very fast on huge models; Revit support; less dev work
− Pay-per-use cloud APIs (no offline); or commercial licence per product
Open source; revisit if very large models perform poorly
UI componentsMUI Core + Apache EChartsMUI X Pro / Premium; DevExpress; Telerik; Syncfusion; Highcharts+ Free; large ecosystem
− Advanced data grid (Excel-like grouping, pivot) must be built or simplified
+ Ready-made advanced grids, schedulers, Gantt; faster delivery
− Per-developer licences; renewals for updates
Open source; buy a grid licence only if CMMS screens need pivot / Excel-like grids
Reports / PDFHTML templates + PlaywrightTelerik Reporting; SSRS; Crystal Reports+ Free; same templates on screen and PDF
− Report designer for business users not included
+ Visual designer for non-developers; many export formats
− Per-developer / server licences; extra runtime
Open source
Kubernetes platformk3s / RKE2Red Hat OpenShift; SUSE Rancher Prime+ Free; light; runs on one VPS
− Self-support; we design the operations
+ Hardened, certified, support, built-in CI / registry
− Per-core subscriptions; heavier footprint
Open source; managed K8s in cloud
MonitoringPrometheus, VictoriaLogs, Jaeger, Grafana OSSDatadog; Dynatrace; Grafana Enterprise / Cloud+ Free; runs on-prem and offline
− Setup and dashboards are our work
+ Fast setup, AI alerting, support
− Per-host / per-GB pricing grows quickly; SaaS sends data off-site
Open source
SIEMWazuh or the client's SIEMSplunk; Microsoft Sentinel; IBM QRadar+ Free; good detection rules
− Needs tuning and a security team to watch it
+ Mature analytics, SOC tooling, compliance reports
− Ingest-based pricing is expensive
Forward to the client's existing SIEM; Wazuh otherwise
Feature flagsOpenFeature + flagdLaunchDarkly+ Free; self-hosted
− Basic UI
+ Rich UI, experiments, audit
− Per-seat / MAU pricing; SaaS
Open source

Overall recommendation: use open source for the whole platform (lowest cost, no lock-in, safe to sell), and add paid support contracts only for the components where the team wants a vendor safety net: typically PostgreSQL, Kafka and Keycloak. Consider buying a licence in only two cases: an advanced data grid if the CMMS screens need Excel-like features, and Tridium Niagara if a site already runs it.

4Edge gateway and BACnet ingestion

One gateway per building (or BACnet segment) reads Honeywell and JCI controllers and streams readings to the platform. It needs no inbound access and keeps working alone if the uplink drops.

1 · Config pullsigned point list & schedule from platform
›
2 · DiscoverWho-Is / I-Am, object lists, EDE import
›
3 · ReadReadPropertyMultiple + SubscribeCOV
›
4 · Filterdeadband + 5 min heartbeat
›
5 · BufferSQLite WAL, ≥ 72 h
›
6 · PublishMQTT/TLS, QoS 1, gzip batches

Collection frequency (configurable per point)

Data classDefaultAllowed rangeMethod
Critical analog (supply/return temps, pressures)15 s5 s – 5 minRPM poll or COV
Normal analog (zone temps, valve positions)60 s15 s – 15 minRPM poll
Binary status / alarmsOn change + 5 min heartbeat—COV, event notification
Energy meters60 s (kW), 15 min (kWh)15 s – 60 minRPM poll
Indoor air quality5 min1 – 15 minRPM poll
Setpoints / configuration15 min1 – 60 minRPM poll

Live values reach the dashboard within 5 s (p95) of arriving at the platform. 15-minute and hourly roll-ups for the current period refresh every minute.

Topics and message format

MQTT topics: t/{tenant}/s/{site}/gw/{gateway}/{data|events|health|config|cmd}

{
  "gw": "GW-RUH-01", "profile": "jci", "batch_id": "01JDX4Q8V7K2",
  "sent_at": "2026-11-30T10:15:00.120Z",
  "readings": [
    { "dev": 3001, "obj": "analog-input:12", "name": "AHU-01.SAT",
      "pv": 13.8, "units": 62, "sf": [0,0,0,0], "ts": "2026-11-30T10:15:00.020Z" }
  ]
}

Hardware (proposed)

Fanless industrial PC or VM · 4 cores · 8 GB RAM · 256 GB SSD · 2 NICs (OT VLAN + uplink) · NTP time sync.

Redundancy

Optional active/standby pair for critical sites; standby takes over if heartbeats stop for 60 s.

Remote updates

Signed container images; automatic rollback if health checks fail after an update.

5Normalisation pipeline

Every reading passes through one normaliser before any module sees it. Raw batches arrive in each vendor's shape and leave as canonical readings keyed by point_id. Anything that can't be parsed or mapped is held, never dropped.

Verifysignature, gateway identity
›
Adapterhoneywell · jci · generic-bacnet · mqtt-json · csv
›
Identity(gateway, device, object) → point_id
›
UnitsBACnet enum → canonical (UnitsNet)
›
QualityStatus_Flags, Reliability, range, skew
›
Canonicalcanonical.readings
Unmapped→ discovered.points (admin maps it)
Failed→ dlq.readings + alert, replay after fix
Raw archive30 days in object storage for re-processing

Topics

TopicKeyRetention
raw.readingsgateway7 d
canonical.readingspoint_id7 d
dlq.readingsgateway30 d
discovered.pointsgateway30 d
gateway.healthgateway7 d
alarm.eventsasset30 d
domain.eventsaggregate30 d

Canonical reading

{
  "tenant_id": "t-internal",
  "point_id": "pt_8f2c1a",
  "ts": "2026-11-30T10:15:00.020Z",
  "value": 13.8, "unit": "degC",
  "quality": "good",
  "source": { "vendor": "jci", "gateway": "GW-RUH-01",
              "device": 3001, "object": "analog-input:12" },
  "flags": [], "mapping_version": 14,
  "received_at": "2026-11-30T10:15:00.410Z"
}

Adapter plug-in interface (C#)

public interface IVendorAdapter
{
    string Profile { get; }                                  // "honeywell", "jci", ...
    IReadOnlyList<RawRecord> Parse(ReadOnlySpan<byte> batch, GatewayMeta meta);
    Quality GetQuality(RawRecord record);
    string SourceUnit(RawRecord record);
}

Idempotent: a reading is unique on (point_id, ts); ClickHouse insert de-duplication (batch ID) plus a table keyed on point and timestamp mean replays never duplicate data (section 8A). Re-processing: after a mapping fix, raw batches for any time range can be replayed with the new mapping_version.

6Data storage and data model

PostgreSQL holds the twin, CMMS, configuration, outbox and sagas, split into a schema per module. Time-series readings live in ClickHouse, a column store built for sensor data. Files live in S3-compatible storage. Every table carries tenant_id: enforced by row-level security in PostgreSQL and by tenant-scoped queries and partitions in ClickHouse.

SchemaMain tablesOwner
twinlocation, position, asset, asset_install, point, point_binding, device, gateway, bim_model, bim_element, documentTwin
ts (ClickHouse)readings, readings_text, rollup_15m / rollup_1h / rollup_1dPipeline
alarmalarm_rule, alarm, alarm_event, fdd_rule, faultAlarms & FDD
cmmswork_order, wo_task, wo_log, ppm_plan, ppm_schedule, part, stock, stock_move, team, technician, sla_policy, service_requestCMMS
energymeter, tariff, baseline_model, target, enpi_value, recommendation, savingsEnergy
opsoutbox, inbox, saga_instance, saga_stepPlatform
audit / cfgaudit_log (append-only), tenant, site_setting, retention_policy, notification_ruleAdmin

Key tables (main columns)

TableMain columnsKeys and indexes
twin.locationid, tenant_id, parent_id, path (ltree), type, code, name, area_m2, capacity, bim_guidPK id; GiST on path; unique (tenant_id, code)
twin.positionid, tenant_id, location_id, asset_code, asset_class (Brick), criticality, status, bim_element_idUnique (tenant_id, asset_code)
twin.assetid, tenant_id, make, model, serial_no, install_date, warranty_end, attributes jsonbUnique (tenant_id, make, serial_no)
twin.asset_installid, position_id, asset_id, from_ts, to_ts, work_order_idExclusion constraint: one active install per position
twin.pointid, point_key (int), tenant_id, position_id, brick_class, unit, kind, interval_s, deadband, min, max, gateway_id, bacnet_device, bacnet_objectUnique (gateway_id, bacnet_device, bacnet_object)
ts.readings (ClickHouse)tenant_id, point_key, ts, value, quality, flags, batch_idReplacingMergeTree, ORDER BY (tenant_id, point_key, ts); monthly partitions; TTL retention
alarm.alarmid, tenant_id, rule_id, point_id, position_id, severity, priority, state, first_seen, last_seen, count, acked_by, acked_atPartial unique (rule_id, point_id) where state is active
cmms.work_orderid, tenant_id, number, type, priority, status, position_id, fault_id, ppm_plan_id, due_date, sla_due, assignee_id, row_versionUnique (tenant_id, number); partial unique (fault_id) where open; unique (ppm_plan_id, due_date)
ops.idempotency / Wolverine envelopes / saga tablesSee sections 8 and 8A—

Every table also has created_at, created_by, updated_at, updated_by and a row_version for optimistic locking. Deletes of business records are soft deletes (deleted_at), purged by the retention job.

Asset codes when equipment is modified, replaced or added

Position

The functional location with the permanent asset code, e.g. RUH-B1-L03-AHU-01. BACnet points and BIM elements bind here.

Asset

The physical, serialised unit: make, model, serial, warranty, its own maintenance history.

Asset install

Which asset sat in which position, from / to dates, and the work order that made the change.

EventWhat the system does
Replaced like-for-likeClose the old install record, open a new one with the new serial. Asset code, points, BIM link and trends continue unchanged.
Modified (new motor, firmware)Asset updated with a version entry in its history; position unchanged.
Newly installedNew position created (code from the site naming rule, editable), linked to the BIM element and to points found by BACnet discovery.
Controller replaced (new BACnet IDs)Admin re-binds the discovered points to the same position; history stays on the position.
RemovedPosition decommissioned; data kept under the retention policy.

These changes are triggered by closing a Replacement / Installation work order, which runs the Asset Change saga (section 8).

Time-series storage (ClickHouse)

  • Raw readings in ts.readings, ordered by tenant, point and time, partitioned by month and compressed column by column (typically around 10× smaller than row storage).
  • Roll-ups (15 min, 1 h, 1 day: avg, min, max, last, count, meter deltas) are written by a roll-up job every minute. It recomputes the recent buckets from de-duplicated raw data and overwrites them, so re-running it is always safe.
  • Retention uses ClickHouse TTL per table; before a partition expires it is exported to Parquet in object storage.
  • Small pilots can run ClickHouse on the same server as PostgreSQL; larger sites add replicas and shards (section 15).

Retention and archival (defaults, configurable per tenant)

Data classOnlineArchive
Raw readings (full resolution)13 months (columnar compression)Monthly Parquet in object storage, 7 years
15-min aggregates3 yearsIn the Parquet archive
Hourly / daily aggregates7 years—
Raw gateway payloads—30 days
Alarms, faults, events3 yearsParquet, 7 years
Assets, work orders, CMMS historyLife of asset + 7 years—
Audit log7 years, append-only—

Archived data can be brought back on demand: pick a date range and ClickHouse queries the Parquet files in object storage directly, or loads them into a temporary table. Legal hold stops deletion.

Sizing estimate (to be validated with the simulator): a 50,000-point building at ~1 reading/point/min produces ~72 million readings/day, roughly 0.3–0.6 GB/day after ClickHouse compression, or about 100–200 GB per year. A 5,000-point pilot needs about one tenth.

7Module design

The Core API is one deployable ASP.NET Core application made of independent modules (one .NET project per module). Each module owns its schema and talks to others only through service interfaces and events, never through another module's tables, so any module can be split into its own service later.

Twin Phase 1

  • Locations, positions, assets, points, BIM links, documents
  • Location tree with PostgreSQL ltree
  • Brick classes on points
  • Publishes: AssetInstalled, PointBound, ModelImported

Live Phase 1

  • Last value per point in Valkey
  • WebSocket subscriptions per floor / asset
  • Changes only, max 1 update/point/s
  • Trend queries from aggregates

Alarms & FDD Phase 1

  • Threshold, rate-of-change, BACnet native alarms
  • FDD rules on time windows
  • Priority, ack, shelve, escalate
  • Publishes: AlarmRaised, FaultDetected

CMMS Phase 1

  • Work order state machine with SLA timers
  • PPM: calendar, run-hours, condition triggers
  • Spares, stock, teams, contractors, requests
  • Technician view for phones / tablets (browser)

Energy Phase 1

  • Meters, virtual meters, tariffs
  • Baselines, EnPIs, EUI, SEUs, targets
  • Recommendations and savings tracking
  • Forecasts (Phase 2)

Portfolio Phase 1

  • Cross-building KPIs and league tables
  • Read models refreshed from events
  • Drill-down in ≤ 3 clicks

Reports & Notifications Phase 1

  • HTML templates → PDF / Excel
  • Routing by event, severity, location, role
  • Email, SMS, in-app; on-call schedules

Admin & Integration Phase 1

  • Sites, gateways, adapters, mappings
  • Retention, users, roles
  • Integration health dashboard

Sustainability · Wellbeing · Space Phase 2

  • Scope 1/2/3, ESG reports, certifications
  • Comfort indices, IAQ alarms
  • Occupancy and utilisation

Module interactions

ModulePublishesConsumes
TwinAssetInstalled, PointBound, ModelImporteddiscovered.points, BimConverted
Alarms & FDDAlarmRaised / Acked / Cleared, FaultDetectedcanonical.readings, gateway.health
CMMSWorkOrderCreated / Assigned / Closed, PartsReservedFaultDetected, AlarmRaised, AssetInstalled
EnergyRecommendationIssued, OverconsumptionDetectedreading aggregates
NotificationsNotificationSentAlarmRaised, WorkOrder*, ReportGenerated
Copilot Phase 3—All read APIs (respects user permissions)

API conventions

  • REST under /api/v1, OpenAPI 3.1, a generated TypeScript client for the web app and for integrations.
  • Cursor pagination, filter by location subtree, ETag optimistic locking, Idempotency-Key on every write.
  • WebSocket channels: points:{ids}, alarms:{location}, workorders:{team}.
  • Integration API: OAuth2 client credentials with scoped tokens; signed (HMAC) webhooks with retry and back-off.

8Reliable messaging: Outbox, Inbox and Saga

Every business change and the event announcing it are saved in one database transaction (outbox). Every consumer records what it has processed (inbox), so duplicates are ignored. Processes that span several modules or workers run as orchestrated sagas with a compensating action for each step.

Transactional outbox (Wolverine)

1 · Commande.g. close work order
›
2 · One DB transactionEF Core saves the work order; Wolverine stores the outgoing event in the same transaction
›
3 · Durability agentsends stored envelopes after commit, retries on failure
›
4 · Publishto domain.events on Kafka
›
5 · Consumer inboxduplicate envelopes ignored, processed once
// Close a work order: state change + event are committed together
public static async Task Handle(CloseWorkOrder cmd, CmmsDbContext db,
                                IDbContextOutbox<CmmsDbContext> outbox)
{
    var wo = await db.WorkOrders.FindAsync(cmd.WorkOrderId);
    wo.Close(cmd.ClosedBy, cmd.Notes);
    await outbox.PublishAsync(new WorkOrderClosed(wo.Id, wo.PositionId, wo.Type));
    await outbox.SaveChangesAndFlushMessagesAsync();   // one transaction
}
  • Storage: Wolverine keeps outgoing and incoming envelopes in PostgreSQL tables in the ops schema, next to the business data.
  • Inbox: every consumer de-duplicates by message ID, so redeliveries and replays are processed once.
  • Ordering: events are keyed by aggregate ID, so all events for one work order or asset stay in order.
  • Retries: exponential back-off, then a dead-letter queue with an admin alert.
  • Used between modules inside the monolith too, so boundaries are already event-based when a module is split out.

Saga orchestration (Wolverine sagas)

Each long-running process is a Wolverine Saga class whose state is saved in PostgreSQL. It sends commands through the outbox, reacts to reply events, schedules timeout messages, and runs compensations in reverse order if a step fails. Saga state survives restarts and is visible on an admin screen.

public class FaultToWorkOrderSaga : Saga
{
    public Guid Id { get; set; }                 // = fault id
    public Guid? WorkOrderId { get; set; }
    public bool PartsReserved { get; set; }

    public static (FaultToWorkOrderSaga, CreateWorkOrder) Start(FaultDetected e) => ...
    public ReserveParts Handle(WorkOrderCreated e) => ...
    public AssignTechnician Handle(PartsReserved e) => ...
    public PutOnHold Handle(PartsUnavailable e) => ...        // compensation path
    public CancelWorkOrder Handle(FaultCleared e) => ...       // compensation path
    public void Handle(TechnicianAssigned e) => MarkCompleted();
}

Saga 1 — Fault to work order

Forward steps
FaultDetectedFDD engine
›
Create WOCMMS (dedupe open WO)
›
Reserve partsinventory
›
Assignby skill, location, shift
›
Notifytechnician + supervisor
›
Donelink fault ↔ WO
Compensations
Parts unavailableWO → On hold, create purchase request
No technicianrelease parts, escalate to supervisor queue
Fault cleared before startcancel WO, release parts, log auto-resolve

Saga 2 — Asset change (replace / install)

WO closedtype Replacement
›
Update twinclose old install, open new
›
Re-bind pointsif BACnet IDs changed
›
Update PPMnew plan for new model
›
Stockconsume part, return old

Compensation: if point re-binding or PPM update fails, the twin change is reverted and the WO goes back to Completed – needs review.

Other sagas

SagaStepsCompensation
BIM importUpload → convert (BIM worker) → extract elements → admin review → commit to twinDelete converted files and staged records; keep the previous model version live
PPM generationGenerate WOs for the window → reserve parts → schedule techniciansRemove generated WOs for the failed batch, release parts
Tenant exportSnapshot → export tables / Parquet / files → package → signed download linkDelete partial packages
BMS write-back Phase 3Approve → send command to gateway → WriteProperty → verify read-back → monitorRelinquish the command (restore previous value) if verify fails or the effect is out of limits

8AIdempotency

Every message in the platform is delivered at least once: networks drop acknowledgements, gateways replay their buffers, Kafka redelivers after a restart, and users double-click. Every receiver is therefore idempotent, so processing the same thing twice has the same effect as processing it once. At-least-once delivery plus idempotent receivers gives effectively-once results end to end.

Rule 1: Every message has a stable ID

Batch ID, event ID, command ID or a natural key, chosen by the sender and never regenerated on retry.

Rule 2: The receiver remembers

A unique constraint, an inbox table or a stored response records what was already done, in the same transaction as the work.

Rule 3: Retries are safe by design

Duplicates are ignored or return the original result; they never create a second record, alarm, work order or notification.

Idempotency at each layer

LayerWhere duplicates come fromIdempotency keyMechanism
Edge gateway → brokerMQTT QoS 1 resends; buffer replay after an outagebatch_id (ULID) + per-gateway sequence numberGateway keeps the same batch_id on every resend; it deletes a batch from its buffer only after the broker acknowledges it
Ingest bridge → KafkaProducer retries after a timeoutKafka producer ID + sequenceIdempotent producer (enable.idempotence=true, acks=all); a short-lived cache of recent batch_ids drops repeated batches
NormaliserKafka redelivery after a crash or rebalance(point_id, ts)Pure, deterministic transformation: the same input always gives the same canonical reading; offsets are committed after publishing
TS writer → ClickHouseRedelivered or replayed readingsbatch_id + (point_key, ts)Insert de-duplication token = batch ID drops repeated batches; ReplacingMergeTree collapses any remaining duplicate rows; queries read de-duplicated values
Valkey last valueLate or out-of-order readingsReading timestampAtomic script updates the value only if the new ts is newer than the stored one
Live hub → browserReconnects, repeated pushes(point_id, ts)Client keeps the latest timestamp per point and ignores older or equal updates
Alarm engineSame condition seen in several readings or after a restart(rule_id, point_id) while activePartial unique index: only one active alarm per rule and point; repeats update the existing alarm's last-seen time and count
Module events (Wolverine)Outbox resend, Kafka redeliveryMessage ID (envelope)Inbox: each consumer records processed message IDs in the same transaction as its work
SagasRepeated or late reply eventsSaga ID + stepSaga state checks the current step; a reply for a step already completed is ignored
Fault → work orderSame fault detected againfault_idUnique partial index: only one open work order per fault; a repeat attaches to the open one
PPM generationJob retried or run twice(ppm_plan_id, due_date)Unique constraint on generated work orders
NotificationsEvent redelivered, escalation re-run(event_id, recipient, channel)Unique key in the notification log; checked before sending to the email / SMS provider, which also receives the key where supported
Scheduled reportsScheduler retry(schedule_id, period)Unique key; a repeat returns the existing report file
REST API writesDouble-clicks, client and proxy retriesIdempotency-Key header (client UUID)Stored with a hash of the request and the response for 24 h; a repeat returns the stored response (details below)
Technician web viewForm re-submitted after a weak phone connectionIdempotency-Key per form submission + client-generated record UUIDsA repeat submission returns the original result; photo uploads are keyed by UUID, so a retry never creates a second copy
BIM importSame file uploaded againSHA-256 of the fileHash match offers to reuse the existing converted model instead of re-processing
BMS write-back (Phase 3)Command retriedcommand_idGateway remembers executed command IDs for 24 h and never writes the same command twice

REST API: Idempotency-Key

1 · Requestclient sends Idempotency-Key: <uuid>
›
2 · Look upkey + user + endpoint in ops.idempotency
›
3a · Newinsert key as in progress, run the command, store the response
›
3b · Seen, donereturn the stored response (same status and body)
›
3c · Mismatch / busydifferent body → 422; still running → 409
-- ops.idempotency
CREATE TABLE ops.idempotency (
  tenant_id     uuid        NOT NULL,
  user_id       uuid        NOT NULL,
  key           uuid        NOT NULL,
  endpoint      text        NOT NULL,
  request_hash  bytea       NOT NULL,          -- SHA-256 of method + path + body
  status        text        NOT NULL,          -- in_progress | completed
  response_code int,
  response_body jsonb,
  created_at    timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, user_id, key)
);   -- rows older than 24 h are purged nightly
// ASP.NET Core endpoint filter applied to all POST / PUT / PATCH / DELETE
app.MapGroup("/api/v1")
   .AddEndpointFilter<IdempotencyFilter>()       // looks up / stores ops.idempotency
   .RequireAuthorization();

-- Readings in ClickHouse: idempotent by design
CREATE TABLE ts.readings (
  tenant_id LowCardinality(String), point_key UInt32,
  ts DateTime64(3, 'UTC'), value Float64, quality UInt8, flags UInt16, batch_id String
) ENGINE = ReplacingMergeTree
PARTITION BY toYYYYMM(ts)
ORDER BY (tenant_id, point_key, ts)
TTL toDateTime(ts) + INTERVAL 13 MONTH          -- exported to Parquet before expiry
SETTINGS non_replicated_deduplication_window = 1000;

-- TS writer: INSERT ... SETTINGS insert_deduplication_token = '<batch_id>' 
Testing. The simulator's data-problem mode sends duplicate and replayed batches, and integration tests run each handler twice with the same input, asserting the database state is identical after the second run.

9BIM pipeline — IFC, FBX and manual

IFC and FBX files (with all MEP components) are imported to build the twin. Each format is a separate import plug-in, so Revit, Navisworks, glTF, OBJ or COBie can be added later.

UploadIFC / FBX + optional asset list
›
ConvertIfcOpenShell / Assimp → glTF + Fragments
›
Extractstoreys, spaces, MEP elements, properties
›
ClassifyIFC classes or FBX name rules
›
Reviewadmin fixes / excludes
›
Commitpositions, assets, BIM links
TopicIFCFBX
Floors & spacesIfcBuildingStorey, IfcSpaceNode hierarchy / layer names, or manual
MEP typesIFC classes + property setsName rules (e.g. AHU-* → Air Handling Unit) or companion list
PropertiesProperty setsFBX user properties or companion Excel / CSV
Stable IDIFC GlobalIdObject name + hash of hierarchy path

Manual route: create or edit floors, spaces and assets in the app, bulk import from Excel / CSV, and link assets by clicking objects in the 3D view. Re-import of an updated model shows a diff and keeps all asset, point and work order links. Original files are versioned in object storage.

10Alarms, fault detection and work orders

Alarms come from four sources, are scored by severity and asset criticality, routed to the right people, and escalate automatically if nobody acknowledges them.

BACnet native

Event notifications from Honeywell / JCI controllers.

Threshold

High/low limits, rate of change, deviation from setpoint, with delay and deadband.

FDD

Diagnostic rules over time windows (e.g. simultaneous heating & cooling, stuck valve, short cycling).

Data & comms

Stale or flat-lining sensors, device / gateway offline, data gaps, DLQ spikes.

Priority matrix (severity × asset criticality)

Severity ↓ / Criticality →A (critical)B (important)C (normal)
CriticalP1P1P2
MajorP1P2P3
MinorP2P3P4
InfoP4P4P4

Alarm lifecycle and escalation (defaults, configurable)

Raiseddedupe, flood suppression
›
Notifiedby rules & on-call
›
EscalateP1: 10 min → supervisor, 30 min → FM
›
Acknowledgedweb (desktop or phone), with note
›
Work orderauto (rule) or one click
›
Cleared & closedroot cause recorded

Flood suppression: if a gateway or device goes offline, its child point alarms are suppressed and one "communication lost" alarm is raised instead. Shelving hides an alarm for a set time with a reason, and is audited.

Sensor faults, abnormal readings, communication failures, data loss

CheckRule (default)Result
Stale valueNo reading for 3× the expected intervalPoint marked stale, data alarm
Flat-lineAnalog value unchanged for 6 h while equipment runsSuspect sensor fault
Out of rangeOutside physical limits for its Brick class (e.g. zone temp < 5 °C or > 50 °C)Quality = bad, value excluded from KPIs
SpikeRate of change above the class limit, or robust z-score > 5Quality = suspect
DriftGap vs a redundant or related sensor grows over daysFDD fault: calibration needed
Device offlineBACnet device fails 3 polls in a rowComms alarm, child alarms suppressed
Gateway offlineNo heartbeat for 90 sP1/P2 comms alarm; data back-filled on return
Data gapsMissing intervals in aggregatesBack-fill from gateway buffer or controller Trend Logs; gaps shown on charts

11Energy analytics

Energy data is correlated with weather, occupancy and equipment state through the twin, then turned into KPIs, gaps and ranked recommendations.

Metersphysical + virtual (formulas)
›
Contextweather, occupancy, schedules, tariffs
›
Baselineregression on CDD, occupancy, hours (nightly refit)
›
KPIsEnPIs, EUI, SEU ranking, cost
›
Gapactual vs target & baseline
›
Recommendranked by saving; M&V

Examples of EnPIs

kWh/m², kWh/occupant, chiller kW/TR, plant COP, after-hours baseload %, peak kW.

Recommendation example

"Reset AHU-03 supply-air setpoint 12 → 14 °C during low load: est. 4,200 kWh / month." Tracked until savings are verified (IPMVP option B/C).

Forecasting (Phase 2)

Day-ahead and month-ahead per building / floor with LightGBM on weather forecast, calendar and occupancy features; peak-demand alerts.

12Web front end (desktop, tablet and phone)

Web app (React + TypeScript)

  • Role-based home dashboards with drag-and-drop widgets (ECharts)
  • 3D twin: Three.js + That Open Engine; colour overlays for alarms, temperature, CO₂, occupancy
  • Asset card: live values, trends, alarms, WOs, documents, BIM position
  • English / Arabic with full RTL; dark and light themes
  • Code-split by module; 3D loads progressively per floor

Technician view (same web app, phone / tablet browser)

  • Responsive layout designed for phones and tablets; no app to install
  • My work orders, checklists, photos (camera upload), signatures, notes
  • QR / barcode scan through the browser camera to open an asset
  • Large touch targets, works over site Wi-Fi or mobile data
  • Alerts by SMS / email and in-app notifications; links open the right work order

13Deploy anywhere: on-premise, VPS or any cloud

The same container images and Helm charts install on an on-premise server, a single VPS, or any cloud (AWS, Azure, Google, Oracle, STC Cloud and others). Hybrid works too: gateways on site, platform in the cloud.

Profile S — single server / VPS

  • Docker Compose or single-node k3s
  • 8–16 vCPU, 32–64 GB RAM, 1 TB SSD (pilot / up to ~20k points)
  • All components on one machine; nightly off-site backup
  • Target 99.5% uptime

Profile M — on-prem HA cluster

  • RKE2 / k3s, 3 control + 3–5 worker nodes
  • Patroni PostgreSQL (3), ClickHouse (2 replicas + 3 Keeper), Kafka (3), Mosquitto (active / standby), Valkey Sentinel
  • Second site or cloud for DR
  • Target 99.9% uptime

Profile L — any cloud

  • Any managed Kubernetes (EKS, AKS, GKE, OKE, …)
  • Self-managed ClickHouse and PostgreSQL in-cluster (or the provider's managed PostgreSQL)
  • Provider S3 for object storage
  • Multi-zone; target 99.9%+

Portability rules

  • Only open protocols and APIs: PostgreSQL, S3, Kafka, MQTT, OIDC, OpenTelemetry. No provider-only services in the code path.
  • All configuration through environment variables and Helm values; secrets in OpenBao or Kubernetes secrets.
  • Fully offline install supported (air-gapped image bundle for on-prem).
  • Data residency set per tenant: for Saudi clients, the platform and backups must be hosted in-Kingdom.

14Security

Defence in depth: OT and IT networks are separated, every connection is encrypted and authenticated, and every action is logged.

OT zone (building)

  • Honeywell / JCI controllers
  • Edge gateway (read-only BACnet by default)
  • No inbound connections allowed
firewall
outbound 8883 only

Platform zone

  • DMZ: Traefik ingress + WAF, Mosquitto
  • App namespace: Core API, workers
  • Data namespace: PostgreSQL, Valkey, S3 (no public access)
firewall
HTTPS 443

Users

  • Corporate LAN / VPN
  • Phones / tablets via browser over TLS
  • SSO + MFA (Keycloak)
AreaControls
Encryption in transitTLS 1.2+ everywhere (MQTT, HTTPS, database, internal service mesh optional); mTLS with X.509 certificates for gateways
Encryption at restAES-256 disk / volume encryption; PostgreSQL and S3 encryption; encrypted backups; keys in OpenBao or the cloud KMS
Identity & accessSSO, MFA, role-based access scoped to portfolio / site / building; least privilege; session timeouts; service accounts with scoped tokens
ApplicationOWASP ASVS L2; input validation; rate limiting; CSP headers; dependency and image scanning (Trivy) in CI; DAST (ZAP) before release
OT safetyIEC 62443 zones and conduits; BACnet read-only by default; write-back only on allow-listed points with limits and automatic relinquish; BACnet/SC where supported
MonitoringCentral audit log (append-only); security alerts from logs and Falco; failed login and privilege-change alerts
TestingAnnual third-party penetration test; vulnerability scans every month; critical patches within 7 days

Incident response

Detectalerts, logs, reports
›
Triageseverity within 1 h
›
Containisolate, revoke keys, block
›
Notifyclient: high-severity within 4 h of confirmation
›
Eradicate & recoverpatch, restore from clean backup
›
Reviewroot-cause report within 5 working days

Personal-data breaches are reported to the regulator as required by the applicable law (for Saudi Arabia, PDPL: within 72 hours of becoming aware). Notification times are defaults to be confirmed in the support agreement. The full data breach response plan is in section 14A.

14AInformation security and data breach management

Security is run as a managed programme aligned with ISO/IEC 27001, IEC 62443, NCA ECC / CCC and the Saudi PDPL. This section covers governance, data classification and privacy, threats and their mitigations, hardening, key management, monitoring, ransomware protection, and the full data breach response plan.

1. Governance and ownership

RoleResponsibility
Security owner (CISO or delegate)Owns the security policy, risk register, exceptions and the incident response plan; reviews them every year
Data protection officer (DPO)Personal data inventory, privacy impact assessments, data subject requests, regulator notifications under PDPL
Platform / DevOps leadHardening, patching, backups, secrets, monitoring and on-call
Product / engineering leadSecure development lifecycle, threat models, fixing vulnerabilities within the SLA
Client contactReceives breach and incident notifications; approves OT access and write-back points

2. Data classification and handling

ClassExamples in this platformHandling rules
InternalBMS telemetry, aggregates, dashboards, energy KPIsEncrypted in transit and at rest; role-based access by site; normal retention
ConfidentialAsset register, CMMS history, BIM models, floor plans, network and point lists, reportsAs above + export logged and limited to authorised roles; watermarked PDF exports; no public sharing links
Personal (PDPL)User and technician names, emails, phone numbers, work logs, photos, signatures, occupant feedbackAs above + minimised, purpose-limited, retention-limited; access audited; subject to data subject rights; never used for unrelated purposes
RestrictedPasswords, keys, certificates, tokens, backups, audit logs, BMS write-back permissionsStored only in OpenBao / KMS or encrypted backups; never in code, logs or tickets; access by named administrators with MFA; every access logged

3. Personal data and privacy (PDPL)

  • Inventory: a register of every personal data field, its purpose, legal basis, retention and where it is stored.
  • Minimisation: occupancy and space utilisation use counts only, never named individuals; technician location is not tracked.
  • Privacy impact assessment before Phase 2 (Space Utilization, Wellbeing feedback) and before any access-control integration.
  • Data subject rights: access, correction and deletion requests handled through a documented admin workflow; work-order history is kept but personal fields are anonymised on deletion.
  • Location of data: personal data stays in the client's chosen region (in-Kingdom for Saudi clients); no transfer abroad without a lawful basis.
  • Logs: application logs never contain personal data, tokens or payload secrets (automatic masking in Serilog).

4. Threats and mitigations

ThreatExampleMitigation
Spoofed gateway or deviceAttacker sends fake readingsmTLS with per-gateway X.509 certificates, topic ACLs per gateway, certificate revocation
Tampered dataReadings altered in transitTLS, signed batches, range and plausibility checks, anomaly alarms
Unsafe BMS controlMalicious setpoint changeRead-only by default; Phase 3 write-back only on allow-listed points, with limits, approval and automatic relinquish; fire / life-safety never writable
Broken access controlUser sees another site's data (IDOR)Authorisation on every request by tenant and location; PostgreSQL row-level security as a second layer; automated access-control tests
Account takeoverPhished passwordSSO + MFA (mandatory for admins), lockout, risk-based login alerts, short sessions
Injection and web attacksSQL injection, XSSParameterised queries (EF Core), output encoding, strict Content-Security-Policy, WAF rules, SAST and DAST in CI
RansomwareServers encrypted, backups deletedImmutable backups (S3 Object Lock where the storage supports it, or an append-only backup server), separate backup credentials, offline copy, monthly restore test
Insider misuseBulk export of the asset registerLeast privilege, export logging and alerts, quarterly access reviews, tamper-evident audit log
Supply chainCompromised library or imagePinned versions, dependency and image scanning, SBOM, signed images (cosign), private registry
Denial of serviceFlood of requests or messagesRate limits per user / gateway, MQTT quotas, provider DDoS protection or upstream firewall, autoscaling

5. Secure development lifecycle

Designthreat model per feature
›
Codepeer review, secure coding standard
›
BuildSAST, secret scan (gitleaks), dependency scan
›
PackageTrivy image scan, SBOM (CycloneDX), cosign signing
›
TestDAST (ZAP), access-control tests
›
Releasesigned images only; pen test yearly and after major changes
Vulnerability severityFix deadline
Critical7 days (actively exploited: 48 hours or a temporary mitigation)
High30 days
Medium90 days
LowNext planned release

6. Identity, privileged access and keys

Identity and privileged access

  • MFA mandatory for administrators and remote access
  • Just-in-time admin rights with expiry; two named break-glass accounts, sealed and monitored
  • Joiner / mover / leaver synced from the corporate directory; quarterly access reviews
  • Service accounts per component, least privilege, no shared accounts
  • Vendor (Honeywell / JCI) remote access only through approved, time-limited, logged sessions

Keys, secrets and certificates

  • All secrets in OpenBao; dynamic, short-lived database credentials
  • TLS certificates renewed automatically (cert-manager, 90 days)
  • Gateway certificates valid 1 year, rotated automatically, revocable
  • API keys and integration tokens scoped and rotated every 90 days
  • Encryption keys in OpenBao / KMS; optional client-managed keys (BYOK) or HSM

7. Hardening

Platform

  • CIS benchmarks for OS, Kubernetes and PostgreSQL
  • Kubernetes network policies: deny by default, allow only required flows
  • Optional service mesh (mTLS between services)
  • No public access to databases, Valkey, Kafka or object storage
  • Admin access only via bastion / VPN with MFA; outbound traffic restricted
  • Containers run as non-root, read-only file systems where possible

Edge gateway

  • Secure boot and full-disk encryption (TPM-backed)
  • No inbound ports; SSH disabled or key-only over the management VPN
  • Only signed updates accepted; automatic rollback on failure
  • BACnet read-only by default; separate NICs for OT and uplink
  • Installed in a locked cabinet; enclosure tamper alarm where available

8. Security monitoring and audit

  • Audit log: every login, permission change, configuration change, export, work-order action and control command; tamper-evident (hash-chained entries, copied to write-once (append-only) storage); kept 7 years.
  • Security logs from ingress, Keycloak, Kubernetes, gateways and databases are centralised (VictoriaLogs) and forwarded to a SIEM: the client's own SIEM via syslog, or open-source Wazuh.
  • Detection rules (examples): repeated failed logins, MFA disabled, new admin created, large or unusual export, access from a new country, gateway certificate errors, unexpected BACnet write attempts, disabled audit logging, backup deletion attempts.
  • Security alerts page the on-call engineer and the security owner around the clock.

9. Data breach response plan

A data breach is any accidental or unlawful loss, disclosure, alteration or access to Confidential, Personal or Restricted data. The plan follows six phases, with a breach register kept for every event, including near-misses.

1 · Detect & reportalert, staff or client report → security owner immediately
›
2 · Triagewithin 1 h: confirm, rate severity, open incident
›
3 · Containrevoke credentials, isolate systems, block traffic; preserve evidence
›
4 · Assesswhat data, how many people, which clients, risk to them
›
5 · Notifyclient, regulator, affected people as required
›
6 · Recover & learnfix root cause, restore, report, update controls

Notification matrix (defaults, confirm in contracts)

WhoWhenWhat
Security owner and managementImmediately on detectionInitial facts, severity, containment actions
Affected clientWithin 4 hours of confirming a high-severity breach; 24 hours for othersWhat happened, data involved, actions taken, contact person; updates every 24 h until closed
Regulator (Saudi Arabia: SDAIA under PDPL)Within 72 hours of becoming aware, for personal data breachesNature of the breach, categories and number of people affected, likely consequences, measures taken
NCA and other authoritiesAs required by NCA ECC and applicable lawPer the authority's reporting format
Affected individualsWithout undue delay where there is a high risk to themPlain-language description, what they should do, contact point
  • Evidence preservation: snapshots of affected systems, logs locked in object storage, chain-of-custody record before any clean-up.
  • Ready-made templates for client, regulator and individual notifications, in English and Arabic.
  • Post-incident report within 5 working days: timeline, root cause, impact, corrective actions with owners and dates.
  • Exercises: a breach tabletop exercise every year and after any major incident; results feed the risk register.

10. Third parties, continuity and compliance

AreaControlStandard alignment
Suppliers and vendorsSecurity assessment before onboarding; contracts include confidentiality, breach notification and data residency clausesISO 27001 supplier controls, NCA ECC
Open-source componentsLicence and vulnerability tracking through the SBOMISO 27001, secure development
Business continuityRPO ≤ 15 min, RTO ≤ 4 h, immutable backups, DR site option, yearly DR test (section 15)ISO 22301 principles, NCA ECC resilience
OT securityZones and conduits, read-only default, gateway hardeningIEC 62443
PrivacyInventory, minimisation, DPIA, subject rights, breach notificationSaudi PDPL
Cloud hostingIn-Kingdom region, provider certifications reviewedNCA CCC, CST regulations
StaffSecurity awareness training at onboarding and yearly; confidentiality agreementsISO 27001 people controls

15Scalability, availability, backup and disaster recovery

The platform starts small and grows in stages without a rewrite. Each stage only adds capacity or splits out a module; data formats and APIs stay the same.

Stage 1 · Pilot

1 server / VPS, 1–2 buildings, ≤ 20k points

  • Compose or k3s
  • Modular monolith

Stage 2 · Campus

HA cluster, ≤ 10 buildings, ≤ 200k points

  • 3-node DB, bus, broker
  • Workers scale on partitions

Stage 3 · Portfolio

≤ 100 buildings, ≤ 2M points

  • Split hot modules (Live, Alarms, CMMS) into services
  • DB read replicas; more Kafka partitions

Stage 4 · Commercial SaaS

Many tenants

  • Shard by tenant / region
  • Per-tenant clusters for large clients
ComponentHow it scalesRedundancy
Edge gatewaysAdd gateways per building / segmentOptional active / standby pair
MosquittoAdd brokers and assign gateway groups to themActive / standby pair per broker
Apache KafkaMore partitions and brokers3 brokers, replication factor 3
Stream workersHorizontal pod autoscaling on consumer lag≥ 2 replicas each
Core APIStateless replicas behind ingress; split modules later≥ 2 replicas
PostgreSQLVertical, then read replicas, then split by tenantPatroni: 1 primary + 2 replicas, automatic failover
ClickHouseAdd shards (by tenant / site); replicas for read load2 replicas per shard + 3 ClickHouse Keeper nodes
ValkeyLarger instance, then Valkey ClusterSentinel (3)
Object storageAdd SeaweedFS volume servers / provider S3Erasure coding or provider replication

Backup and recovery (defaults)

WhatHow oftenKept
PostgreSQLContinuous WAL archiving + daily differential + weekly full (pgBackRest)35 days point-in-time; monthly fulls 12 months
Object storageVersioning + nightly replication to a second location35 days of versions
ConfigurationGit (Helm values, rules, templates); Keycloak export dailyFull history
Edge gatewaysConfig pulled from platform; buffer covers 72 h outages—

≤ 15 min

RPO (data loss)

≤ 4 h

RTO (restore time)

99.5% / 99.9%

Uptime: single server / HA

Monthly

Restore test

Observability and DevOps

  • Metrics (Prometheus), logs (VictoriaLogs), traces (OpenTelemetry → Jaeger), dashboards in Grafana OSS, alert routing in Alertmanager. A trace ID flows from gateway batch to dashboard update.
  • CI: lint, unit and contract tests, image build, Trivy scan, SBOM. CD: Argo CD GitOps with automatic rollback on failed health checks.
  • Environments: dev → test (with simulator) → staging → production. Database migrations are versioned and backward-compatible.

15AProduction readiness

This section covers what it takes to run the platform safely in production: contracts and versioning, resilience patterns, configuration, release and migration practices, service levels and alerting, runbooks, capacity, testing, onboarding, gateway fleet management, and a go-live checklist.

1. API and event contracts

AreaRule
REST versioningVersion in the path (/api/v1). Additive changes only within a version; breaking changes need /v2 with the old version kept for at least 12 months. Deprecations announced with a Sunset header
Error formatRFC 9457 Problem Details (type, title, status, detail, traceId) on every error; validation errors list each field
Event schemasEvery event has a name, version, ID, timestamp, tenant and trace ID. Schemas (JSON Schema) are kept in a schema registry in Git; consumers must ignore unknown fields; breaking changes publish a new event version alongside the old one
Contract testsConsumer-driven contract tests (Pact) between front ends and the API, and between producers and consumers of events, run in CI
Pagination and limitsCursor pagination; maximum page size 500; trend queries limited to 10,000 points per series (the API picks a coarser aggregate automatically)
Rate limitsPer user and per integration client (default 600 requests/min; exports 10/hour); 429 responses with Retry-After

Main endpoint groups: /locations, /positions, /assets, /points, /readings (trend queries), /alarms, /faults, /work-orders, /ppm-plans, /parts, /energy, /reports, /bim-models, /gateways, /admin, /exports.

2. Resilience and error handling

PatternWhereDefault
TimeoutsEvery outbound call (DB, Valkey, Kafka, HTTP, SMTP, SMS)DB 5 s, HTTP 10 s, report rendering 120 s
Retries with back-off and jitterTransient failures only (Polly / Wolverine policies)3 retries: 0.5 s, 2 s, 8 s; then dead-letter
Circuit breakerExternal services (SMS gateway, email, weather API, ERP)Open after 50% failures in 30 s; half-open after 60 s
BulkheadsSeparate worker pools for live data, reports and BIM conversionA slow report never delays alarms
Back-pressureKafka consumers, SignalR, gateway uplinkConsumer lag alerts; live updates throttled to 1 per point per second; gateway buffers when the broker is slow
Graceful degradationDashboard and APIIf Valkey is down, read last values from the database; if analytics is down, dashboards still show live data and alarms
Dead-letter handlingAll topics and Wolverine queuesAdmin screen to inspect, fix and replay; alert when a DLQ grows
Health checksEvery service/health/live and /health/ready (checks DB, Kafka, Valkey); used by Kubernetes and load balancers
Graceful shutdownEvery serviceStop taking work, finish in-flight messages, commit offsets, then exit (30 s)

3. Configuration, secrets and feature flags

  • Configuration through environment variables and Helm values per environment, validated at start-up (the service refuses to start on invalid settings).
  • Tenant and site settings (intervals, retention, escalation timers, naming rules) live in the database with an admin UI and audit history.
  • Secrets only from OpenBao (or Kubernetes secrets on the smallest installs), never in Git or images.
  • Feature flags (OpenFeature with a self-hosted provider such as Flagd or Unleash) to release modules per site, run pilots, and switch off a feature without redeploying. Phase 2 / 3 modules ship behind flags.

4. Environments, releases and database migrations

Devper-developer or shared; simulator data
›
Test / QAautomated tests, simulator with fault injection
›
Stagingproduction-like; anonymised data; load and security tests
›
Productionpilot site first, then all sites
  • Release strategy: rolling updates by default; canary releases (10% → 50% → 100%) for API and workers on the HA profile, with automatic rollback on error-rate or latency alarms (Argo Rollouts).
  • Database migrations: EF Core migrations, run as a separate job before the release. Always expand → migrate → contract: add new columns or tables first, deploy code that uses both, back-fill, then remove the old ones in a later release. No migration locks a large table; large-table changes (PostgreSQL and ClickHouse) are tested on a production-sized copy.
  • Versioning: semantic versions for the platform, the gateway image and the Helm chart; every release has release notes and a rollback plan.
  • Change control: production changes through pull requests and GitOps only, with approval; emergency changes are reviewed afterwards.
  • Maintenance windows agreed per client for anything that may cause downtime (normally none on the HA profile).

5. Service levels and alerting

Service level indicatorObjective (SLO)Alert when
API availability (successful requests)99.9% monthly (HA profile)Error budget burn rate > 2× over 1 h
API latency (p95, excluding exports)< 500 ms> 1 s for 10 min
Data freshness (platform arrival → dashboard, p95)< 5 s> 15 s for 5 min
Gateway connectivity99.5% of gateways onlineAny gateway offline > 90 s
Ingestion lag (Kafka consumer lag)< 10 s> 60 s for 5 min
Alarm notification delay< 30 s from condition to notification> 60 s
Dead-letter queueEmpty or shrinking> 100 messages or growing for 15 min
BackupsDaily backup succeeds; WAL archive lag < 5 minAny failure
CertificatesValidAny certificate expiring within 14 days

Alerts go to an on-call rota (Alertmanager routing to email, SMS and chat) with severity-based paging. Standard dashboards: platform overview, ingestion pipeline, gateways, database, API, business KPIs (alarms open, work orders overdue).

6. Runbooks

Each alert links to a runbook with checks, fixes and escalation. Runbooks written before go-live:

Data path

  • Gateway offline
  • Ingestion lag growing
  • DLQ growing / mapping errors
  • Missing data and back-fill

Platform

  • Database failover and replica rebuild
  • Disk or storage nearly full
  • Kafka broker down
  • Certificate renewal failure

Recovery and security

  • Point-in-time database restore
  • Full DR to a second site
  • Suspected breach (links to 14A)
  • Rotate compromised credentials

7. Capacity and sizing (starting points)

ComponentProfile S (single server, ≤ 20k points)Profile M (HA cluster, ≤ 200k points)
Core API1 replica, 1 vCPU, 1 GB3 replicas, 2 vCPU, 2 GB each
Stream workers (.NET)1 of each, 0.5 vCPU, 512 MB2–6 of each (autoscaled), 1 vCPU, 1 GB
Analytics / BIM workers (Python)1 each, 1 vCPU, 2 GB2 each, 2 vCPU, 4 GB
PostgreSQL2 vCPU, 8 GB, 200 GB SSD3 nodes, 4 vCPU, 16 GB, 500 GB each
ClickHouse4 vCPU, 16 GB, 500 GB SSD2 replicas, 8 vCPU, 64 GB, 2 TB NVMe each + 3 small Keeper nodes
Apache Kafka1 node, 2 vCPU, 4 GB3 nodes, 4 vCPU, 8 GB, 500 GB each
Mosquitto / Valkey / SeaweedFS / KeycloakShared: 2 vCPU, 6 GB total2–3 nodes each

Sizes are estimates to be confirmed by load tests with the simulator: target sustained 50,000 readings/s on Profile M with p95 freshness under 5 s, and 2× headroom.

8. Testing strategy

LevelWhatTools
UnitDomain logic, rules, adapters, unit conversionxUnit, pytest
IntegrationReal PostgreSQL, Kafka, Valkey in containers; outbox, sagas, idempotency (each handler run twice)Testcontainers
ContractAPI ↔ front ends; event producers ↔ consumersPact, JSON Schema
End-to-endKey user journeys on desktop and phone-sized browsers against the simulatorPlaywright
PerformanceIngestion throughput, API latency, dashboard load with many usersLocust, simulator back-fill
ResilienceKill pods, drop the network, fail the DB primary, cut the gateway uplinkChaos Mesh (staging)
SecuritySAST, DAST, dependency scans, yearly pen testSee 14A
User acceptancePilot site sign-off against BRD requirementsTest scripts per requirement ID

9. Building onboarding

1 · PrepareIFC / FBX, BACnet point lists (EDE), asset register, naming rules
›
2 · Modelimport model, review floors, spaces, positions
›
3 · Gatewayinstall, register certificate, discover devices
›
4 · Mapbind points to positions (auto-match + review)
›
5 · Rulesalarm thresholds, FDD rules, escalation, PPM plans
›
6 · Verify & go livedata-quality report, UAT, sign-off

An onboarding checklist and a data-quality report (points mapped, points live, stale points, unit errors) must reach agreed thresholds (e.g. ≥ 98% of points live and mapped) before a building goes live.

10. Gateway fleet management

  • Gateway registry with location, serial, image version, certificate expiry, last heartbeat and buffer depth.
  • Zero-touch provisioning: a one-time enrolment token issues the gateway's certificate; tokens expire after 24 h.
  • Staged updates: one pilot gateway, then 10%, then all, with automatic rollback.
  • Remote diagnostics (logs, BACnet scan results) over the outbound connection, never via inbound access.

11. Time, language and accessibility

  • All timestamps stored in UTC; displayed in each site's time zone (Asia/Riyadh for Saudi sites); gateways synced by NTP with clock-skew alarms.
  • Daily and monthly energy figures use the site's local calendar day and month; reports can show Gregorian and Hijri dates.
  • English and Arabic with full RTL layout; numbers, dates and units formatted per locale; all text in resource files.
  • WCAG 2.1 AA: keyboard navigation, contrast, screen-reader labels; colour is never the only signal for alarm state.

12. Go-live checklist

AreaMust be true before production
SecurityPen test done, no open critical / high findings; MFA on for admins; secrets in OpenBao; audit log on and tamper-evident
ReliabilityHA tested (DB failover, pod loss, gateway outage with back-fill); idempotency tests passing
BackupsBackups running and a full restore tested within the RTO
ObservabilityDashboards, SLO alerts and on-call rota live; every alert linked to a runbook
PerformanceLoad test at 2× the expected pilot volume within SLOs
DataOnboarding data-quality thresholds met; retention and archive jobs scheduled
PrivacyPersonal data register complete; DPIA done where needed; notification templates ready
OperationsSupport process, SLA, escalation contacts and maintenance windows agreed with the client
DocumentationAdmin guide, user guides (English / Arabic), API docs, runbooks, architecture records
Sign-offUAT signed against BRD requirement IDs by the business owner

16Mock data simulator

Until real sites are connected, a simulator acts as a network of BACnet devices shaped like Honeywell and Johnson Controls controllers. The gateway discovers and polls it exactly like real equipment.

Building model

YAML file: floors, zones, chillers, AHUs, FCUs, pumps, VAVs, lighting circuits, meters, IAQ sensors. Can be generated from an imported IFC / FBX model.

Physics-lite behaviour

Occupancy and weather profiles drive loads; setpoint tracking; sub-meters sum to main meters; realistic noise.

Fault & data injection

Stuck valve, simultaneous heating and cooling, sensor drift, meter spike, device offline, malformed or late data, all on demand.

Built with Python + bacpypes3 (virtual BACnet devices) and a scenario API. Back-fill mode generates 12+ months of history in minutes. Every simulated reading is tagged source = simulated.

17Build order (Phase 1) and open decisions

M1 · Foundations.NET solution, CI/CD, Helm, Keycloak, DB schemas, Wolverine outbox / sagas
›
M2 · Data pipelinesimulator, gateway, Mosquitto, normaliser, TS writer, live values
›
M3 · TwinIFC / FBX import, positions, point mapping, 3D viewer
›
M4 · Alarms & FDDrules, priorities, escalation, data-quality checks
›
M5 · CMMSWOs, PPM, spares, technician view, sagas
›
M6 · Energy & PortfolioEnPIs, baselines, recommendations, reports
›
M7 · Pilotreal Honeywell / JCI site, hardening, pen test

Open design decisions

#Decision neededProposed default
OD-1Team skills: C# + Python back end, TypeScript front endConfirm team mix; the edge gateway can move to .NET later if BACnet library tests pass
OD-2Open source or licensed, per componentProposed default: open source everywhere, with optional paid support for PostgreSQL, Kafka and Keycloak; decide per component using the comparison in section 3
OD-3Pilot hosting profile: S (single server) or M (HA cluster)?Profile S for pilot, M for production
OD-4Gateway hardware vendor and whether a redundant pair is neededSingle gateway for pilot
OD-5Real Honeywell / JCI point lists (EDE) and sample IFC / FBX filesNeeded before M2 / M3 finish

18Client questions — how the design answers them

The 20 standard due-diligence questions, answered from this design. Green lines show what can be configured per client or per site.

1

How is data captured from the sensors and sent to the dashboard?

Sensors connect to Honeywell / JCI controllers. An on-site edge gateway reads the controllers over BACnet (polling + change-of-value), buffers locally, and sends encrypted batches over MQTT to the platform. The platform normalises each reading, stores it, and pushes live changes to the dashboard over WebSocket.

Configurable: points, protocols, adapters per vendor
Sections 2, 4, 5
2

How often is data collected, processed and updated on the dashboard?

Defaults: critical points every 15 s, normal analog every 60 s, status changes immediately (COV), meters 60 s / 15 min, IAQ 5 min. Processing is streaming; live values appear within 5 s of arrival, and roll-ups refresh every minute.

Configurable: interval per point (5 s – 60 min), deadband, heartbeat
Section 4
3

How long is data retained, and what is the archival policy?

Raw readings 13 months online, then monthly Parquet archives for 7 years; 15-min aggregates 3 years; hourly / daily 7 years; audit log 7 years; CMMS history for the asset's life + 7 years. Archives can be restored on demand; legal hold stops deletion.

Configurable: every retention period per tenant
Section 6
4

How is a modified, replaced or new component mapped to an existing asset code?

The asset code belongs to the position (functional location), not the physical unit. A replacement closes the old install record and opens a new one under the same code, so sensors, BIM links and trends carry on. New components get a new position and code. This runs through a work order and the Asset Change saga.

Configurable: asset code naming rules per site
Sections 6, 8
5

How are sensor faults, abnormal readings, communication failures and data loss detected?

Automatic checks for stale, flat-lining, out-of-range, spiking and drifting sensors; device offline after 3 failed polls; gateway offline after 90 s without a heartbeat; gap detection with automatic back-fill; failed messages held in a dead-letter queue.

Configurable: thresholds and time windows per point class
Sections 5, 10
6

Which communication protocols are used?

Sensors ↔ controllers: vendor field buses / BACnet MS/TP. Controllers ↔ gateway: BACnet/IP and MS/TP (via routers). Gateway ↔ platform: MQTT 5 over TLS. Platform ↔ users: HTTPS and WebSocket. Other systems: Modbus TCP, MQTT, REST through adapters.

Configurable: new protocols added as adapter plug-ins
Sections 4, 5
7

What happens if the internet, gateway or server goes offline?

Building systems keep running: controllers run their own control. Internet or platform down: the gateway buffers ≥ 72 h and back-fills when the link returns; users on site can still check the BMS head-end. Gateway down: controllers keep their own trend logs, which are back-filled; an optional standby gateway takes over. On-prem installs need no internet at all.

Configurable: buffer size, gateway redundancy
Sections 2, 4, 15
8

How is unauthorised access, cyberattack and data breach prevented?

Separate OT and IT zones, outbound-only gateways, mTLS device certificates, SSO with MFA, role-based access by site, encryption everywhere, WAF and rate limiting, secrets in OpenBao, image and dependency scanning, audit log, monthly scans and an annual penetration test.

Configurable: roles, MFA policy, IP allow-lists, session rules
Sections 14, 14A
9

What is the incident response procedure, and how soon is the client notified?

Detect → triage (1 h) → contain and preserve evidence → assess impact → notify → recover and review. Client notified of high-severity incidents within 4 hours of confirmation; regulator notified as the law requires (PDPL: 72 h); root-cause report within 5 working days.

Configurable: notification times and contacts in the support agreement
Section 14A (data breach response plan)
10

Where is it hosted, and on what infrastructure?

Anywhere the client chooses: on-premise server, a single VPS, any public cloud, or hybrid (gateways on site, platform in the cloud). Same containers and Helm charts everywhere; data residency set per client (in-Kingdom for Saudi clients).

Configurable: hosting profile S / M / L, region
Section 13
11

Is data encrypted in transit and at rest?

Yes. TLS 1.2+ for every connection (mTLS for gateways); AES-256 encryption for disks, database, object storage and backups; keys held in OpenBao or the cloud KMS.

Configurable: client-managed keys (BYOK) option
Sections 14, 14A
12

How often are backups taken, and how are restore and DR handled?

Continuous database log archiving plus daily and weekly backups (35 days point-in-time); object storage versioned and replicated nightly; configuration in Git. RPO ≤ 15 min, RTO ≤ 4 h; restore tested monthly; optional standby site.

Configurable: backup frequency, retention, DR location
Section 15
13

What uptime is expected, and what redundancy exists?

99.5% on a single server, 99.9% on an HA cluster. Redundant database (1 primary + 2 replicas with automatic failover), 3-broker event bus, 2+ MQTT brokers, Valkey Sentinel, 2+ replicas of every service, optional gateway pair.

Configurable: hosting profile decides the uptime target
Section 15
14

How are alarms generated, prioritised, notified, acknowledged and escalated?

Four sources (BACnet native, threshold, FDD, data / comms). Priority P1–P4 from severity × asset criticality. Notifications by email, SMS and in-app via on-call rules. Acknowledged in the web app on desktop or phone. Unacknowledged P1 alarms escalate to the supervisor after 10 min and the facility manager after 30 min. Flood suppression and audited shelving.

Configurable: rules, priorities, recipients, escalation timers
Section 10
15

Can it integrate with HVAC, lighting, fire alarm, access control and energy monitoring?

Yes. HVAC and lighting through BACnet (or KNX / DALI via BACnet gateways); energy meters through BACnet, Modbus or M-Bus; access control and people counters through vendor APIs; fire alarm panels read-only through a BACnet / Modbus interface (life-safety is never controlled). New systems are added as adapter plug-ins.

Configurable: adapters and point mappings per system
Sections 4, 5
16

Who maintains it, how are updates handled, and what are the support SLAs?

Monthly patch releases, quarterly feature releases, critical security patches within 7 days; updates through GitOps with automatic rollback. Gateway software updates as signed images; controller firmware stays with Honeywell / JCI and is coordinated with them. Proposed SLA: P1 response 1 h / restore 4 h; P2 4 h / 1 business day; P3 1 business day / 5 days; P4 next release.

Configurable: maintenance windows, SLA tiers
Sections 4, 15
17

Who owns the data, and can the client export everything at any time?

The client owns all its data. A self-service Tenant Export (run as a saga) produces a complete package at any time: time-series in Parquet / CSV, twin, CMMS and configuration in JSON / CSV, original BIM files and documents, plus the full API.

Configurable: export scope, schedule (e.g. monthly automatic export)
Sections 6, 8
18

How are data, configuration and asset mappings migrated if the platform or provider changes?

Everything uses open formats and standards: Brick / Haystack tags, documented schemas, BACnet point-to-asset mapping exported as CSV, IFC models, Parquet history. The export package plus a documented exit plan lets another platform import it; our own import tools accept the same package for migrating in.

Configurable: export mapping templates
Sections 5, 6
19

Which certifications, audits and compliance standards apply?

Designed to align with ISO/IEC 27001, IEC 62443 (OT security), NCA ECC and CCC, Saudi PDPL, OWASP ASVS L2, and to support ISO 50001 energy management. Annual penetration test and monthly vulnerability scans. Formal certification (e.g. ISO 27001, SOC 2) is planned if the product is sold externally.

Configurable: compliance reports per framework
Sections 14, 14A
20

How is data from different systems correlated and turned into insights, reports and recommendations?

The twin links every point to its asset, system and space, with Brick meaning (e.g. "supply air temperature of AHU-01 serving Floor 3"). Readings are time-aligned into 15-min aggregates and joined with weather, occupancy and tariffs. FDD rules, energy baselines and KPIs run on that model, producing faults, ranked recommendations with estimated savings, and scheduled reports.

Configurable: rules, KPIs, report templates, schedules
Sections 6, 10, 11