Energy Data Aggregation: Getting Units and Time Grains Right
Preventing distorted energy totals in ClickHouse by separating power from energy, stating sampling assumptions clearly, aligning timezone buckets, and preventing duplicate contribution to rollups.

Wrong Energy Totals Usually Start with Physical Semantics, Not Slow SQL
On the energy platform project, I developed backend APIs and application-layer device protocols and designed ClickHouse aggregation tables for operating-data queries. In operational reporting design, accuracy hinges on two fundamentals before query latency even enters the picture: separating power from energy, and preventing duplicate or delayed readings from skewing rollups. The following is an illustrative design informed by that background rather than a disclosure of a specific production schema.
Consider a hypothetical scenario. A circuit metering gateway reports at a regular 15-minute cadence with both instantaneous active power (kW) and a cumulative energy register (kWh). After a brief outage, the gateway reconnects, transmits the 10:15 packet twice across separate batches, and delivers a delayed 09:45 packet at 10:30. Without clear unit semantics and deduplication boundaries, a dashboard can both double-count 10:15 and place 09:45 in the wrong hour bucket.
Keep Power Separate from Energy—and State Sampling Assumptions
Under the International System of Units (SI Brochure), power (W or kW) is an instantaneous rate of energy transfer, whereas energy (Wh or kWh) is the accumulated quantity over a period. They follow distinct aggregation rules:
| Quantity | Typical unit | Valid aggregation across buckets | Common pitfall / assumption |
|---|---|---|---|
| Instantaneous power | kW (or normalized from W) | Arithmetic avg only for equal intervals (otherwise time-weighted), sampled max, sampled min |
Summing kW readings as total energy, or treating a sampled max as the true instantaneous physical peak |
| Interval energy delta | kWh (or Wh) | sum only when duplicate contribution is prevented |
Summing raw retries directly, inflating totals |
| Cumulative register | kWh | End-minus-start delta with meter-reset checks | Producing negative spikes or large jumps after meter swaps or rollovers |
Two statistical details are easy to overlook. First, plain avg(active_power_kw) is valid only when samples share an equal interval (as in a regular 15-minute series without gaps); variable intervals or missing points require explicit time-weighted averaging. Second, max(active_power_kw) is a sampled peak over reported readings, not necessarily the true physical peak occurring between two 15-minute samples.
Time grain and time zones require the same rigor: store event timestamps in UTC, then bucket into daily or monthly periods using the site’s local business timezone. Bucketing a late 23:45 reading by server receive time shifts consumption across reporting days.
ClickHouse Incremental Views and Preventing Duplicate Contribution
In ClickHouse, an incremental materialized view behaves as an INSERT trigger: it transforms only the newly inserted block and writes to its target table without inspecting existing target rows.
Because ReplacingMergeTree deduplicates asynchronously during background part merges, attaching an additive materialized view directly to a ReplacingMergeTree source table does not stop duplicate batches from firing the view twice. Later background merges clean up the source table, yet they cannot retroactively undo duplicate contributions already written to the rollup target.
The core requirement is not tied to one rigid topology; it is preventing any duplicate reading from contributing more than once to the chosen aggregate. Depending on latency and volume constraints, teams can achieve that through upstream deduplication before additive inserts, idempotent or versioned aggregation states, or bounded partition recomputation and compensating corrections. The pseudocode below illustrates a daily rollup over deduplicated regular 15-minute buckets:
// Pseudocode: daily rollup over deduplicated, equal-interval 15-minute buckets
// Assumptions: one valid row per (meter_id, bucket_15m) on a regular 15-minute grid
SELECT
meter_id,
toStartOfDay(bucket_15m, site_timezone) AS local_day,
sum(delta_kwh) AS total_kwh,
avg(active_power_kw) AS sampled_avg_kw,
max(active_power_kw) AS sampled_peak_kw
FROM deduplicated_meter_15m
WHERE local_day = :targetDay
GROUP BY meter_id, local_day
Tradeoffs and Verification
Recomputing affected partitions from deduplicated staging trades slight real-time latency for straightforward correction of late packets, retries, and meter swaps. Pre-aggregated AggregatingMergeTree views speed up high-volume reads, provided upstream ingestion or compensating writes keep each interval’s contribution singular.
Three deterministic checks catch rollup regressions early:
- Cross-batch duplicate reconciliation: insert the same
(meter_id, bucket_15m)in two separate batches and verify dailytotal_kwhmatches a hand-deduplicated baseline. - Cross-midnight late arrival: ingest a
23:45reading after midnight and verify both adjacent site-local days report exact totals. - Unit, interval, and reset edge cases: verify W/kW normalization, compare time-weighted vs unweighted power averages when a sample drops, and confirm register resets are flagged rather than distorting energy sums.