Columnar Analytics Stores - Complete Deep Dive

Prerequisites: Database Indexing, Batch vs Stream Processing Used in: Metrics Monitoring, Ad System, Trending Topics


What is a Columnar Store?

A columnar store keeps each column of a table together on disk, rather than keeping each row together. A query that reads three columns out of fifty reads only those three files and never touches the other forty-seven. That one layout change is what makes a store appropriate for OLAP — online analytical processing, meaning aggregations over huge numbers of rows — instead of OLTP, online transaction processing, meaning reading and updating a handful of specific rows.

Real-world analogy: A filing cabinet of paper invoices is a row store. Each folder holds one complete invoice, so pulling invoice #4,812 is one movement. But answering “what did we bill in total last quarter?” means opening every folder and reading past the address, the line items and the terms to find the one number you want. Now imagine instead a ledger book with one page per field — a page of all customer names in order, a page of all amounts in order. Totalling the quarter is reading one page. Reconstructing a single invoice is now the hard job, because you have to visit every page and take the 4,812th entry from each. Neither cabinet is better; they answer different questions.


Row Layout vs Column Layout

Take a four-row table and write it out the way each engine actually stores it.

Table orders
order_id  user_id  country  amount  created_at
1001      7        IN       250     2026-01-02
1002      7        US       1800    2026-01-02
1003      9        IN       75      2026-01-03
1004      3        DE       920     2026-01-04

A row store (Postgres, MySQL, Oracle) packs each row into a contiguous block of bytes and puts rows into 8KB or 16KB pages:

page 1: [1001|7|IN|250|2026-01-02][1002|7|US|1800|2026-01-02][1003|9|IN|75|...]

A column store writes one stream per column:

order_id   : 1001 1002 1003 1004
user_id    : 7 7 9 3
country    : IN US IN DE
amount     : 250 1800 75 920
created_at : 2026-01-02 2026-01-02 2026-01-03 2026-01-04

Nothing is lost — the position of a value is its row identity, so the third entry of every column belongs to order 1003. That implicit positional join is why column stores can reconstruct a row at all, and also why deleting row 3 is painful: you would have to remove the third entry from every column stream, so instead these engines mark it dead and clean up later during a background merge.

Property Row layout Column layout
Unit of co-location One row, all columns One column, all rows
Reads for 3 of 50 columns All 50 3
Single-row fetch One page read One read per column
Values adjacent on disk Mixed types One type, often similar values
Natural compression Poor Very good

Why a SUM Reads One Fiftieth of the Bytes

Make it concrete. One billion rows, fifty columns, averaging 400 bytes per row, so 400GB of logical data. Now run the single most common analytics query there is.

SELECT country, SUM(amount)
FROM orders
WHERE created_at >= '2026-01-01'
GROUP BY country;

The query touches three columns: created_at, amount, country.

On a row store, the smallest unit the storage engine can read is a page, and a page contains whole rows. To look at amount you must physically read the 400 bytes of the row it is embedded in. There is no way to read one field out of a page without reading the page. So the scan reads ~400GB to use ~20GB of it. An index on created_at narrows which rows, but once the planner estimates it will touch a large fraction of the table it will correctly abandon the index and sequential-scan, because random page fetches for half a billion rows are slower than streaming the file.

On a column store, the three column streams are separate files. amount at 8 bytes per row is 8GB, created_at at 8 bytes is 8GB, and country dictionary-encoded at 1 byte is 1GB. Total 17GB instead of 400GB — a 1/24 reduction here, and genuinely around 1/25 when a query touches two columns of fifty.

The ratio is not magic, and it is worth saying plainly in an interview: it is the ratio of columns you need to columns the table has. A two-column table gets no benefit from columnar storage. A two-hundred-column event table — which is what analytics tables actually look like — gets an enormous one. Then compression multiplies it again.


Compression Is a Speed Win, Not Just a Space Win

Putting like values next to each other makes them extraordinarily compressible, because a column is one data type with a narrow range, while a row is a jumble of a string, a timestamp, a float and a boolean.

Encoding What it does Works on
Run-length Store IN x 400000000 instead of 400M copies Sorted or low-variety columns
Dictionary Map 200 country names to 1-byte codes, keep the map once Repeated strings, enums, user agents
Delta Store the difference from the previous value Timestamps, monotonically increasing IDs
Frame of reference plus bit packing Subtract the block minimum, then use only the bits needed Integers in a narrow range per block
General purpose LZ4 or Zstd Byte-level compression on top of the above Everything, as a final pass

Typical end state is 5-20x on real event data, so our 17GB of columns becomes a couple of gigabytes on disk. The part people miss is that this is primarily a latency win. The bottleneck in an aggregation is bytes pulled off storage or over the network, not CPU cycles. LZ4 decompresses at several gigabytes per second per core, which is faster than a disk or a network link can feed it, so trading CPU for fewer bytes read is always the right trade for a scan. Compressing harder makes a scan faster.

It gets better, because good engines can run the query without decompressing at all. A WHERE country = 'IN' against a dictionary-encoded column becomes “look up IN to get code 7, then compare integers” — no string comparison in the loop. A run-length encoded block lets the aggregator add 250 x 400000 in one step rather than 400,000. And per-block minimum and maximum values let the engine skip whole blocks that cannot satisfy the predicate.

That last trick deserves a name. ClickHouse keeps a sparse primary index with one entry per granule of 8,192 rows and skips granules whose range cannot match; Parquet stores per-row-group statistics; Druid partitions by time so a 7-day query never opens last year’s segments. None maintain a per-row index, because for a scan-shaped workload, block pruning plus a fast scan beats index maintenance.


Vectorised Execution and SIMD

Layout decides how many bytes you read. Execution decides what you do with them, and the classic design is just as wasteful.

A traditional row-at-a-time engine uses the Volcano model: every operator exposes next() and returns one tuple. Summing a billion rows means a billion calls through the filter’s next(), into the scan’s next(), each one a virtual function call, each one re-deciding types and re-checking nulls, for one 8-byte addition. The interpretation overhead dwarfs the arithmetic. A vectorised engine instead passes a batch of a single column — typically 1,024 or 8,192 values in a flat array — through each operator. One call does a thousand additions in a tight loop over contiguous memory of a known type. Three things improve at once:

  • The per-call overhead is amortised across a thousand values instead of paid per value.
  • The loop body has no branching on type, so the CPU’s branch predictor and instruction pipeline stay full.
  • The loop is trivially SIMD-able. SIMD stands for Single Instruction, Multiple Data: one CPU instruction applied to several values simultaneously. An AVX2 register holds eight 32-bit integers and AVX-512 holds sixteen, so a single instruction adds 8 or 16 values. The compiler auto-vectorises a tight typed loop; it cannot do anything with a virtual call per row.
Row at a time : next() -> filter -> add        x 1,000,000,000 calls
Vectorised    : [1024 amounts] -> filter mask -> SIMD add   x ~1,000,000 calls

The alternative school is just-in-time compilation — generate machine code for this specific query and run it over rows, which is what Postgres JIT and Spark’s whole-stage code generation do. Both approaches kill interpretation overhead; vectorisation is simpler to build and debug, and it is what ClickHouse, DuckDB, Druid and Pinot use. Combined with the layout win, this is where “scans a billion rows in under a second on one machine” comes from. It is not a trick, it is fewer bytes and fewer instructions per byte.


OLTP Is Right for One Order and Wrong for Ninety Days

These are two different machines with two different jobs, and most production incidents in this area come from asking one to do the other’s.

“Fetch order 1001 and show the customer their receipt.” A row store is close to optimal: one B-tree lookup, three or four page reads to walk the tree, and the final page holds every column of that row contiguously, so one read gets all fifty fields. Sub-millisecond, and it scales to very high concurrency because each query touches almost nothing. Run it on a column store and it is comically bad — fifty separate reads, one per column, each pulling an entire 8,192-row granule to extract one value, with no row-level index to find it precisely. Megabytes read to answer a question a row store answered with one page.

“Total revenue by country for the last ninety days.” Already covered: the row store reads 400GB to use 20GB, with no index that can save it.

There is a second, less-discussed reason not to run analytics on your OLTP primary. The analytical query evicts your working set from the buffer pool — Postgres caches hot pages in shared memory, and a 400GB sequential scan streams cold pages through that cache, pushing out the pages your checkout path depends on. Your transactional p99 (the latency 99% of requests come in under, the slow tail users actually complain about) degrades for minutes after the report finishes. Postgres softens this with a ring buffer for large scans, but the shared I/O bandwidth and CPU contention are real regardless.

  Row store OLTP Column store OLAP
Built for Point reads and writes of whole rows Aggregations over many rows, few columns
Query shape WHERE id = ? GROUP BY over a time range
Rows per query 1 to a few hundred Millions to billions
Concurrency Tens of thousands of queries per second Tens to low thousands
Updates and deletes In place, transactional Append mostly, background merge, often no real transactions
Joins Many, normalised schema Few, denormalised wide tables
Typical latency Under 1 millisecond 50 milliseconds to minutes

Pre-Aggregation and Rollups

Scanning fast still means scanning. If a dashboard always asks the same question, computing the answer in advance is strictly cheaper than computing it a thousand times.

A rollup aggregates at ingest time to a chosen granularity. Druid does this natively: declare a one-minute granularity and a set of dimensions, and 10,000 raw events in a minute collapse into one row per unique dimension combination with sum, count, min and max columns. A 100x reduction is ordinary. ClickHouse has the same idea via AggregatingMergeTree plus a materialised view, and Pinot has star-tree indexes that pre-aggregate across dimension combinations.

-- Materialised view maintained on write, not on read
SELECT toStartOfMinute(ts) AS minute, country, device,
       sum(amount) AS revenue, count() AS orders
FROM events
GROUP BY minute, country, device;

What you trade is flexibility, in three specific ways:

  • You cannot ask a question the rollup did not anticipate, or drill into one event. Roll up by country and device and “revenue by browser version” is unanswerable; once 10,000 events become one row, the individual event is gone and debugging one user’s request needs raw data.
  • Averages and percentiles are not additive. You cannot average averages. Store sum and count and divide at query time; for percentiles store a sketch such as t-digest or DDSketch, not a number.
  • COUNT DISTINCT is not additive either. Unique users per minute cannot be summed into unique users per hour. Store a HyperLogLog sketch per bucket and merge the sketches, trading a small error bound for mergeability.

The usual resolution is to keep both: raw data with a short retention (7-30 days) for ad-hoc work and debugging, rollups with long retention for dashboards and trends, and a routing rule that sends a query to the rollup when its time range and grouping allow it. See batch vs stream processing for how the two tiers get populated.


The Products and What Separates Them

They all do columnar storage and vectorised scans. The differences that matter in a design discussion are the ingest story and whether they are built to sit behind a user-facing request.

Product Ingest Strongest at Watch out for
ClickHouse Large batch inserts, or a built-in Kafka consumer Raw scan speed per node, full SQL, cheap self-hosting Updates and deletes are asynchronous merges, deduplication is eventual
Apache Druid Native streaming from Kafka or Kinesis, plus batch backfill Sub-second time-sliced dashboards, ingest-time rollup Many node types to operate, limited joins
Apache Pinot Streaming plus offline, with upsert support User-facing queries at high concurrency, star-tree indexes Operationally heavy, smaller community
BigQuery Batch loads plus a streaming write API Serverless petabyte scans with no cluster to run Per-query billing and variable latency, not a serving tier
Redshift COPY from object storage, streaming from Kinesis Warehouse-style joins across big normalised tables Cluster sizing and concurrency limits
Snowflake Batch plus Snowpipe micro-batching Separating storage from compute, isolated warehouses per team Seconds-level floor on latency, credit cost

The useful split is two-way. Warehouses — BigQuery, Redshift, Snowflake — serve analysts and scheduled jobs: huge scans, generous latency, strong SQL, billed per use. Real-time OLAP — Druid, Pinot, ClickHouse — serves dashboards and in-product analytics: streaming ingest, sub-second queries, a cluster you own. Pinot and Druid were both built inside companies specifically to put analytics in front of end users at high request rates, which is exactly what a warehouse is not for.


Why You Do Not Serve a User-Facing p99 From an Ad-Hoc Scan

Suppose a seller dashboard shows “your revenue by region” and you point it straight at a columnar store with the user’s filters passed through.

The failure is structural: a scan’s cost is proportional to the data it scans, and the user chooses how much that is. One seller picks last 7 days and gets 80ms. Another picks 2 years with no dimension filter and scans a thousand times more data. Your p99 is now defined by whichever customer is most curious, and no amount of tuning fixes a query whose cost the client controls. It compounds, because these engines are built to use the whole machine for one query — vectorised scans deliberately saturate CPU and I/O bandwidth, so one heavy query does not just take long, it starves every concurrent query behind it. A handful of expensive requests pushes out the tail latency of all traffic, and OLAP engines have far lower concurrency ceilings than row stores.

What actually works, in order:

  1. Pre-aggregate the exact shape the UI asks for. The dashboard has a fixed set of widgets. Materialise them, because a lookup is not a scan.
  2. Cache the result. Dashboard queries repeat heavily across users and reloads, so a short TTL in Redis absorbs most of the traffic — see caching and cache stampede for the herd problem on expiry.
  3. Bound what a client can ask for. Cap the time range, require at least one dimension filter, set a per-query timeout and a scanned-bytes limit. Reject the unbounded query rather than let it degrade everyone else’s.
  4. Separate the clusters. Serving traffic on one, analyst and ad-hoc traffic on another, with separate quotas. The highest-value operational decision here. For genuine ad-hoc exports, make the query asynchronous — return a job ID and notify on completion rather than holding an HTTP request open for 90 seconds.

Which Store for Which Job

Four stores get confused with each other constantly because all four “hold a lot of data”.

Store type Built for Query it is good at Examples
OLTP row store Transactional reads and writes of individual records WHERE id = ?, multi-row ACID transactions Postgres, MySQL, DynamoDB
OLAP column store Aggregating many rows over few columns GROUP BY over a time range with filters ClickHouse, Druid, BigQuery
Time-series database High-rate metrics keyed by time plus tags Rate, downsample and window over one metric Prometheus, InfluxDB, TimescaleDB
Search index Relevance-ranked retrieval of matching documents Full-text match, fuzzy, faceted filters Elasticsearch, OpenSearch

Time-series databases and columnar OLAP overlap heavily — a time-series database is largely a columnar store with time partitioning, downsampling and a metric-shaped query language baked in. Choose it when every question starts with a metric name and a time range, and choose columnar OLAP when questions involve arbitrary dimensions and GROUP BY. A search index can aggregate too, but its aggregations are a bolt-on over an inverted index and lose badly to a column store on a billion-row SUM.


Getting Data In - Dual Write vs Change Data Capture

Your source of truth is the OLTP database. The columnar store needs a copy. How it gets there is the part of the design that most often breaks.

Dual write — the broken default. The application writes to Postgres and then writes to ClickHouse. There is no transaction spanning two systems, so any failure between them leaves them permanently inconsistent: the Postgres commit succeeds, the ClickHouse insert times out, and nothing ever repairs it. Worse, it fails silently — nobody notices until a number in a report is wrong and nobody can say since when. Retrying does not save you either, because the process can die between the two calls.

Change data capture — the right default. CDC stands for change data capture: reading the database’s own replication log (the write-ahead log in Postgres, the binlog in MySQL) and turning every committed change into an event. Because you are reading the log the database already maintains for replication, every event you emit is a change that definitely committed, in commit order, and there is no second write for the application to get wrong.

flowchart LR
    APP["Application"]
    PG[("Postgres OLTP<br/>source of truth")]
    OUT[("Outbox table")]
    CDC["CDC connector<br/>reads the WAL"]
    BUS[("Kafka or Kinesis")]
    SINK["Sink or native ingest"]
    COL[("ClickHouse or Druid")]
    UI["Dashboards and APIs"]
    APP --> PG
    APP --> OUT
    PG --> CDC
    OUT --> CDC
    CDC --> BUS
    BUS --> SINK
    SINK --> COL
    COL --> UI

Two refinements the diagram shows. Writing a row to an outbox table inside the same transaction as the business change lets you emit a clean domain event instead of a raw table diff that leaks your schema into every consumer — see outbox pattern and change data capture. And putting a log between the connector and the sink means the columnar store can be down, or be rebuilt from scratch, without losing anything.

Three details that always come up:

  • Delivery is at least once, so the sink must tolerate duplicates. A crash between writing and committing an offset replays events. Carry a stable event ID and either deduplicate on it or make the write idempotent — see idempotency and delivery semantics.
  • Updates are awkward, and that is expected. Column stores would rather append. Model the stream as immutable events and compute current state at query time, or use the engine’s merge-on-read support such as ClickHouse ReplacingMergeTree or Pinot upserts, accepting that deduplication is eventual.
  • Batch and stream need the same schema. The streaming path is lower latency and occasionally loses or duplicates; a periodic batch reload from the source of truth corrects it. That periodic reconciliation is what lets you trust the numbers — see batch vs stream processing.

Common Interview Questions

Q1: Why is a columnar store faster for aggregations if it stores exactly the same data?

Because the bytes it has to read are a fraction of the total. A row store’s smallest readable unit is a page containing whole rows, so reading one field means reading all fifty. A column store keeps each column in its own file, so a query touching three columns of fifty reads roughly a twentieth of the data, and compression on same-typed adjacent values cuts that again by 5-20x. Then vectorised execution processes batches of a thousand values per call instead of one row per virtual call. Fewer bytes, fewer instructions per byte.

Q2: Why not just add indexes to Postgres and run analytics there?

An index helps when a query touches a small fraction of the table. An aggregation over ninety days touches a large fraction, and the planner will correctly abandon the index for a sequential scan because random page fetches for half a billion rows are slower than streaming. Even if an index helped, the row layout still forces you to read whole rows to get one column. And the scan evicts your transactional working set from the buffer pool, so your checkout latency degrades for minutes after the report finishes.

Q3: What do you give up when you pre-aggregate?

The ability to ask questions you did not plan for. A rollup by country and device cannot answer “revenue by browser version”, and once 10,000 events become one row you cannot inspect an individual event. Averages and percentiles are not additive, so you must store sums and counts, or a sketch like t-digest. COUNT DISTINCT is not additive either and needs a HyperLogLog sketch to be mergeable across buckets. The standard answer is to keep raw data with short retention alongside rollups with long retention, and route each query to the cheapest tier that can answer it.

Q4: How do you serve a user-facing dashboard with a 200ms budget from an analytics store?

Do not let the user’s query shape decide the cost. Pre-aggregate the specific shapes the UI needs so a widget becomes a lookup rather than a scan, cache results with a short TTL since dashboard queries repeat heavily, bound what a client can request with time-range caps and scanned-bytes limits, and run serving traffic on a different cluster from analyst traffic. A vectorised scan is designed to saturate the machine, so one unbounded query does not just run long — it pushes out the tail latency of everything concurrent with it.

Q5: Why is dual-writing to Postgres and ClickHouse a bug rather than a shortcut?

There is no transaction across two systems. If the Postgres commit succeeds and the ClickHouse insert fails, the two diverge permanently and silently, and retrying cannot fix it because the process can die between the calls. Read the database’s replication log instead: change data capture emits only changes that definitely committed, in commit order, with no second write for the application to get wrong. Add an outbox table if you want clean domain events rather than raw table diffs, and make the sink idempotent because the log gives you at-least-once delivery.


← Tries Caching →
All Concepts HLD Designs