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 1 of 6 · Concept · 25 min · revision 2

Row vs Columnar: Inside Avro and Parquet

See how row and columnar formats order the same bytes, how Avro encodes records and resolves schema changes, how Parquet splits a file into row groups, column chunks and pages with encodings and statistics, and where CSV and JSON go wrong.

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. Why it matters

A data pipeline writes the same facts many times: as messages on a queue, as files in a landing area, as tables for analysts. The file format decides how those facts are laid out as bytes, and the layout decides how many bytes a query must read (on cloud storage you pay for bytes and requests), whether types survive, and what happens when a producer changes the shape of the data.

This lesson looks inside the two formats you will meet most: Apache Avro, a row format with a schema, used for messages and landing data, and Apache Parquet, a columnar format for analytical tables. It ends with CSV and JSON and a short guide to choosing. The examples were tested with Python 3.12, PyArrow 26.0.1 and fastavro 1.13.1.

Terminal
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install pyarrow==26.0.1 fastavro==1.13.1

02. Rows or columns: one table, two byte orders

A file is one long sequence of bytes. A table has two dimensions, so a format must choose an order. A row-oriented format writes one whole record, then the next: id, country and amount of order 1, then the same fields of order 2. A column-oriented (columnar) format writes all the ids, then all the countries, then all the amounts. The script below prints both orders and marks where the amounts end up.

Python · layout.py
"""Print the same three rows in row order and in column order."""
rows = [(1, "DE", 19.99), (2, "FR", 5.0), (3, "DE", 42.5)]

row_order = [value for row in rows for value in row]
column_order = [row[i] for i in range(3) for row in rows]

for name, values in [("row order", row_order), ("column order", column_order)]:
    amounts = [i for i, v in enumerate(values) if isinstance(v, float)]
    print(f"{name:<13}{values}")
    print(f"{'':<13}amounts at positions {amounts}")
Expected output
row order    [1, 'DE', 19.99, 2, 'FR', 5.0, 3, 'DE', 42.5]
             amounts at positions [2, 5, 8]
column order [1, 2, 3, 'DE', 'FR', 'DE', 19.99, 5.0, 42.5]
             amounts at positions [6, 7, 8]

To sum the amounts, a row-layout reader must step over every other field, so it reads and decodes everything; a column-layout reader reads one contiguous run of bytes. With 60 columns and a dashboard that uses 4, that is the difference between reading the whole file and reading about a fifteenth of it. Neighbouring values in a column also share a type and often a value, so encodings and compression work much better on them.

A columnar writer must collect many rows before it can write a column, so columnar files suit batches, not single events. Reading one whole record means visiting every column, and changing one row means rewriting the file. So row formats fit work that handles whole records one at a time (services, queues, landing areas), and columnar formats fit scans of many rows and few columns (reporting, aggregation, feature extraction).

03. Inside Avro: compact rows and a schema that travels

An Avro schema is a JSON document that names a record and lists its fields and types. Data is written in a compact binary encoding that relies on the schema: values follow each other in schema order, with no field names and no separators. Integers use variable-length zig-zag encoding, so small numbers take one byte, and strings are a length followed by UTF-8 bytes. Compare one record with JSON:

Python · avro_bytes.py
"""Encode one record as Avro binary and as JSON, and compare the bytes."""
import io
import json

import fastavro

schema = fastavro.parse_schema({
    "type": "record", "name": "Payment",
    "fields": [
        {"name": "id", "type": "long"},
        {"name": "country", "type": "string"},
        {"name": "amount", "type": "double"},
    ],
})
record = {"id": 42, "country": "DE", "amount": 19.99}

buf = io.BytesIO()
fastavro.schemaless_writer(buf, schema, record)
avro_bytes = buf.getvalue()
json_bytes = json.dumps(record).encode()

print("Avro:", len(avro_bytes), "bytes ->", avro_bytes.hex(" "))
print("JSON:", len(json_bytes), "bytes ->", json_bytes.decode())
Expected output
Avro: 12 bytes -> 54 04 44 45 3d 0a d7 a3 70 fd 33 40
JSON: 44 bytes -> {"id": 42, "country": "DE", "amount": 19.99}

The 12 bytes are 54 (42 in zig-zag form, which maps 42 to 84, hex 54), 04 (a string of length 2), 44 45 ("DE") and an 8-byte IEEE double. Without the schema these bytes mean nothing, so Avro keeps the schema close to the data. An object container file stores it once in the header, followed by blocks of records, each block optionally compressed (deflate, zstandard and others) and followed by a 16-byte sync marker. A message on a queue cannot carry a whole schema each time, so Avro's single-object encoding starts with a two-byte marker and an 8-byte schema fingerprint instead; schema registries use a similar idea with a schema id.

Avro reads with two schemas: the writer schema the data was written with, and the reader schema the consumer expects. Fields are matched by name. A writer field that the reader does not list is skipped. A reader field that the writer never wrote takes the reader's default, and without a default, reading fails. Some type changes are allowed, such as int to long.

Python · avro_evolve.py
"""Read a record written with schema v1 using two newer reader schemas."""
import io

import fastavro
from fastavro.read import SchemaResolutionError

v1 = {"type": "record", "name": "Payment", "fields": [
    {"name": "id", "type": "long"},
    {"name": "amount", "type": "double"},
    {"name": "note", "type": "string"},
]}
buf = io.BytesIO()
fastavro.writer(buf, v1, [{"id": 1, "amount": 9.5, "note": "first"}])

readers = {
    "v2 with default": [
        {"name": "id", "type": "long"},
        {"name": "amount", "type": "double"},
        {"name": "currency", "type": "string", "default": "EUR"},
    ],
    "v3 no default": [
        {"name": "id", "type": "long"},
        {"name": "currency", "type": "string"},
    ],
}
for label, fields in readers.items():
    buf.seek(0)
    reader_schema = {"type": "record", "name": "Payment", "fields": fields}
    try:
        print(label, "->", list(fastavro.reader(buf, reader_schema)))
    except SchemaResolutionError as err:
        print(label, "-> SchemaResolutionError:", err)
Expected output
v2 with default -> [{'id': 1, 'amount': 9.5, 'currency': 'EUR'}]
v3 no default -> SchemaResolutionError: No default value for field currency in Payment

Reader v2 got the old record with note dropped and currency filled from its default. Reader v3 failed, because it asked for a field that old data cannot supply. These rules are why Avro is a common choice for event streams and landing zones: producers and consumers change at different times, and the rules say in advance which changes are safe.

On a queue such as Kafka, a schema registry usually enforces these rules. It stores every schema version under an id; producers put the id in front of each message, and consumers fetch the schema by id. Before accepting a new version, the registry checks it under the compatibility mode you choose. In backward mode it rejects a version like reader v3, which adds a field without a default, because its consumers could not read the messages already on the topic.

04. Inside Parquet: row groups, column chunks, pages and a footer

A Parquet file is split horizontally into row groups. Inside a row group, each column is stored as one column chunk, divided into pages, the unit that is encoded and compressed. After the data comes the footer: the schema plus, for every column chunk, its position, sizes, encodings, codec and statistics such as minimum, maximum and null count. The file starts and ends with the magic bytes PAR1, and the footer length sits just before the final PAR1. A reader reads the end of the file first, learns where every chunk is, and fetches only what it needs; the writer can write the footer last, in one pass.

Each page is first encoded, then compressed with a general codec. The main encodings are:

  • Dictionary (RLE_DICTIONARY): each distinct value is stored once in a dictionary page, and the data holds small integer indexes. If the dictionary grows too large, the writer falls back to plain encoding.
  • Run-length / bit-packing hybrid (RLE): a run of equal values becomes "value, count", and small integers are packed into as few bits as they need. It encodes dictionary indexes and the levels that mark nulls.
  • Delta (DELTA_BINARY_PACKED): differences between neighbouring integers, tiny for sorted ids and timestamps.
  • Plain (PLAIN): values back to back.

The script writes a million city names twice, shuffled and sorted, with no compression, so only the encodings act.

Python · parquet_layout.py
"""Write one low-cardinality column shuffled and sorted, then compare."""
import random

import pyarrow as pa
import pyarrow.parquet as pq

rng = random.Random(1)
cities = ["Berlin", "Lyon", "Leeds", "Porto", "Turin",
          "Graz", "Ghent", "Malmo", "Brno", "Cork"]
values = [rng.choice(cities) for _ in range(1_000_000)]

for name, column in [("shuffled", values), ("sorted", sorted(values))]:
    path = f"{name}.parquet"
    pq.write_table(pa.table({"city": column}), path, compression="none")
    col = pq.ParquetFile(path).metadata.row_group(0).column(0)
    print(f"{name:<9} {col.total_compressed_size:>9,} bytes  "
          f"encodings={col.encodings}")

with open("sorted.parquet", "rb") as f:
    data = f.read()
footer_len = int.from_bytes(data[-8:-4], "little")
print("first 4 bytes:", data[:4], "| last 4 bytes:", data[-4:])
print("footer length:", footer_len, "bytes of", f"{len(data):,}")
plain = sum(4 + len(v) for v in values)
print("plain encoding would need about", f"{plain:,}", "bytes")
Expected output
shuffled    504,753 bytes  encodings=('PLAIN', 'RLE', 'RLE_DICTIONARY')
sorted        2,701 bytes  encodings=('PLAIN', 'RLE', 'RLE_DICTIONARY')
first 4 bytes: b'PAR1' | last 4 bytes: b'PAR1'
footer length: 363 bytes of 3,076
plain encoding would need about 8,700,160 bytes

Plain encoding would need about 8.7 MB: a 4-byte length plus the text per value. With a ten-name dictionary, each value becomes a 4-bit index, so the shuffled column takes about half a byte per row. Sorted, the million values form ten long runs that run-length encoding stores in a few bytes each. No codec ran at all, yet the row order changed the size by a factor of about 190. That is why writers often sort by a column that queries filter on.

Compression comes after encoding and is chosen per column chunk: Snappy and LZ4 are fast with moderate ratios, zstd and gzip compress harder for more CPU. Statistics let an engine skip data unread: if a row group's order_date lies between 1 and 7 March, a query for 20 March skips it. This only works when values are clustered.

05. CSV, JSON and how to choose

CSV is text with commas and nothing else. Every reader guesses the types, and guesses differ: a postcode 02134 becomes the number 2134, an id column with one empty value becomes a float, a date stays a string. RFC 4180 describes common practice for quoting and line endings, but many files ignore it.

JSON names every field in every record, which makes it self-describing but large, and it has no schema to check against. Many parsers, including JavaScript's, turn every number into a 64-bit float, which holds integers exactly only up to 2^53:

Terminal
node -e 'console.log(JSON.parse("{\"order_id\": 9007199254740993}").order_id)'
Expected output
9007199254740992

The id changed by one, without an error. Large ids in JSON are safer as strings.

A practical guide follows from the layouts:

  • Use Avro when records are produced and consumed one at a time or in small batches, when producers and consumers evolve separately, and when you want a schema checked at write time: queues, change streams, landing areas.
  • Use Parquet for data written in batches and read by queries that touch some columns of many rows. Sort it by a common filter column.
  • Use CSV or JSON at the edges, for systems that cannot read anything else. Declare types when you read them, and convert to a typed format early.

06. Check your understanding

Practice check · 3 questions

Rows, columns and schemas

Apply the ideas of this lesson to three new situations. Each question has one best answer.

Q1. Payments were written to Avro files with a schema that has the fields `id`, `amount` and `note`. A new consumer reads them with a reader schema that lists only `id` and `amount`. What does it get?
Q2. A Parquet file of events is sorted by `event_time` and has 8 row groups. Values of `customer_id` are spread evenly over the whole file. A query filters on `customer_id = 42`. How many row groups can min/max statistics rule out?
Q3. A partner sends orders as JSON to your Node.js service, and their 19-digit order ids arrive with the last few digits changed. Which change fixes the cause?
Practice only: not graded, not saved, not evidence.

07. Apply it

The practice project of this skill converts a multi-gigabyte CSV dataset to Parquet and then to an Iceberg table. Prepare for it:

  1. Choose the dataset and list, for every column, the type it should have and how a CSV reader could get it wrong.
  2. Write an Avro schema for one record with an optional field and a default. Encode three records with fastavro and read them back with a reader schema that adds a field with a default.
  3. Choose the column to sort the Parquet output by, and say which queries that order helps.

08. Review prompt

Without looking back:

  1. Describe the byte order of a row format and of a columnar format, and give one workload that suits each.
  2. What three things decide whether an Avro reader can read data written with an older schema?
  3. Name the parts of a Parquet file from the largest to the smallest, and say what the footer holds.
  4. Why did sorting a column shrink it so much, even though no compression codec ran?
  5. Give two ways in which CSV and JSON can change your data without raising an error.

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