Cohort 4Register

Chapter Six

Where Data Lives

Free to readPages 109 to 120 of 244, by Durgesh Yadav

Two million order lines. Nine columns. Written to disk two ways, the same data occupies 148.3 MB or 4.3 MB. Reading one column out of the nine takes 0.49 seconds or 0.05 seconds. Nobody changed the data, the query or the hardware. One decision about file format did all of it, and at a thousand times this volume it is the difference between a platform that costs a lakh a month and one that costs thirty.

Every measurement in this chapter was taken on the machine that produced the book. The script is in the Field Kit and you should run it yourself, because seeing a 34x difference appear on your own terminal changes how you think about storage more than reading about it will.

6.1Rows and columns, physically

Chapter 1 introduced row and column storage as the reason OLTP and OLAP cannot be the same system. Here is what it means on disk.

A row-oriented file keeps all of one row’s values together. To read line_amount for two million rows, the disk must pass over all nine columns two million times and discard eight of them.

A column-oriented file keeps all of one column’s values together. Reading line_amount reads one contiguous region and never touches the other eight columns. This is called column pruning, and it is the single largest source of speed in analytical storage.

Figure 6.1: The same nine-column table, two layouts. To sum one column, the row store reads everything; the column store reads a ninth of it.
Figure 6.1.   The same nine-column table, two layouts. To sum one column, the row store reads everything; the column store reads a ninth of it. In the diagram: Row layout Column layout r1c1 r1c2 ... r1c9 · r2c1 r2c2 ... c1: all rows · c2: all rows ...

Column storage has a second effect that is less obvious and often larger. A column contains values of one type, frequently repeating. Our city column holds six distinct strings across two million rows; status holds three. Stored together, that repetition compresses to almost nothing. Stored row by row, each value sits between a customer id and a date and the compressor cannot see the pattern.

6.2The formats you will actually meet

FormatLayoutSchemaCompressesUse it for
CSVRowNonePoorlyExchange with humans and legacy systems
JSONRowSelf-describingPoorlyAPI payloads, event messages
AvroRowStored with the fileWellStreaming, and writes where whole records are read
ParquetColumnStored with the fileVery wellAnalytics. The default for a data lake
ORCColumnStored with the fileVery wellAnalytics, common in Hive-era stacks

Two properties separate the last three from the first two.

They carry their own schema. A Parquet file knows that order_date is a date and quantity is an integer. A CSV knows nothing; every value is text and every reader guesses. Half the type bugs in a beginner pipeline exist because CSV forgets.

They are splittable and internally indexed. A Parquet file is divided into row groups, each carrying statistics — minimum, maximum, null count — for every column. A query filtering on order_date = '2026-02-15' can read those statistics and skip entire row groups without decompressing them. This is predicate pushdown, and it is why a well-organised Parquet dataset answers a filtered query without reading most of itself.

The rule of thumb: Avro for writing, Parquet for reading. Streaming systems favour Avro because they append whole records; analytics favours Parquet because it reads few columns from many records.

6.3Compression, measured

The same two million rows, written four ways:

FormatSizeVersus CSV
CSV148.3 MB—
CSV + gzip18.4 MB8.0x smaller
Parquet + snappy26.5 MB5.6x smaller
Parquet + zstd4.3 MB34.8x smaller

Two things in that table are worth stopping on.

Gzipped CSV beats Snappy Parquet on pure size. That surprises people, and it is not a reason to use it. Gzip is not splittable, so a large gzipped CSV cannot be processed in parallel — one worker must decompress the whole thing. And you still cannot read one column without reading all of them. Small and unusable is not a win.

Parquet with zstd is six times smaller than Parquet with snappy on this data. Snappy is the historical default because it is fast to decompress and CPU used to be the bottleneck. On modern hardware, and with cloud storage billed per gigabyte and per byte scanned, zstd is very often the better trade. It is worth testing on your own data rather than accepting the default.

6.4Column pruning, measured

Summing one column out of nine:

SQL
SELECT SUM(line_amount) FROM read_csv_auto('orders.csv');       -- 0.49 s
SELECT SUM(line_amount) FROM 'orders_snappy.parquet';           --  0.05 s
Output
CSV       0.49 s
Parquet   0.05 s      10x faster
answer    4,894,500,000.00

Ten times faster on identical data, on the same disk, for the same answer. The CSV read had to parse 148 MB of text and convert every field from a string. The Parquet read decompressed one column and summed numbers that were already numbers.

The gap widens as tables get wider. Nine columns gives 10x. A realistic analytical table with sixty columns, where a query touches three, gives considerably more.

6.5Partitioning

Partitioning means splitting a dataset into directories by the value of a column, so a filter on that column can skip entire directories without opening them.

Files
orders/
  order_date=2026-01-01/data.parquet
  order_date=2026-01-02/data.parquet
  ...
  order_date=2026-03-31/data.parquet

The directory name carries the value. A query with WHERE order_date = '2026-02-15' reads one directory and ignores eighty-nine others. This is partition pruning, and it is a different mechanism from predicate pushdown — pruning happens before any file is opened, pushdown happens inside a file that was opened.

Measured on our dataset, ninety daily partitions against one flat file, filtering to a single day:

Output
one big file      0.051 s
partitioned       0.005 s      10.9x faster

Choosing the partition column

This is where teams go wrong, and the failure has a name.

Partition on a column that queries filter on, that has a moderate number of distinct values, and that produces partitions of a sensible size. Date is the usual answer because analytical queries almost always have a time range and dates arrive in order, so yesterday’s partition is written once and never touched again.

Do not partition on something with high cardinality. Partitioning two million rows by customer_id with 250,000 distinct values would produce 250,000 directories averaging eight rows each. Every query would then hit the problem in the next section, and the metadata alone would be slower than the scan you were trying to avoid.

ColumnDistinct valuesVerdict
order_date~90 per quarterGood — queries filter on it, sizes are even
city6Usable as a second level, if queries filter on it
status3Poor — heavily skewed, DELIVERED holds most rows
customer_id250,000Never

A commonly used starting range is partitions of roughly 128 MB to 1 GB. Much smaller and per-file overhead dominates; much larger and you lose pruning granularity. The right size depends on your query patterns, your engine’s split behaviour and how selective the partition column is, so treat the range as a place to begin measuring.

6.6The small files problem

Here is the same two million rows, written once as a single file and once as two thousand:

Output
2001 files, 32.3 MB total (avg 16 KB each)
one file :  26.5 MB

scan 1 file        0.06 s
scan 2001 files    0.25 s      4.5x slower for identical data

Four and a half times slower for exactly the same rows, plus 22% more storage, because every file repeats the schema and the footer metadata.

That measurement is taken on a local SSD, and it understates the problem substantially. On object storage every file costs a separate network request with its own latency — the ten-millisecond order of magnitude from Figure 2.2, not the microsecond one. Two thousand files becomes two thousand round trips. At the scale where this actually bites, a job that produced three million small files over a year turns a two-minute query into an hour, and almost none of that hour is spent on data.

The causes are always the same three:

Streaming writes. A job writing every ten seconds produces 8,640 files a day.

Over-partitioning. A high-cardinality partition column, as in the previous section.

Too many writers. A Spark job with 2,000 partitions writes 2,000 files per run by default, regardless of how much data is in each.

The fixes are equally standard. Control the number of output files at write time — in Spark this is coalesce or repartition before the write, covered in Chapter 9. Run a periodic compaction job that rewrites small files into large ones. And if you are using a table format, use its built-in maintenance operation, which is the subject of section 6.9.

6.7Object storage is not a filesystem

Data lakes are built on object storage: Amazon S3, Azure Data Lake Storage, Google Cloud Storage. It looks like a filesystem, with paths and folders, and it is not one. The differences matter.

There are no directories. orders/order_date=2026-02-15/data.parquet is one flat key. The slashes are characters. Listing a “folder” is a query over key prefixes, and listing millions of keys is slow — which is another reason small files hurt.

Objects are immutable. You cannot append to an object or edit part of one. You replace the whole thing. Every update-in-place feature you will meet later is built on top of this constraint rather than around it.

Writes are not instantly consistent everywhere. Modern S3 offers strong read-after-write consistency, but listing behaviour and cross-region replication still lag, and pipelines that assume a file is visible the instant it is written occasionally discover otherwise.

It is cheap, durable and effectively unlimited, which is why the entire industry builds on it despite the above.

Object storageBlock storage (a disk)
UnitWhole objectBlocks within a file
Modify part of itNo — rewrite itYes
CapacityEffectively unlimitedFixed, attached to one machine
Accessed byHTTP APIThe operating system
Cost per TBLowestHigher
SuitsData lakes, backups, mediaDatabases, operating systems

6.8Warehouse, lake, lakehouse

Three words that get used loosely. The distinctions are real.

A data warehouse loads data into its own managed, proprietary storage. Snowflake, BigQuery and Redshift do this. You get strong guarantees, excellent query performance, transactions and governance. You give up direct access to the files, and you generally pay more per terabyte.

A data lake is files on object storage, usually Parquet, queried by whatever engine you point at them. Cheap, open, and you own the files. What you lose is everything a database gives you: no transactions, so a reader can see a half-written table; no schema enforcement, so a bad job can corrupt a dataset; no update or delete without rewriting whole partitions by hand.

A lakehouse is the attempt to keep the lake’s economics and openness while adding back the warehouse’s guarantees. It works by adding a metadata layer on top of ordinary Parquet files. That layer is the subject of the next section.

Figure 6.2: The three architectures. The lakehouse is not a product; it is a metadata layer over files you already own.
Figure 6.2.   The three architectures. The lakehouse is not a product; it is a metadata layer over files you already own. In the diagram: 1 Warehouse managed storage, strong guarantees, higher cost 2 Data lake your files on object storage, cheap, no guarantees 3 Lakehouse your files, plus a transaction log that adds the guarantees

6.9Table formats: what Delta and Iceberg actually add

This is the part that most beginners find mysterious, and it is simpler than it sounds.

A folder of Parquet files has one fatal weakness: nothing knows which files belong to the table right now. If a job is halfway through writing a new day’s data when an analyst runs a query, the analyst sees half a day. If a job fails partway, the folder is left in a broken state with no way to tell which files are valid.

A table format — Delta Lake, Apache Iceberg, Apache Hudi — solves this by keeping a transaction log alongside the data. The log is the list of which files make up the table at each version. Writers add files and then, as a single atomic action, append a new entry to the log. Readers read the log first and then read exactly the files it names.

Everything else follows from that one idea:

FeatureHow the log provides it
ACID transactionsA reader sees the table as of one log entry, never a partial write
Time travelRead an older log entry and get the table as it was
UPDATE and DELETEWrite new files, log an entry that removes the old ones
MERGE (upsert)The same, driven by a match condition
Schema enforcementThe log records the schema; incompatible writes are rejected
Compaction (OPTIMIZE)Rewrite small files into large ones, log the swap atomically
SQL
-- Dialect: Delta Lake on Spark SQL. Iceberg supports the same operations
-- with different syntax and different metadata underneath (see below).
MERGE INTO orders AS target
USING daily_batch AS source
   ON target.order_id = source.order_id
 WHEN MATCHED THEN UPDATE SET *
 WHEN NOT MATCHED THEN INSERT *;

OPTIMIZE orders;                      -- compact small files
VACUUM  orders RETAIN 168 HOURS;      -- delete files no version needs
DELETE FROM orders WHERE order_date < '2024-01-01';

The three are not interchangeable

The shared idea is real: all three keep metadata alongside the data that says which files constitute the table. How they do it differs enough to matter.

Delta LakeApache IcebergApache Hudi
MetadataAn ordered JSON transaction log with periodic Parquet checkpointsA snapshot tree of manifest lists and manifest filesA timeline of commits plus per-file indexes
PartitioningDirectory-based, like HiveHidden partitioning — the query need not know the partition schemeDirectory-based, with record-level indexing
Strong atTight Spark and Databricks integrationEngine neutrality and schema/partition evolutionFrequent upserts and streaming ingestion
Watch forHistorically Spark-centric, though engine support has broadenedMore metadata layers to reason aboutMore configuration to get right

They are converging, and the honest position for a beginner is that the concept transfers completely while the operational details do not. Learn one properly. When you meet another, the ideas — snapshots, atomic commits, compaction, time travel — will all be there under different names.

The practical consequence: a claim like “we can swap Delta for Iceberg” is an architecture decision about metadata model, engine support and maintenance tooling, not a syntax translation.

MERGE is the statement that makes idempotent loading possible on a data lake, which is why Chapter 8 leans on it heavily. VACUUM deserves respect: it permanently deletes files that older versions still reference, so an aggressive retention setting silently destroys your ability to time travel.

6.10The medallion pattern

With formats and layout understood, the standard organisation of a lake makes sense.

Figure 6.3: Bronze, silver, gold. Each layer has one job, so when a number is wrong you have three defined checkpoints to walk back through.
Figure 6.3.   Bronze, silver, gold. Each layer has one job, so when a number is wrong you have three defined checkpoints to walk back through. In the diagram: Bronze Silver Gold raw, as it arrived typed, cleaned, deduplicated modelled, business-ready

Bronze is a faithful copy of the source, including its mistakes, partitioned by ingestion date and never edited. Its purpose is reprocessing: when you find a bug in a transformation six months from now, bronze is what lets you fix it.

Silver is where types are enforced, duplicates removed, keys resolved and bad records quarantined. One row means one clean business event. Most of the code you write lives here.

Gold is the dimensional model from Chapter 5 — facts and dimensions, aggregates, the tables analysts and dashboards actually query.

The value of the pattern is diagnostic. When a number is wrong, you check gold against silver, and silver against bronze, and the layer where they stop agreeing is where the bug is. Without the layers you are searching one large transformation for a discrepancy with no way to bisect it.

Summary

  • Column storage prunes columns and compresses far better. Measured here: 34.8x smaller and 10x faster on identical data.
  • Parquet and Avro carry their schema; CSV and JSON do not, and that omission causes most beginner type bugs.
  • Avro for writing and streaming, Parquet for reading and analytics.
  • Partition on a column queries filter on, with moderate cardinality and even sizes. Aim for partitions of 128 MB to 1 GB.
  • Small files are slow because seeks cost more than bytes. Two thousand files were 4.5x slower than one on local disk, and the penalty is far worse on object storage.
  • Object storage is not a filesystem: no directories, immutable objects, listing is a query.
  • A table format is a transaction log over Parquet files. Every feature — ACID, time travel, MERGE, OPTIMIZE — comes from that one idea.
  • Bronze, silver and gold exist so that a wrong number can be bisected.

In the interview

Your team stores daily exports as CSV in S3 and queries are getting slower and more expensive. What would you change, and in what order?

SHORT ANSWER

Convert to Parquet first, because it gives compression and column pruning together and requires no change to how the data is produced. Then partition by event date so time-filtered queries prune whole directories. Then control the output file count so the conversion does not trade one problem for the small files problem.

DEEPER ANSWER

I would measure before and after rather than assert an improvement. On a nine-column dataset I have measured Parquet with zstd at roughly a thirty-fold size reduction over CSV, and a single-column aggregation about ten times faster. The cost saving usually tracks the size reduction directly, because cloud engines bill by bytes scanned. Partitioning comes second because it only helps queries that filter on the partition column, so I would look at the actual query log before choosing one. Date is usually right; status or a customer identifier is usually wrong, the first because it is skewed and the second because the cardinality would create hundreds of thousands of tiny files.

FOLLOW-UP: HOW DO YOU HANDLE UPDATES AND DELETES ON A LAKE?

With bare Parquet you cannot; you rewrite whole partitions and there is a window where the table is inconsistent. That is the argument for a table format like Delta or Iceberg, which keeps a transaction log so that a MERGE or a DELETE is atomic and readers never see a partial state.

SENIOR-LEVEL ANSWER

I would also fix it at the source rather than downstream. If the export is producing CSV daily, the durable change is to have it write partitioned Parquet at ingestion, so every consumer benefits and nobody has to remember to convert. And I would add compaction as a scheduled maintenance job from day one, because small file accumulation is gradual and the failure mode is that nobody notices until a query that used to take two minutes takes an hour.

The other 12 chapters are in the free PDF

This is one of 3 chapters you can read here. The whole book is 244 pages and 15 chapters, and it is free: downloading the PDF takes one Google sign-in.

See all 15 chapters

Also free to read here: Chapter One, What a Data Engineer Actually Does and Chapter Three, SQL to Interview Level.