Engineering
Correcting historical smart-meter readings without rewriting billing history
How I made late and corrected smart-meter readings flow into new bills and adjustments while every issued bill still recalculates to the cent from the data it saw.
On this page
EnergyDesk is one of the showcases in my Industry Demo Kit: a fictional New Zealand electricity retailer billing 2,000 synthetic connections from half-hourly meter data. It is an independent engineering showcase, not a certified billing system. The hard part is not the tariff maths. It is what happens when the data changes after a bill has gone out.
The problem
Meter data does not arrive once and stay put. In the seeded September scenario, one file is a byte-for-byte resend. One connection gets source revision 3 of its readings, then the delayed revision 2. One read is physically implausible (41.8 kWh in 30 minutes on a 60 A single-phase supply). And connection ED-00417 has no data for 21–23 September, so its bill goes out on 144 estimated half-hours. On Monday 5 October the actual readings arrive.
The obvious design is a readings table where a newer file overwrites the old value. It cannot answer the question an auditor or a customer will ask: what exactly did you bill me on? Once the estimate is overwritten, the issued $185.63 bill can no longer be recalculated, and a second late file raises another question: was the first correction already charged?
So the rule I started from was: every issued bill must be reproducible to the cent from the data it saw, and corrections never edit an issued document. The design is recorded in ADR 0009, Versioned meter observations, publication revisions and correction chains.
Test setup. Symfony (PHP) and PostgreSQL 19. Correctness claims come from PHPUnit integration tests against a real PostgreSQL database. The large benchmark ran in a separate, throw-away database on my laptop’s Docker VM: 8 vCPU, 7.75 GB RAM, PostgreSQL 19 default memory settings (128 MB shared buffers), external disk. The command refuses to run in production. Single-machine numbers: indicative, not lab-grade.
Readings are versions, never overwritten
Each meter observation is an INSERT-only row per interval key and version, with its measurement quality (A actual, S substituted by the meter data agent, E estimated by the retailer), validation status (accepted, held, rejected), the agent’s source revision and the publication revision that made it billable. The runtime database role has only SELECT, INSERT on en_observation. A test runs UPDATE en_observation SET value_wh = value_wh + 1 as that role and expects it to fail. Accepting a held reading later adds an en_observation_decision row; it does not rewrite the reading.
The effective value of an interval at publication revision P follows a fixed precedence order. Simplified:
SELECT DISTINCT ON (interval_start) interval_start, value_wh, quality, source_revision
FROM (/* reference layer UNION ALL session versions, accepted and published at <= :p */) v
ORDER BY interval_start,
(quality <> 'E') DESC, -- agent value beats estimate
source_revision DESC NULLS LAST, -- newer agent revision wins
publication_revision DESC -- newest estimate wins
DISTINCT ON would silently pick a winner on a tie, so ingestion stops ties from reaching it. Two different values under the same source revision are a conflict. If one is already published, it stays accepted and the newcomer is held, so an issued bill never changes. That is why the delayed revision 2 is stored but changes nothing.
The watermark is a committed revision, not a timestamp
A bill has to say which data it saw. A timestamp alone cannot: under concurrent transactions a row can commit later than its timestamp suggests. A database sequence has gaps and does not follow commit order either.
Instead, each session has one counter row, and publishing a file, an estimation run or a hold decision increments it inside the same transaction:
UPDATE en_publication_head SET revision = revision + 1
WHERE session_id = :session RETURNING revision;
The row lock is held until commit, so revisions are gap-free and in commit order, and a rolled-back publication leaves none behind. Ingestion takes the lock before validating, so two contradictory files cannot both pass the same-revision check. A concurrency test shows the second publisher blocking on the lock, then its 920 Wh for the same revision being held as a same-revision-conflict against the published 850 Wh.
Every bill calculation stores a full snapshot: dataset version, publication revision, tariff cut-off, occupancy revision, plan segments, tariff, rule and engine versions, plus a SHA-256 input hash of the snapshot (minus the publication revision) and the selected readings. Plan assignments and occupancies are INSERT-only too, so a bill’s pricing context cannot drift underneath it.
Corrections are a chain of documents
When the late file for ED-00417 is published (revision 63), the bill is recalculated with its own pricing context and the newer publication revision. A meter-data correction never re-prices.
The result is a new row in en_bill_review, also INSERT-only, referencing the bill and the previous entry, with UNIQUE (session_id, bill_id, sequence). The runtime role has no UPDATE grant on en_bill, so the original is never touched. Deltas are the difference of independently rounded lines, and of rounded GST components.
| Line (Everyday TOU) | Original, 21–23 Sep estimated | Recalculated, actual reads | Delta |
|---|---|---|---|
| Peak v2 | $29.26 | $31.42 | +$2.16 |
| Off-peak v2 | $26.52 | $27.91 | +$1.39 |
| Night v2 | $8.05 | $8.52 | +$0.47 |
| Five other lines | unchanged | unchanged | — |
| Total incl. GST | $185.63 | $189.65 | +$4.02 |
| GST component | $24.21 | $24.74 | +$0.53 |
The GST row is why the rule matters: 3/23 of $4.02 would round to $0.52, but the difference of the rounded GST figures is $0.53. Only the latter reconciles: original plus adjustments equals the revised total, for money and for tax.
Rebilling is preview, then apply. Apply is a compare-and-swap in one transaction: the chain head must still be the one the preview saw, and a fresh recalculation must still give the preview’s input hash, otherwise it returns 409 stale_preview. The hash leaves out the publication revision, so an unrelated publication does not invalidate a preview; new readings for this bill do. Applying the same preview twice fails, and a second late file is measured against the current revised total, so it cannot charge twice.
A non-zero difference becomes a numbered adjustment (A-2609-00417-1). If actual readings equal the estimates exactly, a quality update records the better data with no financial document.
The customer’s phone view shows the original amount, each adjustment and the revised total, with “Your electricity rates haven’t changed as part of this adjustment.” The operator’s bill page shows the same document chain beside the pinned snapshot.
Proving it
- Reproducibility.
EnergyDeskFixtureBillTestbills ED-00417 at revision 62 ($185.63, GST $24.21), ingests the late file, recalculates at revision 63 ($189.65), asserts only the three v2 consumption lines change, then recalculates at revision 62 and gets the original lines exactly. - The chain.
EnergyDeskRunTest::testTheAdjustmentChainOfAnIssuedBillcovers a stale preview, a double apply, a second correction producing a credit (measured from the revised total, not the original) and a zero-delta quality update, and asserts the original bill never changes. - Two paths. The bulk SQL billing path must match the separate single-connection path, line for line, on at least 50 connections including every story case.
- Rounding. Once per line, half away from zero, in integer arithmetic (−0.5 c becomes −1 c).
The benchmark. Billing reads a daily roll-up of the immutable reference readings and applies only the session’s contested keys on top; a parity test compares that path with a naive raw-readings query, tuple by tuple, after every kind of session change. The benchmark generates 10,000 connections × September: 20.4 M readings (2.6 GB). Every connection has an import channel, 30% also a controlled (hot-water) channel and 12% a solar export channel, and September has 1,438 half-hours because daylight saving starts on the 27th: 10,000 × 1.42 × 1,438 = 20,419,600. The aggregation query the production code uses, run locally, over 40 chunks of 250 connections took 5.2 s in total, median 0.124 s and p95 0.158 s per chunk, and selected all 20,419,600 generated intervals exactly once. Before the roll-up it took 161 s (median 3.4 s per chunk), disk-bound. This is selection and aggregation SQL only, not PHP pricing or persistence, on synthetic reference readings without session corrections.
Trade-offs and limitations
- Publication is serialised per session. Fine for one operator per demo session; a multi-tenant system would shard the counter (documented, not built).
- The roll-up relies on one reference version per interval, which a unique key enforces. A reference layer carrying corrections would need the precedence order inside the roll-up.
- Scope. Synthetic data and tariffs, a documented synthetic CSV instead of real meter-data formats, no payments, switching or settlement. Tariff and occupancy corrections are a different kind of rebill and out of scope.
What I’d do differently/next
- Carry the precedence order into the roll-up, so the reference layer could hold corrections.
- Run the deferred 100,000 connections × month profile rather than reason from the smaller ones.
- Shard the publication counter if several operators had to publish into one dataset.
Takeaways
- Never overwrite the inputs to a financial document. Store versions and resolve what is effective at read time.
- A watermark needs commit order. Timestamps and sequences look like one but are not.
- Corrections are new documents. A chain with a compare-and-swap head means the same correction cannot be applied twice.
- Check the fast path against a slow, obvious one. The bulk and roll-up paths are trustworthy because tests compare them with independent formulations.
You can run the 90-second billing day in the live demo, late reads and +$4.02 adjustment included, read the engineering page with the benchmark table, or see the EnergyDesk case study.