Where cleaning belongs in a pipeline: raw, staging, intermediate and marts, and why raw is never overwritten
TL;DR
Difficulty: Intermediate
Keep an untouched copy of everything exactly as it arrived, and clean it in layers on top of that copy.
- Raw: exactly as received, plus file, line, batch and load time. Append only, never edited.
- Staging: one model per source table, renamed and typed, no joins, no rules.
- Intermediate: business rules, flags instead of deletes, and a quarantine reason for every rejected row.
- Marts: what reports read, protected by contracts.
- Every step idempotent, every row traceable to its raw line, every rule versioned. Keeping raw costs the example shop about two dollars a month.
Every cleaning rule has to live somewhere, and where it lives decides whether you can undo it and explain it later. This chapter builds the layered pipeline step by step for an invented homeware shop in Leeds: a raw layer nobody may change, staging, intermediate and marts in dbt, a quarantine that keeps its reasons, reruns that never double a row, and a trail from any number back to the line in the file it came from.
The question: where does the cleaning go?
The earlier chapters of this series cleaned data one problem at a time: duplicates, missing values, odd spellings, outliers, test orders. Every one of those fixes has to live somewhere. It can live in the source system, in a script that tidies a file, in a dashboard formula, or in a proper pipeline. Where it lives decides two things that matter more than the fix itself: whether you can undo it, and whether you can explain it later.
This chapter answers the reader's question in one sentence, then spends the rest of the article on the detail. Keep an untouched copy of everything exactly as it arrived, clean it in a few clearly separated steps on top of that copy, and never let any step write back into the copy. The rest is how to do that well, with real code, on a real looking shop.
A few terms first, so nobody is left behind.
- A pipeline is the chain of steps that takes data from where it is created (the shop, the warehouse company, the ad platforms) to where people use it (reports, models, emails).
- A layer is one stage of that chain with one job, stored as its own set of tables, usually in its own schema (a schema is a named folder for tables inside a database).
- Raw data is data exactly as it was received. Clean data is data after your rules have been applied.
- A model in dbt (data build tool, the open source transformation tool this series uses) is one SQL file that builds one table or view from other tables.
If you have not read the chapter before this one, business rule cleaning: test orders, bots, refunds and late data, it is worth doing first. It defines the rules. This chapter decides where they run.
Example: the script that ate the evidence
Wrenfield Home is the invented online homeware shop in Leeds that this series follows. Priya owns it, Callum is its developer and data engineer. The shop runs on Ruby on Rails and Solidus, and a third party logistics company (a 3PL, the warehouse that stores, packs and ships the stock) sends a daily CSV file of shipments and returns. The file is semicolon delimited, encoded as Windows 1252, and every SKU (stock keeping unit, the product code) carries the 3PL's own prefix: the shop's WF10234 arrives as TPLWF10234.
Before Callum arrived, a small script handled the file. It opened the CSV, cut the first three characters off every SKU, converted the dates, and saved the result over the original file. Then it loaded that file into the reporting database. It worked for two years.
In spring 2026 the 3PL moved to a new warehouse system, and the prefix became five characters: TPLUKWF10234. The script kept cutting three characters and produced UKWF10234, which matched no product. For six weeks every return failed to match, and the return rate in Priya's report fell from about 9% to nearly zero. Nobody noticed at first, because a falling return rate looks like good news.
When Callum found it, the fix to the script took ten minutes. The data took much longer. The original files no longer existed, because each one had been overwritten by its cleaned version. The only copy of the truth was at the 3PL, and getting six weeks of files resent took a fortnight of emails.
Everything in this chapter exists so that this story cannot happen. With an untouched copy of every file, the fix would have been: change the rule, rebuild from raw, done in an afternoon.
Four layers, each with one job
Almost every well run data platform, whatever it calls things, ends up with the same four stages. The names below are the ones I use, and they follow dbt's own guide to structuring projects.1
- Raw (also called landing): data exactly as received, plus a few columns that record where and when it came in. Nothing is fixed here.
- Staging: one model per source table. Columns renamed to one convention, types cast (text to numbers and dates), light standardisation such as trimming spaces and converting time zones. No joins, no business rules.
- Intermediate: where tables are joined and the business rules live. Test orders flagged, returns matched to orders, duplicates resolved, quarantined rows set aside.
- Marts: tables shaped for the people and tools that use them, one per business concept (orders, customers, returns), with stable column names and tested definitions.
dbt's guide describes this as an arc from "source conformed" data, shaped by systems you do not control, to "business conformed" data, shaped by your own definitions.1 That is the whole idea in four words. The early layers respect the source. The late layers respect the business.
The table below is the one I pin to the wall of every project. It says what each layer may do and, more important, what it may not.
| Layer | May | May not | Usually stored as |
|---|---|---|---|
| Raw | Add load metadata (file, time, batch, row number) | Change, fix, drop or reorder anything that arrived | Append only tables, original files in object storage |
| Staging | Rename, cast types, trim, recode values, convert time zones and units | Join tables, aggregate, apply business rules, drop rows | Views |
| Intermediate | Join, deduplicate, apply business rules, flag and quarantine rows | Be read by reports or end users | Views or ephemeral models |
| Marts | Combine, aggregate, compute business measures | Contain logic that belongs earlier, change column meaning silently | Tables or incremental tables |
Example: one return through all four layers
On Thursday 14 January 2027 a customer's oak serving board comes back to the 3PL damaged. Here is that one return at every layer.
Raw. The line in the 3PL file, character for character, all values stored as text:
| record_type | order_ref | sku | qty | event_time | reason_code | _source_file | _row_number |
|---|---|---|---|---|---|---|---|
| RET | R203948571 | TPLUKWF10234 | 1 | 14/01/2027 16:42 | DAMAGED | movements_20270115.csv | 58 |
Staging. Same row, same grain (one row in, one row out), now typed and renamed. The time, which the 3PL writes in local time with no zone, is converted to UTC (Coordinated Universal Time, the zone the shop database uses). In January, London time equals UTC, so the value does not move. In July it would shift by an hour.
| movement_type | order_number | threepl_sku | quantity | event_at_utc | reason_code |
|---|---|---|---|---|---|
| return | R203948571 | TPLUKWF10234 | 1 | 2027-01-14 16:42:00 UTC | DAMAGED |
Intermediate. The SKU is mapped to the shop's own SKU (WF10234) through a prefix table, joined to the product and the original order, and checked. It passes every check, so its quarantine reason is empty.
Marts. It appears as one row in fct_returns, with the product, the order date, the return reason and the refund value, ready for Priya's monthly return rate.
At no point did any step change the raw row. If the prefix rule turns out to be wrong next year, the raw row is still there, untouched, ready to be cleaned again.
Bronze, silver and gold are the same idea with other names
You will also meet this layering under the name medallion architecture, with bronze, silver and gold layers. The terms come from Databricks, a data platform vendor, and their documentation defines them as bronze for raw data, silver for validated data and gold for enriched data ready for business use.2 It is useful vocabulary, especially when you talk to people who work on Databricks or on a lakehouse (a later chapter on storage explains that word), but it is a vendor's naming, not a standard.
Databricks' own guidance for the bronze layer matches what this chapter recommends for raw: keep the original state of the source, and store most fields as strings so that an unexpected change in the source does not drop data, with metadata columns for provenance such as the file name.2
The mapping is not perfectly one to one, and that is where teams talk past each other.
| This chapter (dbt naming) | Medallion naming | Note |
|---|---|---|
| Raw | Bronze | Same idea |
| Staging | Silver (first half) | Silver often includes deduplication, which here belongs to intermediate |
| Intermediate | Silver (second half) | Business rules may sit in silver or gold depending on the team |
| Marts | Gold | Same idea |
Example: Callum and the agency analyst
A marketing analyst from Priya's ad agency asks Callum for "the silver orders table". Callum checks what she means rather than guessing. She wants orders that are deduplicated and typed but not yet filtered for test orders, because she wants to see the test orders herself. In Callum's project, that is int_orders_deduplicated, an intermediate model. If he had handed her stg_shop__orders (typed but not deduplicated), her customer counts would have been 3.1% too high, because 3.1% of customer accounts at Wrenfield Home are duplicates.
The lesson is small and practical: when someone says bronze, silver or gold, ask which rules have been applied. The colour does not tell you.
The raw layer keeps everything exactly as it arrived
Raw sounds like the easy layer. It is the one most often done wrong, because it is tempting to fix "just one little thing" on the way in. Do not. Raw has three jobs.
- Keep the content exactly. Every row, every column, every odd value. If the source sends a date as "14/01/2027 16:42", raw stores that text, not a parsed date.
- Record where it came from. A handful of metadata columns on every row. I prefix them with an underscore so they never collide with a source column.
- Make it impossible to change afterwards. Permissions and storage settings, not good intentions.
The metadata columns I put on every raw table:
| Column | What it holds | Why |
|---|---|---|
_source_file | File name, or the source table and extract name | Find the original in seconds |
_file_sha256 | A fingerprint (SHA 256 hash) of the original file's bytes | Detect a file sent twice, prove nothing changed |
_row_number | Line number in the file | Point at the exact line when you ask the sender about it |
_batch_id | One identifier per load run | Remove or reload exactly one load if it went wrong |
_loaded_at | When the row was written, in UTC | Freshness checks, and late data detection |
Kimball Group's list of the subsystems every extract, transform and load (ETL) system needs names the tension that this layer solves: the warehouse is expected to fix dirty data, and at the same time to give an accurate picture of the data as the organisation's systems captured it.3 A raw layer that never changes is how you satisfy both. The accurate picture is raw. The fixed picture is everything after it.
The encoding trap
The 3PL file is encoded as Windows 1252. BigQuery's documentation lists the encodings it accepts for CSV loads: UTF-8, ISO-8859-1 and four UTF 16 and UTF 32 variants.4 Windows 1252 is not on the list. It is close to ISO-8859-1, but not the same: the bytes from 0x80 to 0x9F differ, and that is exactly where the euro sign, curly quotes and the long dash live in Windows 1252. Load the file as ISO-8859-1 and a product called "Café set" survives, but a supplier note with a euro sign or curly quotes turns into control characters without any error.
So the original bytes are kept as a file, untouched, and the loader decodes them strictly as Windows 1252 before writing UTF 8 rows into the raw table. "Strictly" matters: five byte values are undefined in Windows 1252, and a strict decoder stops on them instead of guessing. A file that will not decode is itself a finding, and goes to quarantine as a whole file.
Example: landing the 3PL file of 15 January 2027
This is Callum's loader, in Python with Google's client libraries for Cloud Storage and BigQuery. It keeps the original file, refuses to overwrite it, refuses to load the same file twice, decodes strictly, and stores every value as text with the metadata columns.
import csv
import hashlib
import io
import uuid
from datetime import datetime, timezone
from pathlib import Path
from google.cloud import bigquery, storage
RAW_BUCKET = "wrenfield-raw-landing"
RAW_TABLE = "wrenfield-data.raw_threepl.movements"
COLUMNS = ["record_type", "order_ref", "sku", "qty", "event_time", "reason_code"]
def land_threepl_file(path: Path) -> str:
raw_bytes = path.read_bytes()
file_sha256 = hashlib.sha256(raw_bytes).hexdigest()
bq = bigquery.Client()
# 1. Same bytes already loaded? Then do nothing (safe to run twice).
seen = bq.query(
f"select count(*) as n from `{RAW_TABLE}` where _file_sha256 = @h",
job_config=bigquery.QueryJobConfig(
query_parameters=[bigquery.ScalarQueryParameter("h", "STRING", file_sha256)]
),
).result()
if next(iter(seen)).n > 0:
return "already loaded"
# 2. Keep the original bytes. if_generation_match=0 means:
# only create, never replace an existing object.
blob = storage.Client().bucket(RAW_BUCKET).blob(f"threepl/{path.name}")
blob.upload_from_filename(str(path), if_generation_match=0)
# 3. Decode strictly. An undefined byte raises UnicodeDecodeError.
text = raw_bytes.decode("cp1252")
# 4. Every value stays a string. Only metadata is added.
batch_id = str(uuid.uuid4())
loaded_at = datetime.now(timezone.utc).isoformat()
reader = csv.reader(io.StringIO(text, newline=""), delimiter=";")
header = next(reader)
if [h.strip().lower() for h in header] != COLUMNS:
raise ValueError(f"unexpected header in {path.name}: {header}")
rows = []
for line_no, values in enumerate(reader, start=2):
row = dict(zip(COLUMNS, values))
row.update(
_source_file=path.name,
_file_sha256=file_sha256,
_row_number=line_no,
_batch_id=batch_id,
_loaded_at=loaded_at,
)
rows.append(row)
schema = [bigquery.SchemaField(c, "STRING") for c in COLUMNS] + [
bigquery.SchemaField("_source_file", "STRING"),
bigquery.SchemaField("_file_sha256", "STRING"),
bigquery.SchemaField("_row_number", "INT64"),
bigquery.SchemaField("_batch_id", "STRING"),
bigquery.SchemaField("_loaded_at", "TIMESTAMP"),
]
job = bq.load_table_from_json(
rows,
RAW_TABLE,
job_config=bigquery.LoadJobConfig(schema=schema, write_disposition="WRITE_APPEND"),
)
job.result()
return f"loaded {len(rows)} rows, batch {batch_id}"
Three details carry the weight.
- The
if_generation_match=0precondition tells Cloud Storage to create the object only if no live object of that name exists; otherwise the upload fails.5 An accidental second upload cannot replace the original. - The fingerprint check makes the whole function safe to run twice. A scheduler that retries after a timeout loads nothing new the second time.
- The header check stops a silent column shift. If the 3PL adds a column in the middle, the load fails loudly instead of putting quantities into the reason column.
On 15 January the file movements_20270115.csv arrives with 81 data lines: 74 shipments and 7 returns. The loader stores the file, decodes it, and appends 81 raw rows with one batch identifier. The damaged oak serving board is the 57th data line, stored as _row_number = 58, because line 1 of the file is the header. That off by one is why I store the line number from the file, not a counter I invented: when Callum emails the 3PL about "line 58", they open the file and find exactly that line.
Why raw is never overwritten
Keeping raw untouched costs some storage and some discipline. It pays back in four situations, and every data platform meets all four within its first year.
- A rule changes. The SKU prefix story. With raw kept, a changed rule is a rebuild, not a recovery project.
- Someone asks how a number was made. An auditor, a tax adviser or a sceptical director asks where a figure came from. Raw is the evidence that the source really said what you claim it said.
- Something looks wrong and you need to debug. Comparing raw with staging with marts, row by row, tells you exactly which step introduced a problem. Without raw, you can only argue about it.
- A source sends a correction or a late file. The 3PL's returns arrive up to five days late. Payment providers settle days later. With raw kept by load time, you can see exactly what you knew on any given day, which a later chapter on history and audit trails builds on.
Making raw untouchable is a matter of settings, not trust:
- Only the loader's service account may write to the raw dataset, and it may only append. People and dbt get read access.
- The landing bucket keeps object versioning switched on, so even a deleted file survives as a noncurrent version.6
- Cloud Storage also offers Bucket Lock, a retention policy that, once locked, can never be shortened or removed.7 That is right for data you are legally required to keep unchanged. It is wrong for anything holding personal data you might have to erase, which the privacy section below comes back to.
Example: the prefix change, replayed with a raw layer
Replay the spring 2026 story with the layers in place. On the day the prefix becomes TPLUK, the intermediate check finds that 66 shipment rows and 7 return rows in that day's file match no product. They go to quarantine with the reason "sku not in catalogue". The next morning, the data quality summary shows 73 quarantined rows instead of the usual zero to three. Callum looks at the quarantine table, sees the new prefix at a glance, adds TPLUK to the prefix mapping seed, and reruns. The rows leave quarantine on their own, because quarantine is recomputed from raw on every run (more on that below). Return rate for the day: back to normal. Time lost: one day, not six weeks. Emails to the 3PL: none.
What keeping raw actually costs
The usual objection to keeping everything is cost. For a business of Wrenfield Home's size, the honest answer is that raw storage is close to free and the expensive part is something else.
The monthly storage cost is the stored volume above the free allowance, times the price per unit:
where is the monthly cost, is the stored volume in gibibytes (GiB, 1,024 mebibytes), is the free allowance per month and is the price per GiB per month. This is a plain rate times a quantity, see Foundations: ratios and rates.
Google's BigQuery price list, read on 23 November 2026, shows active logical storage at USD 0.000031507 per GiB hour, which is about USD 0.023 per GiB a month, long term storage (tables or partitions not modified for 90 days) at about USD 0.016, and the first 10 GiB free each month.8 Prices differ by region and are listed in US dollars, so check the region you actually use.
Example: Wrenfield Home's raw layer, priced
Callum estimates the raw volume after five years of trading. The numbers are invented for the example, but the proportions are typical: the analytics event export dwarfs everything else.
| Source | Raw volume (GiB) |
|---|---|
| GA4 daily BigQuery export, three years | 90 |
| Supplier product feeds, daily full files | 8 |
| Shop database extracts (changes only) | 6 |
| Newsletter, tickets, marketing cost sheet | 2 |
| Google Ads and Meta cost data | 1 |
| Stripe and PayPal settlement files | 0.5 |
| 3PL shipments and returns | 0.03 |
| Total | 107.53 |
Worked through at the active price, as the worst case:
With , and , that is about dollars a month, and less in practice because most of it is older than 90 days and billed at the long term rate. The 3PL files, the source with the most cleaning problems, cost a fraction of a cent.
Two traps can still make raw expensive, and both are worth knowing.
- Daily full copies of large tables. If the loader copied the whole
spree_orderstable every night instead of only changed rows, five years of nightly copies of a table that ends up around 0.4 GiB would add up to roughly 365 copies a year, over 140 GiB a year for one table. The fix is to land changes only, which the later chapter on incremental loading and change data capture covers, or to keep daily full copies for 30 days and monthly ones after that. - Rebuilding from raw too often. Storage costs little, reading is billed. The price list shows on demand queries at USD 6.25 per tebibyte (TiB, 1,024 GiB) scanned after the first free TiB each month, in the region shown.8 A full rebuild of every model except the GA4 ones reads about 20 GiB at Wrenfield Home: 20 / 1,024 × USD 6.25, about 12 cents. Doing that every hour for a month would be about USD 90. Doing it when a rule changes is nothing.
The real cost of raw is not money. It is the discipline to treat it as read only, and the time to design the metadata properly on day one.
Staging: typed, renamed, one model per source table
Staging turns each raw table into a clean building block. dbt's guide is precise about what belongs here: renaming, type casting, basic computations such as converting units, and categorising values with simple conditions. It is equally precise about what does not: no joins and no aggregations, and staging models are usually built as views.9 Its naming convention is stg_[source]__[entity]s, with a double underscore between the source system and the entity, so stg_threepl__movements and stg_shop__orders can never be confused.9
The reason for these limits is that staging is the one place each source is translated into your conventions, once. Anything every later model needs, such as UTC time stamps or SKUs without stray spaces, belongs here, so nobody has to repeat it. Anything that involves another table, or a decision about what the business means, belongs later.
Before staging can read raw, dbt needs to know raw exists. That is a source definition, which also carries a freshness check: an alert if the newest row is older than you expect. Since dbt 1.10 the freshness settings and the loaded_at_field sit under config.10
# models/staging/threepl/_threepl__sources.yml
version: 2
sources:
- name: threepl
database: wrenfield-data
schema: raw_threepl
tables:
- name: movements
description: "Daily 3PL shipments and returns, exactly as received."
config:
loaded_at_field: _loaded_at
freshness:
warn_after: {count: 26, period: hour}
error_after: {count: 50, period: hour}
The file comes once a day, so a warning after 26 hours catches a missed file before the morning report, with two hours of slack for a late delivery.
Example: the staging model for the 3PL file
This model is BigQuery SQL inside dbt. It keeps one row per raw row, never drops anything, and turns every failed conversion into an empty value instead of an error, so that the checks in the next layer can see and name the problem. The SAFE. prefix in BigQuery makes a function return NULL instead of failing,11 and TIMESTAMP(datetime, time_zone) reads a local date and time as a moment in the named zone.12
-- models/staging/threepl/stg_threepl__movements.sql (BigQuery dialect)
with source as (
select * from {{ source('threepl', 'movements') }}
),
renamed as (
select
-- one stable key per raw line: file fingerprint plus line number
{{ dbt_utils.generate_surrogate_key(['_file_sha256', '_row_number']) }}
as movement_row_id,
case upper(trim(record_type))
when 'SHP' then 'shipment'
when 'RET' then 'return'
end as movement_type,
upper(trim(order_ref)) as order_number,
upper(trim(sku)) as threepl_sku,
safe_cast(trim(qty) as int64) as quantity,
-- the 3PL writes local UK time without a zone
safe.parse_datetime('%d/%m/%Y %H:%M', trim(event_time))
as event_local_datetime,
timestamp(
safe.parse_datetime('%d/%m/%Y %H:%M', trim(event_time)),
'Europe/London'
) as event_at_utc,
nullif(upper(trim(reason_code)), '') as reason_code,
-- the original text, kept for the quarantine report
record_type as raw_record_type,
qty as raw_qty,
event_time as raw_event_time,
_source_file,
_file_sha256,
_row_number,
_batch_id,
_loaded_at
from source
)
select * from renamed
The generate_surrogate_key macro comes from the dbt_utils package and builds a hashed key from the listed fields in a way that works across databases.13 Because the file fingerprint and the line number never change, the same raw line gets the same movement_row_id on every run, forever. That key is what makes lineage and quarantine work later.
Take line 58 from the 15 January file through it. record_type "RET" becomes movement_type "return". qty "1" becomes the integer 1. "14/01/2027 16:42" parses to the local date and time 2027-01-14 16:42, and since London is on UTC in January, event_at_utc is 2027-01-14 16:42:00 UTC. Had the line said "14/07/2027 16:42", the result would be 15:42 UTC, because London is one hour ahead of UTC in summer.
One honest weakness remains. On the last Sunday of October, the clocks go back and the hour from 1am to 2am happens twice. A local time of "25/10/2026 01:30" is genuinely ambiguous, and no function can know which of the two moments the 3PL meant. Callum adds a check for local times inside that hour on that day, and asks the 3PL to send UTC or an offset in the next version of the file. That is a fix at the source, the first choice in when to clean data and when to leave it alone. The full treatment of dates and time zones is in standardising values.
Quarantine: rejected rows keep their reason
Every pipeline meets rows it cannot use: a SKU that does not exist, a quantity of "two", a date that will not parse. There are three things you can do with such a row, and only one of them is good.
- Drop it silently. The total in the report is now wrong, and nobody can ever find out by how much. This is the most common choice and the worst.
- Fail the whole run. Safe, but one bad line in a file of 2,400 stops every report for the whole business until someone fixes it.
- Quarantine it. Set the row aside in its own table, with the reason it failed, keep processing the rest, and report how many rows are in quarantine every day.
Kimball Group calls this "error event tracking": capture every error event, because those events are what data quality improvement is built on.3 In a dbt project, the cleanest way I know is to compute a reason for every row in one intermediate model, then split it. Rows with no reason go on to the marts. Rows with a reason go to the quarantine model. Nothing is ever deleted.
-- models/intermediate/threepl/int_threepl_movements_checked.sql (BigQuery)
with movements as (
select * from {{ ref('stg_threepl__movements') }}
),
prefixes as (
-- seed: one row per known 3PL prefix, e.g. TPL and TPLUK
select prefix from {{ ref('threepl_sku_prefixes') }}
),
mapped as (
select
m.*,
substr(m.threepl_sku, length(p.prefix) + 1) as shop_sku
from movements m
left join prefixes p
on starts_with(m.threepl_sku, p.prefix)
where true
-- keep the longest known prefix that matches, one row per raw line
qualify row_number() over (
partition by m.movement_row_id
order by length(p.prefix) desc
) = 1
),
checked as (
select
mapped.*,
v.variant_id,
row_number() over (
partition by movement_type, order_number, threepl_sku, quantity, event_local_datetime
order by _loaded_at, _source_file, _row_number
) as copy_number,
case
when movement_type is null then 'unknown record type: ' || coalesce(raw_record_type, '')
when quantity is null then 'quantity not a whole number: ' || coalesce(raw_qty, '')
when quantity <= 0 then 'quantity not positive'
when event_at_utc is null then 'event time not parseable: ' || coalesce(raw_event_time, '')
when shop_sku is null then 'sku has no known 3PL prefix'
when v.variant_id is null then 'sku not in catalogue'
end as quarantine_reason
from mapped
left join {{ ref('stg_shop__variants') }} v
on v.sku = mapped.shop_sku
)
select * from checked
Two models then split it. The clean one keeps only the first copy of rows that passed; the quarantine one keeps every row that failed.
-- models/intermediate/threepl/int_threepl_movements_clean.sql
select * from {{ ref('int_threepl_movements_checked') }}
where quarantine_reason is null
and copy_number = 1
-- models/marts/quality/qrn_threepl_movements.sql
{{ config(materialized='table') }}
select
movement_row_id,
quarantine_reason,
_source_file,
_row_number,
_loaded_at,
current_timestamp() as checked_at
from {{ ref('int_threepl_movements_checked') }}
where quarantine_reason is not null
Notice the duplicate handling. A file the 3PL sends twice under different names has a different fingerprint, so the loader accepts it, and its rows land in raw a second time. That is correct: raw records what was received. The row_number() window then keeps the first copy by load time, file name and line number. The order by has three columns on purpose: with only _loaded_at, two rows loaded in the same second could swap places between runs, and the "first copy" would change. A tie breaker that can never tie makes the result deterministic. Exact duplicates are not quarantined, because they are not errors in content. They are counted separately.
The design choice worth naming is that quarantine is recomputed from raw on every run, not a bin that rows fall into and never leave. When Callum adds a missing product to the catalogue, last week's rows for that SKU pass the check on the next run and appear in the marts. That is exactly what you want for correctness. It also means a past week's numbers can change, which is why the later chapter on reporting cleaned data deals with restatements.
Example: January 2027 in the 3PL data
In January 2027 the 3PL sends 31 files with 2,412 data lines in total. After the run on 1 February:
- 2 lines are exact copies from a file the 3PL resent under a new name. Removed as duplicates.
- 9 lines carry SKUs that are not in the catalogue. Seven are a new candle range the 3PL received before the products were set up in the shop, two are a typing error at the 3PL (
WF1O234with a letter O). - 3 lines have the event time "00/01/1900 00:00", the 3PL system's placeholder for "not scanned".
- 2,398 lines pass and reach the marts.
The rows are all accounted for. That is a rule worth writing as a formula, because it is the single most useful test of any cleaning pipeline: every raw row must end up in exactly one place.
where is the number of raw rows in the period, the rows that reached the marts, the rows held in quarantine and the exact copies removed. It is simple counting, the same bookkeeping as in Foundations: ratios and rates, where every part must add back to the whole. Worked through for January:
Here , and , which add back to exactly.
The quarantine rate is a share of the whole, see Foundations: ratios and rates:
where is the quarantine rate and the other symbols are as above. For January:
So of lines are quarantined. Callum sets an alert at 2%, roughly four times the normal level. The spring 2026 prefix change would have pushed one day's rate to 73 out of 81 lines, 90%, and the alert would have fired on the first morning.
The conservation rule becomes a singular dbt test, a SQL file that returns rows only when something is wrong.14
-- tests/assert_threepl_rows_conserved.sql
with counts as (
select
(select count(*) from {{ source('threepl', 'movements') }}) as n_raw,
(select count(*) from {{ ref('int_threepl_movements_clean') }}) as n_clean,
(select count(*) from {{ ref('qrn_threepl_movements') }}) as n_quarantine,
(select count(*) from {{ ref('int_threepl_movements_checked') }}
where quarantine_reason is null and copy_number > 1) as n_dup
)
select * from counts
where n_raw != n_clean + n_quarantine + n_dup
If any later change makes a model lose rows, for example a join that should have been a left join, this test fails before the report is built. dbt can also store the failing rows of its tests in tables of their own with store_failures,15 which is useful for audit. It is not a replacement for quarantine, because test failures describe a model's problems, while quarantine is part of the data flow and is meant to be read by people every week.
Intermediate: where the business rules live
The intermediate layer is where data stops looking like its source and starts looking like the business. dbt's guide describes intermediate models as purpose built steps between staging and marts, named after what they do, with verbs, such as int_order_items_summed_to_orders, and suggests building them as ephemeral models or as views in a schema end users do not read.16
This is where everything from the earlier cleaning chapters lands: duplicate customers merged, values standardised that needed a lookup table, test orders and bots flagged, late returns matched to their orders. Two rules keep this layer honest.
- Flag, do not delete. A test order gets
is_test_order = trueand stays in the table. The mart decides what to exclude. That way the same intermediate model can feed finance (which may need to see every order, including tests) and marketing (which must not). - Every rule carries its version. A rule written down in the rule register from the chapter on when to clean has an identifier and a version number. The model writes that version onto every row it touched.
Example: the test order rule, version 2
About 40 test and staff orders a year sit in Wrenfield Home's order table. The first version of the rule caught only orders placed with an @wrenfieldhome.example email address. In 2026 that flagged 31 orders. Callum then found nine more: staff orders placed with personal email addresses for photo shoots, all paid with a 100% staff voucher. Version 2 adds a seed file of known staff accounts.
rule_id,version,valid_from,owner,description
test_orders,1,2025-03-01,Callum,"Orders from @wrenfieldhome.example addresses are tests"
test_orders,2,2027-01-11,Callum,"Version 1 plus orders from the staff accounts listed in seeds/staff_accounts.csv"
That is seeds/rule_register.csv. Seeds are CSV files kept in the dbt project, version controlled and reviewable, which suits small reference data like this.17 The model:
-- models/intermediate/shop/int_orders_flagged.sql (BigQuery)
with orders as (
select * from {{ ref('int_orders_deduplicated') }}
),
staff as (
select lower(trim(email)) as email from {{ ref('staff_accounts') }}
),
current_rule as (
select max(version) as version
from {{ ref('rule_register') }}
where rule_id = 'test_orders'
)
select
orders.*,
(
ends_with(lower(orders.email), '@wrenfieldhome.example')
or lower(trim(orders.email)) in (select email from staff)
) as is_test_order,
(select version from current_rule) as test_order_rule_version
from orders
With version 2, 40 orders in 2026 are flagged instead of 31. The nine extra orders at the average order value of £72 move £648 out of 2026's reported revenue. Because the rule version sits on every row, Priya's report can say "revenue excludes test orders, rule version 2", and anyone who wants to know what changed can read the register.
Marts: tables shaped for the people who use them
Marts are the only layer reports and tools read. dbt's guide describes them as entity grained: one mart per business concept such as an order, a customer or a payment, each row one instance of it, materialised as tables or incremental tables because that is where speed for the reader matters.18 The grain and the keys behind that idea are explained in data modelling for analytics.
Because marts are what people build reports on, their shape must not change by accident. dbt's model contracts make the column names and data types part of the model's definition: with contract: enforced: true, dbt checks before building that the query returns exactly those columns and types, and refuses to build if not.19
Example: the returns mart and its contract
# models/marts/operations/_operations__models.yml
version: 2
models:
- name: fct_returns
description: "One row per returned item line received by the 3PL. Clean rows only."
config:
contract:
enforced: true
columns:
- name: movement_row_id
data_type: string
constraints:
- type: not_null
- name: order_number
data_type: string
- name: shop_sku
data_type: string
- name: quantity
data_type: int64
- name: returned_at_utc
data_type: timestamp
- name: reason_code
data_type: string
- name: test_order_rule_version
data_type: int64
If Callum later renames reason_code in an intermediate model and forgets the mart, the build stops with a contract error instead of quietly breaking Priya's return reasons chart. Of January's 2,398 clean lines, 176 are returns, from 165 orders. Against 1,834 orders shipped in the month, that is a return rate of about 9.0%, in line with the shop's usual 9%.
Idempotent transformations: same input, same output, safe reruns
Idempotent is an old mathematical word for a simple promise: running a step twice has the same effect as running it once. For a pipeline, it means you can rerun any job, after a failure, a timeout or a fix, without doubling rows or losing them. It is the property that lets you sleep.
Three habits make transformations idempotent.
- Replace, do not append. A model that adds "today's rows" to a table doubles them when it runs twice. A model that replaces a whole day, or the whole table, gives the same result however often it runs.
- No hidden inputs. A model that uses
current_date()inside its logic gives a different answer tomorrow from the same data. Pass the date in as a variable, or derive it from the data. - Deterministic order. Any "keep the first row" logic needs a tie breaker that can never tie, as in the duplicate handling above.
For large tables, dbt's incremental models process only new data. On BigQuery the insert_overwrite strategy replaces whole partitions (a partition is a slice of a table, usually one day) instead of appending rows, and with dynamic partitions dbt exposes the newest partition already in the table as the BigQuery variable _dbt_max_partition.20 Replacing partitions is idempotent by design: the partitions touched by a run are rebuilt completely.
Example: the Tuesday rerun, and the late returns
Returns from the 3PL can arrive up to five days after the event. So fct_returns is partitioned by return date, and every run rebuilds the last seven days of partitions, which covers the five day delay with two days to spare.
-- models/marts/operations/fct_returns.sql (BigQuery)
{{
config(
materialized='incremental',
incremental_strategy='insert_overwrite',
partition_by={'field': 'returned_at_utc', 'data_type': 'timestamp', 'granularity': 'day'},
on_schema_change='fail'
)
}}
select
movement_row_id,
order_number,
shop_sku,
quantity,
event_at_utc as returned_at_utc,
reason_code,
o.test_order_rule_version
from {{ ref('int_threepl_movements_clean') }} m
join {{ ref('int_orders_flagged') }} o using (order_number)
where m.movement_type = 'return'
and not o.is_test_order
{% if is_incremental() %}
-- rebuild the last 7 days of partitions on every run: late 3PL returns land here
and date(m.event_at_utc) >= date_sub(date(_dbt_max_partition), interval 7 day)
{% endif %}
On Tuesday 19 January the nightly run fails halfway because the BigQuery connection times out. The scheduler retries it. With this model, the retry simply rebuilds the partitions from 12 January onwards again, and the 18 January partition still holds seven returns, not fourteen.
Compare the version Callum inherited, which simply appended "returns received since the last run". The retry appended the same seven returns again. That day's return count showed 14 instead of 7, the week's return rate rose from 9% to about 10.3%, and it stayed wrong until someone noticed. One design is safe to retry. The other needs a human every time something hiccups.
The late data case works the same way. A damaged lamp returned on 11 January only appears in the 3PL's file of 15 January. The run on 15 January rebuilds partitions from 8 January onwards, so the lamp lands in the 11 January partition, where it belongs. A return arriving more than seven days late would be missed by the incremental run, so Callum also runs a full refresh every Sunday night (dbt build --full-refresh --select fct_returns).21 At 0.03 GiB of 3PL data, that costs nothing.
Audit columns: every row can say where it came from
By the time a row reaches a mart, it should still be able to answer four questions: which raw line it came from, which load brought it in, which run of the pipeline built it, and which version of each rule touched it. Kimball Group's ETL subsystems include an "audit dimension", metadata attached to each fact that business intelligence tools can show to make data quality visible.3 In a dbt project, a few columns do that job.
| Column | Set in | Holds |
|---|---|---|
movement_row_id | Staging | Stable key of the raw line (file fingerprint plus line number) |
_source_file, _row_number | Raw, carried through | The original file and line |
_batch_id, _loaded_at | Raw, carried through | The load that brought it in |
dbt_run_id | Mart | The dbt run that built it |
test_order_rule_version and similar | Intermediate | The version of each business rule applied |
For the run identifier, dbt provides invocation_id, a unique identifier for each dbt command, which dbt also attaches as a label to every BigQuery job it starts.22 Adding '{{ invocation_id }}' as dbt_run_id to a mart's select list costs one line and connects every row to the run's logs and to the cost of the queries that built it.
Example: what changed between two runs
Priya notices that 2026's revenue in her report fell by £648 between Monday and Tuesday. Callum looks at the orders mart: every row of Tuesday's table carries a new dbt_run_id and test_order_rule_version = 2, and the run log shows Monday's run applied version 1. He lists the orders flagged under version 2 but not under version 1: nine staff orders, nine times £72, exactly £648. A question that used to start an afternoon of guesswork is answered in a query.
Reprocessing: when a rule changes, rebuild from raw
Rules change. A new prefix, a better test order definition, a corrected currency conversion. With raw kept and every step idempotent, there are only two questions to answer when a rule changes.
- Does the change apply to the past? A bug fix almost always does: the old numbers were wrong. A genuine change of definition (from now on, gift card sales count as revenue only when redeemed) may apply only from a date, in which case the rule carries a
valid_fromand the model applies the old or new version by date. - Who relies on the old numbers? A figure already sent to an accountant or a board needs a restatement, handled as the later chapter on reporting describes. A figure only used internally can simply be corrected, with a note.
Rebuilding is one command in dbt: dbt build --full-refresh --select int_orders_flagged+, where the + after a model selects it and everything downstream of it.23 The comparison step is where most teams cut corners, and it is the one that catches the surprise. Before the new output replaces the old, Callum builds it into a development schema and compares totals by month.
Example: rebuilding five years for the test order rule
Version 2 of the test order rule corrects an error, so it applies to all five years. Callum runs the rebuild in his development schema first. It reads about 6 GiB of shop data and builds every downstream model. The comparison:
| Year | Test orders flagged, version 1 | Version 2 | Revenue moved |
|---|---|---|---|
| 2022 | 29 | 37 | £576 |
| 2023 | 33 | 41 | £576 |
| 2024 | 30 | 39 | £648 |
| 2025 | 32 | 40 | £576 |
| 2026 | 31 | 40 | £648 |
The movements are small against annual revenue of about £1.7 million, but 2025's accounts have already gone to the accountant, so Priya decides that the management report shows both figures for 2025 with a note, and the corrected figures from 2026 onwards. The rebuild costs a few cents. The judgement about who needs to know costs a conversation, and that conversation is the real work.
Lineage: from a number in a report back to the raw row
Lineage is the path a number took through the pipeline. At the model level, dbt draws it for you: its documentation site shows a graph of which model reads from which, from sources to marts. A later chapter on metadata and catalogues covers that in depth. At the row level, lineage is what the stable keys and audit columns above are for. Because movement_row_id is computed once in staging and carried to the mart, any row in any report can be traced back to one line in one file.
Example: 23 returns or 24?
Priya compares the January return count for the oak serving board, WF10234: the report says 23, the 3PL's own portal says 24. Callum starts from raw, not from the report, and lets each layer explain itself:
-- BigQuery: every raw line for this product in January, and where it ended up
select
c.movement_row_id,
c._source_file,
c._row_number,
c.copy_number,
c.quarantine_reason,
r.movement_row_id is not null as in_fct_returns
from {{ ref('int_threepl_movements_checked') }} c
left join {{ ref('fct_returns') }} r using (movement_row_id)
where c.movement_type = 'return'
and c.threepl_sku like '%WF1_234'
and date(c.event_at_utc) between '2027-01-01' and '2027-01-31'
order by c._loaded_at
Twenty four rows come back. Twenty three are in fct_returns. The twenty fourth has the reason "sku not in catalogue": its SKU is TPLUKWF1O234, with a capital O instead of a zero, from line 12 of movements_20270122.csv. The pattern WF1_234 in the query, where _ matches any single character, found it on purpose. Callum emails the 3PL with the file name and line number. They correct it at their end and resend the line, the next run picks it up, and both systems say 24. No number was edited by hand anywhere, and the whole trail is in the data.
A dbt project layout for the whole shop
Putting it together, this is the layout Callum uses. It follows dbt's guide: staging folders by source system, intermediate and marts folders by business area.1
wrenfield_dbt/
├── dbt_project.yml
├── seeds/
│ ├── rule_register.csv
│ ├── staff_accounts.csv
│ └── threepl_sku_prefixes.csv
├── models/
│ ├── staging/
│ │ ├── shop/ # stg_shop__orders, stg_shop__line_items, stg_shop__variants ...
│ │ ├── threepl/ # stg_threepl__movements
│ │ ├── ga4/ # stg_ga4__events
│ │ ├── ads/ # stg_google_ads__costs, stg_meta_ads__costs
│ │ └── payments/ # stg_stripe__balance_transactions, stg_paypal__settlements
│ ├── intermediate/
│ │ ├── shop/ # int_orders_deduplicated, int_orders_flagged, int_customers_resolved
│ │ └── threepl/ # int_threepl_movements_checked, int_threepl_movements_clean
│ └── marts/
│ ├── finance/ # fct_orders, fct_refunds
│ ├── marketing/ # fct_ad_costs, dim_customers
│ ├── operations/ # fct_returns, fct_shipments
│ └── quality/ # qrn_threepl_movements, qrn_shop_orders, data_quality_daily
└── tests/
└── assert_threepl_rows_conserved.sql
# dbt_project.yml (the parts that matter here)
name: wrenfield
version: "1.0.0"
profile: wrenfield
models:
wrenfield:
staging:
+materialized: view
+schema: staging
intermediate:
+materialized: view
+schema: intermediate
marts:
+materialized: table
+schema: marts
One detail surprises everyone the first time. By default, dbt names a custom schema by joining the target schema and the custom schema, so with a target schema of analytics, the staging models land in analytics_staging, not staging.24 That is deliberate: two developers working in dbt_callum and dbt_priya never overwrite each other's staging views. You can change the behaviour with a macro, but understand it before you do.
Example: who may read what
Callum maps permissions to the layers, so that the structure also protects people from the wrong table:
| Dataset | Callum (loader and dbt) | Priya and reports | Agency analyst |
|---|---|---|---|
raw_* | Loader appends, dbt reads | No access | No access |
analytics_staging, analytics_intermediate | Read and build | No access | Read, on request |
analytics_marts | Read and build | Read | Read the marketing marts only |
A dashboard that cannot see staging cannot accidentally count duplicate customers.
Raw that must be deleted: the right to erasure
"Never overwrite raw" has exactly one exception, and it comes from the law, not from convenience. If a customer exercises the right to erasure and no exemption applies, their personal data has to go, from raw as well as from everything built on it. This is general information, not legal advice. Your own situation needs your own adviser.
In the UK, Article 17 of the UK GDPR gives people the right to have personal data erased without undue delay where one of its grounds applies,25 and Article 5(1)(e), the storage limitation principle, says personal data may be kept in an identifiable form only as long as necessary for its purpose.26 The Information Commission (formerly the Information Commissioner's Office, ICO) is explicit that this reaches backups: you must take steps to erase from backup systems as well as live ones, and where backup data cannot be overwritten at once, it must be put "beyond use" until it is.27 A raw layer is not a backup, it is a live, queryable copy, so the "beyond use" route does not fit it at all. Raw rows holding personal data must be erasable.
Erasure from raw is therefore a separate, logged process, never a transformation:
- Keep personal data out of raw where you can. The 3PL file needs the order number, not the customer's name. Ask sources for identifiers instead of names and addresses, and drop columns you never use at landing, documented in the loader.
- Erase by key, and log it. For BigQuery raw tables, a
DELETEby customer key, run by a dedicated erasure job, recorded in an erasure log with the date and a pseudonymous reference (not the email address itself). - Rewrite affected files. Original files usually hold many customers, so the erasure job writes a new version without that person's rows and records the old file's fingerprint as replaced by erasure. Noncurrent object versions have to be deleted too, or they still hold the data.
- Reapply after any reload. The erasure log doubles as a suppression list the loader checks, so a source that resends old data cannot bring an erased person back.
- Mind the platform's own retention. BigQuery keeps changed or deleted data in time travel for up to seven days by default (configurable from two to seven) and then a further seven days of fail safe that cannot be shortened.28 Tell the customer honestly when erasure is complete.
This is also why Bucket Lock, mentioned earlier, should never protect a bucket of personal data: a locked retention policy cannot be shortened, so it would make a lawful erasure impossible.7 Records you must keep for tax and company law are a different question, with their own periods, which the chapter on history and audit trails covers. A later chapter on privacy engineering goes much deeper on erasure across a whole platform.
Example: an erasure request at Wrenfield Home
A customer from Bristol asks Wrenfield Home to erase her data. Priya checks with her adviser which records must be kept for tax and which must go. Callum's erasure job then runs: it deletes her rows from raw_shop.users and raw_shop.addresses by user identifier, rewrites the two newsletter export files that contain her address and deletes their old versions, adds her pseudonymous key to the erasure log, and rebuilds the affected marts. The 3PL files need nothing: they never contained her name, only order numbers. The log records the request date, the completion date, and the date by which BigQuery's time travel and fail safe will have expired, fourteen days later. That last date is the one Priya gives the customer.
Smaller shops: the same layers in PostgreSQL alone
None of this requires a cloud warehouse. For a shop smaller than Wrenfield Home, or one just starting, a separate PostgreSQL database (never the shop's live database) with four schemas does the same job: raw, staging, intermediate and marts. dbt Core works with PostgreSQL through its PostgreSQL adapter.29 The SQL changes a little: PostgreSQL converts a local time without zone with AT TIME ZONE,30 for example (event_local_datetime AT TIME ZONE 'Europe/London') gives a timestamp with time zone.
The principles do not change at all. Raw stays append only, staging is one view per source table, rules live in intermediate, reports read only marts, quarantine keeps its reasons, and every run can be repeated. When the data outgrows PostgreSQL, the layers move to a warehouse almost unchanged, which is the subject of the next chapter on storage. If you want the cloud setup for a Rails and Solidus shop, setting up Google BigQuery for a Rails and Solidus shop walks through it, and data warehousing for marketing automation shows what the marts can then feed.
Example: a small homeware shop's first layered pipeline
Picture a shop with 200 orders a month and one person who does the data on Fridays. Week one: create the raw schema and copy the 3PL file into it each day as text, with the five metadata columns. Week two: one staging view per raw table, nothing else. Week three: one intermediate view with the quarantine reasons, and one mart for orders. Week four: the conservation test and a freshness check. A month of Fridays, and the shop has the same guarantees as Wrenfield Home, minus the scale.
How this fits the way I work
I build online shops on Ruby on Rails and Solidus, and I work test first: the test is written before the code, and every release goes through a test gate and into a release register. The layered pipeline is the same idea applied to data. The conservation test, the contract on every mart and the freshness checks are tests written before anyone trusts a number, and the rule register is a release register for cleaning rules. If test first development is new to you, test driven development explained shows why the test comes first.
Conclusion
Cleaning belongs in layers, never in place. Raw keeps everything exactly as it arrived, with five metadata columns and storage settings that make it impossible to change by accident. Staging translates each source into your conventions, one model per table, without joins or rules. Intermediate applies the business rules, flags instead of deleting, and gives every rejected row a quarantine reason. Marts serve people, under contracts that stop accidental change.
Around that, three habits do most of the work. Make every step idempotent, so a rerun never doubles or loses a row. Carry stable keys and rule versions to the end, so any number can be traced to a raw line and any change to a rule. And test that every raw row ends up in exactly one place. Keeping raw costs Wrenfield Home about two dollars a month. Not keeping it once cost six weeks of wrong return rates and a fortnight of emails. The only exception to "never overwrite raw" is the law, and that exception runs as its own logged process, not as a quiet edit.
