CSV, JSON, Avro, Parquet
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 8:15 on Tuesday. Tess's stock report lists product 721, and the warehouse has no such product: the label on the shelf says 00721. Nobody typed it wrong. A CSV file sat between two steps of the pipeline, and the reader guessed. The same nightly job spends twelve minutes parsing yesterday's CSV exports before it does any real work.
You'll learn to
- See why CSV loses types and how Parquet keeps them
- Read an Avro file's layout and its rules for schema changes
- Look inside a Parquet file and skip row groups with statistics
- Pick a compression codec by its speed and size
Learn
A reader guessed, and guessed wrong
The product code left the shop's database as the text 00721. One step of the pipeline wrote it to a CSV file, and the next step read it back.
A CSV file is plain text with commas. It does not say whether a column is text, a number or a date. So every program that reads it has to guess from the values, every time. 00721 looks like a number, and a number has no leading zeros.
The file below holds two product codes. Before you run it, guess what pandas makes of the first one.
CSV makes every reader guess
import duckdb
import pandas as pd
print("pandas: ", pd.read_csv("exports/skus.csv")["sku"].tolist())
print("pandas, typed:", pd.read_csv("exports/skus.csv", dtype={"sku": str})["sku"].tolist())
print("duckdb: ", duckdb.sql("SELECT sku FROM 'exports/skus.csv'").fetchall())
duckdb.sql("COPY (SELECT * FROM 'exports/skus.csv') TO 'skus.parquet' (FORMAT PARQUET)")
print("parquet schema:", duckdb.sql("SELECT name, type FROM parquet_schema('skus.parquet') WHERE name <> 'duckdb_schema'").fetchall())
pandas decided 00721 was a number and lost the zeros. DuckDB noticed the zeros and kept text. Two tools, two answers from one file. Parquet stores the type once, when the file is written (BYTE_ARRAY is text, INT64 a whole number), so every reader sees the same thing.
Five questions to ask a file format
A file format is a set of choices. Five questions cover them.
- Are the types stored in the file, or guessed on every read? The list of column names and types is called the schema.
- Is the data laid out by rows or by columns (Lesson 4.1)?
- Is it compressed, and in pieces of what size?
- Can a big file be split, so many workers each read a part at the same time?
- Can a person open it and read it?
CSV and JSON are text: anyone can open them, and every reader pays to parse them. Avro and Parquet are binary, and both store the schema. Avro keeps rows. Parquet keeps columns.
One table, three files
The same two orders stored three ways: a CSV file of text lines with no types, an Avro file with the schema first and then rows, and a Parquet file with one block per column and a footer holding the schema and statistics.
Read each box top to bottom, as the file is laid out on disk. Look for the violet box: CSV has none, Avro puts it first, Parquet puts it last.
Four formats side by side
| CSV | JSON Lines | Avro | Parquet | |
|---|---|---|---|---|
| Types stored | no | a few | yes, header | yes, footer |
| Layout | rows | rows | rows in blocks | columns in row groups |
| Nesting | no | yes | yes | yes |
| Compression | whole file | whole file | per block | per page |
| Splittable | if uncompressed | if uncompressed | yes, sync markers | yes, by row group |
| Best for | people, partners | raw events, API dumps | Kafka, row-at-a-time | analytics, lakes |
A gzipped CSV or JSON file cannot be split. gzip is one stream, so one worker must read it from the first byte to the last, and a 50 GB .csv.gz is slow on any cluster. bzip2 can be split but is slow. Formats that compress inside the file (Avro blocks, Parquet pages) avoid the problem.
Avro keeps the form with the answers
Avro is built for writing one record at a time, which is what a stream of order events does.
Think of a paper form. The blank form has the labels: order id, status, time. A filled-in copy only needs the answers, in order. An Avro file works the same way. It starts with a header that holds the schema, written once. After it come blocks of records, and a record is only values, in schema order. There are no field names, so records are tiny. Without the schema they mean nothing.
Each block ends with the same random 16-byte sync marker. A worker can jump to any byte, scan forward to the next marker and start reading there. That is what makes the file splittable.
An Avro file, top to bottom
Nested boxes: a header with four marker bytes, the schema and codec and a 16-byte sync marker, followed by data blocks, each holding a record count, a byte size, the compressed records and the sync marker.
Read it top to bottom: the header once, then block after block. The count and size let a reader skip a block without decoding it. A Kafka message has no file header, so it starts with one zero byte and a 4-byte schema id, and the reader looks the schema up.
The shape changes. Old data must still read.
Next month the order event gains a coupon field. Files and messages written last month do not have it, and nobody is going to rewrite them.
Avro handles this by reading with two schemas. The writer's schema says how the bytes were written. The reader's schema says what your program wants today. Avro lines the two up, field by field, with fixed rules.
Changing a schema over time without breaking old data is called schema evolution. Step through one record to see every rule at work.
A version-2 reader meets a version-1 record
A record written with schema version 1 is read by a program that wants version 2: matching fields are copied by name, an int is widened to a long, a field only the writer has is skipped, and a field only the reader has takes its default.
Two schemas. The record on the left was written with version 1. The program wants version 2. Nothing has been matched yet.
Match by name.
statusandorder_idexist on both sides, so their values are copied. Order does not matter: the reader listsstatusfirst and still gets the right value.Widen a type. The writer stored
qtyas an int and the reader wants a long. A small whole number always fits in a bigger one, so Avro promotes it. The other way round would lose values, so it is not allowed.Only the writer has it. The reader's schema has no
legacy_code, so that value is skipped. Deleting a field from the reader is safe.Only the reader has it. The record has no
coupon, so the reader's default fills it: null. With no default, the read fails right here. That one word decides whether old data still reads.
Follow one field at a time from the left box to the right box. A rename breaks the match by name, unless the reader's field lists the old name as an alias.
The registry says no first
Rules only help if someone checks them before bad data ships. In Kafka (the message system of Module 15) that someone is the schema registry: a small service that stores every version of every schema.
When a producer registers a new version, the registry tests it against the previous one and can refuse it. Its default test is called BACKWARD: a program on the new schema must be able to read data written with the old one. So you may add fields that have defaults, and delete fields. You upgrade the readers first.
FORWARD is the mirror image: old readers must cope with new data, so the writers upgrade first. FULL asks for both.
Which change is safe
| Change to the order schema | BACKWARD (new reads old) | FORWARD (old reads new) |
|---|---|---|
| Add coupon with a default | yes: the default fills old records | yes: old readers ignore it |
| Add channel without a default | no: old records have no value | yes |
| Remove a field that had a default | yes: the writer's value is ignored | yes: old readers use the default |
| Remove a field with no default | yes | no: old readers need it |
| Widen qty from int to long | yes: int promotes to long | no: long does not narrow to int |
| Rename status to state | no, unless an alias | no |
This is why every optional field is written with the type ["null", "string"] and "default": null: it keeps both directions open.
Version 2 of the order schema
Runs on a Kafka cluster:
{
"type": "record",
"name": "Order",
"namespace": "swiftkart",
"fields": [
{"name": "order_id", "type": "long"},
{"name": "status", "type": "string"},
{"name": "updated_at", "type": {"type": "long", "logicalType": "timestamp-micros"}},
{"name": "coupon", "type": ["null", "string"], "default": null}
]
}
coupon arrived in version 2: it may be null, and it has a default. So version-2 readers can read version-1 messages (coupon becomes null), and version-1 readers skip it. Avro libraries are not available in this browser, so this is shown, not run.
Parquet keeps its notes at the end
Avro is for the trip in. For data at rest that analysts will scan, SwiftKart wants columns, so it writes Parquet.
A Parquet file cuts the rows into row groups. Inside a row group each column is stored on its own, as a column chunk. A chunk is written as small pages, each encoded and compressed by itself.
The last thing in the file is the footer. It holds the schema, where every chunk starts, and a few statistics for each chunk: the smallest value, the largest, and how many nulls. A reader fetches the footer first, then only the chunks it needs.
Lesson 4.5 opens the file byte by byte. Here, look at the statistics.
Read the notes with parquet_metadata
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 'orders.parquet' (FORMAT PARQUET, ROW_GROUP_SIZE 10000)")
for row in duckdb.sql("""
SELECT row_group_id, row_group_num_rows, stats_min, stats_max, compression
FROM parquet_metadata('orders.parquet')
WHERE path_in_schema = 'order_id'
ORDER BY row_group_id
""").fetchall():
print(row)
One line per row group, for the order_id column. You asked for 10,000 rows a group and got 10,240: DuckDB adds rows in batches of 2,048 and closes a group once it holds more than you asked for. The rows were written sorted by order_id, so each row group covers its own narrow range of ids.
The notes let a reader skip
Now ask that file for one order: WHERE order_id = 300042.
Before it reads any data, the reader checks each row group's smallest and largest order_id in the footer. If 300,042 is outside a group's range, the group cannot hold it, and the reader never touches it. Handing the filter down to the file like this is called predicate pushdown.
It only works when the data is sorted by the filter column. If the ids were scattered, every row group would span almost the whole range and nothing could be skipped. That is why teams sort by date or id when they write, and why Delta Lake has Z-ordering and liquid clustering (Module 13).
One order wanted, three row groups skipped
A Parquet file with four row groups and a footer. The reader reads the footer, skips row groups 0 and 1 because their largest id is too small, reads row group 2, and skips row group 3 because its smallest id is too large.
The footer first. The question is
WHERE order_id = 300042. The reader starts at the end of the file: a few kilobytes that list each row group's smallest and largestorder_id.Row groups 0 and 1. Their largest ids are 128,080 and 256,080. Both are below 300,042, so the order cannot be inside. The reader skips them without touching their bytes.
Row group 2. 300,042 sits between 257,001 and 384,080. The order might be here, so the reader reads this group's
order_idchunk.Row group 3. Its smallest id is 385,001, which is too high. Skipped. The reader opened one row group of four.
The ranges are the ones the example above printed. Each step compares 300,042 with one range and colours the row group read or skipped.
Remember: the footer says what each row group can hold. Sorted data makes those ranges narrow, and narrow ranges get skipped.
Smaller file or faster read: pick a codec
Parquet squeezes data twice. First it encodes each column, with the dictionary and run-length tricks from Lesson 4.1. Then it compresses each page with a general-purpose method, called a codec. You pick the codec when you write the file.
The trade is size against speed. snappy and lz4 unpack very fast and shrink a little. gzip shrinks more and unpacks about four times slower than snappy. zstd gets close to both: it unpacks about as fast as snappy and stores about a third less.
That is why newer defaults moved to zstd, and why gzip mostly survives in old pipelines. The bars show how fast one CPU core unpacks each.
How fast one core unpacks each codec
Bars compare single-core decompression speed: lz4 at 3,850 MB/s, zstd level 1 at 1,550, snappy at 1,500 and zlib level 1 at 390, each with its compression ratio underneath.
A longer bar is a faster read; the ratio under it is how many times smaller the data got. The numbers are the zstd project's benchmark of general files on a desktop CPU. Columnar data compresses far better than those files, because encoding has already removed most repetition.
Write the same orders with each codec
import duckdb, os
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.csv' (HEADER)")
sizes = {"orders.csv": os.path.getsize("orders.csv")}
for codec in ["uncompressed", "snappy", "lz4", "gzip", "zstd"]:
path = f"orders_{codec}.parquet"
duckdb.sql(f"COPY orders TO '{path}' (FORMAT PARQUET, COMPRESSION {codec})")
sizes[path] = os.path.getsize(path)
for path, size in sizes.items():
print(f"{path:28} {size:>10,} bytes {sizes['orders.csv'] / size:5.1f}x smaller than CSV")
The same 40,000 orders. Parquet with no codec is already half the CSV: numbers are binary and text is stored as dictionary codes. snappy and lz4 cut it 6 to 8 times more, zstd and gzip about 20 times. Our copies repeat the same 80 orders, which flatters every codec; real tables usually end up 3 to 10 times smaller than CSV. DuckDB writes lz4 as LZ4_RAW, the framing the Parquet spec now recommends.
ORC, the other column format
| ORC | Parquet |
|---|---|
| Stripes, 64 MB by default (orc.stripe.size) | Row groups, 128 MB in parquet-java (parquet.block.size) |
| Row index every 10,000 rows (orc.row.index.stride), with min/max | Statistics per column chunk; optional page index per page |
| Tail: footer and postscript; the last byte is the postscript length | Tail: footer, its 4-byte length, then PAR1 |
| Nested data as present and length streams | Nested data as repetition and definition levels (from Google's Dremel) |
| Optional bloom filters per row-index group | Optional bloom filters per column chunk |
| Home: Hive and Hive ACID tables | Spark, Databricks, Snowflake, BigQuery, DuckDB, Iceberg and Delta |
The trap: CSV between pipeline steps. Every trip through CSV loses types: leading zeros, dates, the difference between an empty string and a null. Then the next step guesses again. Keep CSV for the edges (partner files, exports for people) and use Parquet inside.
And do not judge a format on a tiny file. Parquet pays a fixed cost per file for its footer, schema and page headers, so its savings show at scale.
Numbers to remember
| What | Number or rule | Good to know |
|---|---|---|
| lz4 | ratio 2.10, unpacks 3,850 MB/s | Fastest to read |
| snappy | ratio 2.09, unpacks 1,500 MB/s | Default in Spark (spark.sql.parquet.compression.codec) and in DuckDB |
| zstd, level 1 | ratio 2.90, unpacks 1,550 MB/s | Default in Iceberg (write.parquet.compression-codec); Databricks writes it for Unity Catalog managed tables. Higher levels trade write time for size: DuckDB's COMPRESSIONLEVEL runs 1 to 22, default 3 |
| gzip (zlib level 1) | ratio 2.74, unpacks 390 MB/s | Compresses at only 105 MB/s |
| Avro header | O, b, j and the byte 1 | Then a map holding avro.schema and avro.codec, then the 16-byte sync marker |
| Avro codecs | null and deflate always | snappy, zstandard, bzip2 and xz are optional |
| Avro type promotions | int to long, float or double; long to float or double; float to double; string to bytes and back | Never the narrowing direction |
| Kafka message with a registry | magic byte 0, then a 4-byte schema id | Confluent's wire format; the reader fetches that schema once and caches it |
| Registry modes | BACKWARD (Confluent's default), FORWARD, FULL | Checked per subject; a TRANSITIVE mode checks every older version, not only the last |
The codec numbers are the zstd project's own lzbench results: one core, Silesia corpus.
What changed at SwiftKart
CSV now lives at the edges only: files from partners, exports for people. Between its own steps the pipeline writes Parquet with zstd, so 00721 stays text and the nightly job no longer spends twelve minutes parsing. Order events on their way in travel as Avro, checked by a schema registry.
That is the common shape: Avro, Protobuf or JSON on the way in, Parquet at rest. Kafka Connect is one tool that lands those messages in the lake as Parquet.
The files are good. Where should they go? Lesson 4.3 sorts them into folders, so a question about one day opens one folder.
In one line
CSV makes every reader guess the types; Avro keeps rows with their schema for data on the move; Parquet keeps columns with statistics for data at rest, compressed with a codec such as zstd.
Interview corner
Why is Parquet preferred over CSV for analytics?
Parquet stores the schema, so types are not guessed on every read. It is columnar, so a query reads only the columns it needs, and each column is encoded (dictionary, run-length) and compressed per page. The footer keeps min, max and null counts per column chunk, so filters skip row groups without reading them. The cost is that people cannot read it directly and it is not meant for appending single records.
How does Avro handle schema evolution, and what does a schema registry add?
Avro decodes with the writer's schema and resolves into the reader's: fields match by name, writer-only fields are ignored, reader-only fields take their default or fail, and int, long and float can widen. A registry stores every version per subject, gives each a 4-byte id that rides in each Kafka message, and rejects incompatible versions at registration time. In BACKWARD mode, the default, you may add fields with defaults and delete fields, and you upgrade consumers before producers.
Snappy, zstd or gzip for a Parquet lake, and why?
All three compress each page independently, so the file stays splittable either way. Snappy and lz4 decompress at well over 1,000 MB/s per core with modest ratios; zstd at level 1 to 3 decompresses about as fast as snappy and is roughly a third smaller, so it usually wins on cost per query; gzip decompresses around 400 MB/s and is slow to write. I default to zstd for tables read by many queries and keep snappy where write latency matters, and I measure on our own data.
What is the difference between ORC and Parquet?
Both are columnar with per-column encoding, compression and statistics. ORC groups rows into stripes (64 MB by default) with a row index every 10,000 rows and a postscript at the very end; Parquet uses row groups, column chunks and pages with a footer, and encodes nesting with repetition and definition levels. ORC grew up with Hive and Hive ACID; Parquet became the default for Spark, Databricks, Snowflake, BigQuery, DuckDB and the table formats, which is why most new lakes use it.