Shelves / Data Engineering for Analytics
DE·01
How Analytical Databases Work
Why the database that runs TiffinBox's orders is the wrong place to ask "revenue by kitchen by month for the last year", and what analytical engines do differently: column storage, compression, vectorised execution, zone maps and late materialisation; massively parallel processing and separated storage and compute in cloud warehouses; where PostgreSQL is still enough; and the shape of an analytics platform from sources to dashboards; with a lab that runs the same queries on 5 million orders in PostgreSQL and DuckDB and compares storage formats.
Start here: two kinds of questions
TiffinBox's PostgreSQL database answers questions like "skip Tuesday for subscription 88" and "show order 4242424" thousands of times a second: each touches a few rows, needs them now, and often changes them. These are OLTP (online transaction processing) workloads.
The finance team asks different questions: "revenue per kitchen per month for the last year", "which customers churned after a price change?", "average delivery time by area and hour". Each touches millions of rows but only a few columns, rarely changes anything, and can take a second or two. These are OLAP (online analytical processing) workloads.
The two shapes want opposite storage designs:
| OLTP | OLAP | |
|---|---|---|
| typical query | a few rows, all columns, by key | millions of rows, a few columns, aggregated |
| writes | many small, concurrent, transactional | bulk loads, appends, periodic rewrites |
| storage layout | rows together (a row's columns side by side) | columns together (a column's values side by side) |
| best index | B-tree on keys | min/max zone maps, sorting, partitioning |
| examples | PostgreSQL, MySQL | DuckDB, ClickHouse, BigQuery, Snowflake, Redshift |
The same questions, measured
The lab loaded the same 5 million orders (12 columns) into PostgreSQL and DuckDB:
| Question | PostgreSQL | DuckDB |
|---|---|---|
| revenue per kitchen per month | 758 ms | 81 ms |
| top 10 customers by spend | 631 ms | 46 ms |
| fetch one order by ID (PostgreSQL with its primary key) | 0.06 ms | 0.9 ms |
| Storage of the same data | Size |
|---|---|
| CSV | 465 MB |
| PostgreSQL table | 558 MB |
| Parquet (columnar, zstd compression) | 34 MB |
The analytical engine was ~10–14× faster on analytical questions; the transactional one was ~15× faster on the transactional question. Same data, same machine: the layout decides.
How deep to go
Volume 17 defines six mastery levels. For analytical databases:
| Level | What you can do |
|---|---|
| L1 | Tell OLTP from OLAP workloads and name engines for each |
| L2 | Load data into a warehouse and query it; choose Parquet over CSV |
| L3 | Explain columnar storage, encodings, vectorisation, zone maps and MPP |
| L4 | Diagnose a slow analytical query (no pruning, skewed join, spilling) and fix it |
| L5 | Design an analytics platform for an organisation with cost and latency targets |
| L6 | Run it: capacity, cost governance, concurrency, upgrades, incidents |
Row stores and column stores
A row store writes each row's values together in a page (PostgreSQL's 8 KB pages). Reading one order means one page; reading one column of every order means reading every page.
A column store writes each column separately, in blocks of many values (Parquet's row groups and column chunks; DuckDB's row groups of ~122,000 rows; ClickHouse's granules). Reading amount_paise for 5 million orders reads only that column's blocks.
The lab's query touched 3–4 of 12 columns. In a row store it still read all 558 MB; in a column store it read the few megabytes those columns occupy (chapter 07's lab measures this: 3 columns of one month were 2% of the bytes).
The trade: inserting or updating one row in a column store touches many column blocks, so column stores batch writes (append in bulk, rewrite blocks, or keep a small row-oriented buffer that's merged later).
Compression
Columns compress well because a column holds one type with patterns:
| Encoding | Works on | Example |
|---|---|---|
| dictionary | low-cardinality values | status ∈ {delivered, cancelled, refunded} stored as 2-bit codes |
| run-length (RLE) | repeated runs (especially after sorting) | kitchen_id = 12 for 40,000 rows → (12, 40,000) |
| delta / frame of reference | sorted or slowly changing numbers | timestamps stored as small differences |
| bit-packing | small integers | ratings 1–5 in 3 bits |
| general-purpose (zstd, Snappy, LZ4) | whatever remains | applied per page after encoding |
In the lab, the same data was 465 MB as CSV, 128 MB as Snappy-compressed Parquet and 34 MB as zstd Parquet. Less data means less I/O, more data in memory, and cheaper storage; engines can even compute on encoded data (comparing dictionary codes instead of strings).
Vectorised execution and late materialisation
A traditional engine passes one row at a time between operators (scan → filter → aggregate), paying function-call and branch overhead per row. A vectorised engine passes batches (e.g. 2,048 values of one column), so each operator runs a tight loop the CPU can pipeline and the compiler can turn into SIMD instructions. Some engines instead compile queries into machine code (code generation); both remove per-row overhead.
Late materialisation: filter on the columns in the WHERE clause first, producing a selection of row positions, and fetch the other columns only for rows that survive. Most columns of most rows are never decompressed.
Skipping data: zone maps, sorting and partitioning
Analytical engines rarely use B-trees. Instead:
- Zone maps (min/max statistics per block, kept by Parquet per row group and by most engines internally): a filter
placed_at >= March 1skips blocks whose maximum is earlier. - Sorting (clustering) makes zone maps effective: chapter 07's lab read 2 of 50 row groups for one week when the file was sorted by time, and all 50 when it wasn't.
- Partitioning splits a table into separate files or directories by a column (usually date), so whole partitions are skipped before any file is opened.
Choosing sort and partition keys from the most common filters is the single most important physical design decision in a warehouse.
Massively parallel processing and the cloud warehouse
A single machine runs out at some point; MPP engines split data across many nodes, each scanning and aggregating its share, then combine partial results. Joins and GROUP BY on keys other than the distribution key require shuffling rows between nodes over the network, which is the expensive part (chapter 03 covers it in Spark).
Cloud warehouses (BigQuery, Snowflake, Redshift, Databricks SQL, ClickHouse Cloud) add separation of storage and compute: tables live as columnar files in object storage; compute clusters (or BigQuery's shared slots) are started, scaled and stopped on demand. Consequences:
- You pay for storage (cheap) and for compute or bytes scanned (expensive); query design is cost design (chapter 09).
- Many teams can query the same data with separate compute, so heavy jobs don't slow dashboards.
- Data loaded once is available to SQL, notebooks and ML tools through open formats (chapter 07).
DuckDB is the in-process version of the same ideas: a columnar, vectorised engine embedded in a Python or Java process, reading Parquet directly. It's excellent for single-machine analytics up to hundreds of gigabytes, for tests and for local development of warehouse models (chapter 04's dbt project uses it).
When PostgreSQL is enough
Not every company needs a warehouse on day one. PostgreSQL works for analytics when:
- data is in the tens of millions of rows and queries can take seconds;
- a read replica or a separate reporting instance keeps scans away from the primary;
- you use materialised views or summary tables refreshed on a schedule;
- columnar extensions or foreign data wrappers to Parquet stretch it further.
The signals that it's time to move: reports slowing the product, analysts waiting minutes, the need to join data from many sources (payments provider, CRM, app events), or history that no longer fits.
The shape of an analytics platform
sources ingestion storage transformation serving
PostgreSQL (CDC) ─┐ ┌─ BI dashboards
Kafka events ─┼─ batch loads / CDC ──→ raw tables in the ──→ staging → marts ──┼─ notebooks, ad-hoc SQL
payment provider ─┤ / streaming warehouse or lake (dbt, Spark) ├─ ML features
app analytics ─┘ (Parquet / Iceberg) └─ reverse ETL to tools
orchestration (chapter 05) · quality (08) · governance and cost (09)
The rest of this volume builds each box for TiffinBox: modelling (02), batch processing (03), transformations (04), orchestration (05), streaming (06), file and table formats (07), quality (08), governance and cost (09), and the whole platform as a project (10).
Common traps
- Analytics on the production primary.
- CSV as a storage format (no types, no compression, no statistics).
- Unsorted, unpartitioned tables that defeat pruning.
SELECT *in a column store, reading every column.- Choosing an engine by brand rather than by data size, concurrency, latency and cost.
Lab: the same data in a row store and a column store
Setup. The lab machine (2 CPUs). DuckDB generated 5,000,000 orders with 12 columns (IDs, kitchen, rider, timestamp over one year, status, amount in paise, payment method, veg flag, a short text note, delivery minutes, rating) and wrote them as CSV and as Parquet (Snappy and zstd). PostgreSQL 16 loaded the CSV into a heap table (vacuumed and analysed, parallel query with 2 workers allowed). DuckDB loaded the zstd Parquet into an in-memory table, and also queried the Parquet file directly. Each query's time is the median of three runs after a warm-up.
Storage
| Format | Size |
|---|---|
| CSV | 465.3 MB |
| PostgreSQL heap table (no indexes) | 558 MB |
| Parquet, Snappy | 128.2 MB |
| Parquet, zstd | 33.9 MB |
| DuckDB database file | 107.8 MB |
Queries
| Query | PostgreSQL | DuckDB table | DuckDB on the Parquet file |
|---|---|---|---|
revenue per kitchen per month (status, kitchen_id, placed_at, amount_paise) |
758 ms | 81 ms | 84 ms |
| top 10 customers by total spend | 631 ms | 46 ms | 65 ms |
| one order by ID, no index | 148 ms | 0.9 ms | 8.2 ms |
| one order by ID, PostgreSQL primary key | 0.061 ms | — | — |
| update one order's rating (PostgreSQL: with commit) | 0.295 ms | 0.68 ms | — |
What it shows
- Columnar plus vectorised won the analytical queries by 10–14×, reading only the needed columns, compressed, in batches. Querying Parquet files directly was nearly as fast as a loaded table: open file formats make "load first" optional.
- The row store with a B-tree won the point lookup by ~15×. DuckDB's 0.9 ms without any index came from zone maps and a fast scan; good, but not what you'd run a transactional API on.
- Single-row updates weren't dramatically different here (0.3 vs 0.7 ms). DuckDB handles occasional updates fine; what it isn't built for is many concurrent writers from many processes, which is OLTP's normal state.
- Compression ratios depend on the data. This synthetic data has regular patterns that compress unusually well (14× from CSV with zstd); real data typically compresses 3–10×.
- On 2 CPUs, PostgreSQL's parallel workers barely helped; with more cores both engines scale, but the gap in bytes read and per-row overhead remains.
Try it yourself
- Add an index on
(kitchen_id, placed_at)in PostgreSQL and rerun the monthly revenue query: does it help an aggregate over a year? - Query only
count(*)andsum(amount_paise)over the whole table in both engines and compare with the 4-column query. - Sort the Parquet file by
kitchen_idand compare its size with the unsorted one. - Try a columnar PostgreSQL extension on the same data, if you can install one.
Revision sheet: how analytical databases work
Key ideas
- OLTP: few rows, all columns, many concurrent writes (row stores, B-trees). OLAP: many rows, few columns, bulk writes (column stores).
- Column storage reads only needed columns; encodings (dictionary, RLE, delta, bit-packing) plus zstd shrink them.
- Vectorised execution and late materialisation remove per-row overhead and avoid decompressing what isn't needed.
- Zone maps, sorting and partitioning skip data; choose sort and partition keys from common filters.
- MPP splits work across nodes; shuffles are the expensive part.
- Cloud warehouses separate storage (object storage) from compute; you pay for compute or bytes scanned.
- PostgreSQL (on a replica) is enough for modest analytics; move when reports hurt the product or sources multiply.
Numbers to remember
- Lab: 5M orders: CSV 465 MB, PostgreSQL 558 MB, Parquet zstd 34 MB.
- Monthly revenue: PostgreSQL 758 ms vs DuckDB 81 ms; point lookup: PostgreSQL PK 0.06 ms vs DuckDB 0.9 ms.
Glossary
- OLTP / OLAP: transactional / analytical processing.
- Column chunk / row group: Parquet's per-column data within a horizontal slice of rows.
- Zone map: min/max statistics per block, used to skip blocks.
- Vectorised execution: operators processing batches of values.
- Shuffle: redistributing rows across nodes by key.