Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Topic 12 — Columnar Storage & Analytics

DuckDB/ClickHouse-style OLAP. The thesis of this topic: compression IS performance. Encoded data is smaller, so scans move fewer bytes — and with lightweight encodings, scanning compressed data is often FASTER than scanning raw, because analytics is memory-bound (topic 11’s lesson) and decode cost < bandwidth saved.

 row store (OLTP)                column store (OLAP)
 ┌──────────────────┐            ┌────┐┌────┐┌────┐
 │ id │ name │ city │  1 row =   │ id ││name││city│   1 column =
 │ id │ name │ city │  1 place   │ id ││name││city│   1 place
 │ id │ name │ city │            │ id ││name││city│
 └──────────────────┘            └────┘└────┘└────┘
 point lookup: 1 cache line      SELECT sum(x): reads ONLY x,
 analytics: reads everything     10-100x less I/O + it compresses

Columns compress because a column is SELF-SIMILAR: same type, similar values, sorted or clustered. Rows interleave types and kill every trick below.

The problem, measured (bench lane 1, provided — runs today)

cargo run --release --bin scan_bench — 100 M u64 (800 MB) per shape, single-threaded fold, best of 3:

shape                       raw sum    raw-equiv GB/s
sorted low-cardinality      0.033 s              24.4
shuffled low-cardinality    0.016 s              50.0
small-range random          0.014 s              57.0

That is the floor every encoding in this topic has to beat: 24–57 GB/s on a machine whose peak memory bandwidth is 150 GB/s. One core gets roughly a third of the bus, with LLVM already vectorizing the fold across several accumulators to manage it. Beating this number is not a matter of shaving instructions; it requires moving fewer bytes, which is the entire thesis — compression IS performance.

Two honesty notes that matter more than the figures. First, the spread across the three shapes is noise, not signal: all three do byte-identical work, and repeat runs put this lane anywhere from 24 to 76 GB/s depending on machine state. A bandwidth-bound single number wants an error bar; take the high end as the target.

Second, the input goes through black_box for a reason that shows up the moment it is removed: the fold is pure, so LLVM hoists it out of the repetition loop, two of three reps time nothing, best-of-3 reports 0.000 s, and the lane prints 19 047 619 GB/s — 19,047,619 / 150 ≈ 127 000× the machine’s peak memory bandwidth, and ~250 000× the 76 GB/s this lane actually reaches. That is topic 0’s first failure mode, and the reason every number here is printed by code and checked against the hardware’s limit rather than asserted.

1. The lightweight encoding zoo

Not gzip. These are encodings the SCAN can execute over directly:

encodingideawins ondecode cost
RLE(value, run_length) pairssorted / low-cardinality~free, can even predicate-push on runs
Dictionaryids into a distinct-value dictstrings, low NDVarray index; comparisons become int ==
Bit-packingints in ceil(log2(max-min+1)) bitssmall int rangesshift+mask, SIMD-able
FOR (frame of reference)store min + deltas from itclustered valuesadd a constant
Deltadiffs from previous valuetimestamps, sequencesprefix sum (SIMD-able, but sequential-ish)
FSSTstring symbol table: 8-byte substrings → 1-byte codesmed-cardinality strings dictionary can’t deduptable lookup per code; random access preserved

DuckDB stacks them: bitpacking.cpp implements CONSTANT / FOR / DELTA_FOR as MODES of one function; dictionary ids get bit-packed; FSST codes get dictionary’d (dict_fsst/). BtrBlocks (SIGMOD ’23) makes the stacking recursive and picks per-block by SAMPLING each encoder.

2. How a system picks: analyze → score → compress

DuckDB’s compression framework (compression_function.hpp:131–139, DuckDB v2.0.0): every candidate encoder gets an analyze pass over the column data, returns a SCORE (estimated compressed size); the cheapest wins, per row-group per column. PRAGMA force_compression (or a declared USING COMPRESSION) narrows the menu to that one type plus UNCOMPRESSED for your experiments — the analyze pass still runs, because the winner compresses from its analyze state. This is the benchmark-before-choosing discipline built into the storage engine. ClickHouse sits at the other end: the user declares a codec per column, and with no declaration the default is chosen by part size — LZ4 for parts under 100 MiB, ZSTD(3) above (reading-clickhouse-mergetree.md, Step 8).

The score can carry more than bytes. A language model that predicts the next token can drive an arithmetic coder, and on Wikipedia text that beats traditional compressors’ ratio by more than 2× (§1 of Kipf, Schmidt, Kuo, Krid, Rengert, Heller, Zimmerer, Stoian, Pandey, van Renen, Waiting to Decompress: The Economics of LLM-Based Compression, CIDR 2026, pdf). Price the encode: with a cost model of S3 storage ($240 per TiB per year) plus GPU rental for compression, LLM-based compression takes 10 years of storage to amortize its compute against storing uncompressed, and 120 years to break even against CPU compressors (abstract, Fig. 1). That is the same analyze → score → compress decision with encode cost in dollars as a new axis — and the opposite end from the encodings this topic scans over directly: nothing it produces can be evaluated without decoding first.

The scan pipeline these encodings plug into

flowchart LR
    Q["scan: WHERE ts BETWEEN a AND b,<br/>SUM(x)"] --> ZM{"zone map:<br/>segment min/max<br/>overlaps the range?"}
    ZM -- "no" --> SKIP["skip: no read, no decode<br/>(section 3)"]
    ZM -- "yes" --> RD["read the segment's<br/>COMPRESSED bytes<br/>(the only I/O)"]
    RD --> ENC{"segment encoding"}
    ENC -- "CONSTANT / RLE" --> RUN["operate on runs:<br/>value x run_length<br/>(no decode)"]
    ENC -- "DICT / FSST" --> CODE["compare on codes,<br/>decode survivors only<br/>(section 5)"]
    ENC -- "FOR / bit-packed" --> UNP["unpack + add base<br/>into a vector of ~2048"]
    RUN --> AGG["aggregate<br/>over the vector"]
    CODE --> AGG
    UNP --> AGG
    AGG --> OUT["result"]

Everything left of AGG is the lightweight-encoding zoo’s job; everything right of it is the vectorized engine of topic 11. The bytes that cross the memory bus are the compressed ones, which is why a scan can beat the raw sum floor above.

3. Zone maps (min/max pruning)

Per-segment min/max stats let the scan SKIP segments that can’t match:

 WHERE ts BETWEEN '2026-01-01' AND '2026-01-02'
 seg 0 [ts: 2025-11-01 .. 2025-12-04]  -> skip (no read, no decode)
 seg 1 [ts: 2025-12-04 .. 2026-01-05]  -> scan
 seg 2 [ts: 2026-01-05 .. 2026-02-11]  -> skip

Effective ONLY if data is clustered on the filter column — zone maps on random data prune nothing (every zone spans the whole domain). That’s why ClickHouse makes you declare ORDER BY at table creation. DuckDB: ColumnData::CheckZonemap (column_data.cpp:482), stats per segment. Parquet: min/max per column chunk + page. Sorted input is also the comparison sort’s cheapest case (10M sorted u64 rows in 2.9 ms against 150 ms random) and a radix sort’s worst: topic 57.

4. The formats: Arrow (memory) vs Parquet (disk)

  • Arrow: columnar IN MEMORY, designed for zero-copy compute: ArrayData (arrow-data/src/data.rs:208) = type + buffers (values, validity bitmap, offsets). No encoding beyond dictionary — layout IS the contract, kernels (topic 11’s polars-compute) run on it directly.
  • Parquet: columnar ON DISK: file → row groups → column chunks → pages, each page encoded (PLAIN / RLE_DICTIONARY / DELTA_BINARY_PACKED / BYTE_STREAM_SPLIT, parquet/src/basic.rs:397+) then optionally block-compressed (snappy/zstd). Min/max stats per chunk and page (metadata/mod.rs:630, :808).
  • The boundary: Parquet optimizes bytes-at-rest + selective reads; Arrow optimizes compute. Decode once at the boundary — unless the engine can execute ON the encoding (DuckDB scans over compressed segments; late materialization below).

Parquet is a decade-old layout whose newer encodings are optional, so a writer cannot assume a reader supports them. F3 (Zeng, Meng, Prammer, McKinney, Patel, Pavlo, Zhang, F3: The Open-Source Data File Format for the Future, Proc. ACM Manag. Data 3(4) (SIGMOD), Article 245, 2025, doi · code) keeps the columnar shape but decouples the physical I/O unit from the logical row group (§5.1), lets a column’s dictionary scope differ from the row group — many small dictionaries for one column, one large one for another (§5.2) — stores metadata in FlatBuffers that can be read per column without deserializing the rest, and embeds WebAssembly decoders in each file so a reader without a native decoder can still decode (§6.2); the built-in encodings come from the Rust BtrBlocks and FastLanes implementations (§7.3). In a wide-table projection test, “even with thousands of columns, the metadata parsing overhead is still around 10ms in F3, an order of magnitude faster than Parquet” (§7.2, Fig. 9), and the Wasm binaries for two custom encodings add about 150 KB (§7.7); compression ratio is slightly worse than Parquet because F3 applies no block compression (§7.3). Vortex is one of the baselines, at v0.21.1, with a footnote that its encodings and layout have changed since (§7.1) — so read that comparison as a snapshot of Vortex v0.21.1. The point for this topic: §1’s cascaded lightweight encodings (reading-btrblocks-fsst.md) are now the building block of a file format, not an engine-internal detail.

The mirror-image question is whether a new format is needed at all for a new processor. Luo, Chen, Binnig, Do GPUs Really Need New Tabular File Formats? (DaMoN ’26, arXiv:2602.17335, doi) argues no: the Parquet that DuckDB writes by default — one page per column chunk, 122,880-row row groups, V1 encodings only (§3 “Baseline”) — starves a GPU reader, and four configuration changes fix it without leaving the format. Pages per column chunk raised to 100 or more, because cuDF maps pages to its kernel grid (Insight 1); row groups of millions of rows, because MiB-scale reads are what GPUDirect Storage needs to saturate an SSD (Insight 2, row-group size 10M in the experiments); a per-chunk choice of whichever Parquet V1 or V2 encoding gives the smallest chunk — the BtrBlocks idea inside plain Parquet (Insight 3); and compression applied only where it shrinks a chunk by more than 10% (Insight 4). On TPC-H SF300 lineitem, one A100, four NVMe SSDs, the effective read bandwidth goes 1 → 3 → 45 → 117 → 125 GiB/s as the four changes are applied one after another (Fig. 1; the abstract says GB/s, the figure’s axis is GiB/s). Read 125 as an effective rate: the paper defines it as the logical raw size after decoding and decompression divided by the scan time (§3, “Encoding Flexibility”), not as bytes crossing a bus. The hardware check is on the same figures: one SSD saturates at 6.4 GiB/s (Fig. 2), so four move at most 4 × 6.4 = 25.6 GiB/s of file bytes; at the compression ratio of 5.3 that Fig. 3 annotates for the encoding-flexible files, 25.6 × 5.3 = 135.7 GiB/s of logical data is the ceiling, and the reported 125 sits just under it; and the one-SSD point checks too, 6.4 × 5.3 = 33.9 against the reported 33 (Fig. 3). So the bandwidth the paper reports is a compression ratio multiplied by a saturated storage bus — the thesis of this topic (“compression IS performance”) measured on a GPU — and not evidence that a GPU kernel decodes at 125 GiB/s. The paper is explicit that in-GPU-memory decoders reach “up to 5700 GB/s” (§5), so on that axis the format is not the bottleneck; the file’s compressed size is.

5. Late materialization

Keep data encoded/columnar as deep into the plan as possible:

  • filter on dictionary column → compare dictionary CODES (int ==), only decode survivors;
  • DuckDB’s DICTIONARY/FSST vector types (topic 11) carry compressed data THROUGH operators;
  • join produces row ids; fetch payload columns only for matches (C-Store’s original pitch).

6. Architectures compared

ClickHouse MergeTreeDuckDBPinot/Druid
shapeLSM-flavored: sorted PARTS merged in background (topic 4!)single file, row groups of 122880ingest-time indexing, segments
primary indexSPARSE: one key per 8192-row granule, binary-search markszone maps onlyper-segment inverted/star-tree
orderingORDER BY key, physical sortinsertion order (+ optional sort)time-partitioned
nichefastest brute-force scansembedded analyticsreal-time slice-and-dice

MergeTree = topic 4’s LSM ideas at analytics scale: immutable sorted parts, background merges, but the “memtable” is a whole part and the index is sparse because scans, not point reads, are the workload.

Experiments (experiments/)

  1. encodings.rs — YOU implement RLE, dictionary, and bit-packing encode/decode for Vec<u64>; tests fix round-trips and exact compressed sizes.
  2. scan_bench — PROVIDED: sum() over raw vs encoded columns for three data shapes (sorted-ish / low-NDV / random). The headline: does decode-while-scanning beat raw’s bandwidth? Includes a sum-WITHOUT-decoding path for RLE (value × run_length) — operate on the encoding.
  3. duckdb-clickbench.md — run 5 ClickBench queries on DuckDB, EXPLAIN ANALYZE, note which compression each hot column chose (PRAGMA storage_info).

Reading guides

guidechapter
reading-duckdb-compression.mdDuckDB’s encoding zoo: analyze, score, commit
reading-clickhouse-mergetree.mdMergeTree: brute force, organized
reading-arrow-parquet.mdArrow & Parquet: the layout compute wants, the bytes disk wants
reading-cstore-compression.mdC-Store: operate on compressed data
reading-btrblocks-fsst.mdFSST & BtrBlocks: compress harder, stay random-access
reading-clickhouse-paper.mdClickHouse: the case for brute force

Further references: “Dremel” (VLDB 2010) — the repetition/definition- level encoding for NESTED data that Parquet adopted wholesale (§4’s format has a whole second half we skip because graphs are flat); “Lakehouse” (CIDR 2021) + “Delta Lake” (VLDB 2020) — what happens when the Parquet files themselves become the database (ACID via a transaction log of file lists — topic 28’s manifest idea).

Capstone M12

Columnar attribute storage + zone-map pruning for property filters:

  • properties stored as columns per label (node id → value), not per-node maps — the schema question: sparse columns for optional properties (validity bitmap, Arrow-style)
  • encodings: dictionary for strings, FOR/bitpack for ints — reuse encodings.rs
  • zone maps per column segment; WHERE n.age > 65 prunes segments before decode
  • the FalkorDB angle: matrices index STRUCTURE (topology), columns store PAYLOAD (properties) — the split mirrors Parquet-stats/Arrow-compute; measure a property-filter query before/after zone maps