Skip to content

Data Pipelines, Warehouses and Lakes

Intermediate 56 min read Part 8 of 18

How data moves from production databases into analytics: OLTP vs OLAP, ETL vs ELT, warehouses, lakes and lakehouses, Parquet, real-time OLAP and Airflow.

Summary#

Production databases are built for OLTP (online transaction processing): many small reads and writes of individual rows, such as "place this order". Analytics needs OLAP (online analytical processing): a few huge queries that scan and aggregate millions or billions of rows, such as "revenue per country per week". One database rarely does both well, so companies copy data out of production systems into analytics systems through a data pipeline. ETL transforms data before loading it. ELT loads raw data first and transforms it inside the warehouse, which is the modern default. A data warehouse (Snowflake, BigQuery, Redshift) stores clean, structured tables in columnar format for fast SQL. A data lake stores raw files of any kind cheaply in object storage, often as Parquet. A lakehouse adds table formats (Iceberg, Delta Lake, Hudi) that give lake files warehouse-like transactions. When results must be fresh within seconds and queried by many users, real-time OLAP stores (ClickHouse, Druid, Pinot) ingest from Kafka and pre-aggregate on ingest. Orchestrators such as Airflow schedule and track the many steps. Every cloud offers the same building blocks under different names.

Why It Exists#

Imagine an online shop with a PostgreSQL database holding orders, customers and products. The finance team asks, "What was revenue per product category per week for the last two years, split by country?" Someone runs that query on the production database. It scans 200 million order rows, joins them with products and customers, and runs for 20 minutes. During those 20 minutes, it uses most of the disk bandwidth and a large share of the CPU. Checkout latency rises from 50 ms to 2 seconds, and customers abandon their carts. That is the first reason analytics moves elsewhere: heavy analytical queries hurt the transactional workload.

The second reason is that the data needed for analysis lives in many places. Orders are in PostgreSQL, payments in a payment provider's API, clicks in Kafka, support tickets in a SaaS tool, and marketing spend in spreadsheets. No single production database holds it all, and no production database should be joined with another company's API at query time. Analysis needs one place where all of it lands, cleaned and joined.

The third reason is history. A production database stores current state: the customer's current address, the product's current price. Analysts want history: what the price was when each order was placed, how many customers lived in each city last year. Analytics systems keep that history deliberately.

The fourth reason is shape. A row-oriented database stores each order's fields together, which is perfect for "fetch order 42" and wasteful for "sum the amount of every order", which needs one column out of fifty. Analytics systems store data by column, compress it heavily, and scan it in parallel across many machines, so the same query that took 20 minutes on production finishes in a few seconds.

A data pipeline is the plumbing that moves data from where it is created to where it is analysed, transforming it on the way, reliably and on a schedule or continuously.

How It Works#

A typical analytics platform has five stages. Data is produced by applications and databases, ingested into a landing area, stored in a lake or warehouse, transformed into clean, modelled tables, and served to dashboards, analysts, machine-learning jobs and sometimes back to applications.

The rest of this page goes through each piece: why analytics needs a different kind of database, how columnar storage makes it fast, the ETL and ELT patterns, warehouses, lakes and lakehouses, real-time OLAP stores, orchestration, and how a full pipeline looks on each major cloud.

OLTP versus OLAP#

OLTP systems run the business. They handle many concurrent, short transactions that read or write a few rows by key: create an order, update a balance, fetch a profile. They need low latency (milliseconds), high concurrency (thousands of transactions per second), and strong guarantees (ACID transactions, see ACID and Isolation Levels). PostgreSQL, MySQL, Oracle, SQL Server, DynamoDB and Cassandra are OLTP systems.

OLAP systems analyse the business. They handle relatively few, very large queries that scan many rows, usually only some columns, and aggregate them: sums, counts, averages, group-bys, joins across large tables. They need high scan throughput (gigabytes per second) more than low latency per row, and they are mostly read-only, loaded in bulk.

PropertyOLTPOLAP
Typical queryFetch or update one order by IDSum revenue by country and week over 2 years
Rows touched per query1 to a few hundredMillions to billions
Columns touchedMost columns of a few rowsA few columns of many rows
WritesMany small, concurrent inserts and updatesBulk loads, appends, periodic merges
Latency target1 to 50 ms100 ms to minutes
ConcurrencyThousands of usersTens to hundreds of analysts, or many dashboard queries
Data volumeGB to a few TB of current stateTB to PB including history
Storage layoutRow-oriented, B-tree indexesColumn-oriented, compressed, partitioned
Schema styleNormalised, to avoid update anomaliesDenormalised star schemas, for fast joins and simple queries
ExamplesPostgreSQL, MySQL, DynamoDBSnowflake, BigQuery, Redshift, ClickHouse, Druid

OLTP versus OLAP, in depth#

Why a row store is slow for analytics, with numbers. Take an orders table with 200 million rows and 40 columns, averaging 400 bytes per row, about 80 GB. The query "total amount per country for 2025" needs three columns: date, country and amount, about 20 bytes per row. A row store must read every page of the table, because each page holds whole rows: 80 GB of I/O. At 1 GB/s from a fast SSD, that is 80 seconds, before any CPU work, and it evicts the hot working set of checkout from the buffer cache. A column store reads only the three columns, 4 GB uncompressed, and with typical compression of 5 to 10 times, under 1 GB. Spread across 16 machines, each reads about 60 MB. The same query finishes in well under a second. Nothing about the hardware changed. Only the layout did.

Indexes do not rescue a row store here. A B-tree index helps when a query selects a small fraction of rows. An aggregate over all of 2025 selects most of the table, so the database correctly ignores indexes and scans. Covering indexes for every analytic query would multiply write cost on the OLTP path, which is exactly the path that must stay fast.

Star schemas. Analytics tables are usually modelled as a star schema, from Ralph Kimball's dimensional modelling approach:

  • A fact table in the centre holds one row per business event, with numeric measures and foreign keys. For example, fact_orders has order ID, date key, customer key, product key, quantity and amount. Fact tables are long (billions of rows) and narrow.
  • Dimension tables around it describe the context of each event: dim_date (day, week, month, holiday flag), dim_customer (country, segment, signup channel), dim_product (category, brand). They are short (thousands to millions of rows) and wide.

Queries join the fact table to a few dimensions, filter on dimension attributes, and aggregate measures. "Revenue by category and month for customers in Germany" is one fact table, three small joins and a group-by. A snowflake schema normalises the dimensions further, for example splitting category out of product. It saves a little space but adds joins, so most teams keep dimensions flat. Some modern warehouses go further and denormalise everything into one big table (OBT), because columnar compression makes repeated values cheap and avoids joins entirely, at the cost of rebuilding the table when a dimension changes.

Keeping history: slowly changing dimensions. If a customer moves from France to Germany, should last year's orders count as French or German? The OLTP database only knows the current address. Dimensional modelling answers with slowly changing dimension (SCD) types. Type 1 overwrites the old value, so history is rewritten to the new country. Type 2 adds a new row for the customer with a new surrogate key and valid_from and valid_to dates. Old orders keep pointing to the old row, so they stay French, and new orders point to the new row. Type 2 is the usual choice when history matters. Building it requires capturing every change to the customer table, which is a natural use of Change Data Capture.

A separate analytics database for a product feature. Analytics is not only for internal analysts. An ad platform must show each advertiser their clicks per minute. One sound design writes raw click events into a write-optimised event store, such as Cassandra, which uses an LSM tree: writes go to a commit log and an in-memory memtable, then are flushed to sorted SSTables. That structure absorbs high write rates, but it is poor at range scans and aggregations. So every few minutes a Spark job reads the new raw events, aggregates them by ad ID and minute, and writes the results into an OLAP database such as Redshift, Snowflake or BigQuery, where a table of (ad ID, minute, clicks) answers advertiser queries quickly. At 10,000 clicks per second and a 5-minute interval, each run handles about 3 million events, roughly 300 MB, small enough for one machine. Spark still earns a place as a familiar map-reduce framework that can grow with the data. The weakness is freshness and spikes: data is always minutes old, and a surge of clicks makes the next batch bigger, so it may overrun its interval and fall further behind exactly during a big campaign. A queue in front of the event store absorbs write spikes but does not fix latency. Replacing the batch step with a stream processor writing to the OLAP store fixes both, as described in Batch vs Stream Processing.

OLAP versus a time-series database. For per-minute metrics, a time-series database such as InfluxDB or TimescaleDB looks tempting. TSDBs shine for "the value of metric X over time range Y", with a modest number of distinct series. An ad platform has millions of ad IDs, and advertisers soon want to slice by device, country and campaign as well. That is high-cardinality, multi-dimensional querying, which OLAP stores handle far better. If the requirement is only simple time-range queries over a single metric, a TSDB is a perfectly reasonable answer. See Time-Series Databases for how they work.

HTAP. Some systems try to serve both workloads from one product, called hybrid transactional and analytical processing. Examples include SingleStore, TiDB with its TiFlash columnar replicas, and Oracle and SQL Server with in-memory column stores. They keep a row-format copy for transactions and a column-format replica for analytics, kept in sync internally. They remove a pipeline for operational analytics on one database's data, but they do not replace a warehouse that combines many sources and years of history.

Columnar storage and Parquet#

A row-oriented store writes all of a row's fields next to each other on disk: order 1's ID, date, country and amount, then order 2's, and so on. A column-oriented store writes all values of one column together: every order's date, then every order's country, then every amount. Three things follow from that simple change:

  • Read only what you need. A query that uses 3 columns out of 40 reads about 3/40 of the data.
  • Much better compression. Values in one column have the same type and often repeat or change slowly. A country column contains a few hundred distinct values repeated millions of times, which compresses dramatically. Columnar files are commonly 5 to 10 times smaller than the same data as CSV or JSON.
  • Faster CPU work. The engine can process a column as a tight array of same-typed values, many at a time, using SIMD (single instruction, multiple data) instructions, instead of interpreting one row object at a time.

The trade-off is writes. Inserting or updating one row means touching every column file. So columnar systems batch writes: they buffer incoming rows, write them as a new chunk of column data, and merge chunks in the background. That suits analytics, which loads data in bulk and rarely updates single rows.

Apache Parquet is the standard open columnar file format for data lakes. It was created in 2013 by engineers at Twitter and Cloudera, based on the design in Google's paper "Dremel: Interactive Analysis of Web-Scale Datasets" by Sergey Melnik and colleagues (VLDB 2010). Almost every analytics engine reads it: Spark, Trino, Athena, BigQuery, Snowflake, Redshift Spectrum, DuckDB, ClickHouse and pandas. Apache ORC, from the Hive project, is a similar format, common in Hadoop-era systems. Apache Arrow is the matching in-memory columnar format, used to pass data between engines and languages without converting it.

Columnar storage and Parquet, in depth#

Inside a Parquet file. A file is split horizontally into row groups (often 64 to 128 MB of data each). Inside a row group, each column is stored as a column chunk, which is split into pages of about 1 MB, the unit of encoding and compression. At the end of the file, a footer stores the schema, the location of every column chunk, and statistics per row group and column: minimum, maximum and null count. A reader first reads the footer, then fetches only the column chunks it needs, from only the row groups that can match.

Encodings, before compression. Parquet first encodes values to exploit their structure, then optionally compresses the result with a general codec (Snappy, ZSTD or gzip).

  • Dictionary encoding replaces each value with a small integer ID into a per-chunk dictionary. A country column with 200 distinct values needs only 8 bits per value instead of a string.
  • Run-length encoding (RLE) stores repeated values as (value, count). If the data is sorted by country, a million consecutive "DE" values become a single pair.
  • Bit packing stores small integers in the minimum number of bits.
  • Delta encoding stores the differences between consecutive values, which suits timestamps and increasing IDs: a column of timestamps one second apart becomes a column of small numbers.

Predicate pushdown and pruning. For WHERE order_date >= '2025-06-01', the reader checks each row group's min and max for order_date, and skips any row group whose maximum is earlier. That only works well if the data is sorted or clustered by the filtered column, because then each row group covers a narrow range. If dates are randomly mixed, every row group spans the whole year, and nothing can be skipped. Writing data sorted by the most common filter, such as date then customer, is one of the cheapest large speed-ups in analytics. Bloom filters, which Parquet also supports per column chunk, help with equality filters on high-cardinality columns such as user ID, where min and max are useless.

A worked example. A table of 1 billion events with 50 columns is about 500 GB as JSON. As Parquet with ZSTD, it is about 60 GB. A query reads 3 columns for the last 7 days of a 365-day table, partitioned by date. Partition pruning keeps 7/365 of the files, about 1.2 GB. Column pruning keeps about 3/50 of that, around 70 MB. Row group statistics may skip more. The engine reads 70 MB instead of 500 GB, roughly seven thousand times less. This is why "store as Parquet, partition by date, sort by the main filter" is the first advice for any data lake.

Nested data. Dremel's contribution was a way to store nested, repeated fields (like JSON with arrays) in columns without flattening them. For each value, it records two small integers. The repetition level says at which level of nesting a new list starts, and the definition level says how many optional fields along the path are actually present. Together they let a reader rebuild the original records from the columns. Parquet adopted this encoding, which is why it handles nested event data well.

The small files problem. Streaming ingestion naturally writes many small files, such as one file per partition per minute. A table with millions of 1 MB files is slow to query, because the engine spends more time listing and opening files, and reading footers, than reading data. Object storage also charges per request. Aim for files of roughly 128 MB to 1 GB, and run compaction jobs that rewrite small files into large ones. Lakehouse table formats, described below, make compaction safe while queries run.

Vectorised execution and late materialisation. Column stores process data in batches of a few thousand values per column, called vectors, through each operator, which keeps data in the CPU cache and lets the compiler use SIMD. This idea comes from the MonetDB/X100 work by Peter Boncz, Marcin Zukowski and Niels Nes ("MonetDB/X100: Hyper-Pipelining Query Execution", CIDR 2005), which became the Vectorwise engine. Late materialisation means the engine applies filters on the filter columns first, keeping a list of matching row positions, and only then reads the other columns for those positions. The academic foundation for column stores as full databases is "C-Store: A Column-oriented DBMS" by Michael Stonebraker and colleagues (VLDB 2005), whose ideas went into the commercial Vertica database.

Columnar is not only for files. Warehouses use their own internal columnar formats: Snowflake's micro-partitions, BigQuery's Capacitor format, Redshift's column blocks, and ClickHouse's MergeTree parts. The principles are the same: store by column, encode and compress, keep min and max per block, and skip what cannot match.

ETL versus ELT#

Every pipeline does three things: extract data from sources, transform it (clean, join, deduplicate, aggregate, reshape into a model), and load it into the analytics store. The order of the last two steps defines the two main styles.

ETL (extract, transform, load) transforms data on a separate processing system before loading it. This was the norm when warehouses were expensive, on-premises appliances with limited compute and storage: you only loaded data that was already clean and in its final shape. Tools like Informatica and Talend, or custom Spark jobs, did the transformation.

ELT (extract, load, transform) loads raw data into the warehouse or lake first, almost unchanged, and then transforms it there, with SQL running on the warehouse's own scalable compute. Cloud warehouses made this practical: storage became cheap, compute scales on demand, and SQL is the language most analysts already know. Tools like Fivetran, Airbyte and Debezium handle the extract-and-load part, and dbt (data build tool) manages the transformations as version-controlled SQL models.

AspectETLELT
Where transformation runsA separate engine before the warehouseInside the warehouse or lakehouse
Raw data kept?Often not; only the transformed result is loadedYes, so you can re-transform history when logic changes
Who writes transformationsData engineers, in code or ETL toolsAnalysts and analytics engineers, mostly in SQL
FlexibilityChanging logic means reprocessing from sourcesRerun the SQL model over the raw tables
Good forSensitive data that must be masked before landing; heavy non-SQL processing; constrained targetsMost modern cloud analytics
RiskPipelines become a bottleneck owned by one teamWarehouse cost grows with careless SQL; raw data includes sensitive fields unless controlled

ETL and ELT, in depth#

Why ELT won for most teams. Keeping raw data means a mistake in transformation is never fatal. You fix the SQL and rebuild the model from the raw tables. With ETL, if the transform dropped a field, it is gone, and you must re-extract from sources that may no longer have the history. ELT also shortens the path from question to answer, because an analyst can write a new model without a data engineer building a new pipeline.

When ETL is still right. Transform before loading when data must be cleaned of sensitive fields before it lands anywhere broad, such as hashing emails or dropping card numbers. Also when the transformation is not SQL-friendly, such as parsing images, running ML inference, or heavy text processing, and when the target is a small or expensive store that should only receive final aggregates, such as a real-time OLAP table fed with per-minute counts. In practice, most platforms mix the two: light ETL at ingestion (parse, validate, mask), then ELT for modelling.

Layers of tables. ELT platforms usually organise tables in layers. One common naming is the medallion architecture, popularised by Databricks:

  • Bronze (raw): data as it arrived, append-only, including duplicates and errors. Kept for replay and audit.
  • Silver (cleaned): deduplicated, typed, validated, with consistent keys. One row per real entity or event.
  • Gold (business): modelled for consumption, such as star schemas, aggregates, metrics tables.

Other teams use "staging, intermediate, marts". The names do not matter. The principle is to separate "what arrived" from "what we believe" from "what we report".

Incremental models and idempotency. Rebuilding a 10 TB table every hour is wasteful. Incremental models process only new or changed data since the last run, then merge it into the target. Two rules keep them correct. First, process by time partition and replace the whole partition on each run, so reruns are idempotent (see Batch vs Stream Processing). Second, reprocess a small lookback window, such as the last 3 days, on every run, so that late-arriving rows are picked up. Where rows change in place, as with CDC from an OLTP table, use a MERGE keyed by the primary key and ordered by the change's log position.

-- dbt-style incremental model: daily revenue, rebuilt for recent days only
-- Runs hourly; reprocesses the last 3 days to absorb late or corrected orders
MERGE INTO gold.daily_revenue AS t
USING (
  SELECT o.order_date,
         c.country,
         p.category,
         SUM(o.amount)              AS revenue,
         COUNT(DISTINCT o.order_id) AS orders
  FROM silver.orders o
  JOIN silver.customers c ON c.customer_id = o.customer_id
  JOIN silver.products  p ON p.product_id  = o.product_id
  WHERE o.order_date >= CURRENT_DATE - INTERVAL '3' DAY
    AND o.status = 'completed'
  GROUP BY o.order_date, c.country, p.category
) AS s
ON  t.order_date = s.order_date
AND t.country    = s.country
AND t.category   = s.category
WHEN MATCHED THEN UPDATE SET revenue = s.revenue, orders = s.orders
WHEN NOT MATCHED THEN INSERT (order_date, country, category, revenue, orders)
  VALUES (s.order_date, s.country, s.category, s.revenue, s.orders);

Extracting from production safely. There are three common ways to get data out of an OLTP database:

  • Full dumps of small tables every night. Simple, but the load grows with the table, and changes between dumps are invisible.
  • Incremental queries on an updated_at column. Cheap, but they miss hard deletes, and they miss rows whose timestamp was not updated correctly.
  • Log-based CDC (Debezium reading the PostgreSQL WAL or MySQL binlog). It captures every insert, update and delete in order, with little load on the source. This is the default for large or important tables. See Change Data Capture.

Always read from a replica or the log, never with heavy queries against the primary.

Data quality is part of the pipeline. A pipeline that silently loads wrong data is worse than one that fails. Add tests at each layer: primary keys unique and not null, foreign keys resolving, row counts within expected ranges compared with yesterday, values within valid ranges, and freshness ("the latest order is less than 2 hours old"). dbt tests, Great Expectations and Soda are common tools. Failed tests should block the downstream models and alert the owner, rather than publish broken dashboards. A data contract between a producing team and the data team, a versioned schema plus guarantees about meaning and freshness, prevents the most common breakage: an upstream team renaming a column without telling anyone.

Reverse ETL. Modelled data increasingly flows back into operational tools: customer segments pushed from the warehouse into the CRM, or churn scores pushed into a support tool. Tools such as Hightouch and Census do this. It closes the loop, but it means warehouse tables now have operational consumers, with the freshness and reliability expectations that come with them.

Data warehouses#

A data warehouse is a database designed for OLAP: columnar storage, massively parallel query execution, SQL, and support for large joins and aggregations over structured tables. Modern cloud warehouses add separation of storage and compute: data lives in cheap, durable object storage, and compute clusters are started, resized and stopped independently. The three most common are Snowflake, Google BigQuery and Amazon Redshift.

Snowflake runs on AWS, Azure and GCP. Data is stored in object storage as compressed, columnar micro-partitions of roughly 50 to 500 MB uncompressed, each with min and max metadata per column. Queries run on virtual warehouses, which are compute clusters you size (X-Small to 6X-Large) and pay for per second while running. Several virtual warehouses can read the same data at once without competing, so the finance team's heavy queries never slow down the dashboards. Its design is described in "The Snowflake Elastic Data Warehouse" by Benoit Dageville and colleagues (SIGMOD 2016). It also supports zero-copy clones of tables, time travel over recent history, and secure data sharing between accounts.

Google BigQuery is serverless: there are no clusters to manage. You load data or point it at files, and run SQL. Its query engine descends from Dremel, and it stores data in a columnar format called Capacitor on Google's distributed file system. Queries are executed by a large shared pool of workers, with Google's fast data-centre network handling the shuffle. Pricing is either on-demand, billed by bytes scanned, or capacity-based, by reserved compute slots. Because on-demand billing follows bytes scanned, partitioning by date and clustering by common filters directly reduce cost, and SELECT * on a big table is literally expensive.

Amazon Redshift started as a cluster-based MPP (massively parallel processing) warehouse. A leader node plans queries, and compute nodes each store a slice of every table and execute in parallel. Table design matters: the distribution style (KEY, EVEN or ALL) decides how rows spread across nodes, and sort keys decide on-disk order, which drives block skipping. Newer RA3 node types separate compute from managed storage on S3, and Redshift Serverless removes cluster management. Redshift Spectrum queries Parquet files in S3 directly. Its history and design choices are described in "Amazon Redshift and the Case for Simpler Data Warehouses" by Anurag Gupta and colleagues (SIGMOD 2015).

WarehouseModelStrengthsWatch out for
SnowflakeVirtual warehouses over shared storage, multi-cloudWorkload isolation, easy scaling, sharing, little tuningCost of warehouses left running; credit consumption with many users
BigQueryServerless, pay per bytes scanned or per slotNo infrastructure, scales to PB, strong GCP integrationUnpartitioned scans cost money; slot contention under capacity pricing
RedshiftMPP cluster or serverless, deep AWS integrationPredictable cost on provisioned clusters, close to S3 and AWS toolsDistribution and sort key design; concurrency on small clusters
Azure Synapse and Microsoft FabricDedicated SQL pools, serverless SQL, and SparkMicrosoft ecosystem, Power BI integrationSeveral overlapping products to choose between
Databricks SQLSQL warehouses over Delta Lake tablesLakehouse on open formats, strong Spark and ML integrationRequires lakehouse table maintenance

Data warehouses, in depth#

How an MPP query runs. Take SELECT country, SUM(amount) FROM fact_orders JOIN dim_customer USING (customer_key) GROUP BY country. The planner splits it into stages. In stage 1, every worker scans its portion of fact_orders, reading only customer_key and amount, and pruning blocks by metadata. Because dim_customer is small, it is broadcast to all workers, which join locally. Each worker computes a partial aggregate per country. In stage 2, the partials are shuffled by country, so each country's partials meet on one worker, and summed. The final result is returned through the coordinator. Every stage runs in parallel, and only small partial results cross the network. When both join sides are large, the planner instead repartitions both by the join key, an expensive shuffle. That is why Redshift lets you choose a distribution key matching the common join, so that matching rows already live on the same node.

Separation of storage and compute changes the economics. With storage in object storage, you pay for storage continuously, which is cheap, and for compute only while queries run. A nightly job can run on a large cluster for 20 minutes and then stop. Dashboards can use a small, always-on cluster. Because compute nodes are stateless with respect to the data, they cache hot data on local SSDs, which is why the first query after resuming a warehouse is slower than the second.

Micro-partition pruning and clustering. Snowflake keeps min and max values for every column in every micro-partition, in its metadata service. A query filtering on order_date checks the metadata first and reads only partitions whose range overlaps. As data arrives in time order, date pruning works naturally. Filtering by customer_id does not, because every partition contains a wide range of customers. Defining a clustering key makes the service reorganise data in the background so that partitions cover narrow ranges of that key. BigQuery's partitioning plus clustering, and Redshift's sort keys, serve the same purpose.

Concurrency and workload isolation. A warehouse that serves both a nightly batch and 200 analysts' dashboards needs isolation. Options include separate virtual warehouses in Snowflake, separate reservations in BigQuery, workload management queues and concurrency scaling in Redshift, and result caches that return the same answer instantly for repeated identical queries. For user-facing analytics with thousands of concurrent queries and sub-second latency targets, a general warehouse is usually the wrong tool. That is the job of the real-time OLAP stores described below.

Cost control is a design concern. Warehouse bills scale with bytes scanned or compute time, so design choices show up on the invoice. Partition every large table by date. Cluster or sort by the main filter. Avoid SELECT *. Materialise expensive, frequently used aggregates instead of recomputing them for every dashboard view. Set auto-suspend on idle compute, and set query limits and budgets per team. A single dashboard that scans a 50 TB table on every refresh, every 5 minutes, can cost more than the rest of the platform.

Data lakes and the lakehouse#

A data lake is a large store of raw files in object storage (Amazon S3, Google Cloud Storage, Azure Data Lake Storage), holding data of any kind: Parquet and JSON event files, CSV exports, logs, images, model checkpoints. It is schema-on-read: files are written as they come, and a schema is applied only when a query reads them. A warehouse is schema-on-write: data must fit a table's schema when it is loaded. Lakes are cheap (object storage costs a few cents per GB per month), scale without limit, and can be read by many engines: Spark, Trino, Athena, Flink, and ML frameworks.

A metastore or catalog, such as the Hive Metastore, AWS Glue Data Catalog or Unity Catalog, records which files make up which table, their schema and partitions, so that engines can query the files as tables.

Plain lakes have well-known problems. There are no transactions, so a reader can see a half-written set of files while a job is writing. Updating or deleting rows means rewriting files by hand, which makes privacy deletions (such as GDPR erasure requests) painful. Listing millions of files in object storage to plan a query is slow. And without discipline, a lake turns into a data swamp: thousands of undocumented folders that nobody trusts.

The lakehouse fixes these problems by adding a table format, a metadata layer over Parquet files that provides warehouse-like features on the lake. The three open table formats are:

  • Apache Iceberg, created at Netflix.
  • Delta Lake, created at Databricks.
  • Apache Hudi, created at Uber.

They provide ACID transactions, consistent snapshots for readers, row-level updates and deletes, schema evolution, time travel to earlier versions, and efficient planning without listing files. The term and the argument for it are laid out in "Lakehouse: A New Generation of Open Platforms that Unify Data Warehousing and Advanced Analytics" by Michael Armbrust, Ali Ghodsi, Reynold Xin and Matei Zaharia (CIDR 2021), and Delta Lake's design is described in "Delta Lake: High-Performance ACID Table Storage over Cloud Object Stores" (VLDB 2020).

AspectData warehouseData lakeLakehouse
StorageProprietary columnar format, managedOpen files in object storageOpen files plus an open table format
SchemaOn write, enforcedOn read, looseOn write for tables, with evolution
TransactionsYesNoYes, via metadata commits
Updates and deletesEasyRewrite files by handSupported (copy-on-write or merge-on-read)
EnginesThe warehouse's ownAny engine that reads the filesAny engine with table-format support
CostHigher per TB, includes compute optimisationLowestLow storage, compute chosen separately
Best forBI and SQL analytics on clean dataRaw archive, ML data, unstructured filesOne platform for BI, ML and streaming on open data

Lakes and lakehouses, in depth#

How a table format provides transactions on object storage. Object storage has no multi-file transactions, but it does offer atomic writes of a single object, and conditional writes or atomic renames, depending on the store. Table formats build transactions on that. Take Iceberg:

  • Data lives in ordinary Parquet files, which are never modified once written.
  • Manifest files list data files, with each file's partition values and per-column statistics.
  • A manifest list lists the manifests that make up one snapshot of the table.
  • A table metadata file records the schema, the partition spec, and the list of snapshots, including which snapshot is current.
  • The catalog holds a pointer to the current metadata file.

A write creates new data files, new manifests, a new manifest list and a new metadata file, and then atomically swaps the catalog pointer from the old metadata file to the new one. If two writers race, only one swap succeeds, and the other retries on top of the new snapshot. This is optimistic concurrency control (see Concurrency Control and Locking). Readers use whichever snapshot was current when they started, so they never see half-written data. Old snapshots remain readable until they are expired, which gives time travel: "query this table as of yesterday at 09:00".

Delta Lake follows the same idea with a different layout: an ordered transaction log of JSON commit files in a _delta_log folder, with periodic Parquet checkpoints that summarise the log. Hudi keeps a timeline of commits and organises files into file groups keyed by record key, which suits frequent upserts.

Planning without listing. On a plain lake, the engine lists the folder date=2026-12-01/ to find files, and listing millions of objects is slow. With a table format, the engine reads the manifests, which already list the files and their column statistics. It can prune files by any column's min and max, not just the partition column, before opening a single data file.

Row-level changes: copy-on-write versus merge-on-read.

  • Copy-on-write rewrites each affected data file with the change applied. Reads stay fast, but writes are expensive. Updating one row in a 512 MB file rewrites 512 MB.
  • Merge-on-read writes small delete files (listing deleted rows by position or key) or log files of changes, and readers merge them with the base files at query time. Writes are cheap, and reads pay a cost until compaction folds the changes into new base files.

CDC ingestion with many updates favours merge-on-read plus regular compaction. Tables that are written in bulk and read heavily favour copy-on-write.

Schema and partition evolution. Table formats track columns by ID, not by name or position, so renaming a column or adding one does not require rewriting data. Iceberg also supports hidden partitioning: the table is declared as partitioned by day(event_time), and queries that filter on event_time are pruned automatically, without users needing to know about a separate date column. The partition scheme can even change over time, for example from daily to hourly, with old data keeping its old layout.

Maintenance is part of owning a lakehouse. Streaming writes create many small files and many snapshots. Run regular jobs to compact small files, expire old snapshots (keeping, say, 7 days for time travel), and remove orphan files left by failed writes. Without these, query planning slows down and storage costs grow. Managed services (Databricks, Snowflake's Iceberg tables, AWS S3 Tables, BigQuery's Iceberg support) increasingly automate them.

Privacy deletion on a lake. A user asks to be forgotten. On a plain lake, you must find every file containing their rows and rewrite it. On a lakehouse, you run DELETE FROM events WHERE user_id = 42, which writes delete files or rewritten files in a new snapshot. But the old snapshots still contain the data, so the deletion is complete only after those snapshots expire and the old files are physically removed. Your retention settings must therefore fit within the legal deadline for erasure.

Query engines on the lake. Trino (and its predecessor Presto, created at Facebook) is a distributed SQL engine that queries files and table formats directly, with no storage of its own. Amazon Athena is a managed service based on Trino. Spark SQL serves heavy batch transformations. DuckDB runs analytical SQL in-process on one machine, and is surprisingly capable for datasets up to hundreds of GB. Because the data is open, teams can use the best engine for each job on the same tables.

Real-time analytics stores#

Warehouses are built for analysts running heavy queries, with latency of seconds and tens of concurrent users. Some products need analytics that are fresh within seconds, answered in tens of milliseconds, and served to thousands of concurrent users: an advertiser's campaign dashboard, a "who viewed your profile" page, a restaurant's live order metrics, a top-K list of trending videos. Real-time OLAP stores fill that gap. The three best known are:

  • ClickHouse, created at Yandex for its web analytics product, Yandex.Metrica, and open-sourced in 2016.
  • Apache Druid, created at Metamarkets for ad-tech analytics, described in "Druid: A Real-time Analytical Data Store" by Fangjin Yang and colleagues (SIGMOD 2014).
  • Apache Pinot, created at LinkedIn for member-facing analytics, and later adopted by Uber and others.

All three ingest directly from Kafka (or Kinesis), make new events queryable within seconds, store data in columns with indexes, and, most importantly, pre-aggregate data on ingest. They differ in how they pre-aggregate:

  • Druid does ingestion-time rollup. You declare dimensions (such as video ID) and a time granularity (such as one minute), and Druid groups incoming events by time bucket plus dimensions, storing pre-summed rows with count and sum aggregators. A million views of one video in one minute become a single row. Background compaction can re-roll older data at coarser grains, such as hours or days, which speeds up queries over long windows.
  • Pinot uses star-tree indexes and pre-aggregated views. A star-tree pre-computes aggregates for chosen combinations of dimensions, so a fixed query pattern such as GROUP BY video_id ORDER BY views DESC LIMIT K over a time window touches a small fraction of the data. You can also generate pre-aggregated offline segments per minute, hour or day in a batch job, and query the table that matches the window.
  • ClickHouse uses materialized views that run on every insert and write into SummingMergeTree or AggregatingMergeTree tables, which maintain per-minute, per-hour or per-day rollups. This moves work to the write path. Queries for fixed windows read the small rolled-up table and run ORDER BY views DESC LIMIT K.
-- ClickHouse: raw events plus a per-minute rollup maintained on insert
CREATE TABLE views_raw (
  video_id   UInt64,
  user_id    UInt64,
  event_time DateTime
) ENGINE = MergeTree
PARTITION BY toDate(event_time)
ORDER BY (video_id, event_time);
 
CREATE TABLE views_per_minute (
  minute   DateTime,
  video_id UInt64,
  views    UInt64
) ENGINE = SummingMergeTree
PARTITION BY toDate(minute)
ORDER BY (minute, video_id);
 
CREATE MATERIALIZED VIEW views_per_minute_mv TO views_per_minute AS
SELECT toStartOfMinute(event_time) AS minute, video_id, count() AS views
FROM views_raw
GROUP BY minute, video_id;
 
-- Top 100 videos in the last hour: sum again, because merges are background work
SELECT video_id, sum(views) AS v
FROM views_per_minute
WHERE minute >= now() - INTERVAL 1 HOUR
GROUP BY video_id
ORDER BY v DESC
LIMIT 100;

These systems are powerful, but at large scale they can be operationally demanding. Node failures, rebalancing and heavy compaction can push query latency past its targets, and that is true of nearly any system at this scale. If you propose one in an interview, be ready to explain its ingestion path step by step. An interviewer may say "I have not used Druid, walk me through what happens to an event", and you should be able to teach it.

Real-time analytics stores, in depth#

Druid's architecture. Druid splits responsibilities into process types. Ingestion tasks (managed by the Overlord) consume Kafka partitions, roll up events in memory, make them queryable immediately, and periodically hand off immutable segments (columnar files covering a time interval, typically an hour or a day) to deep storage such as S3. Historical processes download segments from deep storage and serve queries over them. The Coordinator decides which historicals hold which segments, and how many replicas. Brokers receive queries, find which real-time tasks and historicals hold the relevant time ranges, fan the query out, and merge the partial results. Dimensions have bitmap indexes, so a filter like country = 'DE' AND device = 'ios' becomes a fast AND of two compressed bitmaps. Because segments are immutable and stored in deep storage, losing a historical node loses no data; another node downloads the segments.

Rollup arithmetic. Suppose 700,000 view events per second arrive, across 5 million distinct videos per hour, but most views are concentrated: in a typical minute, only 1 million distinct videos are viewed. Raw storage would be 42 million rows per minute. Rolled up per minute and video, it is at most 1 million rows per minute, a 42-times reduction, and coarser rollups for older data shrink it further. Rollup loses the individual events, so you cannot later ask per-user questions of the rolled-up table. Keep raw events in the lake for that.

Pinot's table types. Pinot has real-time tables that consume from Kafka, and offline tables loaded from batch jobs, and it can combine both as a hybrid table. Queries for recent time ranges read the real-time segments, and older ranges read the offline segments produced by an accurate nightly job. This is the lambda architecture built into the database. Pinot also supports upserts on a primary key in real-time tables, useful when events update an entity's state, such as an order's status. Its index choices include inverted, sorted, range, text, JSON and geospatial indexes, plus the star-tree.

ClickHouse's MergeTree. Each insert writes a new immutable part, sorted by the table's ORDER BY key. Background merges combine parts into larger ones, like an LSM tree (see Storage Engines). The primary index is sparse: it stores the key of every 8,192nd row (a granule), so even a table of billions of rows has an index that fits in memory, and a range query reads only the matching granules. SummingMergeTree sums rows with the same key when parts merge, which happens at an unpredictable time. That is why queries must still use sum() and GROUP BY: at any moment, some rows are merged and some are not. ClickHouse prefers large, infrequent inserts, such as batches of 10,000 to 100,000 rows every second or so, rather than many single-row inserts, because each insert creates a part and too many parts slow merges and queries. Its Kafka engine or a buffering consumer handles that batching.

Choosing among them. ClickHouse is the simplest to start with: one binary, SQL, very fast scans, and good for both internal and user-facing analytics. Druid and Pinot have more moving parts, but are built around streaming ingestion, time-based segments, and high-concurrency serving, with tight query latency at thousands of queries per second. All three need careful choice of sort keys and rollups. If the query patterns are few and known in advance, any of them can serve them in milliseconds. If analysts need arbitrary ad hoc SQL over years of data, that is the warehouse's job.

A time-series database as the "good" answer. For top-K over fixed windows, a time-series extension such as TimescaleDB with continuous aggregates (automatically refreshed per-minute and per-hour rollups) is a reasonable step below a full real-time OLAP store. Notice how closely its design matches a streaming design: per-minute counts, rolled up to coarser windows, queried with order-by and limit. That is not a coincidence. The right design is usually the one that most directly expresses the ideal data flow, and the same flow can be implemented in a stream processor, in a database's rollups, or in both.

Derived data stores beyond analytics#

Pipelines also feed operational read stores, not just reports. The same principle applies: keep the source of truth in one system, and maintain specialised copies for specific access patterns. Three common cases show the benefits and the costs.

A search index for real-time queries. A dating app's feed needs "users within 10 km, aged 25 to 35, matching these preferences, not already swiped". Indexes on the most-used fields, especially a geospatial index on location, make that fast. A search-optimised store such as Elasticsearch or OpenSearch handles combined geo, range and text filters with low latency. The challenge is keeping it consistent with the primary database. Any delay or failed update means users see stale profiles or miss new matches. The standard answer is CDC from the primary database into the index (see Change Data Capture). Because search engines are optimised for reads rather than heavy writes, it often helps to batch updates, applying them every second or two instead of one at a time.

An in-memory store for ephemeral, high-rate data. A ride-hailing app receives driver locations every few seconds from hundreds of thousands of drivers. Writing each update to a disk database, or batching them through a pipeline, either overloads the database or leaves matching with stale positions. A better fit is an in-memory store with geospatial support, such as Redis. Redis encodes each latitude and longitude as a geohash turned into a 52-bit integer, used as the score in a sorted set whose members are driver IDs. GEOADD overwrites a driver's position, and GEOSEARCH (added in Redis 6.2, replacing GEORADIUS and GEORADIUSBYMEMBER) finds drivers within a radius or box. No batch processing is needed, because each update simply replaces the last. Stale drivers who went offline are removed by a periodic clean-up, for example using a second sorted set scored by last-update time and deleting entries older than 30 seconds from both sets. Durability is the weak point, but it matters little here. RDB snapshots or AOF persistence, plus Redis Sentinel for failover, reduce the risk, and even after total loss, the next round of updates rebuilds the whole state within about 5 seconds. See Geospatial Indexing.

Splitting data across two stores has a price. A grocery delivery service might keep orders in a relational database and inventory in a key-value store, each the best fit for its job. Placing an order then means: lock the inventory records, create the order, decrement inventory, release the lock. It has nasty failure modes. If the service crashes after creating the order but before decrementing inventory, another customer may be sold the same item, so a sweeper job must find and reverse half-finished orders. If two orders need overlapping items and lock them in different orders, they can deadlock: user 1 holds item A and waits for B, while user 2 holds B and waits for A. Ordering lock acquisition consistently (always by item ID) avoids the deadlock, and timeouts with retries reduce the damage. Often the simplest answer is to keep orders and inventory in one transactional database, so a single ACID transaction covers both, and to derive any other copies through CDC. See Distributed Locking and Distributed Transactions.

The lesson for pipelines: derived stores, whether a warehouse, a search index or a cache, should be downstream copies fed from a single source of truth, not peers that the application writes to in parallel.

Orchestration with Airflow#

A real platform runs hundreds or thousands of steps: extract 40 source tables, load them, run 300 SQL models in dependency order, test them, refresh dashboards, train a model, export segments. Cron on a single machine cannot express "run model B only after A and C have succeeded for the same day", retry failures, or show what is late. An orchestrator does.

Apache Airflow, created at Airbnb in 2014 by Maxime Beauchemin and now an Apache project, is the most widely used. Its core ideas:

  • A DAG (directed acyclic graph) defines a pipeline: tasks and the dependencies between them. DAGs are written as code, so they are versioned and reviewed like any other software.
  • A task is one unit of work, created from an operator: run this SQL, start this Spark job, call this API, copy these files. Sensors are tasks that wait for a condition, such as a file landing in S3 or an upstream DAG finishing.
  • The scheduler decides which task instances are ready, based on schedules and dependencies, and hands them to an executor (local processes, a Celery worker pool, or Kubernetes pods) to run.
  • A metadata database records every run, every task's state and every retry, which powers the web UI showing what ran, what failed and what is late.
  • Each run covers a data interval, such as 2026-12-01 00:00 to 2026-12-02 00:00. Tasks should process exactly that interval, not "whatever is new now", so that any run can be rerun, and backfills of past intervals produce the same result.
DAG daily_revenue   schedule: daily at 02:00 UTC   retries: 3, 5 min apart
  for each interval [start, end):
    wait_orders    = Sensor   "CDC has delivered silver.orders up to end"
    wait_payments  = Sensor   "partner payments file for start has landed"
    stage          = SQL      "load payments file into bronze.payments, partition = start"
    model_revenue  = SQL      "MERGE gold.daily_revenue for days [start - 3, end)"
    test_revenue   = Tests    "unique keys, no nulls, total within 30% of last week"
    publish        = Task     "refresh dashboards, notify finance channel"
 
  wait_payments >> stage
  [wait_orders, stage] >> model_revenue >> test_revenue >> publish

Alternatives include Dagster, which models pipelines around the data assets they produce and their freshness, Prefect, and managed or cloud-native services: AWS Step Functions and Amazon MWAA (managed Airflow), Google Cloud Composer (managed Airflow), and Azure Data Factory. dbt Cloud schedules dbt models, and many warehouses have their own scheduled queries and task graphs.

Orchestration, in depth#

Idempotent tasks are the foundation. Retries, backfills and manual reruns all assume that running a task twice for the same interval gives the same result. Write to a partition named after the interval, and overwrite it. Never "append whatever arrived since the last run", because a retry would double it.

Orchestrate, do not compute. Airflow workers should start work on systems built for it (a warehouse query, a Spark job, a Kubernetes job) and wait for the result. They should not process large data inside the worker. Small metadata can pass between tasks (Airflow calls this XCom), but data itself should pass through storage.

Time-based versus data-aware scheduling. "Run at 02:00" assumes the input is ready at 02:00. When an upstream source is late, the job runs on incomplete data. Better: make the first tasks sensors that check the input is complete, such as a CDC connector's high-water mark passing the interval's end or a _SUCCESS marker in the partition. Or use data-aware scheduling, in which a DAG runs when the datasets it depends on are updated. Sensors that poll should run in a mode that releases the worker slot between checks, otherwise hundreds of waiting sensors block real work.

Catch-up and backfills. If a DAG was paused for a week, should it run the 7 missed intervals when it resumes? Airflow's catchup setting decides. Backfilling 90 days after a logic change means 90 runs, which should be throttled with concurrency limits and pools, so that they do not overwhelm the warehouse or starve daily jobs.

SLAs and freshness. Measure what users care about: "the revenue dashboard reflects yesterday by 07:00". Alert when a task misses its expected finish time, not only when it fails. A task that hangs for 6 hours is often worse than one that fails at once.

Scaling the orchestrator. With thousands of DAGs, the scheduler's loop of parsing DAG files and checking dependencies becomes a bottleneck. Keep DAG files cheap to parse, without network calls or heavy imports at the top level. Run several schedulers (supported since Airflow 2), and use a Kubernetes executor, so that each task gets an isolated pod with its own resources.

A typical pipeline on AWS, GCP and Azure#

Every major cloud provides the same stages under different product names. The architecture matters more than the brand, but knowing the names helps when discussing a design on a particular cloud.

StageAWSGoogle CloudAzure
Event ingestionKinesis Data Streams, Amazon MSK (managed Kafka)Pub/Sub, Managed Service for Apache KafkaEvent Hubs
Database CDC and replicationDatabase Migration Service, MSK Connect with DebeziumDatastreamData Factory, Event Hubs with Debezium
Delivery to storageKinesis Data FirehoseDataflow templates, Pub/Sub subscriptions to BigQueryEvent Hubs Capture, Stream Analytics
Object storage (lake)S3Cloud StorageAzure Data Lake Storage Gen2
Stream processingManaged Service for Apache FlinkDataflow (Apache Beam)Stream Analytics, Databricks, Fabric Real-Time Intelligence
Batch processingEMR (Spark), Glue jobsDataproc (Spark), DataflowDatabricks, Synapse Spark, Fabric
WarehouseRedshift, Athena over S3BigQuerySynapse Analytics, Microsoft Fabric warehouse
Catalog and governanceGlue Data Catalog, Lake FormationDataplex, BigQuery catalogMicrosoft Purview, Unity Catalog on Databricks
OrchestrationMWAA (managed Airflow), Step FunctionsCloud Composer (managed Airflow), WorkflowsData Factory, Fabric pipelines
BI and dashboardsQuickSightLooker, Looker StudioPower BI

Snowflake and Databricks run on all three clouds, and many companies use them as the warehouse or lakehouse whatever the cloud.

On Google Cloud, the same picture uses Pub/Sub, Datastream for CDC, Dataflow for both streaming and batch, Cloud Storage for the lake, BigQuery as the warehouse (it can also write streaming inserts directly), Cloud Composer for orchestration, and Looker for dashboards. On Azure, it uses Event Hubs, Data Factory, Data Lake Storage Gen2, Databricks or Synapse Spark, Synapse or Fabric as the warehouse, and Power BI.

Cloud pipelines, in depth#

Sizing an event pipeline. A product emits 50,000 events per second at peak, 20,000 on average, each about 1 KB as JSON. That is about 1.7 billion events and 1.7 TB of JSON per day. As Parquet, it is around 200 GB per day, or about 73 TB per year. On Kinesis, a shard accepts up to 1 MB/s or 1,000 records per second for writes, so a 50 MB/s peak needs at least 50 shards, more with headroom, or on-demand capacity. On Kafka, a few brokers handle it easily; size partitions for consumer parallelism, for example 64. Firehose buffers data for up to a configurable size or time, such as 128 MB or 5 minutes, before writing a file, which keeps file counts sane. The lake grows by about 200 GB per day, and by the end of a year, storing all of it in standard object storage costs somewhere under two thousand US dollars a month at typical list prices, which is modest compared with query compute.

Latency budget of a typical batch path. Events wait up to 5 minutes in the delivery buffer, then the hourly Spark job runs at 10 minutes past the hour for about 15 minutes, then the dbt models run for 10 minutes, then the dashboards refresh. End to end, data is 30 to 90 minutes old. That is fine for most internal reporting. When a product needs seconds, add the streaming branch rather than trying to make every batch step run every minute.

Managed versus self-hosted. Managed services remove a great deal of operational work, such as upgrades, failover and scaling, at a higher unit price, and with limits you must design within (shard limits, maximum record sizes, API quotas). Self-hosting Kafka, Flink, Spark or ClickHouse on Kubernetes is cheaper at large scale, and gives control, but needs a team that knows how to run them. A common path is to start managed and move the most expensive components in-house only when the bill justifies the team.

Security and governance. Pipelines copy production data, often including personal data, into places many more people can read. Classify columns (personal, sensitive, public), mask or tokenise sensitive columns at ingestion, grant access by role through the catalog with column-level and row-level policies, encrypt at rest and in transit, and log access. Lineage, meaning which tables and dashboards derive from which sources, lets you answer "what breaks if this column changes?" and "where does this person's data live?". Catalogs such as Unity Catalog, DataHub (from LinkedIn) and OpenMetadata track it. See Security Fundamentals.

When to Use It#

  • Analytics queries are hurting production, or soon will. Move them to a replica first, then to a warehouse once they need history or other sources.
  • Questions span several systems: orders plus payments plus marketing spend plus support tickets. Only a central store can join them.
  • You need history that production does not keep: prices at the time of sale, slowly changing customer attributes, deleted records.
  • Machine-learning teams need training data: large, consistent snapshots of features and labels, best served from a lake or lakehouse in Parquet.
  • Product features show aggregates to users: dashboards for advertisers, sellers or creators, top-K lists, usage meters. Use a real-time OLAP store fed by a stream.
  • Regulation or audit requires keeping and reproducing figures, such as financial reporting, where an immutable raw layer plus reproducible transformations is the evidence.

When NOT to Use It#

  • Small data and few questions. If the whole database is 20 GB and a handful of people run reports, a read replica with a few well-indexed views, or DuckDB over a nightly export, is enough. A warehouse plus Airflow plus dbt is a platform someone has to own.
  • Do not build a lake without an owner and a catalog. Dumping files into object storage with no schema, documentation or retention rules creates a swamp that costs money and answers nothing.
  • Do not serve user-facing, high-concurrency queries from a general warehouse. Thousands of concurrent sub-second queries belong in a real-time OLAP store or a pre-computed cache, not in a warehouse priced and tuned for analysts.
  • Do not route operational, ephemeral data through analytics. Live driver locations, inventory reservations and session state belong in operational stores (Redis, the OLTP database), not in a pipeline with minutes of delay.
  • Do not make the warehouse a hidden dependency of the product without treating it as production. If an app reads a gold table, that table needs freshness monitoring, on-call ownership and change control.
  • Do not stream into analytics because you can. If the dashboard is read once a morning, an hourly or daily batch is cheaper and simpler.

How to Implement It#

  1. List the questions and consumers first: which dashboards, which models, which product features, and how fresh each must be. Freshness decides batch versus streaming per consumer.
  2. Inventory the sources and choose an extraction method for each: log-based CDC for large, changing OLTP tables, managed connectors for SaaS APIs, and Kafka for events.
  3. Land raw data unchanged in a bronze layer (lake tables in Parquet with Iceberg or Delta, or raw warehouse tables), partitioned by ingestion date, with retention rules. Mask sensitive fields at this step if policy requires.
  4. Model the data in layers: clean silver tables with types, deduplication and consistent keys, then gold star schemas and metric tables. Use dbt or Spark, with every model in version control.
  5. Make every step idempotent by processing per time partition, overwriting or merging, and reprocessing a lookback window for late data.
  6. Add data-quality tests and freshness checks, and block downstream steps on failure.
  7. Orchestrate with Airflow, Dagster or the cloud's managed service, with sensors for input readiness, retries, SLAs and backfill limits.
  8. Add a streaming branch only where needed: Kafka into Flink into ClickHouse, Druid or Pinot for user-facing or seconds-fresh metrics. Keep raw events in the lake for reconciliation.
  9. Govern and control cost: catalog, column and row access policies, lineage, partitioning and clustering, auto-suspend, budgets and alerts per team.
TechnologyFits when
SnowflakeA managed, multi-cloud SQL warehouse with workload isolation and little tuning
BigQueryServerless warehousing on GCP; spiky or unpredictable query loads
Amazon RedshiftAWS-centric warehousing, with provisioned clusters or serverless
Databricks (Delta Lake)A lakehouse combining Spark, SQL and ML on open table formats
Apache Iceberg with Trino, Spark or AthenaOpen lakehouse tables readable by many engines, avoiding lock-in
Apache HudiLake tables with very frequent upserts, such as CDC-heavy ingestion
ClickHouseFast SQL analytics, internal or user-facing, with simple operations
Apache DruidTime-based, streaming-ingested, high-concurrency dashboards with rollup
Apache PinotUser-facing analytics at high query rates, with upserts and star-tree indexes
dbtSQL transformations as tested, version-controlled models (ELT)
Fivetran, AirbyteManaged or open-source connectors from SaaS tools and databases
DebeziumLog-based CDC from PostgreSQL, MySQL and others into Kafka
Apache Airflow, DagsterOrchestrating pipelines with dependencies, retries and backfills
DuckDBSingle-machine analytics on Parquet up to hundreds of GB

Trade-offs#

OptionProsConsPick when
Query the OLTP replicaNo new system; data is freshLimited history; heavy queries still slow the replica; no cross-source joinsSmall data, few users, early stage
ETLOnly clean, approved data lands; heavy non-SQL processingRaw data lost; logic changes need re-extraction; engineering bottleneckSensitive data must be masked first, or the target is small and costly
ELTRaw data kept; SQL-based; fast iterationWarehouse cost; raw sensitive data needs controlsMost cloud analytics
Cloud warehouseFast SQL, managed, strong concurrency featuresProprietary storage; cost grows with useBI and SQL analytics on structured data
Data lakeCheapest storage; any format; any engineNo transactions; swamp risk; slow planning on many filesRaw archives, ML data, unstructured data
LakehouseOpen formats with transactions, updates and time travelTable maintenance; engine support varies by featureOne platform for BI, ML and streaming, avoiding lock-in
Real-time OLAPSeconds-fresh data, millisecond queries, high concurrencyOperational complexity; best for known query patternsUser-facing analytics, live dashboards, top-K
Batch pipelineSimple, exact, reproducibleMinutes to hours of delay; spikes extend runsReports and models refreshed hourly or daily
Streaming pipelineSeconds of delayHarder to build, test and operateFreshness is a product requirement

Common Pitfalls#

  • Running analytics on the primary database. The first big report slows checkout. Use a replica at minimum.
  • Append-only loads without deduplication. Retries and CDC replays create duplicate rows, and revenue doubles. Deduplicate by key in the silver layer.
  • Incremental extraction by updated_at only. It misses hard deletes and rows whose timestamp was not updated. Prefer log-based CDC for important tables.
  • Unpartitioned, unsorted tables. Every query scans everything, and on BigQuery-style billing, every query costs the full table.
  • Millions of small files. Streaming writes without compaction make queries slow and object storage requests expensive.
  • No tests, no freshness checks. Broken or stale data reaches the CEO's dashboard before anyone notices.
  • Mixing time zones and event versus load time. "Revenue per day" differs depending on whether the day is the order's local date, UTC date, or the date it was loaded. Define it once, in a shared model.
  • Metric definitions copied into every dashboard. "Active user" ends up with five definitions. Define metrics once in a modelled table or a semantic layer.
  • Forgetting deletion. Erasure requests must reach every copy: lake files, snapshots, warehouse tables, derived aggregates and backups.
  • Warehouse used as an application database. Hundreds of users clicking a product page that queries the warehouse cause timeouts and huge bills. Serve them from a real-time OLAP store or a cache of pre-computed results.

Real-World Examples#

  • Google described Dremel (VLDB 2010), whose columnar nested format inspired Parquet and whose engine underlies BigQuery.
  • Netflix created Apache Iceberg to manage very large analytic tables on S3 reliably, and donated it to the Apache Software Foundation.
  • Uber created Apache Hudi to support incremental upserts into its Hadoop data lake, and is a well-known user of Apache Pinot.
  • Databricks created Delta Lake, and its founders published the lakehouse paper (CIDR 2021).
  • LinkedIn created Apache Pinot for member-facing analytics, as well as Kafka and the DataHub metadata catalog.
  • Metamarkets created Apache Druid for real-time ad-tech analytics, and Yandex created ClickHouse for its Metrica web analytics service.
  • Airbnb created Apache Airflow. Facebook created Apache Hive (SQL on Hadoop) and Presto, from which Trino descends.
  • Typical scenario: a mid-sized e-commerce company streams PostgreSQL changes with Debezium into Kafka, lands them as Iceberg tables in S3, models them with dbt in Snowflake, orchestrates with Airflow, and serves seller-facing sales dashboards from ClickHouse fed by Flink.

In the Interview#

Deep Dive: How an analytical query engine turns 10 TB into a two-second answerShow

Follow one query through a modern engine: "revenue by category for German customers in November 2026", on a fact table of 20 billion rows (about 10 TB in compressed columnar form, 40 columns) and two small dimension tables.

1. Planning with metadata. The engine parses and optimises the SQL. It pushes the filters down: order_date in November becomes a partition filter, and country = 'DE' is pushed into the customer dimension scan. It reads table metadata (Iceberg manifests, Snowflake's metadata service, or Parquet footers) and prunes. Of 365 daily partitions, 30 remain, which is 820 GB. Of 40 columns, it needs order_date, customer_key, product_key and amount, about 4/40 of the bytes, so 82 GB.

2. Building the small sides first. The engine scans dim_customer for German customers, finding, say, 3 million of 100 million, and dim_product for category names. Both results are small, so they are broadcast to every worker as hash tables. Better still, the set of German customer keys can become a runtime filter, a Bloom filter or a min and max range, applied during the fact scan, so rows for other countries are dropped before they are even decoded.

3. Scanning the fact table in parallel. 200 workers each scan about 400 MB. Each worker reads column chunks, skips row groups whose customer_key range or Bloom filter cannot match, decodes dictionary and run-length encoded values in vectors of thousands, and applies the runtime filter with SIMD. Late materialisation means amount and product_key are decoded only for the rows that survive the filter. At a few GB/s per worker from local SSD cache, or a few hundred MB/s from object storage, the scan takes about one to two seconds.

4. Partial aggregation, then shuffle. Each worker joins its surviving rows with the product hash table and keeps a partial sum per category, perhaps 500 categories, so its output is tiny. The partials are shuffled by category to a few workers, which sum them, and the coordinator returns 500 rows.

What made it fast: pruning removed 99% of the bytes before reading, columnar layout removed most of the rest, compression shrank it again, broadcast joins avoided shuffling the big table, runtime filters avoided decoding irrelevant rows, and partial aggregation meant almost nothing crossed the network. Remove any of these and the query takes minutes. Each one is a design decision you control: partitioning, clustering, data types, and the shape of your star schema.

Where it goes wrong. A filter on a column the data is not clustered by (such as user_id in a date-clustered table) prunes nothing. A join between two huge tables forces a full shuffle. A COUNT(DISTINCT user_id) over billions of rows needs either a large shuffle or an approximate algorithm such as HyperLogLog, which most warehouses offer as APPROX_COUNT_DISTINCT. Skewed join keys overload one worker. The fixes mirror those in Batch vs Stream Processing: clustering, pre-aggregation, salting and approximation.

Deep Dive: Pipelines as software, with lineage, contracts and reproducibilityShow

Reproducibility. A figure in a board report must be reproducible months later: "Why does Q3 revenue say 41.2 million?". That requires three things. First, immutable raw data: the bronze layer is append-only, and table-format snapshots let you read it as it was. Second, versioned logic: every model is code in version control, so the SQL that produced the figure is known. Third, recorded runs: the orchestrator records which version of which model ran over which input snapshot. With those three, any number can be traced and recomputed. Without them, the answer is "it was correct when we ran it".

Lineage. Column-level lineage records that gold.revenue.amount comes from silver.orders.amount_cents, divided by 100, which comes from the orders table in PostgreSQL via CDC. It answers impact questions ("what breaks if we rename this column?"), debugging questions ("why is this dashboard wrong?") and compliance questions ("where is customer email stored?"). Tools derive lineage by parsing SQL, from dbt's dependency graph, or from the OpenLineage standard, which orchestrators and engines emit as they run.

Data contracts and schema evolution. Most pipeline incidents start upstream: a column renamed, a field's meaning changed, an enum value added. A data contract makes the producing team's output an explicit API, with a schema, semantics, freshness, and a promise of notice before breaking changes. Enforce it in CI: a change to the source schema that breaks the contract fails the build. In streaming, a schema registry with compatibility rules does the same (see Pub/Sub and Event Streaming). For changes that must happen, use expand and contract: add the new column, backfill it, migrate consumers, then remove the old one.

Testing pipelines. Unit-test transformation logic on small fixtures, including late rows, duplicates, nulls and time-zone edges. Run models in CI against a sampled copy of production data, and compare row counts and key aggregates with the current production version before deploying. Treat a change in an important metric of more than a small threshold as something to explain, not merely to ship.

Observability for data. Monitor five signals per important table: freshness (how old is the newest row?), volume (are row counts in the expected range?), schema (did columns change?), distribution (did the null rate or the share of a category jump?), and lineage health (did an upstream table fail?). Alert the owning team, and show the status next to the dashboard, so that consumers know when to distrust a number.

The cost model. Analytics spending follows a few levers: bytes stored (cheap), bytes scanned or compute time (expensive), and data moved across regions or out of the cloud (surprisingly expensive). Partitioning, clustering, materialising common aggregates, expiring old snapshots, tiering cold data to cheaper storage classes, and keeping compute in the same region as storage address each lever. Showing costs per team or per dashboard is the most effective cost control, because people optimise what they can see.

Key Takeaways#

  • OLTP systems handle many small transactions on current data. OLAP systems scan and aggregate huge volumes of history. Keep them separate, and copy data from one to the other with pipelines.
  • Columnar storage reads only the needed columns, compresses well and enables vectorised execution. Parquet is the open standard; partition by date and sort by the main filter.
  • ELT, loading raw data and transforming it in the warehouse with tested SQL models, is the modern default. Use ETL when data must be cleaned or masked before landing.
  • Warehouses (Snowflake, BigQuery, Redshift) give fast SQL over structured data with separated storage and compute. Lakes give cheap storage of any data. Lakehouse table formats (Iceberg, Delta, Hudi) add transactions, updates and time travel to lake files.
  • Real-time OLAP stores (ClickHouse, Druid, Pinot) ingest from streams and pre-aggregate on ingest, to serve fresh, high-concurrency, user-facing analytics.
  • Derived stores, whether warehouses, search indexes or caches, should be fed from a single source of truth, usually through CDC, not written to in parallel.
  • Orchestrate idempotent, partition-based tasks with Airflow or similar, test data quality at every layer, and design for reproducibility, lineage and cost from the start.