Storing clean data: warehouses, lakes, lakehouses and file formats
TL;DR
Difficulty: Intermediate
Store clean data where your questions run fast and the bill stays boring.
- Row stores (PostgreSQL) run the shop and often handle its own reporting too; column stores win when questions scan years of history.
- Keep raw files exactly as received in object storage, and convert them on arrival to Parquet: typed, compressed and readable one column at a time.
- Add an open table format (Iceberg, Delta, Hudi) only when files need updates, history and safe concurrent writes.
- Partition big event tables by day, cluster small fact tables, set retention per table, keep every dataset in one region, grant access by role.
- For a shop with 1,980 orders a month, the platform bill is a few pounds a month. The care in setting it up is the real cost.
Cleaning data is only half the job. Where the clean data lives, and in what shape on disk, decides how fast your reports run, what they cost and whether customer data sits where your privacy notice says. This chapter walks through every option for a growing online shop, measures the formats on example data and prices the result from the vendors' own pages.
Clean data needs a home that fits the questions you ask
The previous chapter, cleaning pipelines with raw, staging and clean layers, settled what happens to data on its way through. Raw files arrive and are never touched. Staging gives them types and names. Business rules sort out test orders and duplicates. Marts shape the result for reporting. This chapter answers the next question: where do all those layers physically live, and in what shape on disk?
It sounds like a question for the IT cupboard. It is not. Where and how you store data decides three things a business owner feels directly:
- Speed. Whether "revenue by month for five years" comes back in a second or in four minutes.
- Cost. Whether the monthly bill is the price of a coffee or the price of a part time hire.
- Trust and law. Whether you can prove what a number looked like last Tuesday, and whether customer data sits in a country your privacy notice promises.
None of these needs a big platform to get right. Most of them come down to a handful of decisions that a small shop can make in an afternoon, once someone explains the options plainly. That is the job here.
A few words first, so nobody is left behind. A database is software that stores data in tables and answers questions about it. A data warehouse is a database built for answering questions across lots of history, rather than for running the shop. A data lake is a store of plain files, usually in cloud storage. A file format is the way those files arrange the data inside them. Each gets its own section below, with a worked example.
Example: what Wrenfield Home has to store
Wrenfield Home is the invented homeware shop in Leeds this series follows (wrenfieldhome.example). Priya owns it. Callum builds and runs the shop and its data. The shop runs on Ruby on Rails and Solidus with PostgreSQL, takes 1,980 orders a month, and has five years of order history.
Callum lists every source and its size. Some sizes are measured, the rest are estimates for the example, and the table says which.
| Source | What it holds | Size today | How it grows |
|---|---|---|---|
Shop database (spree_orders, spree_line_items and friends) | 118,800 orders, 285,050 order lines | about 44 MB as CSV for these two tables (measured on invented data) | 1,980 orders a month |
| GA4 daily export to BigQuery | every page view, click and purchase event | about 117 GiB (estimate, see below) | about 2.7 million events a month |
| Google Ads and Meta Ads cost data | spend per campaign per day | under 1 GiB | a few thousand rows a day |
| Stripe and PayPal settlement files | payouts, fees, refunds | under 1 GiB | one file a day each |
| 3PL warehouse CSV | shipments and returns | under 1 GiB | one file a day |
| Supplier feeds (CSV and XML) | prices, stock, dimensions | about 7 GiB if every daily file is kept for five years (estimate) | four feeds a day |
| Newsletter export, service tickets, marketing cost sheet | lists and tickets | under 1 GiB | small |
The order tables come from Solidus, and the column names used in this chapter (item_total, shipment_total, promo_total, included_tax_total, completed_at and so on) are the ones in the Solidus schema1. The GA4 estimate assumes about 1.2 KB per event in BigQuery's logical size, times about 2.7 million events a month, times 36 months since the export was switched on: roughly 3.3 GB a month and 117 GiB in total. GA4 caps the daily export for a standard property at one million events a day2, and Wrenfield's 90,000 or so a day sit well inside it.
The lesson of the table is the first lesson of storage: the shop's own data is small, and the behavioural data is big. Five years of orders fit on a memory stick. One month of clickstream is larger than the whole order history. Every decision below follows from that imbalance.
Rows or columns: the layout on disk decides the speed
A table looks the same on screen whether it is stored by row or by column. On disk it is completely different, and that difference is why a warehouse exists at all.
A row store keeps each record together. PostgreSQL, which runs most Rails shops, stores a table as pages of 8 kB, and each page holds complete rows, every column of one order side by side, each row behind a header of 23 bytes3. That is perfect for the shop. When a customer checks out, the shop reads and writes one whole order at a time, every column of it.
A column store keeps each column together. All the order dates sit in one place, all the totals in another. BigQuery stores each column separately4, and so do Amazon Redshift5, Snowflake inside its micro partitions6 and ClickHouse, which calls itself a column oriented database for online analytical processing7. That is perfect for questions. "Revenue by month for five years" needs two columns out of nineteen, and a column store reads only those two.
The research that made column stores famous found them more than an order of magnitude faster than row stores on analytical workloads, and showed that the gap is not only about reading fewer bytes: compression and the way the engine processes whole columns at a time matter as much8. You cannot fully turn PostgreSQL into a column store by indexing every column.
How much a question reads
The share of a table a query has to read in a column store is a simple ratio (see Foundations: ratios and rates if ratios are rusty):
where is the fraction of the stored bytes the query reads, is the set of columns the query uses, is the set of all columns in the table, and is the number of bytes column takes on disk.
The number of columns is a poor guide on its own, because columns differ hugely in size. A column of country codes compresses to almost nothing. A column of time stamps down to the microsecond barely compresses at all.
Example: two questions, two very different shares
Callum wrote the invented Wrenfield data (five years of orders, one month of GA4 style events) to Parquet files with Zstandard compression and read the size of every column from the file's own metadata, as shown further down.
Question one: "revenue by month for five years". It needs completed_at and total from the orders file. Those two columns take 1.04 MB and 0.28 MB. The whole file, all 19 columns, takes 4.85 MB.
So : the query reads 27.2% of the file, although it uses only 2 of 19 columns (10.5%). The time stamp column alone is a fifth of the file.
Question two: "which events happened on which day in October" over the month of events. It needs event_date (0.30 MB) and event_name (0.89 MB) out of 27.80 MB across 13 columns.
So : it reads 4.3% of the data. In a row store it would read all of it. That is the whole case for columnar storage in one line, and the reason the size of a column matters more than the count.
Why columns compress so well
A column holds one type of value, and neighbouring values are often alike. Twenty thousand orders in a row say GB in the country column. A column store can write GB once with a count, or replace each distinct value with a small number from a dictionary. A row store sees GB sandwiched between a price and an email address and can do far less with it. Redshift's documentation makes the same point: because each block holds one type of data, it can use a compression scheme chosen for that type5.
Example: the smallest and the largest column
In the measured orders file, ship_country (six distinct values) takes 0.01 MB for 118,800 rows. That is less than one tenth of a byte per row. The order number column, a random string such as R482913377 on every row, takes 0.73 MB, about 6 bytes per row. The created_at time stamp takes 1.04 MB, about 9 bytes per row. Callum now knows where storage goes: into unique identifiers and precise time stamps, never into repetitive labels. If a report only needs the day, storing a separate order_date column (four bytes, and very repetitive) makes the common questions read a fraction of the bytes.
PostgreSQL alone is enough for longer than people think
Before any cloud warehouse, an honest question: does a shop of Wrenfield's size need one? For the shop's own data, often not yet. Forty four megabytes of orders is nothing for PostgreSQL. A query that sums five years of spree_orders finishes in well under a second on modest hardware, row store or not.
What goes wrong is not size but contention. Heavy reporting queries on the live shop database compete with checkouts for memory and disk. The standard fix costs little:
- Point reporting at a read replica, a copy of the database that follows the main one and serves only reads.
- Or copy the data you need each night into a separate analytics database, which is also where the staging and mart layers from the previous chapter live.
- Give the big fact tables a BRIN index on the order date. A BRIN index stores just the smallest and largest value for each block of pages. PostgreSQL's documentation names exactly this case: a table of sales orders where earlier orders sit earlier in the table9. The index is tiny and lets a date filter skip most of the table.
- Only consider partitioning (splitting one table into many by date) when a table grows very large. PostgreSQL's own rule of thumb is that partitioning pays when the table would be bigger than the server's memory10.
Example: Callum's analytics schema in PostgreSQL
Callum creates a separate analytics database on a managed PostgreSQL server and builds the daily revenue mart there. The SQL is PostgreSQL:
-- PostgreSQL: one schema per layer, as in the previous chapter
CREATE SCHEMA IF NOT EXISTS staging;
CREATE SCHEMA IF NOT EXISTS marts;
-- A BRIN index on the date the order was completed:
-- tiny, and perfect for "last 90 days" filters on an append mostly table
CREATE INDEX IF NOT EXISTS stg_orders_completed_brin
ON staging.stg_orders USING brin (completed_at);
-- A daily revenue mart, refreshed each night after the load
CREATE MATERIALIZED VIEW IF NOT EXISTS marts.daily_revenue AS
SELECT
date_trunc('day', completed_at)::date AS order_date,
count(*) AS orders,
sum(total) AS gross_revenue,
sum(included_tax_total) AS vat_included
FROM staging.stg_orders
WHERE state = 'complete'
AND is_test_order = false
GROUP BY 1;
CREATE UNIQUE INDEX IF NOT EXISTS daily_revenue_date
ON marts.daily_revenue (order_date);
-- CONCURRENTLY lets dashboards keep reading during the refresh;
-- it needs the unique index above
REFRESH MATERIALIZED VIEW CONCURRENTLY marts.daily_revenue;
is_test_order is the flag the business rule chapter added in staging. It is not a Solidus column. The materialised view stores the result of the query like a table, so dashboards read 1,800 or so daily rows instead of 118,800 orders.
What does this cost? DigitalOcean, as one example of a managed PostgreSQL provider, listed its smallest plan with 1 GiB of memory and one virtual CPU at USD 15.15 a month, and a plan with 4 GiB and two virtual CPUs at USD 60.90, with extra storage at USD 0.215 per GiB a month (prices as listed on 23 November 2026)11. For the shop's own data, the small plan is plenty.
The limit arrives with the clickstream. Putting 117 GiB of GA4 events, 2.7 million new rows a month, into a row store means every "sessions by channel" question reads whole rows of a fat table. It works, slowly, and it needs the bigger server. There is also a practical reason to move: the GA4 export already lands in BigQuery. Joining it to orders is easiest where it already lives.
Cloud warehouses, described fairly
Four names come up for a business of this size. All four are column stores, all four speak SQL, and all four separate the cost of storing data from the cost of querying it. They differ mainly in how they charge and how much tuning they ask of you.
| BigQuery | Snowflake | Amazon Redshift | ClickHouse | |
|---|---|---|---|---|
| Who runs it | Google Cloud | Snowflake, on AWS, Azure or Google Cloud | Amazon Web Services | open source, or ClickHouse Cloud |
| How queries are charged | on demand per TiB scanned, first 1 TiB a month free, or reserved capacity in slots12 | credits per hour a virtual warehouse runs, billed per second with a 60 second minimum each start13 | Serverless: per RPU hour, billed per second, 60 second minimum14 | self hosted: your own servers; Cloud: per usage |
| Storage | per GiB a month, about half price after 90 days untouched12 | billed separately | managed storage per GB a month14 | your disks, or per usage in Cloud |
| How data is organised | partitions and up to four clustering columns | automatic micro partitions of 50 MB to 500 MB uncompressed6 | sort keys and distribution | sorting key in the MergeTree engine |
| Time travel by default | 7 days, configurable 2 to 715 | 1 day, up to 90 on Enterprise16 | snapshots | not built in |
| Fits best when | GA4 is already there, usage is spiky, nobody wants to run servers | several teams, several clouds, steady workloads | the business already lives in AWS | very large event volumes, real time dashboards, a team happy to run it |
A few fair notes. BigQuery's on demand model means a careless query can cost money, because you pay for bytes scanned whether or not the answer was useful. Snowflake's model means an idle warehouse costs nothing once it suspends, which it does automatically by default, but a warehouse left running costs credits every second. Snowflake does not state a single credit price in its documentation and points to its pricing guide instead17, so this chapter does not quote one. Redshift Serverless charges for the capacity your queries use, with a base capacity that starts at 4 RPUs14. ClickHouse can be run on your own servers at no licence cost, and that is also its catch: self hosting it is real operational work.
Example: the same month in four currencies of compute
Callum estimates Wrenfield's monthly query work: the nightly dbt build, Priya's dashboards and his own analysis. He expresses it once per platform, because each one counts differently.
- BigQuery: about 775 GiB scanned a month (75 GiB for the nightly build reading three days of events plus the shop tables, 300 GiB for dashboards, 400 GiB for analysis). That is 0.76 TiB, inside the free 1 TiB.
- Snowflake: an
X-Smallwarehouse uses 1 credit an hour13. If the same work keeps it running 30 minutes a day, that is 15 hours and 15 credits a month, times whatever credit price the contract sets. - Redshift Serverless: at the 4 RPU base, 15 hours of query time a month is RPU hours. At the USD 0.375 per RPU hour listed for US East14, that is USD 22.50.
- ClickHouse self hosted: the cost of one server, whatever the workload, plus the time to run it.
None of these numbers decides anything on its own. They show that at Wrenfield's size, the compute bill is small on every platform, and the deciding factors are where the data already is and who will look after it.
Data lakes: plain files in low cost storage
A data lake is simpler than its name. It is a folder structure in object storage, such as Google Cloud Storage or Amazon S3: a service that stores files (objects) of any size, very durably, for a low price per gigabyte, and knows nothing about what is inside them. There are no tables and no SQL until some engine reads the files.
For a small business, the lake is the natural home of the raw layer. The 3PL's daily CSV, the supplier feeds, the settlement files: each arrives as a file, and the rule from the previous chapter says keep it exactly as received. Object storage is the least expensive and most durable place to do that.
The danger is the one everyone names: a lake without rules becomes a swamp, a heap of files nobody can find or trust. The cure is boring and effective. A fixed folder convention, one folder per source, the load date in the path, and never a file overwritten.
Example: the raw folders at Wrenfield
Callum creates one bucket for raw files and fixes the layout:
gs://wrenfield-raw/
3pl/shipments/ingest_date=2027-01-18/shipments_20270118.csv
3pl/returns/ingest_date=2027-01-18/returns_20270118.csv
suppliers/oakline/ingest_date=2027-01-18/feed.xml
suppliers/hearthco/ingest_date=2027-01-18/feed.csv
stripe/settlements/ingest_date=2027-01-18/payouts.csv
The ingest_date= part is the convention many engines read as a partition: a query that filters on the ingest date only opens the matching folders. The date is the day the file arrived, not the day of the business events inside it, because the 3PL's returns file can describe returns from five days earlier. Keeping both dates apart is what makes late data traceable.
Five years of these files come to roughly 10 GiB. At the Google Cloud Storage list price of about USD 0.020 per GiB a month for the Standard class18, that is about USD 0.20 a month.
File formats: how the data sits inside each file
Once data is in files, the format of those files matters as much as the database did. Here are the five you will meet.
| Format | Layout | Types stored with the data | Compression | Good for | Poor for |
|---|---|---|---|---|---|
| CSV | rows of text | no | only the whole file, from outside | exchange with other businesses, spreadsheets | anything you query often |
| JSON (lines) | rows of text, nested allowed | partly (numbers, strings, booleans) | only from outside | APIs, logs, nested events | large scale analysis |
| Avro | rows, binary | yes, the schema travels with the file | yes, per block | data in motion, streams, schema changes | reading a few columns |
| ORC | columns, binary | yes | yes, per column | Hive and Hadoop based platforms | small ecosystems outside them |
| Parquet | columns, binary | yes | yes, per column chunk | analytics, lakes, almost every engine | appending one row at a time |
CSV is for moving data, not for keeping it
CSV looks universal, and that is its trap. The format was only written down in 2005, in an informational RFC whose own text notes that there was no formal specification in existence, which allows a wide variety of interpretations19. Every CSV file is a small negotiation: which delimiter, which quote character, which encoding, which line ending, and is "1.234" a thousand or one and a bit?
The types are the worst of it. A CSV file stores 00412 and the reader decides whether it is a number (412) or a code (00412). The chapter on data types, schemas and formats covers those failures one by one. For storage, the rule is short: accept CSV at the door, keep the original in the raw layer, and convert it to a typed format immediately.
Example: turning the 3PL file into Parquet
The 3PL sends a semicolon separated file in Windows 1252 encoding, with its own SKU format and local times without a zone. Callum reads it with pyarrow, the Python library of the Apache Arrow project, states every type explicitly so nothing is guessed, and writes Parquet:
import pyarrow as pa
import pyarrow.csv as pacsv
import pyarrow.parquet as pq
# The 3PL file: semicolons, Windows 1252, its own SKU format
read = pacsv.ReadOptions(encoding="cp1252")
parse = pacsv.ParseOptions(delimiter=";")
convert = pacsv.ConvertOptions(column_types={
"shipment_ref": pa.string(),
"sku_3pl": pa.string(), # e.g. 3PL-WH00412, mapped to the shop's SKU in staging
"qty": pa.int32(),
"shipped_local": pa.string(), # local time, no zone: converted in staging, not here
"status": pa.string(),
})
table = pacsv.read_csv(
"shipments_20270118.csv",
read_options=read, parse_options=parse, convert_options=convert,
)
pq.write_table(table, "shipments_20270118.parquet", compression="zstd")
print(table.schema)
Two choices deserve a word. The SKU and the local time stay as text here, because converting them is a cleaning rule with a version and a test, and it belongs in staging, not hidden in a file conversion. And the encoding is declared, never guessed: a "ü" in a German supplier's product name read as UTF 8 when it is really Windows 1252 becomes two strange characters, silently, forever. Run on a sample file, the script prints a schema with qty: int32 and the other columns as string, and the German status "retourniert, beschädigt" survives intact.
Parquet from the inside
Parquet is the format worth understanding properly, because nearly every engine reads it: BigQuery, Snowflake, Redshift, ClickHouse, DuckDB, Spark, pandas and polars. Its structure, as the specification describes it20, has three levels.
- A file is split into row groups, horizontal slices of the table.
- Inside each row group, each column is stored as one column chunk, and each chunk is divided into pages.
- At the end of the file sits the footer: the schema, where every column chunk starts, and statistics such as the minimum and maximum value of each chunk. The file starts and ends with the four bytes
PAR1.
The footer is what makes Parquet fast. A reader opens the footer first, works out which column chunks it needs, and checks the statistics. If a query asks for orders from October 2026 and a row group's completed_at ranges from 2022 to 2023, the reader skips the whole row group without decompressing a byte.
Example: reading the footer
Callum checks what a reader would see in the converted 3PL file and in the big events file:
import pyarrow.parquet as pq
meta = pq.ParquetFile("shipments_20270118.parquet").metadata
print(meta.num_rows, meta.num_row_groups)
# Statistics of the qty column in the first row group
stats = meta.row_group(0).column(2).statistics
print(stats.min, stats.max, stats.null_count)
# Bytes per column across all row groups: where does the space go?
sizes = {}
for rg in range(meta.num_row_groups):
for ci in range(meta.num_columns):
col = meta.row_group(rg).column(ci)
sizes[col.path_in_schema] = sizes.get(col.path_in_schema, 0) + col.total_compressed_size
print(sizes)
# A reader that only needs two columns asks only for them
events = pq.read_table("ga4_events_2026_10.parquet", columns=["event_date", "event_name"])
The events file holds 2,713,738 rows in three row groups (pyarrow's default row group holds up to 1,048,576 rows). The per column loop is how the sizes in the earlier example were measured: event_timestamp alone takes 18.58 MB of the 27.80 MB, because every value is a different microsecond. The last line reads 1.19 MB from disk instead of 27.80 MB.
Avro and ORC in one paragraph each
Avro is a compact binary format whose schema is saved with the data, so any tool can read the file later, and a reader expecting a slightly different schema can resolve the difference because both schemas are known21. It writes record after record, which makes it a strong choice for data in motion: messages in a stream, change events from a database. A later chapter on streaming meets it again. For analysis, convert it to a columnar format.
ORC is a self describing, type aware columnar format built for Hadoop workloads, split into stripes with indexes that let a reader skip data22. It is excellent inside the Hive and Hadoop world it came from. Outside it, Parquet has the wider support, which is why this series uses Parquet.
Compression makes files smaller, and that is not the whole story
Compression rewrites data so it takes fewer bytes, and decompresses it on reading. Parquet supports several codecs per column chunk, among them Snappy, GZIP, Brotli, LZ4 and Zstandard (ZSTD)23. The trade is speed against size: Snappy is quick and moderate, Zstandard and GZIP squeeze harder and cost a little more processor time.
The measure is the compression ratio:
where is the compression ratio, is the size of the data as plain CSV, and is the size of the stored file. A ratio of 4 means the stored file takes a quarter of the space. It is the same kind of ratio as before (Foundations: ratios and rates).
Example: the measured sizes
All figures in this example come from an invented data set built to Wrenfield's volumes (118,800 orders, 285,050 order lines, one month of 2,713,738 events) and written with pyarrow 26. Real files differ, the proportions are what matter.
| File | CSV | CSV gzip | Parquet, no compression | Parquet Snappy | Parquet Zstandard |
|---|---|---|---|---|---|
| Orders (19 columns) | 21.32 MB | 4.95 MB | 10.24 MB | 6.54 MB | 4.85 MB |
| Order lines (11 columns) | 22.63 MB | 4.56 MB | 7.29 MB | 5.54 MB | 4.07 MB |
| One month of events (13 columns) | 495.61 MB | 40.77 MB | 35.52 MB | 30.85 MB | 27.80 MB |
For the month of events:
so for the events, and for the orders:
so . Text with many repeated strings, like page addresses, compresses far better than numbers that are all different.
Look closely and an honest surprise appears. For the order tables, a gzipped CSV is almost exactly as small as Zstandard Parquet: 4.95 MB against 4.85 MB. If size were the only reason, gzip would do. It is not the only reason. The gzipped CSV still has no types, and a reader still has to decompress and parse every byte of every column to answer any question. Parquet's real advantage shows when you ask a question.
Example: what a two column question actually reads
Priya's dashboard asks how many events of each type happened per day in October. Here is what each format makes the reader do with the month of events:
The gzipped CSV reads 40.77 MB from disk and then has to decompress and parse all 495.61 MB of text. The Parquet reader asks the footer where event_date and event_name live and reads 1.19 MB. That is 34 times less than the gzip file, before counting the parsing. Multiply by every dashboard refresh for a year and the format choice is no longer a detail.
Open table formats: a folder of Parquet files that behaves like a table
Parquet files on their own have a weakness. A folder of them is not a table in the database sense. Nothing stops a reader from seeing half written files while a job is still writing. Changing a single row means rewriting a whole file. Renaming a column means rewriting everything, or living with confusion. And there is no memory of what the folder looked like yesterday.
Open table formats fix this by adding a layer of metadata on top of the data files: a log of which files make up the table at each moment. Every change writes new files and then, in one atomic step, a new version of that metadata. Readers always see a complete version, never a half one. The three you will meet:
| Apache Iceberg | Delta Lake | Apache Hudi | |
|---|---|---|---|
| Atomic changes | yes, readers never see partial or uncommitted changes24 | yes, serializable isolation25 | commits on a timeline, see the docs26 |
| Schema changes | add, drop, rename, reorder columns without side effects24 | schema enforcement stops bad records at write time25 | see the docs |
| Time travel | query an exact earlier snapshot, roll back24 | VERSION AS OF, TIMESTAMP AS OF, 30 days by default27 | time travel queries26 |
| Partitioning | hidden partitioning: queries do not need to know the layout28 | partition columns | partition paths |
| Updates | MERGE INTO rewrites affected files29 | merge, update, delete25 | Copy on Write or Merge on Read tables, built for frequent upserts26 |
Hidden partitioning deserves a sentence, because it removes a classic mistake. In older Hive style lakes, a table partitioned by an event_date column needs every query to filter on event_date explicitly. Filter on the time stamp instead and the engine scans every file. Iceberg records that the partition is derived from the time stamp (for example day(event_time)), so a filter on the time stamp alone is enough to skip files, and the documentation notes that consumers no longer need to know how the table is partitioned28.
Delta's retention defaults deserve another, because they surprise people. Time travel reaches 30 days back by default, but VACUUM removes data files older than the deleted file retention, which defaults to 7 days, and once those files are gone, so is time travel to those versions27. Keeping history costs storage, and the settings decide how much.
Example: the late 3PL returns in a table format
The 3PL's returns file arrives up to five days late. On Monday, last Wednesday's orders need their return status updated. In a plain Parquet folder Callum would rewrite last Wednesday's files himself and hope no dashboard reads them halfway. With Iceberg, written here in Spark SQL, he merges:
-- Spark SQL on an Apache Iceberg table
MERGE INTO lake.marts.fct_order_lines t
USING lake.staging.stg_3pl_returns s
ON t.order_line_id = s.order_line_id
WHEN MATCHED THEN UPDATE SET
t.returned_qty = s.returned_qty,
t.returned_at = s.returned_at,
t.return_source = '3pl_file'
WHEN NOT MATCHED THEN INSERT *;
Iceberg rewrites only the data files that hold affected rows and commits a new snapshot. A dashboard reading during the merge sees the table either before or after it, never between. And if the merge turns out wrong, the previous snapshot is still there:
-- Spark SQL: list snapshots, then read the table as it was before the merge
SELECT committed_at, snapshot_id, operation FROM lake.marts.fct_order_lines.snapshots;
SELECT sum(returned_qty)
FROM lake.marts.fct_order_lines VERSION AS OF 10963874102873;
The snapshot id here is a placeholder. The query syntax for snapshots and time travel is Iceberg's own30. Keeping history in depth, including slowly changing dimensions and how long to keep snapshots, is the subject of the next chapter.
The lakehouse: warehouse features on lake storage
"Lakehouse" is a term from Databricks, introduced in a 2021 paper by Armbrust, Ghodsi, Xin and Zaharia. They describe it as an architecture based on open direct access data formats such as Apache Parquet, with first class support for machine learning and data science, and with competitive performance31. In plain words: keep one copy of the data as open files in object storage, put an open table format on top for transactions and history, and let several engines (SQL for reports, Python for data science) read the same tables.
The appeal is real for large organisations. No copy of the data locked inside one vendor's storage, no second copy for the data scientists, storage at object storage prices. The cost is also real: someone has to choose and run the catalogue that tracks the tables, compact small files, tune the engines and keep the formats and versions compatible. Warehouses do all of that for you, at a price that is very low at small scale.
The medallion naming (bronze, silver, gold) from the previous chapter also comes from Databricks. It maps onto raw, staging plus intermediate, and marts, whatever storage sits underneath.
Example: does Wrenfield need a lakehouse?
Callum weighs it against the size table from the start. The total is about 125 GiB in the warehouse and 10 GiB of raw files. One person looks after it. Every consumer speaks SQL, and the only machine learning, a demand forecast, reads a mart of a few hundred thousand rows. A lakehouse would add a catalogue, a compute engine and file maintenance to solve problems Wrenfield does not have.
He does take one idea from it: the raw files sit in object storage as plain, open files, so the business could change warehouse later without losing its history. A full lakehouse becomes worth a second look if event volumes grow by a hundred times, if a data science team arrives with its own tools, or if Wrenfield ends up on two clouds.
Partitioning and clustering: read less, pay less
A warehouse charges, in time or money, for what it reads. Two tools make it read less.
Partitioning splits a table into separate segments, usually by date. A query filtered on the partition column opens only the matching segments. BigQuery partitions by a date or time stamp column (hourly, daily, monthly or yearly), by ingestion time, or by integer ranges, up to 10,000 partitions per table32.
Clustering sorts the data inside the table (or inside each partition) by up to four columns, so that rows with the same values sit in the same storage blocks, and a filter on those columns skips the other blocks. BigQuery reclusters automatically in the background33.
When to use which? Google's own guidance is concrete. Prefer clustering when partitioning would leave less than about 10 GB per partition, when you would need more partitions than the limit allows, or when queries filter on several columns or on columns with very many distinct values32. The trade off: with clustering, BigQuery cannot tell you the exact bytes a query will scan before it runs33.
Google also recommends partitioning over sharding, the habit of one table per day named like events_20261018, because partitioned tables perform better and every shard carries its own copy of schema and metadata32. The GA4 export arrives sharded, as events_YYYYMMDD tables, so staging it into one partitioned table is a good first transformation.
The saving from partitioning is the share of partitions a query touches:
where is the bytes query scans, is the set of partitions that survive the query's filter, and is the bytes in partition for the columns the query reads. If the partitions are about equal in size, is simply the table's bytes times the share of partitions kept (Foundations: ratios and rates).
Example: partitioning the events, clustering the orders
The GA4 events take about 117 GiB over 1,095 days, so about 0.107 GiB a day. Priya's "last 28 days by channel" question on a daily partitioned table scans:
so is 3.0 GiB at most, instead of 117 GiB: 39 times less, and fewer still once only the needed columns count. Daily partitions of about 0.1 GiB are well under Google's 10 GB guide, but the alternative, monthly partitions, would make every "last 28 days" question read up to two whole months. Callum keeps daily partitions for events and clusters them by event_name, because most questions filter on the event type.
The orders are the opposite case. The whole fact table of order lines is far below 10 GB. Partitioning it by day would create 1,800 tiny partitions. Callum clusters it by order_date and customer_key instead, with no partitions at all.
The DDL in BigQuery's GoogleSQL:
-- BigQuery (GoogleSQL), dataset in europe-west2 (London)
CREATE TABLE IF NOT EXISTS staging.stg_ga4_events (
event_date DATE NOT NULL,
event_timestamp TIMESTAMP NOT NULL,
event_name STRING NOT NULL,
user_pseudo_id STRING,
ga_session_id INT64,
page_location STRING,
source STRING,
medium STRING,
campaign STRING
)
PARTITION BY event_date
CLUSTER BY event_name
OPTIONS (
require_partition_filter = TRUE, -- a query without a date filter fails instead of scanning everything
description = 'GA4 export, flattened, one partition per day'
);
CREATE TABLE IF NOT EXISTS marts.fct_order_lines (
order_line_id INT64 NOT NULL,
order_id INT64 NOT NULL,
order_date DATE NOT NULL,
customer_key STRING,
sku STRING,
quantity INT64,
net_revenue NUMERIC,
returned_qty INT64
)
CLUSTER BY order_date, customer_key;
require_partition_filter is the best value insurance in this chapter: a dashboard that forgets the date filter fails loudly on day one instead of quietly scanning 117 GiB every hour. In dbt, the same settings sit in the model config, using the keys dbt documents for BigQuery34:
-- models/staging/stg_ga4_events.sql (dbt Core on BigQuery)
{{ config(
materialized = 'incremental',
incremental_strategy = 'insert_overwrite',
partition_by = {"field": "event_date", "data_type": "date", "granularity": "day"},
cluster_by = ["event_name"],
require_partition_filter = true
) }}
select
parse_date('%Y%m%d', event_date) as event_date,
timestamp_micros(event_timestamp) as event_timestamp,
event_name,
user_pseudo_id,
(select value.int_value from unnest(event_params) where key = 'ga_session_id') as ga_session_id,
(select value.string_value from unnest(event_params) where key = 'page_location') as page_location,
traffic_source.source as source,
traffic_source.medium as medium,
traffic_source.name as campaign
from {{ source('ga4', 'events') }}
{% if is_incremental() %}
-- rebuild the last three days, so late arriving events are picked up
where _table_suffix >= format_date('%Y%m%d', date_sub(current_date(), interval 3 day))
{% endif %}
With insert_overwrite, dbt replaces only the partitions the run produces, so a rerun of the same three days gives the same result, which is the idempotence the previous chapter asked for. The source must be declared in a sources file pointing at the events_* wildcard table. With require_partition_filter switched on, every test and every model that reads this table needs a date filter too, which dbt's documentation warns about34. One caution on the columns: traffic_source in the GA4 export describes the source that first acquired the user, not the current session35, so session level channel reporting needs the session's own parameters.
Retention and storage tiers: old data can cost less
Not all data is read equally. Last month's events are queried daily. Events from 2023 are read twice a year. Storage prices reflect that.
- BigQuery drops the price of any table or partition untouched for 90 consecutive days by about 50%, automatically, with no difference in performance12. On the page's US list price, active logical storage is USD 0.000031507 per GiB hour (about USD 0.023 a month) and long term logical storage USD 0.000021918 per GiB hour (about USD 0.016 a month). Daily partitions help here too: old partitions go long term on their own while new ones are written.
- Google Cloud Storage offers Standard, Nearline, Coldline and Archive classes, each less expensive to store and more expensive to read, with minimum storage durations of none, 30, 90 and 365 days. Deleting a file early still bills the minimum18.
- Expiry removes data on a schedule. BigQuery tables and partitions can expire automatically (
partition_expiration_daysin the DDL or in dbt34).
Expiry is where storage meets the law. UK GDPR's storage limitation principle says personal data must be kept no longer than necessary for its purposes36. At the same time, company and tax law require accounting records to be kept for years: the Companies Act 2006, for example, sets three years for a private company's accounting records and six for a public company's37. Those periods, and how to keep the records while deleting the person, belong to the chapters on history and on privacy engineering later in this series. For storage, the practical point is that every table needs a written retention rule, and the platform can enforce most of them for you. This is general information, not legal advice.
Example: Wrenfield's retention plan
Callum writes one line per table:
| Data | Where | Rule |
|---|---|---|
| Raw 3PL, supplier and settlement files | Cloud Storage | Standard for 90 days, then Coldline, supplier feeds deleted after two years |
| GA4 events, flattened | BigQuery, daily partitions | kept 36 months, partitions expire automatically |
| Order and finance marts | BigQuery | kept for the legal record period, no expiry |
| Customer level marts with emails | BigQuery | rebuilt nightly, so erasures flow through (see the privacy chapter) |
The supplier feeds show the arithmetic. Four feeds of about 1 MB a day come to roughly 1.4 GiB a year. In Coldline, at the page's US list price of about USD 0.004 per GiB a month18, the whole two years cost about a cent a month. The cost of keeping raw files is almost never the reason to delete them. Privacy and clarity are.
Where the data lives: region and transfers
Every cloud dataset lives in a location: a region (one city's data centres) or a multi region (several). BigQuery offers London (europe-west2) among its European regions, and an EU multi region that stores data only in Belgium or the Netherlands, never in London or Zürich38. AWS, where Snowflake and Redshift often run, has London (eu-west-2), Ireland (eu-west-1) and Frankfurt (eu-central-1) among others39.
Two practical rules follow.
- Keep everything that is joined in one location. BigQuery returns an error when a query's location does not match the datasets it reads38. If the GA4 export lands in
EUand the shop data in London, the join does not run. Pick one location and create every dataset there. - Choose the location your privacy notice and contracts describe. For a UK business, keeping data in London is the simplest story. Sending personal data outside the UK is a restricted transfer under Chapter V of the UK GDPR40, with its own rules and paperwork, explained in the Information Commission's (formerly the ICO's) guidance on international transfers41. Data flowing the other way, from EU customers to a UK business, is covered by the European Commission's adequacy decision for the UK, which the Commission renewed in December 202542.
Vendor contracts, sub processors and the transfer paperwork are covered in vetting data processors and transfers. Again, general information, not legal advice.
Example: choosing the location for Wrenfield
Callum creates the BigQuery project with every dataset in europe-west2, and links the GA4 export to the same location. The raw bucket also sits in London. A PostgreSQL analytics database, if he kept one, would be created in a UK region too. The privacy notice says customer data is stored in the UK, and now it is true by construction, not by hope.
Access control: who may read what
A warehouse puts every customer's email, address and order history in one place, which makes it the most valuable thing to protect. Four habits cover most of it.
- Separate roles for separate jobs. The loader may write to raw and nothing else. The transformation tool (dbt) may read raw and write staging and marts. People read marts.
- Grant on datasets or schemas, never on single tables one by one. It keeps the rules few enough to check.
- Protect sensitive columns. BigQuery's column level access control uses policy tags: tag the email column, and only people with the Fine Grained Reader role can read it, while data masking can show them a hashed or empty value instead43.
- Filter rows where needed. BigQuery's row access policies44 and PostgreSQL's row security policies45 show each reader only the rows they may see.
Example: the ad specialist and the email column
Wrenfield works with an outside paid search specialist who needs order revenue by campaign, and never customer emails. Callum grants dataset access to marts only, tags the email column so it stays hidden, and adds a row policy so the specialist sees only paid channel orders:
-- BigQuery (GoogleSQL): only paid channel rows for the outside specialist
CREATE ROW ACCESS POLICY paid_channels_only
ON marts.fct_orders_by_campaign
GRANT TO ('user:paid-search@partner.example')
FILTER USING (channel_group IN ('Paid search', 'Paid social'));
In a PostgreSQL only setup the same idea looks like this:
-- PostgreSQL: a read only role for the specialist, limited to paid channels
CREATE ROLE paid_search_reader LOGIN PASSWORD 'set-me-from-a-secret-store';
GRANT USAGE ON SCHEMA marts TO paid_search_reader;
GRANT SELECT ON marts.fct_orders_by_campaign TO paid_search_reader;
ALTER TABLE marts.fct_orders_by_campaign ENABLE ROW LEVEL SECURITY;
CREATE POLICY paid_channels_only ON marts.fct_orders_by_campaign
FOR SELECT TO paid_search_reader
USING (channel_group IN ('Paid search', 'Paid social'));
One catch from PostgreSQL's documentation: the table's owner normally bypasses row security unless the table is set to FORCE ROW LEVEL SECURITY45. Test the policy as the reader, never as yourself.
A decision guide for a shop this size
Put together, the choices fall into a short sequence. The guide below is the path for a business like Wrenfield: one shop, a few external sources, one person or a small team looking after the data.
And the same guide as a table of stages, so you can find where you stand:
| Stage | Typical signs | Storage | What to add next |
|---|---|---|---|
| 1 | under a few GB, reports from the shop admin | the shop's PostgreSQL | nothing yet, write down the questions |
| 2 | reports slow the shop | read replica or analytics PostgreSQL | BRIN indexes, materialised views |
| 3 | clickstream and ad data, several sources | cloud warehouse plus raw bucket | partitioning, clustering, access roles |
| 4 | terabytes, several teams, several engines | lake with an open table format, or a lakehouse | catalogue, compaction, cost monitoring |
Most shops of Wrenfield's size sit between stages 2 and 3, and stage 3 is where this chapter's example lands.
What it costs: an honest estimate for Wrenfield Home
Cost estimates for data platforms are usually either vague or sales material. This one is built from the vendors' own price pages, as listed on 23 November 2026, and every assumption is written down. Google lists the BigQuery and Cloud Storage prices on its pages in US dollars for its default US region. European regions are priced separately, so check your region on the page before you budget. If you pay in pounds, Google bills the prices listed in your currency12.
The monthly BigQuery bill has three parts:
where is the monthly cost in dollars, is active storage in GiB (with the first 10 GiB free), its price per GiB a month, is long term storage in GiB, its price, is the data scanned by queries in TiB (with the first TiB free), and the on demand price per TiB. The free allowances come from the pricing page12, and the formula is a sum of quantities times prices (Foundations: ratios and rates).
Example: Wrenfield's monthly bill
The inputs, with their sources:
- GiB: the last three months of events (about 9.8 GiB) plus the marts rebuilt nightly (about 8 GiB). Estimate.
- GiB: the older event partitions. Estimate.
- and dollars per GiB a month: the listed hourly prices times 730 hours12.
- TiB: the 775 GiB of query work estimated earlier.
- dollars per TiB above the first free TiB12.
So about USD 1.90 a month for BigQuery, plus about USD 0.20 for the raw bucket: roughly USD 2.10 a month. In a heavy month, with 2 TiB of queries, the query part becomes and the total about USD 8.35.
The comparison with the alternatives, using the same assumptions:
- Redshift Serverless: 60 RPU hours at USD 0.375, plus 125 GB of managed storage at USD 0.024 per GB a month14: USD 22.50 plus USD 3.00, about USD 25.50.
- Managed PostgreSQL large enough to hold the events as well: the 4 GiB plan at USD 60.90, before any storage beyond what the plan includes11.
- Snowflake: 15 credits a month at the credit price in the contract. Not charted, because no public credit price could be verified for this chapter.
Two honest caveats. First, the lowest priced option on paper only stays low while queries stay disciplined. Here is the classic mistake priced out: a dashboard tile that reads the whole 117 GiB event table without a date filter, refreshing every hour of every day.
TiB a month, and dollars. The require_partition_filter option from the partitioning section makes that query fail instead. A later chapter on performance and cost goes into monitoring and budgets in depth. Second, the platform bill is the small part. The real cost of a data platform is the time of the person who builds and looks after it, which is why the lowest effort option often beats the lowest price.
To see what your own tables take, BigQuery reports it per table:
-- BigQuery (GoogleSQL): storage per table in the London region
SELECT
table_schema,
table_name,
ROUND(total_logical_bytes / POW(1024, 3), 2) AS logical_gib,
ROUND(long_term_logical_bytes / POW(1024, 3), 2) AS long_term_gib,
ROUND(total_physical_bytes / POW(1024, 3), 2) AS physical_gib,
ROUND(time_travel_physical_bytes / POW(1024, 3), 2) AS time_travel_gib
FROM `region-europe-west2`.INFORMATION_SCHEMA.TABLE_STORAGE
ORDER BY total_logical_bytes DESC;
The view and its columns are documented by Google, and it needs a region qualifier that matches where the data lives46. Callum runs it once a month and puts the top ten tables in the release register next to the data platform's other checks.
Conclusion
Where you store clean data is not a technology contest. It follows from the shape of your data and the questions you ask. Row stores like PostgreSQL run the shop, and for the shop's own data they are often enough for analysis too, with a replica, BRIN indexes and materialised views. Column stores win once questions scan a lot of history, because they read only the columns a question needs and compress each column well. The cloud warehouses differ more in how they charge than in what they can do: pick the one where your data already is and that the people you have can look after.
Keep raw files exactly as received in object storage, and convert them on arrival into a typed columnar format, which in practice means Parquet. Compression alone makes a CSV small. Parquet makes it small, typed and readable a column at a time. Add an open table format such as Iceberg or Delta when files need updates, history and safe concurrent writes, and consider a full lakehouse only when volume, engines or teams demand it. Partition big event tables by day, cluster small fact tables, set retention per table, keep every dataset in the one location your privacy notice names, and grant access by role. For a shop the size of Wrenfield Home, all of that costs a few pounds a month in platform fees. The care in setting it up is where the value lies.
