Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 25 min · revision 2

Lab: The Same Data as CSV, Avro and Parquet

Write one seeded set of 100,000 orders as CSV, Avro and Parquet, measure the file sizes, watch CSV lose types, read the Avro schema from the file header and the Parquet footer, and count the bytes each format reads for a two-column query.

Contentsand lesson path

What you will learn

  • Choose between CSV/JSON, Avro and Parquet for a workload by comparing row vs columnar layout, encoding, compression and schema support.

01. Goal and setup

In the previous lesson you saw how row and columnar formats lay out bytes. Here you check those claims. You generate 100,000 shop orders from a fixed seed, write exactly the same rows as CSV, Avro and Parquet, and measure four things: file sizes, which types survive a round trip, what metadata each file carries, and how many bytes each format reads to answer a question that needs two of the seven columns.

You need: Python 3.12 with PyArrow 26.0.1, fastavro 1.13.1, pandas 3.1.1 and DuckDB 1.5.6 (the versions the lab was tested with on Linux). All outputs come from a real run. Sizes are deterministic for a fixed seed and fixed library versions; other versions can change them, because the libraries choose page and block sizes themselves.

Project layout at the end of the lab
formats-lab/
├── data.py           step 1: seeded order generator
├── write_all.py      step 2: writes the same rows as 8 files
├── csv_pitfall.py    step 4: what CSV type inference does
├── avro_inspect.py   step 5: header, schema and blocks of the Avro file
├── parquet_meta.py   step 6: row groups, encodings and statistics
├── projection.py     step 7: bytes read for a two-column query
└── out/              the data files
Terminal
mkdir formats-lab && cd formats-lab
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install pyarrow==26.0.1 fastavro==1.13.1 pandas==3.1.1 \
    duckdb==1.5.6

02. Step 1: Generate the orders

The generator uses random.Random(42), so every run produces the same orders. The data is shaped like a real shop table, not pure noise, which would compress badly in every format and hide the differences. Order ids grow with time. Each customer has one country and one postcode, a five-digit string that sometimes starts with zero. Amounts come from a price list of 500 products, so many repeat. About 2% of orders have no customer_id (guest checkouts).

Python · data.py
"""Seeded order data shared by every step of the lab."""
import random
from datetime import datetime, timedelta, timezone

COUNTRIES = ["DE", "FR", "GB", "ES", "IT", "NL", "PL", "SE"]
STATUSES = ["paid", "shipped", "delivered", "refunded"]
START = datetime(2026, 3, 1, tzinfo=timezone.utc)


def make_orders(n=100_000, seed=42):
    rng = random.Random(seed)
    prices = [round(rng.uniform(2, 120), 2) for _ in range(500)]
    customers = {}
    for c in range(1, 20_001):
        country = rng.choices(COUNTRIES, [30, 20, 15, 10, 10, 7, 5, 3])[0]
        customers[c] = (country, f"{rng.randrange(3_000) * 33:05d}")
    seconds = sorted(rng.randrange(31 * 86_400) for _ in range(n))
    rows = []
    for i, s in enumerate(seconds):
        cust = rng.randrange(1, 20_001)
        country, postcode = customers[cust]
        rows.append({
            "order_id": 1_000_001 + i,
            "order_ts": START + timedelta(seconds=s),
            "customer_id": None if rng.random() < 0.02 else cust,
            "postcode": postcode,
            "country": country,
            "status": rng.choices(STATUSES, [50, 30, 17, 3])[0],
            "amount": round(rng.choice(prices) * rng.randint(1, 4), 2),
        })
    return rows


if __name__ == "__main__":
    rows = make_orders()
    print(len(rows), "orders")
    for key, value in rows[24].items():
        print(f"  {key:<12}{value!r}")
Terminal
python data.py
Expected output
100000 orders
  order_id    1000025
  order_ts    datetime.datetime(2026, 3, 1, 0, 8, 37, tzinfo=datetime.timezone.utc)
  customer_id 15245
  postcode    '06006'
  country     'IT'
  status      'paid'
  amount      12.9

Keep an eye on order 1000025. Its postcode is the string 06006, with a leading zero, and it has a real customer_id. You will follow this one row through every format.

03. Step 2: Write the same rows as CSV, Avro and Parquet

The script writes eight files from the same rows:

  • CSV, plain and gzip-compressed. CSV has no types, so the timestamp becomes ISO 8601 text and a missing customer_id an empty field. mtime=0 keeps the current time out of the gzip header.
  • Avro with the null codec (no compression) and the deflate codec. The schema is stored once, as JSON, in the header; customer_id is a union of null and long, Avro's way to say "optional".
  • Parquet with no compression, Snappy and Zstandard (zstd), in row groups of 25,000 rows. The last file also stores the two sorted integer columns with DELTA_BINARY_PACKED, which keeps the differences between neighbouring values.
Python · write_all.py
"""Write the same 100,000 orders as CSV, Avro and Parquet; compare sizes."""
import csv
import gzip
from pathlib import Path

import fastavro
import pyarrow as pa
import pyarrow.parquet as pq

from data import make_orders

rows = make_orders()
out = Path("out")
out.mkdir(exist_ok=True)

# CSV: text only. Timestamps become ISO strings, None becomes "".
with open(out / "orders.csv", "w", newline="") as f:
    writer = csv.DictWriter(f, fieldnames=list(rows[0]))
    writer.writeheader()
    for r in rows:
        writer.writerow({**r, "order_ts": r["order_ts"].isoformat()})
raw = (out / "orders.csv").read_bytes()
with gzip.GzipFile(out / "orders.csv.gz", "wb", mtime=0) as gz:
    gz.write(raw)

# Avro: rows in binary, with the schema stored once in the header.
schema = fastavro.parse_schema({
    "type": "record", "name": "Order", "namespace": "shop",
    "fields": [
        {"name": "order_id", "type": "long"},
        {"name": "order_ts",
         "type": {"type": "long", "logicalType": "timestamp-micros"}},
        {"name": "customer_id", "type": ["null", "long"], "default": None},
        {"name": "postcode", "type": "string"},
        {"name": "country", "type": "string"},
        {"name": "status", "type": "string"},
        {"name": "amount", "type": "double"},
    ],
})
for codec in ["null", "deflate"]:
    with open(out / f"orders.{codec}.avro", "wb") as f:
        fastavro.writer(f, schema, rows, codec=codec)

# Parquet: typed columns, row groups, statistics in the footer.
table = pa.Table.from_pylist(rows, schema=pa.schema([
    ("order_id", pa.int64()),
    ("order_ts", pa.timestamp("us", tz="UTC")),
    ("customer_id", pa.int64()),
    ("postcode", pa.string()),
    ("country", pa.string()),
    ("status", pa.string()),
    ("amount", pa.float64()),
]))
for codec in ["none", "snappy", "zstd"]:
    pq.write_table(table, out / f"orders.{codec}.parquet",
                   compression=codec, row_group_size=25_000)
pq.write_table(
    table, out / "orders.zstd_delta.parquet", compression="zstd",
    row_group_size=25_000,
    use_dictionary=["customer_id", "postcode", "country", "status",
                    "amount"],
    column_encoding={"order_id": "DELTA_BINARY_PACKED",
                     "order_ts": "DELTA_BINARY_PACKED"},
)

csv_size = (out / "orders.csv").stat().st_size
print(f"{'file':<28}{'bytes':>11}{'vs CSV':>8}")
for p in sorted(out.iterdir(), key=lambda p: -p.stat().st_size):
    size = p.stat().st_size
    print(f"{p.name:<28}{size:>11,}{size / csv_size:>8.2f}")
Terminal
python write_all.py
Expected output
file                              bytes  vs CSV
orders.csv                    6,267,059    1.00
orders.null.avro              3,897,977    0.62
orders.none.parquet           3,119,516    0.50
orders.snappy.parquet         2,288,136    0.37
orders.deflate.avro           1,990,569    0.32
orders.csv.gz                 1,671,234    0.27
orders.zstd.parquet           1,643,725    0.26
orders.zstd_delta.parquet       954,906    0.15

Uncompressed Avro is already 38% smaller than CSV, because it stores numbers in binary and never repeats field names. Uncompressed Parquet is smaller again, because dictionary encoding stores each distinct country, status and postcode once per column chunk. Then the surprise: gzip CSV beats Snappy Parquet and deflate Avro and is almost as small as zstd Parquet. A size comparison alone would wrongly crown gzip CSV. The last line shows one encoding choice at work: delta-encoding the ids and timestamps takes zstd Parquet from 0.26 to 0.15 of the CSV size. Steps 4 to 7 show what gzip CSV cannot offer: types, metadata and selective reads.

04. Step 3: Check that the sizes are reproducible

A measurement you cannot repeat is an anecdote. Run the writer twice, keep both size reports and a SHA-256 checksum of every file, and compare them.

Terminal
python write_all.py > sizes1.txt && sha256sum out/* > sums1.txt
python write_all.py > sizes2.txt && sha256sum out/* > sums2.txt
cmp sizes1.txt sizes2.txt && echo "sizes: identical"
diff sums1.txt sums2.txt | awk '/^>/ {print "content changed:", $3}'
Expected output
sizes: identical
content changed: out/orders.deflate.avro
content changed: out/orders.null.avro

The sizes match, and the CSV, gzip and Parquet files are identical byte for byte. The Avro files have the same size but different bytes, by design: the Avro specification says each container file has a 16-byte, randomly generated sync marker, repeated after every block so that a reader can find block boundaries in a damaged file. fastavro accepts a fixed sync_marker argument if you need reproducible bytes.

05. Step 4: Watch CSV lose its types

A CSV file is text plus a convention. Whoever reads it must guess every type, and pandas guesses by looking at the values. Read the CSV with default settings and follow order 1000025.

Python · csv_pitfall.py
"""Read the CSV back with type inference and compare it with Parquet."""
import pandas as pd
import pyarrow.parquet as pq

df = pd.read_csv("out/orders.csv")
print("pandas guessed these types from the CSV text:")
print(df.dtypes.to_string())

one = df[df["order_id"] == 1_000_025].iloc[0]
print()
print("order 1000025 from CSV:     ", one["postcode"], one["customer_id"])

pf = pq.read_table("out/orders.zstd.parquet",
                   filters=[("order_id", "==", 1_000_025)]).to_pylist()[0]
print("order 1000025 from Parquet: ", pf["postcode"], pf["customer_id"])
ts_type = pq.read_schema("out/orders.zstd.parquet").field("order_ts").type
print("Parquet type of order_ts:   ", ts_type)

fixed = pd.read_csv("out/orders.csv",
                    dtype={"postcode": "string", "customer_id": "Int64"},
                    parse_dates=["order_ts"])
again = fixed[fixed["order_id"] == 1_000_025].iloc[0]
print("CSV with explicit types:    ", again["postcode"],
      again["customer_id"], fixed["order_ts"].dtype)
Terminal
python csv_pitfall.py
Expected output
pandas guessed these types from the CSV text:
order_id         int64
order_ts           str
customer_id    float64
postcode         int64
country            str
status             str
amount         float64

order 1000025 from CSV:      6006 15245.0
order 1000025 from Parquet:  06006 15245
Parquet type of order_ts:    timestamp[us, tz=UTC]
CSV with explicit types:     06006 15245 datetime64[us, UTC]

Three silent changes happened. The postcode 06006 became the integer 6006: the leading zero is gone for good. customer_id became a float (15245.0), because the empty fields of guest orders become NaN, and NumPy integers have no missing value. The timestamp stayed a string, so date filters would compare text. Nothing failed, which is the danger: wrong types flow on and surface weeks later as a join that misses rows. Declaring the types when you read fixes all three, as the last line shows, but then the schema lives in reader code. Parquet and Avro store it with the data.

06. Step 5: Read the Avro schema from the file header

An Avro container file is self-describing: the header holds the magic bytes Obj plus a version byte, a metadata map with the schema and the codec, and the sync marker. After the header come blocks, each holding a count, a run of encoded records and the sync marker again. fastavro.block_reader lets you see those blocks without decoding the records.

Python · avro_inspect.py
"""Look inside the Avro container file: header, schema and blocks."""
import json

import fastavro

with open("out/orders.deflate.avro", "rb") as f:
    print("magic bytes:", f.read(4))
    f.seek(0)
    blocks = fastavro.block_reader(f)
    print("codec:", blocks.metadata["avro.codec"])
    schema = json.loads(blocks.metadata["avro.schema"])
    print("schema:", schema["name"], "with fields")
    for field in schema["fields"]:
        print(" ", json.dumps(field))
    counts = [block.num_records for block in blocks]

print("blocks:", len(counts), "| records in the first three:", counts[:3])

with open("out/orders.deflate.avro", "rb") as f:
    total = sum(rec["amount"] for rec in fastavro.reader(f))
print("sum(amount), decoding every whole record:", round(total, 2))
Terminal
python avro_inspect.py
Expected output
magic bytes: b'Obj\x01'
codec: deflate
schema: shop.Order with fields
  {"name": "order_id", "type": "long"}
  {"name": "order_ts", "type": {"logicalType": "timestamp-micros", "type": "long"}}
  {"default": null, "name": "customer_id", "type": ["null", "long"]}
  {"name": "postcode", "type": "string"}
  {"name": "country", "type": "string"}
  {"name": "status", "type": "string"}
  {"name": "amount", "type": "double"}
blocks: 243 | records in the first three: [417, 417, 417]
sum(amount), decoding every whole record: 15263538.29

The schema travelled with the data, including the logical type timestamp-micros and the default of the optional customer_id. The records sit in 243 blocks of roughly 16 KB, fastavro's default block size. Blocks are the unit of compression and the points where a file can be split between workers, but they do not help you skip columns: to sum amount, the reader decoded every field of every record.

07. Step 6: Read the Parquet footer

Parquet keeps its metadata in a footer at the end of the file: the schema, and for every row group and column chunk the physical type, codec, encodings, sizes and min/max statistics. PyArrow exposes the footer as FileMetaData, and DuckDB reads the same information with its parquet_metadata() table function.

Python · parquet_meta.py
"""Print the Parquet footer: row groups, encodings and statistics."""
import duckdb
import pyarrow.parquet as pq

PATH = "out/orders.zstd_delta.parquet"
md = pq.ParquetFile(PATH).metadata
print(f"rows={md.num_rows} row_groups={md.num_row_groups} "
      f"footer_bytes={md.serialized_size}")
print("created_by:", md.created_by)

rg = md.row_group(0)
print(f"row group 0: {rg.num_rows} rows")
for j in range(rg.num_columns):
    col = rg.column(j)
    print(f"  {col.path_in_schema:<12}{col.physical_type:<11}"
          f"{col.compression:<5}{col.total_compressed_size:>7} B  "
          + ", ".join(col.encodings))

print("min/max per row group:")
print(duckdb.sql(f"""
    SELECT row_group_id AS rg, path_in_schema AS col,
           stats_min_value AS min, stats_max_value AS max
    FROM parquet_metadata('{PATH}')
    WHERE path_in_schema IN ('order_ts', 'amount')
    ORDER BY col, rg
"""))
Terminal
python parquet_meta.py
Expected output
rows=100000 row_groups=4 footer_bytes=3824
created_by: parquet-cpp-arrow version 26.0.1
row group 0: 25000 rows
  order_id    INT64      ZSTD     206 B  RLE, DELTA_BINARY_PACKED
  order_ts    INT64      ZSTD   62705 B  RLE, DELTA_BINARY_PACKED
  customer_id INT64      ZSTD   72211 B  PLAIN, RLE, RLE_DICTIONARY
  postcode    BYTE_ARRAY ZSTD   46968 B  PLAIN, RLE, RLE_DICTIONARY
  country     BYTE_ARRAY ZSTD    9086 B  PLAIN, RLE, RLE_DICTIONARY
  status      BYTE_ARRAY ZSTD    5482 B  PLAIN, RLE, RLE_DICTIONARY
  amount      DOUBLE     ZSTD   40890 B  PLAIN, RLE, RLE_DICTIONARY
min/max per row group:
┌───────┬──────────┬────────────────────────┬────────────────────────┐
│  rg   │   col    │          min           │          max           │
│ int64 │ varchar  │        varchar         │        varchar         │
├───────┼──────────┼────────────────────────┼────────────────────────┤
│     0 │ amount   │ 2.05                   │ 479.68                 │
│     1 │ amount   │ 2.05                   │ 479.68                 │
│     2 │ amount   │ 2.05                   │ 479.68                 │
│     3 │ amount   │ 2.05                   │ 479.68                 │
│     0 │ order_ts │ 2026-03-01 00:00:26+00 │ 2026-03-08 17:29:17+00 │
│     1 │ order_ts │ 2026-03-08 17:29:23+00 │ 2026-03-16 12:02:19+00 │
│     2 │ order_ts │ 2026-03-16 12:03:12+00 │ 2026-03-24 06:59:55+00 │
│     3 │ order_ts │ 2026-03-24 07:00:48+00 │ 2026-03-31 23:58:46+00 │
└───────┴──────────┴────────────────────────┴────────────────────────┘

The footer is under 4 KB. RLE encodes the definition levels, the small integers that record which values are null. PLAIN, RLE, RLE_DICTIONARY means a plain-encoded dictionary page plus data pages of dictionary indexes. The 25,000 sorted ids of row group 0 take about 200 bytes, because every delta is 1.

The statistics tell the main story. The order_ts ranges of the four row groups do not overlap, because rows were written in time order, so a query for the last week of March can skip three row groups using the footer alone. The amount ranges are the same everywhere, so amount > 400 skips nothing. Statistics only help on clustered columns, which is why write order matters.

08. Step 7: Count the bytes a two-column query reads

The question is "what is the total amount per country?", which needs two of the seven columns. A small wrapper class counts every byte handed to the reader, and since PyArrow accepts any Python file-like object, it works for all three formats. The last query adds a filter on order_ts, so the Parquet reader can use the statistics from step 6. use_threads=False stops PyArrow from calling the Python wrapper from several threads at once.

Python · projection.py
"""Count the bytes each format reads to answer: total amount per country."""
import csv
import io
from datetime import datetime, timezone

import fastavro
import pyarrow.parquet as pq


class CountingFile(io.RawIOBase):
    """A read-only file wrapper that counts the bytes read through it."""

    def __init__(self, path):
        self.f = open(path, "rb")
        self.bytes_read = 0

    def readable(self):
        return True

    def seekable(self):
        return True

    def seek(self, offset, whence=0):
        return self.f.seek(offset, whence)

    def tell(self):
        return self.f.tell()

    def readinto(self, buf):
        n = self.f.readinto(buf)
        self.bytes_read += n
        return n


def report(label, src, pairs):
    totals = {}
    for country, amount in pairs:
        totals[country] = totals.get(country, 0.0) + amount
    top = max(totals, key=totals.get)
    print(f"{label:<34}{src.bytes_read:>10,} bytes   "
          f"top: {top} {totals[top]:,.2f}")


src = CountingFile("out/orders.csv")
rows = csv.DictReader(io.TextIOWrapper(src, newline=""))
report("orders.csv", src, ((r["country"], float(r["amount"])) for r in rows))

src = CountingFile("out/orders.deflate.avro")
recs = fastavro.reader(src)
report("orders.deflate.avro", src, ((r["country"], r["amount"]) for r in recs))

PARQUET = "out/orders.zstd_delta.parquet"
src = CountingFile(PARQUET)
t = pq.read_table(src, columns=["country", "amount"], use_threads=False)
report("orders.zstd_delta.parquet", src,
       zip(t["country"].to_pylist(), t["amount"].to_pylist()))

src = CountingFile(PARQUET)
last_week = datetime(2026, 3, 25, tzinfo=timezone.utc)
t = pq.read_table(src, columns=["country", "amount"], use_threads=False,
                  filters=[("order_ts", ">=", last_week)])
report("  same, only order_ts >= 25 March", src,
       zip(t["country"].to_pylist(), t["amount"].to_pylist()))
Terminal
python projection.py
Expected output
orders.csv                         6,267,059 bytes   top: DE 4,610,959.74
orders.deflate.avro                1,990,569 bytes   top: DE 4,610,959.74
orders.zstd_delta.parquet            287,836 bytes   top: DE 4,610,959.74
  same, only order_ts >= 25 March    183,566 bytes   top: DE 1,053,671.24

All three formats give the same answer from very different amounts of data. The CSV and Avro readers read their whole files, because both store rows. The Parquet reader read the footer and the country and amount chunks only: 4.6% of what the CSV reader needed, and with the date filter it also skipped three of the four row groups. This is column projection (reading only the named columns) and predicate pushdown (using a filter to skip data before decoding it). On object storage, where every byte and request is billed, this matters more than the size at rest.

09. Troubleshooting

10. Check your understanding

Practice check · 3 questions

Reading the lab results

Use what you measured in the lab. Each question has one best answer.

Q1. A CSV export has a column `sku` with the values `0042`, `0107` and an empty field in the third row. What does `pd.read_csv()` with default settings give you for that column in pandas 3?
Q2. You change `projection.py` so that the Parquet read also asks for `order_id`, and you sum it as well. Roughly how do the bytes-read numbers change?
Q3. In step 3, a colleague concludes that fastavro must be non-deterministic, because the Avro checksums changed between runs. What actually differs between the two files?
Practice only: not graded, not saved, not evidence.

11. Apply it: stretch tasks

These tasks start the practice project of this skill, which converts a multi-gigabyte CSV dataset to Parquet and later to an Iceberg table.

  1. Your own CSV. Pick a public CSV dataset of at least 1 GB whose licence allows reuse. Convert it to Parquet with explicit types (pyarrow.csv.read_csv with convert_options, or DuckDB COPY ... TO ... (FORMAT parquet)) and note every column whose inferred type was wrong.
  2. Three queries, measured. Run a one-column query, a date-filtered query and a query over most columns with DuckDB on both files, three times each. Report median time, bytes read, machine and versions.
  3. Order. Sort the Parquet output by the date column and compare the statistics and the date query before and after.

12. Review prompt

Without looking back:

  1. Which file was smallest at rest, and why is file size alone a poor way to choose a format for analytics?
  2. Name the three type changes that pandas made when it read the CSV, and the cause of each one.
  3. Where does an Avro file keep its schema, and why do two runs give different bytes but the same size?
  4. What does a Parquet reader read first, and what lets it skip row groups for a date filter but not for an amount filter?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check