← Building blocks

Analytics without hurting production

Storage & data modellingsenior

Reporting queries scan millions of rows and slow the transactional database.

Say it like this

Reporting scans hundreds of millions of rows and must not slow the transactional database, so I stream a copy into a column store built for aggregation and run every dashboard and ad-hoc query there, accepting that it is minutes behind.

Basic solution

Copy data to a column store built for aggregation and run analytics there.

ClickHouseBigQuerySnowflakeRedshiftDruid

Copy events out, aggregate in a column store, serve from a summary

Redirects publish click events; a consumer batches them into the column store, where dashboards and ad-hoc queries run. The per-alias summary that the stats API reads is materialised out again so the hot path never touches the OLAP store.

How it works

  1. Rows are copied out of the transactional stores and loaded into the analytical store, either continuously through change data capture or an event stream, or once a night by a batch job. The transactional store never answers an analytics query.
  2. The analytical store lays data out by column, not by row: all values of one column are stored together, sorted and compressed. Dictionary encoding replaces repeated strings with small integers, run-length encoding collapses runs of the same value, and delta encoding stores differences between neighbours. The result is often 10× smaller than row storage.
  3. A query such as sum(clicks) by day where referrer = X reads only the clicks, day and referrer columns, skips whole blocks whose stored min and max for referrer cannot contain X, and processes the remaining values in batches of thousands per CPU instruction (vectorised execution) across many cores.
  4. Data is partitioned by time and sorted by the columns you filter on most, so a date-range query opens only the partitions in that range and seeks to the matching sorted region inside each.
  5. Materialised views or pre-aggregated tables hold the answers to the standing dashboard queries, updated as data arrives, so those dashboards read a few rows instead of scanning billions. Raw data stays for ad-hoc questions.
  6. The store is append-only in spirit: updating or deleting a row means rewriting the partition or merging it later, which is why it is unsuitable for per-request reads and writes.

Why not run it on the primary

  • A scan of 1B rows holds I/O and CPU for minutes and evicts the hot working set from the buffer cache, so user-facing latency spikes.

Worked example

Click analytics for the URL shortener

  • 10B redirects/month ≈ 330M click events/day, each {alias, ts, referrer, country, ua_hash} ≈ 60 B as rows.
  • Row store: 20 GB/day, 7 TB/year. A query "clicks per day for alias X over 90 days" on Postgres scans or walks an index over 30B rows; it takes minutes, and it competes for disk and cache with the redirects users are waiting on.
  • Column store (ClickHouse) partitioned by day, sorted by (alias, ts): compressed to ~4 GB/day, 1.5 TB/year. The same query touches 90 partitions, seeks to alias X in each, reads three columns: tens of milliseconds, because almost all of the 30B rows are skipped without being read.
  • Dashboard "top referrers today": one partition, group by referrer over 330M rows, vectorised on 16 cores: about a second. Materialise it hourly and it is instant.
  • Pipeline: redirect service → Kafka → ClickHouse Kafka engine or a consumer writing 10K-row batches every second. Freshness ~5 s; good enough for a stats page that says "updated a moment ago".
  • Cost: 3 nodes with 2 TB NVMe each hold two years with replication, versus a sharded Postgres fleet just for reporting.

Variants and when each wins

Self-managed column store (ClickHouse, Druid, Pinot)

  • A cluster you run that ingests from Kafka in real time and answers queries over billions of rows in under a second. It wins for product-facing analytics where freshness and latency matter; Druid and Pinot lean toward dashboards, ClickHouse toward general SQL.

Cloud warehouse (BigQuery, Snowflake, Redshift)

  • Storage and compute are separate and billed per query or per warehouse-hour, with no cluster to run. It wins for internal analysts who run a few big queries; it loses for a user-facing stats page, where seconds of latency and per-query billing at high QPS are both wrong.

Lakehouse (Parquet in object storage + Trino, Spark, Iceberg)

  • Raw events kept as open-format files in object storage, queried by whichever engine you point at them. It wins for cheap long-term retention and batch jobs; interactive latency is worse than a warehouse.

Read replica of the OLTP database

  • A copy of the transactional database that takes the reporting queries. It wins only as a stopgap: it protects the primary, but it is still row storage, so big scans are still slow and still hog the replica.

Use ClickHouse or Druid for product-facing analytics with real-time ingestion; a cloud warehouse for internal analysts; a lakehouse for long-term raw retention. A replica is only a stopgap.

Failure modes

Pipeline lag becomes user-visible

  • You notice a creator seeing zero views on a video that went viral an hour ago. It happens because the analytics store is loaded by a batch job once an hour, so the dashboard lags by up to an hour. Stream events through Kafka in small batches so the lag is seconds, and show an "as of" timestamp so the remaining delay reads as honest rather than broken.

Small inserts

  • You notice the column store slowing down and its file count climbing. It happens because each insert of one row creates a tiny new file part, and the engine must merge thousands of them in the background. Batch inserts to thousands of rows, letting a buffer table or the Kafka consumer accumulate them.

Using it as a serving store

  • You notice the stats API's p99 rising to seconds under load. It happens because thousands of concurrent small queries are hitting an engine built to run a few large scans at a time. Materialise the per-alias daily counts into a key-value store or a compact pre-aggregated table, and serve the API from that.

Wrong sort key

  • You notice a query filtered by referrer scanning every row. It happens because the data is sorted by (alias, ts), which lets the engine skip blocks for an alias filter but not for a referrer filter. Add a projection or a second copy of the table sorted by referrer, or a materialised view grouped by referrer.

Duplicates from at-least-once delivery

  • You notice counts running 1–2% high after a consumer restart. It happens because the stream redelivered a batch the consumer had already written, and the column store appended it again. Deduplicate on an event id within a time window, use the engine's replacing merge so the later copy wins, or document the counts as approximate.

Interviewer follow-ups

Answer out loud before you open each one.

Why are column stores so much faster for aggregates?

A sum over one column reads only that column, which is contiguous and compressed, instead of every byte of every row. Sorted blocks carry min and max so whole ranges are skipped, and the engine processes thousands of values per CPU instruction batch. Row stores pay for columns they never use.

How fresh can analytics be?

Seconds, if you stream through Kafka and insert in batches of a few thousand rows. The limit is the batch interval, not the engine. Hourly batch is only acceptable for internal reports.

How do you serve per-user stats at high QPS from analytics data?

Do not query the column store per request. A scheduled or streaming job writes the per-entity aggregates (clicks per alias per day) into a key-value store or a compact table, and the API reads that. The OLAP store answers the ad-hoc questions.

How do you handle updates and deletes in a column store?

Badly, by design. Model events as immutable facts and derive state by aggregation. Corrections become compensating events; GDPR deletes become a partition rewrite or a periodic merge that drops flagged rows.

Connections

Built on
Bitmap index · Inverted index
Pairs with
Keep events as a replayable log · React to database changes · Compute over events as they arrive · Process large data offline · Count big things with small memory
Pulls against
Default to a relational database · Key → value at any scale
Used in
URL Shortener (TinyURL / bit.ly) · Video Streaming Platform (YouTube / Netflix)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingRedirect service, Stats APICompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon MSK (Kafka)Kafka: clicksManaged Service for Apache KafkaEvent Hubs (Kafka API)Confluent Cloud, Redpanda
Amazon ElastiCacheSummary KVMemorystoreAzure Managed RedisRedis, Valkey, Memcached