Someone asks “what was the average order value per region, for the electronics category, over the last quarter” against a table with 50 columns and 20 billion rows, and expects an answer in under two seconds. That one sentence kills a normal database. A row-store like Postgres or MySQL stores each row contiguously - all 50 columns of order 1, then all 50 columns of order 2 - so to sum one column it reads every row in full, dragging 50 columns off disk to use 3. Add an index and you have just moved the pain: an index on region still points at full rows, and the query touches so many rows that the planner ignores the index and full-scans anyway. The whole table is tens of terabytes, the scan is single-threaded, and the answer arrives in four minutes if it arrives at all. OLTP engines are built to fetch and mutate a handful of rows by key with transactional guarantees; this workload fetches billions of rows, three columns wide, aggregates them, and never updates anything. Wrong tool, wrong data layout, wrong execution model.

This post is about the analytical database - the OLAP engine, the thing BigQuery, Redshift, Snowflake, ClickHouse, and DuckDB all are underneath. I am not designing the dashboards on top, the ETL that loads it, or a transactional system that also does a bit of reporting. I am designing the engine that has to store wide tables cheaply, scan a few columns out of many at tens of gigabytes per second, prune away the data a query does not need before reading a byte of it, and parallelize one SQL statement across a fleet of machines. The design comes down to four decisions: how you lay bytes on disk so a query reads only the columns it projects (column-oriented segments), how you make those bytes tiny so the scan is I/O-bound on little data (run-length and dictionary encoding), how you skip entire chunks a query cannot match without decoding them (zone maps and partition pruning), and how you turn one SQL string into thousands of vectorized operators running in parallel across worker nodes (the distributed planner and execution engine). Everything else is detail.

Let me build it properly.

Functional Requirements (FR)

In scope:

  • Load data in bulk. Ingest large batches - a daily load of billions of rows, a streaming micro-batch every few minutes, a COPY from object storage. The write pattern is append and bulk-insert, not single-row OLTP writes. Loaded data becomes immutable columnar segments.
  • Run analytical SQL. Support SELECT with projections, WHERE filters, GROUP BY aggregations (sum, count, avg, min, max, count(distinct), percentiles), ORDER BY, LIMIT, and JOINs between a large fact table and smaller dimension tables. These are the queries that scan millions-to-billions of rows and return small aggregated results.
  • Scan only projected columns. A query touching 3 of 50 columns must read only those 3 columns off storage. This is the entire reason the system exists.
  • Prune irrelevant data before reading it. Skip partitions, files, and column chunks that cannot contain rows matching the filter, using metadata (min/max zone maps, partition values) without decoding the data.
  • Execute in parallel. One SQL statement must fan out across many worker nodes and many CPU cores, each scanning a slice of the data, with partial aggregates merged into the final result.
  • Compress aggressively. Store columns encoded (run-length, dictionary, delta, bit-packing) so the on-disk footprint and the bytes scanned are a fraction of raw.

Explicitly out of scope (own the boundary):

  • OLTP: single-row reads/updates by primary key, transactions with row-level locking. This is not a key-value store or a system of record you update in place. We bulk-load immutable segments; we do not UPDATE WHERE id = 5 on the hot path. Point lookups are allowed but not optimized for.
  • Strict serializable multi-statement ACID transactions across concurrent writers. Analytical warehouses use snapshot isolation over immutable segments - a query sees a consistent snapshot, loads are atomic commits of new segments - not two-phase-locking OLTP transactions.
  • Sub-millisecond latency. Analytical queries target seconds, not milliseconds. We optimize throughput (bytes scanned per second, rows aggregated per second), not per-query tail latency on a single row.
  • The BI tool, the ETL/orchestration, and the semantic layer. Dashboards, scheduling, and metric definitions are clients of the SQL API. We expose SQL; we do not build Looker.
  • The storage of the raw files themselves. We assume durable object storage (S3/GCS) or a distributed filesystem exists. We design the format we write into it and the engine that reads it.

The single decision that drives everything: an OLAP database is a read-heavy, scan-wide-tables-narrow, aggregate-billions-of-rows engine over immutable bulk-loaded data, so it must be built as a column-oriented, heavily-encoded, prune-before-you-read store with a distributed vectorized query engine - not as a row store with indexes. Every other choice follows from that.

Non-Functional Requirements (NFR)

  • Scale: a fact table on the order of 50 billion rows, ~50 columns, growing by ~500M rows/day (bulk loads). Total raw logical size ~10-20 TB/table uncompressed, a few TB compressed. Concurrency on the order of hundreds of concurrent analytical queries, each potentially scanning billions of rows.
  • Latency: interactive dashboard queries (filtered, well-pruned, hitting rollups or recent partitions) target p95 under ~2s. Heavy ad-hoc full-table aggregations target tens of seconds, not minutes. There is no millisecond requirement; there is a “it must not take four minutes” requirement.
  • Throughput: the scan engine must move data at tens of GB/sec aggregate across the cluster (many nodes, many cores), because the fundamental limit on an aggregation is bytes scanned per second. Loads must sustain the daily volume without blocking reads.
  • Availability: the read path targets 99.9%+. Because storage is immutable segments on durable object storage, compute is stateless and restartable - a crashed worker’s slice is just rescheduled. The system degrades (a slow query, a retried task) rather than losing data.
  • Consistency: snapshot isolation. A query runs against a consistent snapshot of committed segments; a load is an atomic metadata commit that makes a new set of segments visible. Readers never see a half-loaded batch. No cross-row transactional updates.
  • Durability: committed data lives on replicated durable object storage (11-nines class). Segments are immutable, so durability is “the object exists”; compute holds nothing that cannot be recomputed by re-reading storage.
  • Cost is a first-class NFR. Scanning tens of TB per query is a cost problem before a latency problem. Compression ratio, column pruning, and partition pruning are not optimizations - they decide whether a query costs a cent or a dollar, and whether the cluster is affordable at all. The whole design is organized around touching the fewest bytes.

Back-of-the-Envelope Estimation (BoE)

Grounding the design in numbers before drawing boxes.

Data size - the whole ballgame:

Fact table:          50,000,000,000 rows (50B)
Columns:             50
Avg bytes/value:     ~8 bytes uncompressed
Row size:            50 * 8 = 400 bytes
Uncompressed table:  50B * 400 B = 20 TB
Compressed (~8x via encoding): ~2.5 TB on object storage

The column-pruning win (why columnar at all):

Query: SELECT region, avg(order_value)
       FROM orders WHERE category='electronics' AND ts > now()-90d
       GROUP BY region

Columns actually touched: region, order_value, category, ts = 4 of 50.

Row store reads:      full rows = 20 TB (all 50 columns) to use 4.
Column store reads:   4/50 of the data = ~1.6 TB uncompressed,
                      ~200 GB compressed on disk.
-> ~12x less data read from projection alone, before any pruning.

The pruning win (zone maps + partitioning):

Table partitioned by day (ts). Query filters ts > now()-90d.
   Total partitions:  ~3 years = ~1,095 daily partitions.
   Partitions kept:   90.
   -> 90/1095 ≈ 8% of partitions scanned. ~12x fewer rows from
      partition pruning alone.

Within kept partitions, category='electronics' zone-map prune:
   Segments whose [min,max] for category excludes 'electronics' skip.
   Say electronics is ~20% of rows, clustered -> ~5x further cut.

Stacked: 1/12 (columns) * 1/12 (partition) * 1/5 (zone map)
   = roughly 1/700 of the raw 20 TB actually decoded ≈ ~30 GB.
   That is the difference between a 2-second query and a 4-minute one.

Scan throughput and parallelism:

Bytes to scan (compressed, after pruning):   ~30 GB
Target latency:                              ~2 s
Required scan rate:                          ~15 GB/s
Per-core vectorized decode+scan:             ~1-2 GB/s
   -> need ~10-15 cores busy. Across a 16-core worker that is 1 node;
      across the fleet, trivially parallel. Full-table unpruned query
      (2.5 TB compressed) needs ~1,250 core-seconds -> ~80 cores for ~16s.

Load traffic:

Daily load:          500M rows * 400 B = 200 GB/day uncompressed
                     ≈ 25 GB/day compressed written as new segments.
Micro-batch:         every ~5 min -> ~1.7M rows/batch, written as a
                     new immutable segment, committed atomically.

Memory / cache:

Dictionary + zone-map metadata per segment: tiny (KBs/segment).
   50B rows / 1M rows-per-segment = 50,000 segments.
   Metadata (min/max per column + dict ptr) ~2 KB/segment
   -> ~100 MB of pruning metadata, cacheable in RAM on the coordinator.
Hot recent partitions cached on worker local SSD -> avoid object-store
   round trips for dashboard queries over recent data.

Two conclusions drive the design. First, the only thing that matters is bytes decoded, and three independent filters - column projection (~12x), partition pruning (~12x), zone-map pruning (~5x) - multiply to turn 20 TB into tens of GB, which is the entire reason an analytical query is fast. Second, once pruned, the work is embarrassingly parallel - independent segments, partial aggregates merged at the end - so the engine is a distributed, vectorized scan-and-aggregate machine, and the planner’s job is to prune hard then fan out wide.

High-Level Design (HLD)

The database separates storage (immutable columnar segments on object storage, described by a metadata catalog) from compute (a stateless coordinator that plans queries and a fleet of stateless workers that scan and aggregate). A query is parsed, optimized, pruned against the catalog, split into parallel tasks, and executed as vectorized operators across workers.

            LOAD PATH (bulk / micro-batch, append-only, immutable segments)
  ┌────────────────────────────────────────────────────────────────────────────┐
  │  Loader  --read rows, sort, encode columns, build zone maps + dictionaries-->│
  │          writes immutable SEGMENT files to object storage, then atomically   │
  │          COMMITs their metadata into the Catalog (new snapshot version).     │
  └───────────────────────────────────────┬────────────────────────────────────┘
                                          │
                              ┌───────────▼────────────┐
                              │   Metadata Catalog      │  (strongly consistent)
                              │  tables, partitions,    │
                              │  segments, zone maps,   │
                              │  dict refs, snapshots   │
                              └───────────┬────────────┘
                                          │ (plan reads catalog for pruning)
   QUERY PATH                             │
  ┌───────────────────────────────────────▼───────────────────────────────────┐
  │                           COORDINATOR (stateless)                           │
  │  1. Parse SQL -> logical plan (projections, filters, joins, group-by)       │
  │  2. Optimize: predicate pushdown, projection pushdown, join reorder         │
  │  3. PRUNE: partitions + segments via catalog zone maps  -> segment list     │
  │  4. Build physical plan of vectorized operators; split into parallel tasks  │
  │  5. Schedule tasks across workers; manage exchange/shuffle between stages   │
  └───────┬───────────────────────────┬───────────────────────────┬────────────┘
          │ task (segments 1..k)       │ task (segments k..m)       │ ...
  ┌───────▼─────────┐         ┌────────▼────────┐          ┌────────▼────────┐
  │   WORKER 1      │         │   WORKER 2      │          │   WORKER N      │
  │  scan operator  │         │  scan operator  │          │  scan operator  │
  │   - fetch cols  │         │   - fetch cols  │          │   - fetch cols  │
  │   - zone-skip   │         │   - zone-skip   │          │   - zone-skip   │
  │   - decode (RLE/│         │   - decode      │          │   - decode      │
  │     dict) batch │         │     batch       │          │     batch       │
  │  filter (SIMD)  │         │  filter         │          │  filter         │
  │  partial agg    │         │  partial agg    │          │  partial agg    │
  └───────┬─────────┘         └────────┬────────┘          └────────┬────────┘
          │ partial groups             │ partial groups             │
          └───────────────┬───────────┴───────────────┬────────────┘
                          │  EXCHANGE / SHUFFLE (hash by group key)
                  ┌───────▼────────────────────────────────┐
                  │  Aggregation stage (merge partials)     │
                  │   final sum/count -> avg, order, limit  │
                  └───────┬────────────────────────────────┘
                          ▼  result to client
  ┌─────────────────────────────────────────────────────────────────────────────┐
  │  Object storage (segments) + local SSD cache of hot segments on workers      │
  └─────────────────────────────────────────────────────────────────────────────┘

Load path - a batch becoming queryable:

  1. The Loader reads a batch of rows, optionally sorts them by a chosen sort key (clustering column - typically the partition/time column and a frequently-filtered column), then transposes them into columns.
  2. For each column it chooses an encoding (run-length, dictionary, delta, bit-pack) based on the column’s data, builds the dictionary where used, and computes a zone map (min, max, null count, distinct estimate) per chunk. It writes an immutable segment file (columnar, chunked, encoded) to object storage.
  3. It atomically commits the new segments into the Metadata Catalog, producing a new snapshot version. Until the commit, readers see the old snapshot; after it, they see the new one. A load is all-or-nothing at the metadata level - no reader ever sees a half-loaded batch.

Query path - one SQL statement:

  1. The Coordinator parses SQL into a logical plan and optimizes it: predicate pushdown (move filters as close to the scan as possible), projection pushdown (read only referenced columns), join reordering (scan the small dimension table, build a hash table, probe with the big fact table).
  2. It prunes against the catalog: eliminate partitions whose partition value cannot match the filter, then eliminate segments whose zone map [min, max] for a filtered column cannot contain a matching value. What survives is a (usually tiny) list of segments to actually read.
  3. It builds a physical plan of vectorized operators and splits the surviving segments into parallel tasks, scheduling them across workers. A GROUP BY plan has two stages: a per-worker partial aggregation stage and a merge stage, connected by an exchange (shuffle) that hash-partitions partial groups by group key.
  4. Each Worker runs its scan: it fetches only the projected column chunks for its segments (ranged reads from object storage, or local SSD cache), skips chunks its zone map rules out, decodes in batches (vectors of thousands of values), applies the filter with SIMD over the batch, and feeds survivors into a partial aggregation hash table. It emits partial groups, not raw rows.
  5. The exchange shuffles partial groups by hash of the group key so each final-aggregation worker owns a disjoint set of groups; it merges partials (sum the sums, sum the counts, derive avg = sum/count), applies ORDER BY/LIMIT, and streams the (small) result to the client.

The architectural core: storage is immutable, column-oriented, heavily-encoded segments described by a metadata catalog, so a query reads only the columns it projects and prunes away partitions and segments via zone maps before decoding a byte; and compute is a stateless coordinator that plans and prunes plus a worker fleet that runs vectorized scan-and-aggregate operators in parallel, merging partial aggregates through a shuffle. The database is a distributed columnar scan machine, and every choice is downstream of “read the fewest bytes, then parallelize.”

Component Deep Dive

The four hard parts, each walked from the naive approach to where it breaks to the real design: (1) the columnar storage format, (2) encoding and compression, (3) pruning with zone maps and partitioning, and (4) the distributed query planner and vectorized execution engine.

1. Storage Layout: Row Store -> Column-Oriented Segments

The workload scans a few columns out of many across billions of rows. The physical layout of bytes on disk decides whether that is 20 TB of reading or 1.6 TB.

Approach A: Row-major storage, add indexes (the OLTP instinct)

Store each row contiguously (row 1: all 50 cols | row 2: all 50 cols | ...) and build B-tree indexes on filtered columns.

disk: [r1c1 r1c2 ... r1c50][r2c1 r2c2 ... r2c50][r3...] ...
index on category -> row pointers

Where it breaks:

  • Every scan reads every column. To sum(order_value) the engine must stride through rows, and because columns are interleaved, reading the order_value of each row drags its other 49 columns into cache and off disk too. You read 20 TB to use 2.5 TB of it - an 8x-12x waste on projection alone, and the disk, not the CPU, is the wall.
  • Indexes do not help a scan-heavy aggregation. An index on category points at full rows; a query matching 20% of rows (billions of them) does billions of random row fetches, which is slower than a sequential full scan, so the planner correctly ignores the index. Indexes win when you fetch few rows by key; analytical queries fetch most rows. Worse, indexes bloat storage and slow loads.
  • Poor compression. A row mixes a timestamp, a float, a short string, an enum - adjacent bytes have no shared structure, so a general compressor finds little. Columnar’s compressibility is lost because like values are not adjacent.

Row-major is optimal for “fetch and update one whole row by key.” It is pessimal for “scan one column across all rows.” Wrong layout.

Approach B: Column-oriented segments (the OLAP layout)

Store each column’s values contiguously, in immutable, self-describing segments (also called row groups or stripes - Parquet, ORC, ClickHouse parts, Redshift blocks all do this).

  • Transpose to columns. All values of column 1, then all of column 2, and so on. A query reads only the byte ranges of the columns it projects. Reading order_value touches the order_value run and nothing else. This is the ~12x projection win from the BoE, and it is the whole point.
  • Chunk into segments of ~1M rows. A table is a set of immutable segments, each holding a horizontal slice of rows but internally column-major. Segments are the unit of parallelism (one task per segment group), the unit of pruning (one zone map per segment per column), and the unit of load commit (write new segments, never mutate old ones). ~1M rows per segment balances pruning granularity against per-segment metadata overhead.
Segment (immutable, ~1M rows):
  ┌─────────────────────────────────────────────────────────────┐
  │ header: row count, schema, encoding per column               │
  ├─────────────────────────────────────────────────────────────┤
  │ column: ts        [chunk][chunk]...  zone map {min,max,nulls} │
  │ column: region    [dict + RLE codes] zone map {min,max}       │
  │ column: category  [dict + RLE codes] zone map {min,max}       │
  │ column: order_val [bit-packed floats]zone map {min,max,sum?}  │
  │ ...                                                           │
  ├─────────────────────────────────────────────────────────────┤
  │ footer: per-column chunk offsets + zone-map index            │
  └─────────────────────────────────────────────────────────────┘
  • Columns stored in independently-decodable chunks (say ~64K values each) with an offset index in the footer, so a query that further prunes by zone map can read and decode just the chunks it needs, not the whole column. Ranged GETs from object storage fetch exactly those byte ranges.
  • Immutability is the gift. A segment never changes, so there are no in-place updates, no locking on read, trivial caching (a cached segment is never stale), and loads are pure appends. “Updates” and “deletes” are handled by writing new segments plus a small delete/tombstone set (delete vectors marking row positions as removed), merged away during background compaction - we do not mutate a segment in place.

A column store reads only what it projects and stores like-with-like so it compresses hard. Every serious analytical system (Parquet/ORC on the lake, Redshift, Snowflake micro-partitions, ClickHouse MergeTree, BigQuery Capacitor, Vertica) is this: immutable, column-oriented, chunked, self-describing segments.

2. Encoding and Compression: Making Columns Tiny

After column projection, the next lever on bytes-scanned is encoding. Columnar data compresses far better than row data because a column holds values of one type with massive local redundancy - and the right trick is lightweight, type-aware encoding that you can scan without fully decompressing, not a heavyweight general compressor.

Approach A: Store raw values, gzip the whole segment (naive)

Keep each column as raw fixed-width values and run gzip/zstd over the segment file.

Where it breaks: a general compressor treats the column as an opaque byte stream. It gets some ratio (maybe 3-4x) but it is block-oriented - to read any value you must decompress the whole block, burning CPU to inflate megabytes when the query wanted a 64K-value chunk, and you cannot evaluate a filter without first fully decompressing. You also leave huge ratios on the floor because gzip does not know region has 12 distinct values repeated billions of times (dictionary + RLE would crush it) or that ts is a monotonically increasing sequence (delta would). Heavyweight general compression fights the scan engine instead of helping it.

Approach B: Lightweight, type-aware, scan-friendly encodings

Pick a per-column encoding from the column’s actual data, chosen to be cheap to decode in a vectorized loop and, ideally, filterable without decoding.

  • Dictionary encoding for low-cardinality columns. Columns like region, category, status, country have few distinct values repeated endlessly. Build a per-segment dictionary mapping each distinct value to a small integer code, then store the column as a stream of codes. region with 12 values becomes a 4-bit code per row instead of a variable-length string - a 10-20x shrink - and, crucially, the filter category='electronics' becomes “find electronics’ code once, then compare small integers,” which is fast and SIMD-friendly. Strings only materialize at the very end.
category raw:     "electronics","electronics","books","electronics","toys"
dictionary:       {electronics:0, books:1, toys:2, ...}
codes:            0,0,1,0,2            (tiny ints, bit-packable)
filter cat=0 runs as integer compare over the code vector (SIMD).
  • Run-length encoding (RLE) for sorted/clustered columns. If a column is sorted or clustered (because we sorted the segment by it on load), identical values appear in long runs. Store (value, run_length) pairs instead of repeating the value. A date column in a day-partitioned, time-sorted segment might be a single run. RLE over dictionary codes is the killer combo: electronics repeated 400,000 times is one (0, 400000) pair. Aggregations can even operate on runs directly (sum += value * run_length) without expanding them.
dict codes (sorted): 0,0,0,0,0,0,1,1,1,2,2,2,2,2
RLE:                  (0,6)(1,3)(2,5)      -> 3 pairs for 14 rows
count(*) where code=0 = 6, read directly from the run. No expansion.
  • Delta + bit-packing for sequential numerics. Monotonic or slowly-changing numeric columns (id, ts, running counters) store the delta between consecutive values, then bit-pack the deltas into the minimum bits needed. A timestamp column at 1s cadence stores ~small constant deltas in a handful of bits each. Frame-of-reference (store values as offsets from the chunk’s min) + bit-packing does the same for bounded-range integers.
  • Encoding is chosen per column per segment, and recorded in the header, so the loader can pick dictionary+RLE for category, delta for ts, bit-packing for quantity, and raw+light-compress for a high-cardinality order_value. The scan engine dispatches the right vectorized decoder per chunk.
  • Scan without full decode where possible. Dictionary filters compare codes; RLE aggregations consume runs; zone maps (next section) skip chunks entirely. The encodings are designed so the filter and aggregate run over the encoded form, materializing raw values only for the rows that survive to the output - which is why a well-encoded column store scans tens of GB/s per node.

The mindset: do not compress bytes, encode the structure. Low cardinality wants a dictionary; clustering wants RLE; sequences want delta - each a cheap, vectorizable, often filter-in-place encoding, stacked (dictionary then RLE then bit-pack) to reach 8-15x while keeping the scan fast. That stacked, scan-friendly encoding is the difference between a columnar engine and “a row store with gzip.”

3. Pruning: Skip Data Without Reading It

Encoding shrinks what you read; pruning removes the need to read it at all. The fastest scan is the one that never happens. Three levels - partition, segment zone map, chunk zone map - let the planner discard the overwhelming majority of data using only tiny metadata.

Approach A: Scan every segment, filter during the scan (naive)

Read all segments of the table, decode, apply the WHERE predicate on the decoded values, discard non-matches.

Where it breaks: correctness is fine, cost is catastrophic. A query filtering ts > now()-90d AND category='electronics' on a 3-year, 50B-row table decodes all 50B rows to keep maybe 0.1% of them - you pay the full scan to throw away 99.9% of the work. At tens of TB that is minutes and dollars per query. You must eliminate data using metadata, before decoding, or the system does not meet its latency or cost NFRs.

Approach B: Partitioning + zone maps (min/max pruning)

Carry just enough metadata per partition and per segment that the planner can prove “no matching row can be here” and skip it entirely.

  • Partitioning by a high-value column (usually time). Physically organize the table into partitions by date(ts) (and optionally a secondary key like region). The partition value lives in the catalog, so a filter on ts eliminates whole partitions by metadata: a 90-day filter over 3 years of daily partitions reads 90 of 1,095 partitions - the ~12x partition-pruning win. Partitioning is the coarsest, cheapest prune; it is a directory-level decision, not a data read.
  • Zone maps per segment per column. For every segment, store the min and max (and null count) of each column - a few bytes. The planner evaluates the predicate against the zone map: if category’s [min,max] for a segment does not include 'electronics', or order_value’s max is below the filter’s > 1000, that segment cannot contain a match and is skipped without a single byte of column data read. This is min/max pruning, and it is why clustering matters: if the data is sorted/clustered by the filtered column, each segment’s [min,max] is a narrow, non-overlapping range, so a filter hits only a few segments. On an unclustered column, every segment’s range is [global_min, global_max] and the zone map prunes nothing - so the loader’s choice of sort/clustering key is a first-class performance decision.
Segment zone maps for column `category` (dictionary codes):
  seg 1: min=books(1)       max=books(1)        -> skip (no electronics=0)
  seg 2: min=electronics(0) max=electronics(0)  -> KEEP
  seg 3: min=electronics(0) max=toys(5)         -> KEEP (might match)
  seg 4: min=sports(4)      max=toys(5)         -> skip

Filter category='electronics' reads 2 of 4 segments. Clustering by
category would make these ranges tight and non-overlapping -> maximal skip.
  • Chunk-level zone maps for a finer cut. Within a kept segment, each ~64K-value chunk carries its own min/max, so even inside a surviving segment the engine decodes only the chunks whose range overlaps the predicate. Pruning is hierarchical: partition -> segment -> chunk, each a cheaper-than-reading metadata check.
  • Richer skip indexes where min/max is weak. Min/max prunes range and clustered-equality predicates well; it is weak for a needle in an unsorted haystack (WHERE user_id = X on an unclustered column). There, add a lightweight bloom filter per segment on that column: the planner asks “could user_id=X be here?” and skips segments that answer no. Bloom filters handle high-cardinality equality that min/max cannot, at the cost of a little metadata.
  • Metadata is small and cacheable. 50,000 segments * ~2 KB of zone-map/dict/bloom metadata ≈ ~100 MB, held in RAM on the coordinator. Pruning a query is a scan over this metadata, not over data - microseconds to eliminate terabytes.

The trade is explicit: you spend a little metadata and a loader-time sort to let the planner prove, cheaply, which data cannot match and skip it - turning a full-table scan into a scan of the few percent that might contain an answer. Column projection, partition pruning, and zone-map pruning stack multiplicatively (the ~1/700 from the BoE), and that stack is the entire reason an analytical query returns in seconds. The leverage is the clustering key: pick it to match your dominant filters, and the zone maps do the rest.

4. The Distributed Planner and Vectorized Execution Engine

A pruned list of segments still holds tens of GB and billions of rows. Turning one SQL string into a plan that decodes, filters, joins, and aggregates that in parallel across a fleet - fast - is the engine’s core.

Approach A: Parse SQL, pull rows one at a time through a tree of operators on one node (naive)

Classic Volcano model: a tree of operators (scan -> filter -> aggregate), each exposing next() that returns one row, run on a single node.

Where it breaks:

  • Row-at-a-time is death by function-call. next() per row means billions of virtual function calls, branch mispredictions, and cache misses; the CPU spends its time on interpretation overhead, not on the actual sum. On a billion-row aggregate this is 10-50x slower than it needs to be, and it defeats SIMD entirely because you process one value at a time.
  • Single-node cannot hold the throughput. Even perfectly coded, one machine scans a handful of GB/s; tens of GB/s needs tens of machines. One node is also a single point of failure and a hard concurrency ceiling.
  • No pushdown or parallel aggregation. Aggregating billions of rows on one node means all the data funnels to one hash table on one box - memory and CPU bound, with the network dragging raw rows to it.

Approach B: A cost-based planner producing a vectorized, parallel, multi-stage physical plan

Two shifts: vectorized execution (process batches, not rows) and distributed parallelism (many workers, partial aggregates, a shuffle).

  • Plan then optimize. The coordinator parses SQL to a logical plan and applies cost-based and rule-based optimizations against catalog statistics: predicate pushdown (evaluate filters at the scan, over encoded data), projection pushdown (read only referenced columns), pruning (section 3), and join reordering - for a star-schema query, scan the small dimension tables first, build in-memory hash tables, then stream the big fact table and probe (a broadcast hash join when the dimension fits in memory; a shuffle hash join when it does not).
  • Vectorized operators: batches of ~1,024-4,096 values. Every operator processes a column batch (a vector of values) at a time, not a row. The filter runs a tight SIMD loop producing a selection vector (the indices that passed); the aggregator updates hash-table slots for a whole batch; decode runs a per-encoding vectorized kernel. This amortizes function-call overhead across thousands of values, keeps data in L1/L2 cache, and lets the CPU vectorize - the 10-50x win over row-at-a-time, and why modern engines (DuckDB, ClickHouse, Velox, Photon, BigQuery) are vectorized (or compile the plan to native code, the related JIT approach).
Vectorized scan+filter+partial-agg on one worker, one segment:

  decode chunk -> [order_value vector: 4096 floats]
                  [category code vector: 4096 int8]
  filter(category==0) over the batch (SIMD) -> selection vector [idx...]
  gather order_value at selected idx
  partial hash-agg by region code:  ht[region] += sum, count
  -> emit partial groups, not rows
  • Two-stage (or multi-stage) distributed aggregation. The planner splits a GROUP BY into a partial aggregation stage on each worker (every worker builds a local hash table over its segments) and a final aggregation stage, connected by an exchange/shuffle that hash-partitions partial groups by group key so each final worker owns a disjoint key range. Partial aggregation collapses billions of rows to (number of groups) partial entries before the network, so the shuffle carries kilobytes of partial groups, not billions of rows. Final workers merge partials (sum the sums, sum the counts, avg = sum/count), then ORDER BY/LIMIT the small result. count(distinct) uses a sketch (HyperLogLog) that merges across workers the same way.
  • Stateless workers, segment-granular tasks, restartable. Work is split into tasks of (segments to scan); a worker holds no durable state (storage is on object store), so a crashed worker’s task is simply rescheduled on another - no data loss, just a retry. This is what makes compute elastic (add workers for more concurrency/throughput) and cheap (spot/preemptible instances are fine). It also decouples storage and compute: scale them independently, the Snowflake/BigQuery model.
  • Scheduling, backpressure, and spill. The coordinator schedules tasks respecting data locality (prefer a worker whose SSD cache holds the segment), limits per-query memory, and when a hash aggregation or join exceeds memory it spills to disk (partition the hash table, process partition by partition) rather than OOMing - essential for high-cardinality GROUP BY and large joins. Pipelines stream batches between stages with backpressure so a slow consumer does not blow up producer memory.

The core idea: prune hard, then run batch-at-a-time vectorized operators in parallel across stateless workers, collapsing data with partial aggregation before any shuffle. The planner’s optimizations (pushdown, pruning, join order) decide how little data enters the pipeline; vectorization decides how fast each core chews it; partial-aggregate-then-shuffle decides how little crosses the network; statelessness decides how elastically and cheaply it scales. Stack those and one SQL string becomes tens of GB/s of parallel scan-and-aggregate.

API Design & Data Schema

Query API (the read plane)

The public interface is SQL over a session, plus an async job API for heavy queries.

POST /v1/query
  {
    "sql": "SELECT region, avg(order_value) AS aov
            FROM orders
            WHERE category='electronics' AND ts >= '2026-08-01'
            GROUP BY region ORDER BY aov DESC LIMIT 20",
    "snapshot": "latest",        # or a pinned snapshot id for reproducibility
    "max_bytes_scanned": 50000000000   # cost guardrail (reject if plan exceeds)
  }
  200 OK
  {
    "job_id": "q_8f3a...",
    "schema": [ {"name":"region","type":"string"},
                {"name":"aov","type":"double"} ],
    "rows": [ ["blr", 8421.5], ["del", 7990.2], ... ],
    "stats": { "bytes_scanned": 31200000000, "segments_pruned": 48210,
               "segments_read": 190, "ms": 1840 }
  }
  400 -> parse/type error.  402 -> would exceed max_bytes_scanned (cost guard).

# Async for heavy queries
POST /v1/jobs      { "sql": "..." }            -> { "job_id": "..." }
GET  /v1/jobs/{id}                             -> status + result page cursor
GET  /v1/jobs/{id}/results?page_token=...      -> paged result rows

Load / ingest API (the write plane)

POST /v1/load
  { "table":"orders",
    "format":"parquet",
    "files":[ "s3://bucket/incoming/2026-11-24/part-*.parquet" ],
    "mode":"append" }                 # append | overwrite-partition
  202 Accepted -> { "load_id":"l_..." }   # loader encodes + commits atomically

POST /v1/stream                            # micro-batch ingest
  { "table":"orders", "rows":[ {...}, {...} ] }   # buffered -> segment -> commit

# DDL / layout
POST /v1/tables
  { "name":"orders",
    "columns":[ {"name":"ts","type":"timestamp"}, {"name":"region","type":"string"},
                {"name":"category","type":"string"}, {"name":"order_value","type":"double"}, ... ],
    "partition_by":["date(ts)"],           # partitioning scheme
    "cluster_by":["category","region"] }   # sort/clustering key -> zone-map quality

Data model: a catalog, immutable segments, dictionaries, and zone maps

The engine is not one relational table - it is a metadata catalog pointing at immutable encoded segment files.

Metadata Catalog (strongly consistent, transactional - the control plane):

tables(table_id, name, schema_json, partition_spec, cluster_spec, current_snapshot_id)
partitions(partition_id, table_id, partition_values, segment_count)
segments(segment_id, partition_id, object_path, row_count, byte_size,
         min_row_pos, created_snapshot_id, deleted_snapshot_id NULL)   # MVCC
column_meta(segment_id, column_name, encoding, dict_path NULL,
            zmin, zmax, null_count, bloom_path NULL, chunk_offset_index)
snapshots(snapshot_id, table_id, created_at, segment_set_ref, parent_snapshot_id)

Keys/indexes:
  PK segments(segment_id); index segments(partition_id);
  index column_meta(segment_id, column_name)  -> fast zone-map lookup for pruning.
Why SQL/transactional here: the catalog is small (~100s MB), and load commits
  + snapshot isolation need ATOMIC multi-row commits. A replicated SQL/Raft
  store (or an ACID table-format log like Iceberg/Delta) fits exactly.

Segment file (immutable, columnar, encoded - the bulk data, on object storage):

segment {
  header: row_count, schema, per-column encoding descriptor
  columns: [
     ts:          delta + bit-packed       | zone map {min,max,nulls}
     region:      dict codes + RLE         | zone map {min,max} + dict ref
     category:    dict codes + RLE         | zone map {min,max} + bloom
     order_value: frame-of-ref bit-pack    | zone map {min,max}
     ...
  ]
  footer: per-column chunk offset index + per-chunk zone maps
}
Why custom columnar, not SQL rows: append-only, immutable, column-major,
  8-15x encoded, scanned not point-fetched. A B-tree row store reads 12x
  too many bytes and cannot sustain scan-aggregate at this scale. This is
  the Parquet/ORC/Capacitor layout.

Delete vectors (for the rare update/delete):

delete_vector(segment_id, deleted_row_positions bitmap, snapshot_id)
  - "deleting" a row marks its position; the scan skips marked positions.
  - never mutates the immutable segment; compaction later rewrites segments
    dropping deleted rows and merging small segments.

The split is deliberate: a strongly-consistent catalog for schema, snapshots, pruning metadata, and atomic load commits; immutable encoded segments on cheap durable object storage for the bulk data; dictionaries and zone maps as small sidecar metadata that powers decoding and pruning; delete vectors to express mutation without mutating. Only the catalog needs transactions, and it is tiny; the petabytes of data are immutable and eventually-compacted. It is a purpose-built OLAP engine, not a relational OLTP database, because the workload - bulk-append, immutable, column-major, encoded, scan-and-aggregate, snapshot-isolated - is nothing like transactional point reads and updates.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each.

1. Bytes scanned per query (the fundamental cost). A full-table aggregation reads tens of TB; naively that is minutes and dollars. Fix: the stacked filter - column projection (read only referenced columns, ~12x), partition pruning (eliminate partitions by filter, ~12x), zone-map + bloom pruning (skip segments/chunks that cannot match, ~5x), and encoding (8-15x fewer bytes per value). Stacked, these turn 20 TB into tens of GB. Nothing else matters as much; the planner’s job is to make each query touch the least data.

2. Single-node scan throughput. One machine scans only a few GB/s; tens of GB/s is impossible on one box. Fix: stateless worker fleet, segment-granular parallel tasks, vectorized (batch-at-a-time) execution per core. Throughput scales with cores; add workers to scan faster. Vectorization gives 10-50x per core over row-at-a-time.

3. Aggregation / shuffle hot spots. Funneling billions of rows to one aggregator saturates it; a skewed GROUP BY key sends most rows to one final worker. Fix: two-stage aggregation - partial aggregate on each worker collapses rows to groups before the network, so the shuffle is tiny; hash-partition groups across final workers. For skew, detect hot keys and salt them (split a hot group across workers, merge at the end), or pre-aggregate the heavy hitters separately. count(distinct) uses HLL sketches that merge cheaply.

4. Poor clustering -> useless zone maps. If data is not sorted by the filtered column, every segment’s [min,max] spans the whole range and zone maps prune nothing - the query degrades to a full scan. Fix: choose the cluster/sort key to match dominant filters at load time; run background compaction that re-sorts and merges small segments into large, well-clustered ones. Add bloom filters for high-cardinality equality filters that min/max cannot prune. Clustering is the single biggest lever on pruning effectiveness.

5. Small-file / small-segment explosion. Frequent micro-batch loads create millions of tiny segments; per-segment metadata and per-file object-store round trips dominate, and pruning granularity gets too fine to help. Fix: a compaction/merge background job that rewrites many small segments into fewer ~1M-row segments (the LSM-style merge idea), applies delete vectors, and re-clusters. Keeps file count bounded and scan efficiency high. Streaming ingest writes small segments for freshness; compaction trades them for scan speed.

6. Object-storage latency and request cost. Each query issues many ranged GETs to object storage, which has ~tens-of-ms latency and per-request cost; a wide fan-out multiplies it. Fix: coalesce reads (one ranged GET per column chunk, prefetch footers), a local SSD cache of hot segments on workers (dashboard queries over recent partitions hit cache, skipping the object store), and columnar layout so a GET fetches a contiguous column run. The catalog’s offset index points straight at the needed byte ranges.

7. Join on two huge tables. A fact-to-fact join (billions x billions) does not fit the broadcast-hash-join pattern and can explode memory and network. Fix: shuffle hash join - hash-partition both sides by the join key so matching keys co-locate on the same worker, then join locally; spill partitions to disk when they exceed memory. Prefer broadcast join when one side is small (the common star-schema dimension case). Push join predicates down to prune both inputs first.

8. Memory pressure from high-cardinality GROUP BY / large hash tables. A GROUP BY user_id over billions of users builds a hash table too big for RAM. Fix: spill-to-disk aggregation - partition the group space, process partition by partition so only a slice of the hash table is in memory at once; pre-aggregate in the partial stage to shrink what the final stage holds; enforce per-query memory limits so one query cannot OOM a worker shared by others.

9. Concurrency / noisy-neighbor contention. Hundreds of concurrent queries contend for worker CPU and memory; one giant ad-hoc scan starves interactive dashboards. Fix: separate compute pools / virtual warehouses (interactive vs batch) over the same immutable storage (decoupled storage-compute makes this free), admission control and query cost guardrails (max_bytes_scanned), and priority scheduling so cheap interactive queries preempt or run alongside without being blocked by a monster scan.

10. Catalog as a single point of failure / contention. Every query reads the catalog for pruning; every load commits to it. A slow or unavailable catalog stalls the cluster. Fix: replicate the catalog (Raft/replicated SQL), cache pruning metadata in RAM on coordinators (it is small, ~100s MB, and only changes on commit), and make load commits atomic, append-only snapshot bumps so readers never block writers - a reader pins a snapshot and is isolated from in-flight loads. The catalog is small and read-mostly, so caching and replication handle it.

Wrap-Up

The trade-offs that define this design:

  • Column-oriented, immutable, encoded segments over a row store with indexes. We store like-with-like so a query reads only the columns it projects and the data compresses 8-15x, trading cheap in-place updates (which OLAP does not need) for a layout that scans a few columns out of fifty at tens of GB/s. A row store reads an order of magnitude too many bytes and its indexes do not help a scan that touches most rows.
  • Prune before you read, and let clustering decide how well. Column projection, partition pruning, and zone-map/bloom pruning stack multiplicatively to turn 20 TB into tens of GB using tiny metadata, and the loader’s sort/clustering key is what makes zone maps tight enough to skip most segments - the single biggest performance lever a user controls.
  • Encode the structure, do not compress the bytes. Dictionary for low cardinality, run-length for clustered runs, delta + bit-packing for sequences - stacked, scan-friendly, and filterable in encoded form, which both shrinks storage and lets filters and aggregates run without full decode. That is categorically different from gzip over rows.
  • Vectorized, parallel, stateless execution with partial-aggregate-then-shuffle. Batch-at-a-time operators give 10-50x per core over row-at-a-time; stateless workers scanning immutable segments scale and fail over trivially; partial aggregation collapses billions of rows to groups before the network, so the shuffle is kilobytes. Storage and compute scale independently.
  • Snapshot isolation over OLTP transactions. Loads are atomic snapshot commits of immutable segments and queries run against a pinned snapshot, so readers never block writers and never see a half-load - we spend the relaxation of strict serializability on throughput, elasticity, and cost, because analytics tolerates it and OLTP-grade locking would wreck all three.

One-line summary: an OLAP engine that stores wide tables as immutable, column-oriented, run-length-and-dictionary-encoded segments described by a strongly-consistent catalog, so a cost-based distributed planner can prune away partitions and segments via zone maps, read only projected columns, and fan the survivors out as vectorized scan-and-aggregate operators across stateless workers that partial-aggregate before a hash shuffle - trading in-place updates and strict transactions for a database that answers billion-row aggregations over terabytes in seconds instead of minutes.