Inside a Parquet file

Part of the free LogicWiz Data Engineering course, Module 4: Storage and file formats. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 11:30 on Friday. Tess asks for one day of orders from last month's Parquet export, a 40 GB folder. The query plan says it read 38 GB. The files have statistics and her filter is on order_date, so most of it should have been skipped. Nora's advice: "Open one file and read what the footer says."

You'll learn to

  • Walk a Parquet file from its first bytes to its footer
  • Explain how dictionary, run-length and delta encoding shrink a column
  • Predict what statistics, page indexes and bloom filters can skip
  • Read a file's metadata with DuckDB and spot a bad layout

Learn

Open the file from the back

Nora's advice is to see the file the way a reader does. A reader does not start at the top.

A Parquet file begins with 4 bytes, PAR1. Then come the row groups: slices of the table, many thousands of rows each. Inside a row group every column is stored on its own, as a column chunk, and a chunk is a run of small pages. After the last row group sits the footer: the schema and, for every chunk, where it starts, how big it is and a few statistics. The file ends with the footer's length and PAR1 again.

The footer is last so the writer can stream the file out in one pass and note the offsets as it goes. A reader works backwards: the tail, the footer, then only the bytes it needs.

Anatomy of orders.parquet

Nested boxes: a file holding the PAR1 marker, two row groups each with an order_id chunk of data pages and a status chunk of a dictionary page plus data pages, then the footer with the schema and per-chunk metadata, and the footer length with PAR1 at the end.

Read it top to bottom, as the bytes sit in the file. A reader takes the last box first, then the amber footer, then picks the chunks it wants.

A six-million-row orders file drawn as its bytes from front to back: the magic number, six row groups of four column chunks each sized to scale, the footer and the tail; stepping through highlights each part and tapping a chunk shows the offset, size, encodings, pages and statistics its footer entry records.

Press Next step to walk the file, then tap different chunks to see what the footer records about each. Notice how small status and order_date are next to order_id and amount, which take 8 bytes a row.

Read the footer yourself

import duckdb, struct

duckdb.sql("""CREATE TABLE orders AS
    SELECT o.* REPLACE (o.order_id + 1000 * r.range AS order_id)
    FROM 'data/orders.csv' AS o, range(500) AS r
    ORDER BY order_id""")
duckdb.sql("COPY orders TO 'orders.parquet' (FORMAT PARQUET, ROW_GROUP_SIZE 10000)")

with open("orders.parquet", "rb") as f:
    head = f.read(4)
    f.seek(-8, 2)            # 8 bytes before the end
    tail = f.read(8)
footer_len = struct.unpack("<I", tail[:4])[0]
print("first 4 bytes:", head, " last 4 bytes:", tail[4:])
print("footer:", footer_len, "bytes")

groups, chunks = duckdb.sql("SELECT COUNT(DISTINCT row_group_id), COUNT(*) FROM parquet_metadata('orders.parquet')").fetchone()
print(groups, "row groups,", chunks, "column chunks: about", footer_len // chunks, "footer bytes per chunk")

f.seek(-8, 2) jumps to 8 bytes before the end, and <I reads a little-endian unsigned 4-byte number. The footer grows with row groups times columns: about 90 bytes per chunk here. That is one cost of tiny row groups. 10,000 row groups of 50 columns make a footer of tens of megabytes, and every reader parses it first.

Same rows, very different sizes

Now weigh the parts. The bar below is the same 40,000 orders written as one row group: 216,031 bytes.

Three quarters of the file is order_id. status is 2,906 bytes and currency is 56. Each column holds 40,000 values, and their sizes are nowhere near each other.

The reason is how a page is written. Each page is encoded first, then compressed. Encoding uses what the writer knows about the column: few different values, long repeats, numbers that climb. Compression (the codec of Lesson 4.2) then squeezes whatever is left.

The next sections take the encodings one at a time.

Where the 216,031 bytes of orders.parquet go

One bar splitting the real 40,000-row DuckDB file into its magic number, six column chunks of very different sizes, the footer and the tail: order_id takes three quarters, status and currency almost nothing.

Read it left to right: the file from its first byte to its last. Measured with parquet_metadata (each chunk's total_compressed_size) and the footer length from the tail, written with DuckDB 1.0's defaults. The parts add up to the file size exactly.

Write each word once

The simplest encoding is called PLAIN: write each value as it is. A whole number of type INT64 is 8 bytes. A piece of text is a 4-byte length, then its letters. One million order ids take exactly 8,000,000 bytes.

Now take status: five different words, repeated a million times. Dictionary encoding writes each word once, in a dictionary page at the start of the chunk, and replaces every value by its position in that list: 0, 1, 2, 3 or 4.

Those positions are small, so the writer packs them into as few bits as the largest one needs. Positions 0 to 4 fit in 3 bits. A million statuses become 1,000,000 x 3 / 8 = 375,000 bytes, against about 12 MB as plain text.

Eight statuses, encoded step by step

A column of eight status words is written in full, then as a three-word dictionary with eight positions, then with the positions packed at two bits each, and finally sorted so equal positions form runs.

  1. PLAIN. Every word is written in full, with a 4-byte length in front: 10 bytes for placed, 11 for shipped, 13 for delivered. Eight values take 85 bytes.

  2. Build the dictionary. Each different word is written once and gets a position: 0, 1, 2. Three words in full take 10 + 11 + 13 = 34 bytes.

  3. Replace words by positions. The data page no longer holds words. It holds eight small numbers that point into the dictionary.

  4. Pack the bits. The largest position is 2, which fits in 2 bits. 8 positions x 2 bits = 16 bits = 2 bytes, plus 2 bytes of header. In all 34 + 4 = 38 bytes, where PLAIN took 85.

  5. Sort the rows first. Now equal values sit together: position 2 once, 0 five times, 1 twice. On a real page of thousands of rows, each run is written as "this position, this many times" in a few bytes, however long the run is.

Follow the Data page box: it goes from words, to positions, to packed bits, to runs. The dictionary page itself is written PLAIN and the data pages are RLE_DICTIONARY, so the footer lists both encodings for one chunk.

Runs shrink to a count

The last step of that walkthrough has a name. When the same position comes many times in a row, the writer stores it once with a count. This is run-length encoding, RLE for short. 200,000 copies of position 2 take 4 bytes.

When the values keep changing, the writer packs them instead, 8 at a time, at the bit width. It mixes the two freely inside one page, and switches to a run when a value repeats about 8 times or more.

So the order of the rows changes the size of the file. A status column in random order is pure bit-packing: 3 bits a row. Sorted by status, it is five runs per page: a few bytes.

The simulator encodes 64 real values both ways.

Sixty-four status values shown as coloured squares, then as a five-entry dictionary and 3-bit indices, then as RLE and bit-packed runs with their byte sizes; a toggle sorts the column, and a second column shows sorted order ids delta-encoded into 27 bytes against 512 as PLAIN.

Step through unsorted first: 59 bytes of dictionary and 26 of indices, against 767 as PLAIN. Then sort the file by status and watch the indices drop to 13 bytes. Last, switch to order_id to see the encoding of the next section.

Numbers that climb: store the steps

order_id took three quarters of our file because every id is different: no dictionary helps, and there are no runs. But ids are not random. They climb.

Delta encoding (DELTA_BINARY_PACKED) stores the first value, then only the steps between neighbours. Take the ids 1001, 1002, 1004, 1005. The steps are 1, 2, 1. Store the smallest step once (1), then each step minus that: 0, 1, 0. Those fit in 1 bit each.

Sorted ids and timestamps shrink to almost nothing this way. Text has delta encodings too, for similar lengths and shared beginnings. Not every writer uses them: DuckDB 1.0 writes whole numbers PLAIN, which is what the bar above showed.

Encodings at a glance

Encoding (id)Used forWins when
PLAIN (0)any type; the fallbackvalues are unique and random
RLEDICTIONARY (8)dictionary indices; replaces PLAINDICTIONARY (2)few distinct values: statuses, countries, currencies
RLE (3)definition and repetition levels, booleanslong runs, such as a column that is rarely null
DELTABINARYPACKED (5)INT32, INT64sorted or slowly changing numbers: ids, timestamps
DELTALENGTHBYTEARRAY (6)stringsmany strings of similar length
DELTABYTEARRAY (7)stringsshared prefixes: sorted keys, URLs, paths
BYTESTREAMSPLIT (9)FLOAT, DOUBLEfloats that a codec then compresses

DELTA_LENGTH_BYTE_ARRAY delta-encodes the lengths and joins the bytes. DELTA_BYTE_ARRAY stores each value as "the first n bytes of the previous one, plus this ending". BYTE_STREAM_SPLIT splits floats into byte streams so the codec compresses them better.

Which encoding did DuckDB pick?

import duckdb

duckdb.sql("""
    COPY (
        SELECT 'cust-' || range || '@example.com' AS email,
               ['placed', 'shipped', 'delivered'][range % 3 + 1] AS status,
               CASE WHEN range % 4 = 0 THEN NULL ELSE 'SAVE' || (range % 10) END AS coupon
        FROM range(5000)
    ) TO 'customers.parquet' (FORMAT PARQUET)
""")
for row in duckdb.sql("""
    SELECT path_in_schema, encodings, stats_null_count, stats_distinct_count,
           total_uncompressed_size, total_compressed_size
    FROM parquet_metadata('customers.parquet')
    ORDER BY column_id
""").fetchall():
    print(row)

email is different on every row, so a dictionary would be as big as the data: PLAIN. status (3 values) and coupon (10) are dictionary-encoded, and the footer records how many different values each has. coupon has 1,250 nulls. A null is not stored as a value: a small marker per row, called a definition level, says "nothing here". The last two numbers are bytes before and after snappy.

Three ways to skip

Small files are half the story. The other half is reading less of them. A writer can leave three kinds of notes, from coarse to fine.

  • Statistics in the footer: the smallest value, the largest and the null count of every column chunk. They let a reader skip whole row groups.
  • A page index: the smallest and largest value of every page, and where each page starts. On a sorted column, a lookup then reads one page, not a whole chunk.
  • A bloom filter: a small bit pattern per chunk that answers "definitely not here" or "maybe here". It is for exact matches on columns where min and max say nothing, such as an email or a UUID.

The picture shows the order a reader uses them in.

How a reader decides what to read

Five steps down the page: read the footer, drop row groups with min and max, check bloom filters for exact matches, drop pages with the page index, then read and decode only the wanted columns of the pages that are left.

Read it top to bottom. Every step is optional and depends on what the writer stored. Spark pushes filters into the Parquet reader by default (spark.sql.parquet.filterPushdown = true) and decodes the pages that survive in batches of 4,096 rows.

Why 38 GB of 40 were read

Back to Tess's query. The files had statistics and the filter was on order_date. The statistics did nothing, because of one thing: the order the rows were written in.

A min and a max can rule out a row group only when the wanted value falls outside them. If rows were written in arrival order, or after a shuffle, every row group holds a bit of every day. Each one's range runs from the first of the month to the last, and nothing can be ruled out.

The example writes the same 40,000 orders twice with the same row-group size: once sorted by order_id, and once striped, so every group gets ids from the whole range. Then it asks each file for order 300042.

Sorted against striped: what min and max can skip

import duckdb

duckdb.sql("""CREATE TABLE orders AS
    SELECT o.* REPLACE (o.order_id + 1000 * r.range AS order_id)
    FROM 'data/orders.csv' AS o, range(500) AS r
    ORDER BY order_id""")
duckdb.sql("COPY orders TO 'sorted.parquet' (FORMAT PARQUET, ROW_GROUP_SIZE 10000)")
duckdb.sql("COPY (SELECT * FROM orders ORDER BY order_id % 7, order_id) TO 'striped.parquet' (FORMAT PARQUET, ROW_GROUP_SIZE 10000)")

def groups_that_may_hold(path, value):
    rows = duckdb.sql(f"""
        SELECT row_group_id, stats_min, stats_max FROM parquet_metadata('{path}')
        WHERE path_in_schema = 'order_id' ORDER BY row_group_id
    """).fetchall()
    for g, lo, hi in rows:
        print(f"  {path} group {g}: {lo:>6} to {hi:>6}")
    return [g for g, lo, hi in rows if int(lo) <= value <= int(hi)]

for path in ["sorted.parquet", "striped.parquet"]:
    print(path, "must read groups", groups_that_may_hold(path, 300042))

Same rows, same row-group size. Sorted, one group of four can hold order 300042. Striped (every seventh id first, then the next seventh), every group spans almost every id and the statistics rule out nothing. That is the dashboard that read 38 of 40 GB.

Remember: statistics only skip what is sorted. Sort by the column you filter on when you write, and run parquet_metadata (or parquet-tools meta) on one file of a slow table before you blame the engine.

How big should a row group be

Rows decoded divided by rows needed is called read amplification. In the question above it is 5.

Smaller groups do not always help. With groups of 500,000 rows, day 3 falls across two of them, so the reader still decodes 1,000,000 rows. One giant group of 6,000,000 makes it 30. A page index brings any of these back down to the day itself.

Bigger row groups mean longer straight reads, better compression and a smaller footer. They cost the writer memory, because it holds a row group's pages until the group is complete, and they skip more coarsely. Common defaults sit around 128 MB. The size matters less than the order: sort by the column you filter on, or nothing gets skipped.

Rows decoded to answer one day (sorted file)

Bars compare rows decoded for a one-day filter over six million sorted orders: six million with one row group, two million with 2,000,000-row groups, one million with 1,000,000-row and 500,000-row groups, 200,000 with 200,000-row groups or with a page index.

Each bar is the rows decoded to return one day (200,000 rows) of 6,000,000 sorted orders. Day 3 is rows 400,000 to 599,999; the numbers come from the simulator's model.

The six-million-row orders file with a one-day filter on order_date: row groups whose min and max cannot hold the day are greyed out, only the chosen columns are read, and totals show row groups, bytes, requests and rows decoded; toggles change sorting, row-group size and the page index.

Try sorted with 1,000,000-row groups (5x read amplification), then unsorted (all six groups are read), then 6,000,000-row groups (30x), then turn on the page index (1x).

The trap: trusting statistics on unsorted data. A file written in arrival order or after a shuffle has every row group spanning nearly every value, so min and max skip nothing. Fix it on write: sort or cluster by the main filter column (Z-order or liquid clustering for two or three columns), and keep row groups large. Tiny row groups (DuckDB's 2,048-row minimum, a streaming writer flushing every second) give a huge footer and one request per chunk, and compress badly.

Numbers to remember

WhatNumberGood to know
File start and endPAR1, 4 bytes, at both endsThe 4 bytes before the last PAR1 are the footer length, little-endian
FooterFileMetaData, in Thrift compact encodingPer chunk: byte offset, sizes, encodings, codec, statistics
Page size in parquet-java (the writer inside Spark)about 1 MB or 20,000 rowsparquet.page.size, parquet.page.row.count.limit. Small pages are cheaper for lookups; large pages compress better
Page headertype, sizes before and after compression, value count, encodingData page v2 also keeps the repetition and definition levels (nulls and nesting) outside the compressed body
Dictionary page limit in parquet-java1 MB (parquet.dictionary.page.size)Past it the writer falls back to PLAIN for the rest of the chunk, so the metadata lists both encodings
RLE runheader count << 1, then the value in ceil(width / 8) bytesHeaders are ULEB128 varints; the lowest bit says which kind of run follows
Bit-packed runheader (groups << 1) | 1, then groups of 8 valueswidth bytes per group
Dictionary indices (RLEDICTIONARY)a 1-byte bit width, then the runsThe width is the number of bits of the largest index: 300 values need 9
DELTABINARYPACKED block128 values in 4 miniblocks of 32 (parquet-java)The header holds the block size, miniblock count, value count and the first value (zigzag varint); each block stores its smallest delta once and a bit width per miniblock
Delta encodings in parquet-javaonly with format v2parquet.writer.version = PARQUET20 (default PARQUET10); on Databricks, parquet.format.version = 2.12.0
Page indexColumnIndex and OffsetIndexMin and max per page (truncated to 64 bytes by default in parquet-java) and each page's start and first row. Stored near the footer but outside it, so readers that do not filter never load it
Bloom filtersplit block: 32-byte blocks, hashed with XXH6410.5 bits per distinct value give about 1% false positives. Off unless parquet.bloom.filter.enabled
Default row groupparquet-java 128 MB, Iceberg 128 MB, DuckDB 122,880 rowsparquet.block.size, write.parquet.row-group-size-bytes. The Parquet docs recommend 512 MB to 1 GB for scan-heavy tables
Skipping whole filesDelta: min, max and null count per file for the first 32 columnsdelta.dataSkippingNumIndexedCols. Iceberg keeps per-file lower and upper bounds in manifests

What changed at SwiftKart

You run parquet_metadata on one file of last month's export. Every row group's order_date runs from the 1st of the month to the last: the export was written in arrival order. The job now sorts by order_date before it writes, and Tess's one-day query reads the few row groups that hold her day.

Delta Lake and Iceberg lift the same idea one level up. They keep each file's min and max in the table's own metadata, so whole files are skipped before their footers are even fetched.

That metadata is the last piece of this module. Lesson 4.6 opens the logs behind Delta, Iceberg and Hudi, and lets two writers commit at the same moment.

In one line

A Parquet file is row groups of column chunks with a footer of notes at the end; columns shrink by encoding, and a reader skips row groups only when the rows were sorted by the column it filters on.

Interview corner

Walk me through how a reader reads one column with a filter from a Parquet file on object storage.

It range-reads the last 8 bytes to get the footer length, then the footer: schema, row groups and per-chunk offsets and statistics. It drops row groups whose min/max cannot match, optionally checks bloom filters and the page index to drop more, and issues range GETs for just the needed column chunks of the surviving groups. Each page is decompressed with the chunk's codec, decoded (dictionary indices, RLE runs, deltas) into batches, 4,096 rows in Spark's vectorised reader, and the filter runs on those batches. So it reads a few percent of the bytes, if the data was sorted by the filter column.

Why is dictionary encoding so effective, and when does it stop working?

A column with few distinct values stores each value once in a dictionary page and only small indices per row, bit-packed at the width of the largest index: five statuses are 3 bits a row, so a million rows are 375 KB instead of about 12 MB of text, and runs of equal values collapse further with RLE. It stops working at high cardinality: the dictionary grows past its limit (1 MB in parquet-java) and the writer falls back to PLAIN for the rest of the chunk, or, as DuckDB does, never uses it for a column like email. For equality filters on such columns, a bloom filter is the tool.

How do you choose a Parquet row-group size?

Larger groups mean longer sequential reads, better compression, fewer chunks and a smaller footer; smaller groups mean finer skipping and less writer memory. Defaults sit around 128 MB (parquet-java, Iceberg) or 122,880 rows (DuckDB), and the Parquet docs suggest 512 MB to 1 GB for scan-heavy data. I compute read amplification for the common filter: if one day is 200,000 rows and groups hold 1,000,000, a one-day query decodes 5 times what it needs, which a page index or a finer sort can fix. Sorting by the filter column matters more than the exact size.

A filter on customer_id reads every row group of a large Parquet table. What do you do?

First confirm with the metadata: if every group's min and max span nearly all customer ids, the data is not clustered on that column. Options: rewrite sorted by customer_id if it is the main filter; cluster on several columns with Z-order or Delta's liquid clustering if there are a few; add bloom filters on customer_id for point lookups; or bucket the table by customer_id. Partitioning by customer_id is wrong: millions of tiny files. Then measure bytes read before and after.