All field guides

FIELD GUIDE Published

Row stores vs columnar stores: when Postgres stops being your analytics database

Keep analytics in Postgres while the queries are few and bounded, using a read replica, time partitions and BRIN indexes. Move it to a column store once reports scan most rows of wide tables: a column store reads only the columns a query names, and Amazon's Redshift documentation says a query that uses five of 100 columns reads about five percent of the table. The move costs a CDC pipeline and a plan for updates: with 90% of its upserts being updates, Notion found Snowflake ingestion slower and more costly.

Written with AI and checked against the cited sources before publication.

The mechanism

A row store and a column store hold the same table in different byte orders. The order decides which queries are cheap.

A row store keeps each row together. PostgreSQL stores every table as "an array of pages of a fixed size (usually 8 kB)". Each page starts with a 24-byte header, then a 4-byte item identifier per row, then the rows themselves. Each row has a fixed header "occupying 23 bytes on most machines", followed by the values of all its columns, one after another. To read one column of one row, Postgres reads the whole 8 kB page that holds that row. To read one column of every row, it reads every page of the table, and with them every other column, unless an index contains that column and an index-only scan can answer from the index alone.

That layout is right for OLTP, where transactions read and write whole records a few at a time. Even Amazon's documentation for Redshift, a column store, says "row-wise storage is optimal for OLTP databases." A point lookup walks a B-tree to one heap page. An update writes one new row version.

A column store keeps each column together. The values of one column for many rows sit in the same blocks: 1 MB blocks in Redshift, per-column files in ClickHouse's MergeTree that are read in granules of 8,192 rows by default, micro-partitions of "between 50 MB and 500 MB of uncompressed data" in Snowflake, inside which "columns are stored independently". The C-Store paper (Stonebraker et al., VLDB 2005) gives the main consequence: "a DBMS need only read the values of columns required for processing a given query, and can avoid bringing into memory irrelevant attributes." Redshift's documentation gives the arithmetic: in a table of 100 columns, "a query that uses five columns will only need to read about five percent of the data contained in the table."

Three more effects follow from putting like values next to each other:

  • Compression works better. A block of one type and one column compresses far better than a block of mixed rows. Cloudflare's capacity estimate put its average HTTP request record at 360 bytes as a zstd-compressed Cap'n Proto message and 36.74 bytes in ClickHouse.
  • Execution can be vectorised. The MonetDB/X100 paper (Boncz, Zukowski and Nes, CIDR 2005) found that the usual iterator model "leads to tuple-at-a-time execution, which causes both high interpretation overhead, and hides opportunities for CPU parallelism from the compiler", and reports raw execution power on 100 GB TPC-H "between one and two orders of magnitude higher than previous technology".
  • Data can be skipped by range. Columnar engines keep small summaries per block, such as a minimum and maximum, or a sparse index with "one entry per granule" in ClickHouse, so a filter on the sort column skips most blocks unread.

The price is paid on writes and point reads. A row is now scattered across as many places as it has columns, and blocks are compressed and immutable. An update is worse. In ClickHouse's MergeTree, a classic ALTER TABLE … UPDATE is "a heavy operation not designed for frequent use": mutations are "asynchronous background processes" that "execute by rewriting whole data parts", every updated column in full. Newer lightweight UPDATE and DELETE statements write only the changed rows, as patch parts or a deleted-row mask, and queries do extra work to apply them until merges fold them in. ReplacingMergeTree, the other common workaround, changes what queries return: it deduplicates only "during a merge", which happens "at an unknown time", so a query without FINAL can count a row twice.

Why analytics hurts the primary. Postgres has no separate read path for reports. A 20-minute aggregate over orders uses the same disks, CPUs and connection slots as checkout. Under MVCC, "an UPDATE or DELETE of a row does not immediately remove the old version of the row", and a long-running query keeps old versions visible: the PostgreSQL documentation warns that "an open transaction prevents vacuuming away recently-dead tuples that may be visible only to this transaction". So one 20-minute report lets dead rows pile up on hot tables for those 20 minutes. Our episode The Report Works. Is All That Database Work Necessary? follows a paginated export that finishes while other reports on the same database slow down, and traces the cost to how each page is reached.

The steps before a new database

  1. A read replica for analytics. It moves the reads off the primary but not out of Postgres's rules. When a replica query conflicts with replayed WAL, the standby waits up to max_standby_streaming_delay, "The default is 30 seconds", and then cancels it. Set it to -1 and the replica can "wait forever", which means it lags. Turn on hot_standby_feedback and cancellations from cleanup stop, but it "can cause database bloat on the primary for some workloads". Pick one: cancelled reports, a lagging replica, or bloat on the primary.
  2. Partitioning and BRIN. If most analytics filter on time, partition by time. The PostgreSQL documentation says performance "can be improved dramatically" when the heavily accessed rows sit in one or a few partitions, and dropping a partition "is far faster than a bulk operation" and avoids the VACUUM overhead of a bulk DELETE. For an append-only table whose physical order follows a timestamp, a BRIN index stores one summary per block range and lets a scan skip ranges that cannot match. Both cut rows read. Neither cuts columns read.
  3. A columnar extension inside Postgres. Citus columnar (USING columnar) showed "a compression ratio of better than 8X" on its documentation's sample data. It keeps SQL, joins and one database to run, but its documentation lists it as "Append-only (no UPDATE/DELETE support)". It suits history that is no longer updated, such as last year's partitions.
  4. A separate columnar engine. DuckDB runs inside your process over files; in that in-process mode its documentation offers one read-write process or many read-only ones, and writing from several processes needs its Quack client-server protocol or the DuckLake format. ClickHouse is a server you operate or buy as a service. BigQuery, Redshift and Snowflake are managed warehouses. All of them need the data copied out of Postgres.

Worked numbers

All inputs here are illustrative; the page and header sizes are PostgreSQL's documented ones. Rerun it with your own table.

The table. orders has 100 million rows and 40 columns, about 180 bytes of values per row. With the 23-byte row header and 4-byte item identifier, each row takes about 207 bytes, ignoring alignment padding. An 8,192-byte page has 8,168 bytes after its header, so it holds 39 whole rows (8,168 ÷ 207 = 39.46). That is 2.56 million pages, about 21 GB.

The query. A dashboard runs SELECT status, sum(amount) ... WHERE created_at > now() - interval '90 days' GROUP BY status. It needs three columns: created_at (8 bytes), status (4 bytes) and amount (8 bytes), 20 bytes per row. The table covers two years.

LayoutBytes readTime at an illustrative 1 GB/s
Row store, full scan21 GB (every page)21 s
Row store, monthly partitions, 4 of 24 touched (90 days spans up to 4 months)21 × 4 ÷ 24 = 3.5 GB3.5 s
Column store, 3 columns, uncompressed100M × 20 B = 2.0 GB2.0 s
Column store, 3 columns, illustrative 5× compression0.4 GB0.4 s
Column store, compressed, sorted by created_at, 90 of 730 days0.4 × 90 ÷ 730 ≈ 0.05 GB0.05 s

In the row store, only 20 of every 207 bytes read, under 10%, are values the query uses. Partitioning or sort order cuts the rows; the column store cuts the columns; and the two multiply.

Why it hurts the primary. Twenty people with that dashboard open, each refreshing once a minute on the unpartitioned table, ask for 20 × 21 GB = 420 GB a minute, 7 GB/s, seven times the illustrative disk if the table does not fit in memory; if it does, they fight for CPU and buffers instead. Checkout queries queue behind them either way.

What the column store pays. A point lookup in the row store reads about four B-tree pages, most of them cached, and one 8 kB heap page. SELECT * for one order in a column store sorted by id decompresses one 8,192-row granule in each of 40 columns: 8,192 × 180 bytes ≈ 1.5 MB to return 180 bytes. If the store is sorted by created_at instead, finding the id means scanning the whole id column, 800 MB uncompressed. An update of 1,000 random orders in Postgres writes 1,000 new row versions. In a MergeTree table stored as 20 parts of 5 million rows, those 1,000 rows almost certainly touch every part. If each update sets every column, as a CDC upsert of the whole row does, an ALTER TABLE … UPDATE mutation rewrites close to the whole table, about 3.6 GB compressed, to change about 180 kB. Setting only status still rewrites the whole status column in every part, about 80 MB. A lightweight UPDATE avoids the rewrite.

The pipeline's cost. CDC from Postgres reads the WAL through a replication slot, and the slot keeps the primary from deleting WAL its consumer has not confirmed. If the primary writes 20 MB/s of WAL and the consumer is down for six hours, the primary keeps 20 MB × 21,600 s = 432 GB of extra WAL. The PostgreSQL documentation warns that slots "can cause the server to retain so many WAL segments that they fill up the space allocated for pg_wal", and offers max_slot_wal_keep_size as the limit. Past that limit, the slot's consumer "may no longer be able to continue replication due to removal of required WAL files", which for CDC means a fresh snapshot.

How it fails

  • Analysis queries on a production database (GitHub, 1 June 2022). From 09:40 UTC, for 48 minutes, GitHub Actions customers saw delays in workflows starting. "The cause of these delays was excessive load on a proxy server that routes traffic to the database", and GitHub traced it to "a set of data analysis queries being pointed at an incorrect database." The fix was structural: "These queries have been moved to a dedicated analytics setup that does not serve production traffic".
  • An unbounded query on a primary (GitHub, 10 April 2024). Between 08:18 and 09:38 UTC, "an overloaded primary database instance caused by an unbounded query" produced "a 17% failure rate for web-based repository file editing" and smaller failure rates in other repository operations and in search, which shared the primary. GitHub scaled up the instance and "shipped an improved version of the query to run against read replicas."
  • Postgres as the analytics store (Sentry, May 2019). Sentry's search and tag counts ran on Postgres. Its tag-count store reached the point where "the number of mutations executed exceeded our ability to replicate them on a single Postgres machine", and spreading it over a fleet of machines left problems that more hardware "just could not resolve". After the move to ClickHouse, sorted, individually compressed columns "enabled the data behind Tagstore to go from terabytes to gigabytes on disk."
  • The column store's weak spot (Notion, July 2024). Notion fed Snowflake from the Postgres WAL with Fivetran, through 480 hourly-run connectors for its 480 logical Postgres shards. Its block data is "update-heavy—90% of Notion upserts are updates", and "Most data warehouses, including Snowflake, are optimized for insert-heavy workloads". Ingestion "became slower and more costly".

GitLab's runbook shows a common end state: Contribution Analytics, "originally implemented using PostgreSQL, which performed poorly", now reads from ClickHouse, while "Data is always present in PG and it’s the source of truth".

Traps without a published incident

  • A CDC slot nobody watches. Set max_slot_wal_keep_size and alert on retained WAL per slot, or a stopped consumer fills pg_wal on the primary.
  • Deletes and updates that never arrive. A pipeline that copies inserts but not deletes, or a ReplacingMergeTree queried without FINAL, gives counts that drift above the source. ClickHouse's own example counts 200 rows without FINAL and the correct 100 with it.
  • **SELECT * in a column store.** It reads every column and gives back the advantage. BigQuery's documentation adds that "Applying a LIMIT clause to a SELECT * query does not affect the amount of data read."

Decision table

OptionWhat it costsChoose it when
Stay on the primary, with statement_timeout, indexes and summary tablesAnalytics still shares CPU, disk and vacuum with OLTPA few known queries, each bounded in rows, a small share of the primary's time
Read replica for analyticsCancelled queries, replica lag or primary bloat; a second serverReports are ad hoc but fit in minutes, and data must stay in Postgres
Time partitions and BRINPartition management; queries must filter on the keyMost analytics filter on time over append-mostly tables
Columnar extension in PostgresAppend-only tables, fewer index and lock featuresCold history that is no longer updated, queried with Postgres SQL
In-process engine over exported files (DuckDB)Batch freshness; one writer process unless you run it as a server or on DuckLakeOne team or a job analyses snapshots, not live data
Separate columnar server fed by CDCA pipeline, minutes of lag, a second copy, update and delete handlingHigh-volume events or user-facing analytics that must answer in seconds over billions of rows
Managed warehouse (BigQuery, Redshift, Snowflake)Ingestion cost per change, usage-based billing, lagAd hoc BI across many sources, mostly inserts, and analysts who should never touch production

Sort your analytical queries by two questions: do they read most rows of a wide table, and how fresh must the answer be? Queries that read few rows stay in Postgres. Queries that read most rows and can be minutes stale belong in a column store. Queries that read most rows and must be current to the second are the expensive case; look first at whether a summary table maintained by the write path answers them.

A check you can run this week

Find the queries that read the most data on the primary. With pg_stat_statements loaded (it needs shared_preload_libraries, a restart and CREATE EXTENSION pg_stat_statements in the database you query; the column names below are PostgreSQL 14 and later), run:

SELECT left(query, 80) AS query,
       calls,
       round((total_exec_time / 1000)::numeric) AS total_s,
       round(mean_exec_time::numeric) AS mean_ms,
       rows / greatest(calls, 1) AS rows_per_call,
       pg_size_pretty((shared_blks_hit + shared_blks_read) * 8192 / greatest(calls, 1)) AS touched_per_call,
       round((100 * total_exec_time / sum(total_exec_time) OVER ())::numeric, 1) AS pct_time
FROM pg_stat_statements
WHERE toplevel
ORDER BY shared_blks_hit + shared_blks_read DESC
LIMIT 15;

touched_per_call counts 8 kB shared-buffer accesses, cached or not and repeats included, so it overstates bytes from disk; treat it as a ranking that puts the big scans near the top, then confirm with EXPLAIN (ANALYZE, BUFFERS). The analytical queries are the ones that touch gigabytes per call and return a few dozen rows. Add up their pct_time. Our rule of thumb, not a published threshold: if they take more than about a fifth of the execution time pg_stat_statements has recorded, or if any of them runs during your peak hour, move them first to a replica, and decide whether it cancels, lags or bloats the primary. Then check how many of the table's columns they read: queries that read most rows but few columns of a wide table are the ones a column store runs for a fraction of the bytes, and the ones that justify the pipeline.

Sources

The primary sources this guide was checked against.

Hear it discussed

Episodes of the show that work through this decision.