Versioning, history and audit trails for cleaned data
TL;DR
Difficulty: Advanced
A past number changes for three reasons: the description changed, the facts arrived late or were corrected, or the cleaning rules changed. Keep history for each.
- Version dimensions column by column: type 2 for what must stay as it was, type 1 only for corrections, a mini dimension for what changes often.
- Use dbt snapshots with the check strategy in a Rails shop, because every sign in moves updated_at.
- Give facts a second date, when you recorded them, and add correcting rows instead of editing.
- Time travel is an undo button of days, not an archive. Freeze each quarter close and register every report.
- Stamp every row with its rule version, and know your legal retention and erasure path.
What to read first
A quarter's revenue looks different in January from how it looked in October, although nobody touched the past. This chapter shows how to keep history so that every past number can be reproduced to the penny and every difference explained, using the same invented homeware shop in Leeds throughout.
The number that changed although nobody touched the past
In early October, Priya presented the third quarter at Wrenfield Home, the online homeware shop in Leeds that this series follows. The Kitchen category had brought in £96,300 between July and September, including VAT. In January she opened the same dashboard to prepare the annual review, filtered it to the same quarter, and read £76,510. No order had been added to the quarter since October, and nobody had deleted one. Yet a fifth of the Kitchen revenue had gone somewhere else.
This chapter answers the question behind her frown: how do I keep history so that I can explain any past number? Not only "what is the number today", but "what did the report say on the day I sent it, why was it different, and can I produce that exact figure again". The answer is a handful of techniques with dry names (slowly changing dimensions, snapshots, bitemporal tables, time travel, rule versions) and one discipline: never let a change destroy the information that came before it.
If you have read where and how to store clean data, you know where the data lives. This chapter is about time: what happens to that data as the world, your knowledge of it and your rules change underneath.
Three kinds of change move a past number
A past number can change for three quite different reasons, and each needs its own kind of history. Mixing them up is the most common reason a data team cannot answer "why did this change".
- The description changed. A customer moved from Leeds to Manchester. A product moved from one category to another. A price went up. The orders themselves did not change, but the labels you group them by did. These labels live in what data modellers call dimensions (the "by what" of a report: customer, product, region), as opposed to facts (the "how much": orders, line items, refunds). Data modelling for analytics explains that split in depth.
- The facts were corrected or arrived late. A return from the warehouse arrived five days after the quarter closed. A refund was issued in October for a September order. An order was edited after completion. Nothing about the past was different in reality, but your knowledge of it was incomplete when you reported.
- The rules changed. Callum, Wrenfield's developer and data engineer, improved the rule that removes test and staff orders. Version 3 catches four orders that version 2 missed. Reality did not change and no new data arrived. The way you clean it did. Business rule cleaning covers those rules themselves.
Example: the Kitchen quarter, taken apart. Callum traced Priya's £19,790 gap and found all three kinds at once:
| Change | Kind | Effect on Q3 Kitchen revenue |
|---|---|---|
| On 1 October, 120 table linen products moved from Kitchen to a new Dining category | Description | minus £18,400 |
| Returns for Q3 orders arrived from the warehouse in October and were booked back into Q3 | Late facts | minus £1,150 |
| Cleaning rule v3 excludes four staff orders that v2 kept | Rule | minus £240 |
| Total | minus £19,790 |
Check it: £96,300 minus £18,400 is £77,900. Minus £1,150 is £76,750. Minus £240 is £76,510, the January figure. Every pound is accounted for, but only because Callum could still see the old category, the date each return was recorded and the rule version each row was built with. Without that history, the honest answer would have been "I don't know", which is the one answer that destroys trust in a dashboard fastest.
The rest of this chapter takes the three kinds in turn: dimensions first, then facts and knowledge, then rules, and finally how to freeze a report so it can be reproduced to the penny.
What your shop database already keeps, and what it throws away
Before you build history in a warehouse, look at what the source system keeps by itself. A well designed shop already protects some history, and knowing exactly which parts saves you work and prevents a nasty surprise.
Wrenfield runs on Solidus, the open source Ruby on Rails shop. Four details of its data model matter here:
- Line items freeze the price. The Solidus source describes a line item as "the permanent record of the customer's order by recording relevant price, taxation, and inventory concerns"1. When a vase sold for £34 in July,
spree_line_items.pricesays £34 forever, even if the catalogue price is £39 today. - Addresses are treated as values, not edited in place. When a customer changes an address, Solidus looks for an identical address or creates a new row (the method is called
immutable_merge)2. The old address row survives, and old orders still point at it. - Catalogue prices are overwritten.
spree_pricesholds the current amount per variant, currency and country, and an edit changes that row3. Solidus does not keep a price history for you. - Category membership is overwritten. A product's categories (taxons, in Solidus terms) live in a join table called
spree_products_taxons4. Move a product to another taxon and the old link is simply gone.
Example: which Wrenfield questions the shop can answer alone. "What did customer 48213 pay for the vase in July?" The line item says £34. Answerable. "Where did order R204518 go in August?" The order points at the address row that was used, which still exists. Answerable. "What was the catalogue price of the vase on 1 August?" The price row says £39 today, with no trace of £34. Not answerable. "Which category was the table linen in during Q3?" The join table shows Dining. Not answerable. That last one is Priya's £18,400. The gap is exactly where the warehouse has to keep history itself.
Slowly changing dimensions: the vocabulary for describing change
Ralph Kimball and Margy Ross gave the industry a numbered vocabulary for how a dimension handles change, called slowly changing dimensions (SCD)56. "Slowly" means the attributes change now and then, not every second. The numbers are not a ranking. They are just names for different techniques, and a single dimension usually mixes several of them, column by column.
| Type | Kimball's name | What happens when a value changes | Keeps history? |
|---|---|---|---|
| 0 | Retain original | Nothing. The first value stays forever | The original only |
| 1 | Overwrite | The old value is replaced | No |
| 2 | Add new row | A new row with a new surrogate key, the old row is closed | Full |
| 3 | Add new attribute | A "previous value" column holds the old value | One step back |
| 4 | Add mini dimension | Fast changing attributes move to a small separate dimension | Full, through the facts |
| 5 | Mini dimension plus type 1 outrigger | Type 4 plus a link to the current profile | Full plus current |
| 6 | Type 1 attributes added to type 2 | Type 2 rows that also carry today's value | Full plus current |
| 7 | Dual type 1 and type 2 | Facts carry both a version key and a durable key | Full plus current |
The rest of this section walks through the ones you will actually use, each with the same customer or product so you can compare.
Type 0: keep the original value forever
Some attributes describe how something started, and must never move. The date of a customer's first order, the channel that brought them, the cohort they belong to. Kimball's design tip on the less common types lists "original" attributes and durable identifiers as the natural home for type 07.
Example: the acquisition channel. Customer 48213 first ordered on 4 March 2021 after a Google Ads click. In 2026 she clicks a Meta ad and orders again. If acquisition_channel were overwritten, your cohort analysis would quietly move her from the Google cohort of 2021 to Meta, and the 2021 Google cohort would shrink by one customer and her five years of orders. As type 0, the column says "Google Ads" forever, and her later Meta click is recorded where it belongs: on the 2026 order.
Type 1: overwrite, and accept that the past moves
Type 1 replaces the old value. It is the right choice when the old value was simply wrong, and the wrong choice when it was right at the time.
Example: a typo versus a move. A customer's town was stored as "Leeds " with a trailing space, and "Leeds" without it. Correcting that should change every past report, because the customer never lived anywhere else. Type 1 is correct. Now the table linen: it really was in Kitchen during Q3, and the business really did reorganise in October. Overwriting the category is what turned Priya's £96,300 into £77,900. Same mechanism, opposite verdict. The question is never "does this column change", but "when it changes, was the old value true at the time".
Type 2: add a new row for every version
Type 2 is the workhorse. When a tracked attribute changes, you close the current row and insert a new one. Kimball's definition asks for three extra columns at minimum: a row effective date, a row expiration date and a current row indicator, plus a new surrogate key for each version8. A surrogate key is a meaningless number the warehouse assigns, as opposed to the natural key from the source (the customer id in Solidus). Facts point at the surrogate key of the version that was valid when they happened.
Example: customer 48213 moves. She lived in Leeds and moved to Manchester on 1 October 2026. After the change, the customer dimension holds two rows for one person:
| customer_key | customer_id | city | valid_from | valid_to | is_current |
|---|---|---|---|---|---|
| 9001 | 48213 | Leeds | 2021-03-04 | 2026-10-01 | false |
| 15774 | 48213 | Manchester | 2026-10-01 | 9999-12-31 | true |
Her August order carries customer_key 9001, so "revenue by city" counts it in Leeds, which is where she lived when she ordered. Her November order carries 15774 and counts in Manchester. Nothing moves when you rerun Q3. The date 9999-12-31 is a convention for "still valid", which keeps date comparisons simple.
Notice the intervals: the Leeds row is valid up to but not including 1 October, and the Manchester row from 1 October on. This is called a half open interval, and it matters. If both rows included 1 October, an order placed that day would join to both and be counted twice.
Type 3: a column for the previous value
Type 3 adds a column such as previous_category next to category. It keeps exactly one step of history, and it shines in one situation: a one off reorganisation where people want to see both the old and the new structure side by side for a while.
Example: the October reorganisation. Wrenfield adds category_before_oct_2026 to the product dimension. For the 120 linen products it says Kitchen while category says Dining. Priya can now show Q3 both ways: £96,300 in Kitchen under the old structure, or £77,900 in Kitchen and £18,400 in Dining under the new one. If the linen moves again next year, the October value is overwritten, so type 3 is a tool for a transition, not for an archive.
Type 4: a mini dimension for attributes that change often
Some attributes change too often to version the whole customer row each time. A segment recalculated every month, an order frequency band, a lifetime spend band. Type 4 moves them into a small separate dimension, a mini dimension, with one row per combination of values, and the fact table carries its key alongside the customer key7.
Example: Wrenfield's customer profile. Callum builds a profile dimension from three banded attributes: segment (five values: new, active, loyal, lapsed, lost), orders in the last twelve months (four bands: 1, 2 to 3, 4 to 6, 7 or more) and twelve month spend (four bands). That is 5 times 4 times 4, so 80 rows, built once. Every order row stores the profile key that applied on the day it was placed. The customer dimension itself stays small and changes only when an address or email changes. "Revenue from loyal customers by month" becomes a simple join on the fact's profile key, and it is correct for every past month.
Type 6: the version as it was, and today's value next to it
Type 6 is a type 2 dimension where every row also carries the current value of some attributes, overwritten in all versions when it changes. The name comes from 1 plus 2 plus 37. It answers the two questions people ask most, "as it was" and "as it is now", from one table. Type 7 achieves the same by giving the fact table two keys, one for the version and one durable key that always reaches the current row7.
Example: both views of Q3. The product dimension gets category (type 2) and current_category (overwritten in every version). For Q3, grouping by category shows Kitchen £96,300, as it was. Grouping by current_category shows Kitchen £77,900 and Dining £18,400, as the shop is organised today. Priya picks the view to suit the question, and the dashboard says which one she is looking at.
What type 1 and type 2 do to a trend line
The difference between overwriting and versioning is easiest to see on a chart. Take a simple question: how many customers were in the loyal segment at the end of each month?
Example: loyal customers through 2026. With a type 2 (or type 4) history, Callum counts the customers whose loyal version was valid on the last day of each month. The count climbs from 2,410 in January to 2,930 in December. With a type 1 dimension there is only one value per customer, today's. Every month shows 2,930, because the only thing the warehouse knows is who is loyal now. The trend has been erased.
Choosing a type, column by column
A dimension is not "a type 2 dimension". Each column gets its own type, decided by one question: when this value changes, do reports about the past need the old value?
Example: Wrenfield's customer and product dimensions. Callum and Priya went through the columns one by one and wrote the answer into the model's documentation:
| Column | Type | Why |
|---|---|---|
| first_order_date, acquisition_channel | 0 | They describe how the relationship started |
| name spelling, email case and whitespace | 1 | A correction, the old value was never right |
| city, country (default address) | 2 | Revenue by region must stay where the customer lived |
| segment, frequency band, spend band | 4 | Recalculated monthly for thousands of customers |
| product category | 6 | Both "as it was" and "as it is now" are asked weekly |
| product name | 1 | A renamed vase is the same vase |
| catalogue price | 2 | Needed for "price before and after", which Solidus overwrites |
Writing the "why" down is the part people skip. It is also the part that settles the argument six months later when someone asks why the region report did not move after a customer relocated.
Building type 2 by hand in PostgreSQL
Most of the time a tool builds type 2 for you, and the next section shows dbt doing it. But you should be able to write it yourself once, because then you understand what the tool does and where it can go wrong. This is plain PostgreSQL, version 15 or later.
The dimension table holds one row per version:
-- PostgreSQL: the customer dimension, one row per version
CREATE TABLE dim_customer (
customer_key bigserial PRIMARY KEY, -- surrogate key, one per version
customer_id bigint NOT NULL, -- natural key: spree_users.id
email text NOT NULL,
city text,
country_code char(2),
row_hash text NOT NULL, -- fingerprint of the tracked columns
valid_from timestamptz NOT NULL,
valid_to timestamptz NOT NULL DEFAULT 'infinity',
is_current boolean NOT NULL DEFAULT true
);
-- at most one current version per customer
CREATE UNIQUE INDEX dim_customer_one_current
ON dim_customer (customer_id) WHERE is_current;
The incoming data sits in a staging view with the same columns plus a fingerprint, a hash of the tracked columns. Comparing one hash is simpler and faster than comparing every column, and it treats a missing value consistently:
-- PostgreSQL: staging view with a fingerprint of the tracked columns
CREATE VIEW stg_customer AS
SELECT
u.id AS customer_id,
lower(trim(u.email)) AS email,
a.city,
c.iso AS country_code,
u.updated_at AS changed_at,
md5(concat_ws('|',
coalesce(lower(trim(u.email)), '~null~'),
coalesce(a.city, '~null~'),
coalesce(c.iso, '~null~'))) AS row_hash
FROM spree_users u
LEFT JOIN spree_user_addresses ua ON ua.user_id = u.id AND ua."default"
LEFT JOIN spree_addresses a ON a.id = ua.address_id
LEFT JOIN spree_countries c ON c.id = a.country_id;
The coalesce calls look fussy, and they are there for a reason: concat_ws silently skips nulls, so without them a customer with no city and a customer whose city is empty would get the same fingerprint, and two different missing values in different columns could collide.
Now the load. It runs as two statements inside one transaction:
-- PostgreSQL: type 2 load in one transaction
BEGIN;
-- 1. Close the current version of every customer whose tracked columns changed
UPDATE dim_customer d
SET valid_to = s.changed_at,
is_current = false
FROM stg_customer s
WHERE d.customer_id = s.customer_id
AND d.is_current
AND d.row_hash <> s.row_hash;
-- 2. Insert a current version for every customer that now has none:
-- brand new customers, and the ones closed a moment ago
INSERT INTO dim_customer (customer_id, email, city, country_code, row_hash, valid_from)
SELECT s.customer_id, s.email, s.city, s.country_code, s.row_hash, s.changed_at
FROM stg_customer s
LEFT JOIN dim_customer d
ON d.customer_id = s.customer_id AND d.is_current
WHERE d.customer_id IS NULL;
COMMIT;
Why not a single MERGE? PostgreSQL has had MERGE since version 159, but for each source row it runs at most one action10. A type 2 change needs two: close the old row and insert a new one. You can work around that by feeding every changed customer in twice through a union, and many tools do, but two plain statements in a transaction are easier to read, test and debug. The transaction makes sure no report ever sees a customer with no current row.
Example: one night's load at Wrenfield. On the night of 1 October, the staging view holds 78,000 customers. Three things differ from the dimension: customer 48213 now has Manchester as her default city, customer 61022 replaced an old work email with a new address, and 41 customers signed up that day. A fourth customer typed her email in capitals this time, but staging lower cases it, so her fingerprint is unchanged and nothing happens to her. Step 1 compares fingerprints and closes two rows, 48213 and 61022. Step 2 finds 43 customers without a current row: the two just closed and the 41 new ones, and inserts 43 rows. Every count adds up: 2 rows closed, 43 inserted, 77,957 untouched, and still exactly one current row per customer.
Let the database refuse overlapping versions
The worst type 2 bug is silent: two versions of the same customer valid at the same moment, so one order joins twice and revenue doubles for that customer. PostgreSQL 18 can make that impossible with a temporal constraint. A primary key or unique constraint may end with a range column marked WITHOUT OVERLAPS, and the database then checks that no two rows with the same key have overlapping ranges11.
-- PostgreSQL 18 or later: no two versions of a customer may overlap in time
CREATE EXTENSION IF NOT EXISTS btree_gist; -- lets the bigint key join a GiST index
ALTER TABLE dim_customer
ADD COLUMN valid_during tstzrange
GENERATED ALWAYS AS (tstzrange(valid_from, valid_to, '[)')) STORED,
ADD CONSTRAINT dim_customer_no_overlap
UNIQUE (customer_id, valid_during WITHOUT OVERLAPS);
The '[)' makes the range half open, exactly like the intervals in the type 2 example. The documentation adds a detail that turns out to be useful: empty ranges are not permitted in a WITHOUT OVERLAPS column11. A version that starts and ends at the same instant, which usually means two changes arrived with the same timestamp, is rejected instead of slipping through. On PostgreSQL 17 and earlier, the same guarantee comes from an exclusion constraint, EXCLUDE USING gist (customer_id WITH =, valid_during WITH &&), which is what the new syntax does under the hood11.
Join facts to the version that was valid
If your fact table stores the surrogate key at load time, the join is trivial. If it only has the natural key and a timestamp, you join on the interval:
-- PostgreSQL: each order gets the customer version valid when it was completed
SELECT o.number, o.completed_at, d.city
FROM spree_orders o
JOIN dim_customer d
ON d.customer_id = o.user_id
AND o.completed_at >= d.valid_from
AND o.completed_at < d.valid_to;
Greater than or equal at the start, strictly less than at the end. That one character is the half open interval in code, and it is what stops a midnight order from being counted twice.
dbt snapshots: type 2 without writing the merge
dbt, the transformation tool this series uses, has a built in mechanism for type 2 history called snapshots. Since dbt Core 1.9, a snapshot is configured in a YAML file: you name the relation to watch, the key, and how dbt should detect a change12. Each run compares the current data with the last recorded version and writes new versions where something changed. dbt adds the columns dbt_valid_from, dbt_valid_to, dbt_scd_id and dbt_updated_at, and leaves dbt_valid_to empty on the current row unless you set a placeholder date with dbt_valid_to_current12.
Two strategies detect change. The timestamp strategy trusts an updated_at column: if it moved, the row changed. The check strategy compares the columns you list in check_cols. The documentation recommends timestamp as the default12, and for most tables that is right. For a Solidus customer table it is a trap.
The timestamp trap in a Rails shop
Solidus customer accounts use Devise, the Rails authentication library, with its trackable module switched on13. Trackable updates sign_in_count, current_sign_in_at and the IP columns every time a customer signs in, and saves the record14. Saving a record in Rails updates updated_at. So with the timestamp strategy, every sign in looks like a change, and the snapshot writes a new version of a customer whose name, email and address are exactly the same.
Example: what the trap costs Wrenfield. Of 78,000 customers, about 21,000 sign in during a typical month (an invented figure for the example). With the timestamp strategy, that is around 21,000 new versions a month. Real changes to email or default address affect perhaps 1,200 customers a month. So more than 94% of the versions are noise: 21,000 versions, of which 1,200 carry a real change, leaves 19,800 empty ones, and 19,800 divided by 21,000 is 94.3%. Worse than the storage, any question like "how many customers changed address this year" now returns nonsense.
The fix is the check strategy on the columns that matter, fed from a light staging model. This one is BigQuery SQL, the warehouse Wrenfield uses:
-- models/staging/shop/stg_shop__customers.sql (BigQuery)
select
u.id as customer_id,
lower(trim(u.email)) as email,
a.city as default_city,
c.iso as default_country_code
from {{ source('shop', 'spree_users') }} as u
left join {{ source('shop', 'spree_user_addresses') }} as ua
on ua.user_id = u.id and ua.`default`
left join {{ source('shop', 'spree_addresses') }} as a
on a.id = ua.address_id
left join {{ source('shop', 'spree_countries') }} as c
on c.id = a.country_id
# snapshots/customers_snapshot.yml (dbt Core 1.9 or later)
snapshots:
- name: customers_snapshot
relation: ref('stg_shop__customers')
config:
schema: snapshots
unique_key: customer_id
strategy: check
check_cols: ['email', 'default_city', 'default_country_code']
hard_deletes: new_record
hard_deletes: new_record tells dbt what to do when a customer disappears from the source entirely: instead of ignoring it (the default) it writes a final version flagged in a dbt_is_deleted column15. For customers that matters, as the section on erasure below shows. You run it with dbt snapshot, and dbt ignores --full-refresh for snapshots, so a careless rebuild cannot wipe the history12.
Three things snapshots cannot do
Snapshots are a camera, not a recorder, and that has consequences you should know before you rely on them.
- They only see what exists when they run. If a customer changes her address at 10am and changes it back at 4pm, a nightly snapshot never sees the detour. If that matters, you need change data capture from the database log, which a later chapter in this series covers.
- A version starts when dbt notices it, not when it happened. With the check strategy, the new version's start is the time of the snapshot run, unless the source gives you a trustworthy change timestamp. For a nightly run that is up to a day late. Orders placed in that window join to the old version.
- There is no history before the first run. On the day you start, every customer has exactly one version. Orders from the five years before it have no version to join to.
Example: the first run and the five years before it. Wrenfield starts snapshots on 1 January 2027. Customer 48213's first version says Manchester, valid from 1 January 2027. Her 2021 to 2026 orders fall before any version. Callum has two honest options. He can stretch the first version back to the beginning of time, which assigns all old orders to Manchester and is exactly type 1 behaviour for the past. Or he can rebuild the earlier history from the shop's own data: Solidus kept every address she used, so her orders' ship addresses tell him she lived in Leeds until October 2026. He does the second for city, where the evidence exists, and the first for segment, where it does not, and writes both decisions into the model documentation. Where the old orders came from a previous platform, migrating order and purchase history explains what usually survives such a move.
-- models/marts/dim_customer.sql (BigQuery)
select
dbt_scd_id as customer_key,
customer_id,
email,
default_city,
default_country_code,
case
when row_number() over (partition by customer_id order by dbt_valid_from) = 1
then timestamp '1900-01-01' -- first known version stretched back, a documented choice
else dbt_valid_from
end as valid_from,
coalesce(dbt_valid_to, timestamp '9999-12-31') as valid_to,
dbt_valid_to is null as is_current
from {{ ref('customers_snapshot') }}
Flow: a change arriving and being versioned
The whole journey of one change, from the nightly load to the facts that point at it, fits on one page:
What history costs, and how to keep it lean
At the size of most shops, history is not expensive in storage. It is expensive in meaning: every needless version makes the table harder to read and the questions harder to answer. A quick estimate tells you which kind of problem you have.
If a share of your customers has a change in a tracked column each month, the number of rows after months is roughly the starting number plus one new row per change:
where is the number of rows in the dimension after months, is the number of customers (held constant here to keep the estimate simple), is the share of customers with a tracked change per month, and is the number of months. It is a plain rate times a time, the same arithmetic as in Foundations: ratios and rates.
Example: three ways to version Wrenfield's customers for five years. is 78,000 and is 60.
- Address and email only, with about 1.5% of customers changing one of them a month: rows.
- Segment tracked in the same dimension, about 8% of customers changing segment a month: rows.
- The timestamp trap from above, 21,000 of 78,000 customers (about 27%) getting a version every month: rows.
A warehouse handles 1.3 million narrow rows without noticing, so storage is not the argument. The argument is that in the third table 17 rows out of every 18 say nothing, and in the second the customer dimension changes eight times faster than any address does. That is exactly what the type 4 mini dimension and the check strategy fix: the first option, with segment moved to the 80 row profile dimension, gives you complete history at a tenth of the rows of the third.
Two clocks: when it was true, and when you knew it
So far every version had one time range: when it was valid. That is enough to answer "what was true in August". It is not enough to answer "what did my report say in October", because in October you may not yet have known what was true in August. For that you need a second clock.
Database researchers call this bitemporal data. Richard Snodgrass's book on time in SQL databases names the two clocks valid time (when a fact was true in the world) and transaction time (when the database recorded it)16. Martin Fowler calls them actual time and record time, because people in his workshops kept confusing the older names17. The SQL:2011 standard added both kinds of period to SQL itself18, though support differs a lot between databases. You do not need a special database to use the idea. Two ranges per row are enough.
Example: the move she told the shop about late. Customer 48213 moved to Manchester on 1 October, but only updated her account on 10 November. A table with both clocks records this in three rows:
| Row | city | valid_during (true in the world) | recorded_during (what the warehouse believed) |
|---|---|---|---|
| 1 | Leeds | from 4 Mar 2021, open ended | 4 Mar 2021 to 10 Nov 2026 |
| 2 | Leeds | 4 Mar 2021 to 1 Oct 2026 | from 10 Nov 2026, open ended |
| 3 | Manchester | from 1 Oct 2026, open ended | from 10 Nov 2026, open ended |
Nothing is ever updated except the end of a recorded_during range. Row 1 is not deleted on 10 November. It is closed in record time, because from that day the warehouse no longer believes it. Now two different questions get two different, correct answers:
-- PostgreSQL: where did she live on 15 October, as the warehouse knew it on 1 November?
SELECT city
FROM customer_address_bitemporal
WHERE customer_id = 48213
AND valid_during @> date '2026-10-15'
AND recorded_during @> timestamptz '2026-11-01 00:00:00+00';
-- returns Leeds (row 1)
-- and where did she live on 15 October, as the warehouse knows it today?
SELECT city
FROM customer_address_bitemporal
WHERE customer_id = 48213
AND valid_during @> date '2026-10-15'
AND recorded_during @> now();
-- returns Manchester (row 3)
The first query reproduces the October report. The second gives today's best knowledge. Both are right, and the difference between them is precisely the explanation a finance director wants when the two reports disagree.
Where bitemporal data earns its keep in a shop
You do not need two clocks on every table. In an online shop, the second clock pays for itself on facts that arrive late or get corrected, because that is where "what was reported" and "what was true" drift apart:
- Returns from the warehouse, which at Wrenfield arrive up to five days late in the 3PL file.
- Refunds, which can arrive weeks after the order.
- Chargebacks and settlement corrections from Stripe and PayPal.
- Orders edited after completion.
For each, keep the event date (when it happened) and the recorded date (when your warehouse first loaded it). That pair is enough to rebuild any past report as it was known on any day.
Facts keep history by adding rows, never by changing them
Dimensions keep history through versions. Facts keep history the way accountants always have: by never changing a posted line, and adding a correcting line instead. An accountant who finds an error does not rub out last month's ledger entry. She posts a reversing entry this month that refers to it.
Example: an order edited after completion. Order R204518 was completed on 28 September for three table runners at £24 each, £72 in total. On 6 October the customer asked to reduce it to two, and the shop refunded £24. In an update in place world, the line item now says quantity 2, amount £48, and the September report silently loses £24 next time it runs. In an append only fact table, it looks like this:
| order_number | event_date | recorded_date | quantity | amount | reason |
|---|---|---|---|---|---|
| R204518 | 2026-09-28 | 2026-09-28 | 3 | £72.00 | original |
| R204518 | 2026-09-28 | 2026-10-06 | minus 1 | minus £24.00 | edit after completion |
Sum all rows and you get today's truth: two runners, £48. Filter recorded_date to on or before 30 September and you get what was known at quarter end: three runners, £72. Choose event_date to decide which period the correction belongs to, or put it in October's numbers instead, which is the restatement decision. The next chapter in this series covers restatements and how to communicate them. The point here is only that with both dates on the row, you can do either, and explain either.
Time travel: the warehouse's undo button, with a short memory
Cloud warehouses and open table formats offer a feature called time travel: you query a table as it was at an earlier moment, without having built any history yourself. It feels like the answer to this whole chapter. It is not, and the reason is in the retention limits.
- BigQuery keeps a time travel window of seven days by default, configurable between two and seven days. You query it with
FOR SYSTEM_TIME AS OF, and the timestamp must fall inside the window1920. After that there is a seven day fail safe period that you cannot query yourself and that cannot be extended19. - Snowflake keeps one day by default. On Enterprise Edition and above, a permanent table can keep up to 90 days, set with
DATA_RETENTION_TIME_IN_DAYS. After that, data moves to a further seven day recovery period that Snowflake calls Fail safe21. - Apache Iceberg tables keep every snapshot until you expire them. The default age used by snapshot expiry is five days, and at least one snapshot is always kept22. Queries can travel with
TIMESTAMP AS OForVERSION AS OF23. - Delta Lake keeps the table history for 30 days by default and deleted data files for seven days before
VACUUMcan remove them. Time travel to a version needs both its log and its data files, so in practice the shorter limit applies unless you raise it24.
A quarter lasts about 91 days. Not one of these defaults reaches back to last quarter's close, and Snowflake's maximum, 90 days, falls just short. Time travel is an undo button for mistakes you notice within days. It is not an archive.
Example: the Monday delete. On a Monday at 9.40am, Callum runs a cleanup that deletes all Q3 rows from fct_orders instead of only the test orders. He notices at 10.15am. With BigQuery time travel he restores the table as it was at 9.30am in one statement, and nobody downstream notices. That is what time travel is for. Now imagine Priya asks in January what the Kitchen number looked like on 3 October. The time travel window ended in mid October. Without snapshots, versions or a frozen copy, that question has no answer.
Keep the rule version with every row
The third kind of change was a change of rules. You can only explain it if every cleaned row says which version of the rules made it. That takes three audit columns, set by the pipeline itself:
- rule_version: the version of your cleaning rules, a value you bump on purpose whenever a rule changes.
- build id: an identifier of the run that produced the row. dbt provides
invocation_id, a UUID generated for each dbt command25. - code version: the git commit of the transformation code, passed in from your deployment.
In dbt this is a few lines. The rule version lives in the project file, where a change shows up in code review:
# dbt_project.yml (excerpt)
vars:
cleaning_rules_version: "v3"
-- models/intermediate/int_orders_cleaned.sql (BigQuery)
select
o.*,
'{{ var("cleaning_rules_version") }}' as rule_version,
'{{ invocation_id }}' as dbt_invocation_id,
'{{ env_var("GIT_SHA", "unknown") }}' as code_version,
current_timestamp() as built_at
from {{ ref('int_orders_classified') }} as o
where not o.is_test_or_staff_order
var reads a project variable26 and env_var reads an environment variable with a fallback when it is missing27. Neither is clever. Their value is that every row now carries its own explanation.
Example: proving what rule v3 changed. Callum keeps the rows that each rule version excluded in a quarantine table, also stamped with the rule version, as the chapter on cleaning pipelines describes. When Priya asks about the £240, he runs one query: excluded rows for Q3 Kitchen where rule_version = 'v3' and the order was not excluded under v2. Four orders come back, each from an email address on the staff list that v3 added, with a combined value of £240. The rule change is no longer a mystery inside a total. It is four named rows.
Where the change happens in the shop itself, not in the warehouse, the same idea applies one level down. For Rails models, the PaperTrail gem stores every create, update and destroy in a versions table, with the changed object and who made the change, and can return a record as it was at any time with version_at28. For catalogue prices, which Solidus overwrites, it gives Wrenfield the price history the shop never kept.
# app/overrides/wrenfield/price_history.rb (Rails 8, Solidus override)
# Keep a version of every catalogue price change, with who made it
module Wrenfield
module PriceHistory
def self.prepended(base)
base.has_paper_trail
end
::Spree::Price.prepend self
end
end
With before_action :set_paper_trail_whodunnit in the admin controllers, each version also records which admin user changed the price28.
Reproducing last quarter's report exactly
Everything so far comes together in one practical task: in January, produce the Q3 report exactly as it was sent in October, to the penny, and then explain every difference from today's version of it.
Four things must be the same as they were on the day: the data as it was known, the code, the rules and the parameters. Each needs its own mechanism:
| Ingredient | How to keep it | At Wrenfield |
|---|---|---|
| Data as known | Bitemporal facts, snapshots, or a frozen copy at close | Snapshot table of the marts at each quarter close |
| Code | A git tag on the commit that produced the report | report-2026-q3 |
| Rules | The rule version on every row and in the project file | v2 in October |
| Run and parameters | A row in a report run register | One row per published report |
The frozen copy is the simplest and the most robust. In BigQuery, a table snapshot is a read only copy of a table at a point in time, and you pay storage only for the bytes that differ from the base table29. Without an expiration time, it stays until you delete it2930. One statement freezes the quarter:
-- BigQuery: freeze the order facts at quarter close (no expiration, kept until deleted)
CREATE SNAPSHOT TABLE `wrenfield-analytics.closes.fct_orders_2026_q3`
CLONE `wrenfield-analytics.marts.fct_orders`;
On Apache Iceberg the equivalent is a tag on the table's current snapshot. Tags and branches are kept forever unless you give them a retention, and snapshot expiry does not remove a tagged snapshot31. Again, one statement:
-- Spark SQL on Apache Iceberg: keep the quarter close state of the table
ALTER TABLE marts.fct_orders CREATE TAG `close_2026_q3`;
Then the register. It is the reporting version of something I do for software: every release goes through a test gate and into a release register, so that anyone can see what changed, when and why. A report run register does the same for numbers:
-- BigQuery: one row per published report
CREATE TABLE IF NOT EXISTS `wrenfield-analytics.governance.report_runs` (
report_name STRING NOT NULL,
period STRING NOT NULL,
published_at TIMESTAMP NOT NULL,
code_version STRING NOT NULL, -- git tag or commit
rule_version STRING NOT NULL,
dbt_invocation STRING NOT NULL,
frozen_source STRING NOT NULL, -- the snapshot table or tag
headline_value NUMERIC NOT NULL, -- the main figure as published
published_by STRING NOT NULL
);
Example: Q3 reproduced in January. Priya's register row for the October report says: Q3 category report, published 3 October 2026, code report-2026-q3, rules v2, frozen source closes.fct_orders_2026_q3, Kitchen £96,300. Callum checks out the tag, sets cleaning_rules_version to v2, points the report at the frozen table and runs it. Kitchen: £96,300. The figure matches the register, so the reproduction is proven, not assumed. He then changes one ingredient at a time. Today's code and product dimension, still on the frozen facts and still with rules v2: £77,900, so the category change accounts for £18,400. Today's facts as well, rules still v2: £76,750, so late returns account for £1,150. Finally rules v3: £76,510, so the rule change accounts for £240. Four runs, three differences, and they add up to the £19,790 in the waterfall at the top. That is the answer Priya needed in January, built from parts that each take minutes.
Changing one ingredient at a time, in a fixed order, is the trick. If you change two at once, the difference between them cannot be split cleanly, and the explanation turns into a guess.
How long history must be kept: the legal side in the UK
History is not only an analytical luxury. Some of it is a legal duty, and the duty sets a floor on how long you keep the records behind your numbers. This section is general information, not legal advice. For your own business, ask your accountant or solicitor.
For a UK limited company, two rules overlap:
- The Companies Act 2006 requires a private company to preserve its accounting records for three years from the date they are made, and a public company for six years32.
- HMRC's guidance says company records must be kept for six years from the end of the last company financial year they relate to, and longer in some cases, for example when a transaction spans several accounting periods or HMRC has started a compliance check33.
The longer period wins in practice. Note what the law asks for: the accounting records. Those live in your shop database, your payment providers' statements and your accounting software, not primarily in your analytics warehouse. But if you produce figures from the warehouse that feed tax or statutory reports, being able to show how those figures were built is part of keeping proper records, and the techniques in this chapter are how you do it.
Example: how long Wrenfield keeps an order. Wrenfield's financial year ends on 31 March. An order from 15 May 2026 falls in the year ending 31 March 2027. Six years from the end of that year is 31 March 2033. Until then, the order, its line items, refunds and the payment records stay, in the shop database and in the warehouse's raw layer. The order facts in the warehouse follow the same date, so any report built on them can be rebuilt for as long as the underlying records must exist.
When history meets the right to erasure
Keeping history and deleting personal data pull in opposite directions, and a warehouse full of versions, snapshots and frozen copies makes the conflict sharper. Under UK GDPR, a person can ask you to erase their personal data34, and personal data must not be kept in identifiable form for longer than necessary35. At the same time, the right to erasure does not apply where processing is necessary to comply with a legal obligation34, such as keeping the records HMRC requires.
The Information Commission (formerly the Information Commissioner's Office, ICO) adds two points that matter for data engineers. If the law requires you to keep certain personal data, you can refuse erasure for that data. And erasure can reach backups too: where data cannot be deleted at once, it must be put "beyond use" and held only until it is replaced on the normal schedule36.
In practice, design for it from the start:
- Separate identity from history. Keep the facts keyed on a customer id, and keep the name, email and address in a dimension that you can scrub. A type 2 dimension then has to be scrubbed in every version, not only the current one.
- Remember every copy. Raw tables, snapshot tables, quarter close copies, Iceberg tags and time travel windows all hold the data. Time travel expires by itself (seven days plus seven days fail safe in BigQuery, as above), which is the kind of short, known retention that fits the "beyond use" approach. Frozen quarter copies do not expire, so they need a scrub step too.
- Keep what the law requires, and only that. The order, its amounts and its tax stay for the HMRC period. The marketing segment and the newsletter history of a person who asked to be erased do not.
Example: an erasure request at Wrenfield. Customer 61022 asks to be erased in February 2027. Callum's checklist touches: one row in spree_users, which the shop anonymises; six versions in customers_snapshot (the hard delete becomes a final version flagged deleted, and every version's email and city are scrubbed); her newsletter and segment history, which is deleted; and the two quarter close snapshot tables, where the customer rows are scrubbed the same way. Her 14 orders stay, with amounts, VAT and dates, because they are accounting records, but they now point at a customer key with no name or email behind it. A later chapter in this series covers privacy engineering in pipelines in full. For what the right to be forgotten means once data has reached a model, see GDPR and AI: when the right to be forgotten reaches the model.
A history checklist for a shop of this size
Pulling the chapter together into something you can act on this month:
| Area | Do this | Done at Wrenfield with |
|---|---|---|
| Dimensions | Decide a type per column and write down why | Model documentation, table above |
| Customer history | Snapshot with the check strategy, not timestamp | customers_snapshot, check on email and default address |
| Fast changing attributes | Move them to a mini dimension | 80 row profile dimension |
| Prices and categories | Version them, since Solidus overwrites them | PaperTrail on prices, snapshot on taxons |
| Facts | Append corrections, never update in place | Event date and recorded date on every row |
| Rules | Stamp rule version, run id and code version | rule_version, invocation_id, GIT_SHA |
| Report close | Freeze the marts and register the run | Snapshot tables plus report_runs |
| Recovery | Know your time travel window | BigQuery, seven days |
| Law | Know the retention period and the erasure path | Six years from year end, scrub every version |
None of this needs a big platform. A PostgreSQL database with two date ranges per row and a disciplined habit of never updating in place gets you most of the way. A cloud warehouse with dbt snapshots and quarter close copies gets you the rest.
Conclusion
A past number changes for three reasons: the description changed, the facts were corrected or arrived late, or the rules changed. Each needs its own kind of history. Version dimensions column by column with the slowly changing dimension types, using type 2 for what must stay as it was, type 1 only for corrections, a mini dimension for what changes often and type 6 when people want both views. Let dbt snapshots do the work, with the check strategy wherever updated_at moves for reasons that are not real changes, as it does on every sign in to a Rails shop. Give late and corrected facts a second clock, the date you recorded them, and add correcting rows instead of editing old ones. Treat time travel as an undo button, not an archive. Stamp every row with its rule version, freeze the data at each close, and register every published report. Then, when someone asks why the Kitchen quarter is £19,790 lower than it was, you do not guess. You show them the four runs and the waterfall, and you move on.
