Inside a cloud warehouse

Part of the free LogicWiz Data Engineering course, Module 14: Cloud data platforms. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 6:50 on 1 July and the nightly rebuild of fact_order_line is still running. In May it took 9 minutes. In June it takes 41: same Medium warehouse on Snowflake, same SQL. Nora opens the query profile and points at two numbers: partitions scanned 18,402 of 18,410, and 212 GB spilled to remote storage. "Read the evidence."

You'll learn to

  • Tell a shared-nothing warehouse from separated storage and compute
  • Explain pruning metadata and measure clustering depth
  • Predict what a join moves from how tables are distributed
  • Read a query profile and name the fix from the evidence

Learn

Same SQL, 9 minutes then 41

Same SQL, so look inside the warehouse.

Every cloud warehouse is MPP, massively parallel processing: a query is cut into pieces that run on many nodes at once. The designs differ in where the data lives.

  • Shared-nothing (Redshift's classic design, Synapse dedicated pools): each node owns a slice of every table on its own disks. Work runs where the rows are, and adding nodes means redistributing data.
  • Separated storage and compute (Snowflake, BigQuery, Redshift RA3 with managed storage): the master copy lives in object storage, or Google's Colossus. Compute reads what a query needs, caches it locally, and can be resized, paused or multiplied without moving the data.

Both still shuffle: rows with one join key must meet on one worker.

Where the data lives

Two groups of boxes: a Redshift cluster with a leader node and two compute nodes, each holding two slices with their rows on local disk; and Snowflake with cloud services, two independent warehouses with local caches, and one copy of the data in object storage.

Left: every slice keeps its own rows on its own disk. Right: two warehouses share one copy in object storage and keep only a cache.

Clue one: 18,402 of 18,410

The profile's first number is Partitions scanned out of Partitions total: the rebuild read nearly the whole table.

For every micro-partition Snowflake keeps the range of values of each column, the number of distinct values and more, in the cloud services layer. At compile time the optimiser compares the filters with those ranges and drops every micro-partition that cannot match, before any warehouse reads a byte.

Pruning fails in three ways:

  • the data is not ordered by the filter column, so every range overlaps the value;
  • the filter wraps the column in a function;
  • the value comes from a subquery, on which Snowflake's documentation says it does not prune.

How deep is one value?

The first of those failures, the wrong order, has a measure. For one column, the depth at a value is the number of micro-partitions whose range contains it: how many a point filter must open. Depth 1 is perfect.

Snowflake reports the average depth through SYSTEM$CLUSTERING_INFORMATION, with average_overlaps and a histogram of depths: smaller is better. Rows that arrive in time order are shallow on time and deep on everything else.

A clustering key makes Snowflake re-sort micro-partitions in the background (Automatic Clustering, billed in credits). It pays off on large tables filtered the same way all day. It is a choice: clustered by customer, order-date filters go deep (Lesson 14.4).

customer_id ranges in four files, two layouts

Eight bars, one per file: in arrival order each of four files covers almost every customer id, so a filter on customer 7 touches all four; clustered by customer, each file covers a narrow range and the filter touches one.

Each lane is one file's range of customer_id, real footer values. The line at 7 crosses four red bars and one green: depth 4 in arrival order, 1 clustered.

Measure clustering depth from Parquet footers

import duckdb

def write_files(name, order_by, files=4, rows=20):
    """The 80 orders as 4 small Parquet files, standing in for micro-partitions."""
    for i in range(files):
        duckdb.sql(f"""
            COPY (SELECT * FROM 'data/orders.csv' ORDER BY {order_by} LIMIT {rows} OFFSET {i * rows})
            TO 'mp_{name}_{i}.parquet' (FORMAT PARQUET)
        """)

def ranges(name, column):
    """(file, min, max) of one column in each file, read from the Parquet footers."""
    return duckdb.sql(f"""
        SELECT file_name, MIN(stats_min_value)::INT, MAX(stats_max_value)::INT
        FROM parquet_metadata('mp_{name}_*.parquet')
        WHERE path_in_schema = '{column}'
        GROUP BY file_name ORDER BY file_name
    """).fetchall()

def depth_at(rngs, value):
    """How many files a point filter on value must open."""
    return sum(1 for _, lo, hi in rngs if lo <= value <= hi)

write_files('arrival', 'order_ts, order_id')        # rows as they arrived
write_files('clustered', 'customer_id, order_id')   # the same rows, sorted by customer
customers = [r[0] for r in duckdb.sql("SELECT DISTINCT customer_id FROM 'data/orders.csv' ORDER BY 1").fetchall()]

for name in ['arrival', 'clustered']:
    r = ranges(name, 'customer_id')
    depths = [depth_at(r, c) for c in customers]
    print(name, [(lo, hi) for _, lo, hi in r], 'depth at 7:', depth_at(r, 7),
          'average depth:', round(sum(depths) / len(depths), 2))

Over the 28 customers who ordered, a point filter opens 3.71 of 4 files in arrival order and 1.07 clustered: what average_depth summarises.

Clue two: 212 GB spilled

The second number follows from the first: the rebuild read everything, and its join no longer fit in memory.

When an operator's working set (a hash table for a join, a sort, an aggregate) does not fit in memory, every engine spills: it writes the overflow to disk and reads it back later. Think of a desk too small for the paperwork: first the floor, then a storeroom down the corridor.

Snowflake reports both. Bytes spilled to local storage is the warehouse nodes' own disks. Bytes spilled to remote storage starts once those fill too. Its documentation warns that spilling "can have a profound effect on query performance (especially if remote disk is used for spilling)".

A join outgrows its warehouse

Three places a join can keep its working set, memory, the local disk of the warehouse nodes and remote storage, fill one after another as the table grows from May to June, and empty again on a larger warehouse.

  1. May: it fits. The join builds its hash table in the memory of the Medium warehouse. Nothing touches a disk, and the rebuild takes 9 minutes.

  2. June: memory fills. The table has grown and the query prunes nothing. The hash table overflows, and 96 GB goes to the nodes' own disks: spilled to local storage.

  3. Local disk fills too. The rest, 212 GB, is written to remote storage and read back over the network. That is the slow part: 41 minutes.

  4. A larger warehouse. An X-Large brings more memory and local storage. Nothing reaches remote storage, and the same SQL runs in 6 minutes. Snowflake's other fix: process the data in smaller batches.

Read each step left to right: memory, local disk, remote storage. BigQuery's in-memory shuffle falls back to disk the same way (shuffleOutputBytesSpilled); so do Spark (Lessons 12.8 and 12.9) and Postgres (work_mem, Lesson 2.8).

The June rebuild on three warehouse sizes

Bars compare the credits one run of the June rebuild uses: 2.73 on Medium in 41 minutes, 1.73 on Large in 13 minutes and 1.60 on X-Large in 6 minutes.

Credits per run of this lesson's example query. Billing is per second, so a size up that removes remote spilling can cost less; once nothing spills, the next size mostly doubles the bill. Change one size at a time and read the profile.

Remember: read the profile before you resize. Scanned against total first, then spilled bytes.

Triage the query history

SELECT query_id,
       warehouse,
       ROUND(100.0 * partitions_scanned / partitions_total, 1) AS pct_scanned,
       spilled_remote_gb,
       queued_s,
       elapsed_s
FROM query_history
ORDER BY spilled_remote_gb DESC, pct_scanned DESC, query_id;

A simplified copy of SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY (real columns include PARTITIONS_SCANNED, BYTES_SPILLED_TO_REMOTE_STORAGE, QUEUED_OVERLOAD_TIME). Query 101 is the rebuild: it spills and does not prune. 103 and 104 wait longer than they run.

Where a join moves rows

In a shared-nothing warehouse the distribution style decides where each row lives, and so what a join must move. Redshift has four, and uses AUTO when you name none:

  • KEY: rows are placed by the hash of one column. Two tables distributed on their join key meet on the same slice, with no movement.
  • EVEN: round-robin. Balanced, but joins must move rows.
  • ALL: a full copy on every node. No movement, at the cost of storage and slower loads. For small dimensions.
  • AUTO: Redshift picks ALL, then KEY, then EVEN as the table grows.

Each node is split into slices. A row hashed over N slices is already on the right one 1 time in N, so redistributing a table moves (N - 1)/N of it.

The data movement labels in a Redshift EXPLAIN

LabelWhat movesVerdict
DSDISTNONEnothing: rows already collocatedgood
DSDISTALLNONEnothing: inner table is ALLgood
DSDISTINNERthe inner table is redistributedfine if the inner table is small
DSDISTOUTERthe outer table is redistributedwatch the outer table's size
DSBCASTINNERthe whole inner table to every nodebad on big tables
DSDISTALLINNERthe whole inner table to one slicebad
DSDISTBOTHboth tables are redistributedbad

Spark makes the same choices under other names (Lesson 12.4).

GB moved for one join, 4 nodes and 8 slices

Bars compare zero gigabytes for a collocated join, 8 for broadcasting a 2 GB dimension to four nodes, 350 for redistributing a 400 GB table over eight slices, and 1,400 for redistributing 1.6 TB on both sides.

With 8 slices a redistributed row stays put 1 time in 8, so 7/8 of the table moves; a broadcast sends the whole inner table to each node. Distributing orders and order_items on order_id makes the 350 GB join DS_DIST_NONE.

Redshift: choose keys, then read the plan

Runs in the cloud:

CREATE TABLE orders (
  order_id BIGINT, customer_id BIGINT, order_date DATE, status VARCHAR(12)
) DISTSTYLE KEY DISTKEY (customer_id) SORTKEY (order_date);

CREATE TABLE order_items (
  order_id BIGINT, line_no INT, product_id INT, qty INT, unit_price DECIMAL(10,2)
) DISTSTYLE KEY DISTKEY (order_id);

EXPLAIN
SELECT o.order_date, SUM(i.qty * i.unit_price)
FROM order_items i
JOIN orders o ON o.order_id = i.order_id
WHERE o.order_date = '2025-06-03'
GROUP BY o.order_date;
XN HashAggregate  (cost=...)
  ->  XN Hash Join DS_DIST_INNER  (cost=...)
        Hash Cond: ("outer".order_id = "inner".order_id)
        ->  XN Seq Scan on order_items i  (cost=...)
        ->  XN Hash  (cost=...)
              ->  XN Seq Scan on orders o  (cost=...)
                    Filter: (order_date = '2025-06-03'::date)

Costs trimmed. orders is distributed by customer, so this join redistributes it; the sort key lets zone maps skip blocks for the date filter. If this join is the hot path, distribute orders on order_id instead.

Three ways to pay for data you did not need. A filter that wraps the column in a function or takes its value from a subquery cannot prune: compute the value first and pass a literal. SELECT * with LIMIT on an unclustered table reads everything. And the result cache is per role: the same dashboard SQL under two roles is paid for twice.

Answered without a warehouse

A repeat can be answered without new work, three ways:

  • Result cache (cloud services). Snowflake keeps a result for 24 hours, and each reuse resets the clock, up to 31 days. It is reused only if the text matches exactly (case counts), the data and its micro-partitions have not changed, no non-reusable function is used, and the role is the same. A hit needs no warehouse.
  • Metadata. SELECT COUNT(*) FROM orders can be answered from micro-partition metadata, shown as a Metadata-based Result, with no warehouse.
  • Warehouse cache. A running warehouse keeps the table data it has read. It is dropped when the warehouse suspends.

Where a repeated Snowflake query is answered

Five steps down: the result cache, then metadata, then pruning with min and max ranges, then the warehouse cache, and finally remote storage for whatever is left.

Read it top to bottom: each step answers what it can and passes the rest down. The two green steps need no warehouse.

BigQuery: stages, slots, one slow worker

BigQuery shows the same evidence under other names. It runs a query as a graph of stages, the heir of Dremel's multilevel tree: leaf workers read columns from Colossus (stored in the Capacitor columnar format), and later stages join and aggregate. Each stage runs on slots, and stages pass rows through shuffle.

The plan gives each stage recordsRead, shuffleOutputBytes, shuffleOutputBytesSpilled, slotMs (slot-milliseconds), and wait, read, compute and write ratios, average and maximum, each relative to the longest time any worker spent.

When computeRatioMax is far above computeRatioAvg, a few workers did most of the work: skew, as in Spark. Average slots used is slot-milliseconds divided by elapsed milliseconds: 7,200,000 slot-ms in 60 seconds is 120 slots.

Revenue by country for June, as BigQuery stages

A graph of stages: three input stages read order_items, orders and customers, two of them shuffle by order_id into a join stage and the small table is broadcast, the join shuffles by country into an aggregate stage, which feeds the output stage.

Read it left to right. Real stage names look like S03: Join+. Each stage runs on many slots at once, and its slowest worker sets its time.

BigQuery: read the stage statistics of a job

Runs in the cloud:

bq show --format=prettyjson -j bquxjob_5e1c_june_revenue \
  | jq '.statistics.query.queryPlan[] | {name, slotMs, shuffleOutputBytes, shuffleOutputBytesSpilled, computeRatioAvg, computeRatioMax}'
{
  "name": "S03: Join+",
  "slotMs": "5400211",
  "shuffleOutputBytes": "18734022110",
  "shuffleOutputBytesSpilled": "6102345678",
  "computeRatioAvg": 0.0827,
  "computeRatioMax": 1
}

One stage of an example job. Integers come back as strings. The join spilled a third of its shuffle output, and its busiest worker computed twelve times longer than average (1 / 0.0827): skew.

Reading a query profile: evidence, cause, fix

EvidenceWhereLikely causeFix
Partitions scanned near the totalSnowflake profilelayout not ordered by the filter; a function or subquery in itliteral filters; a clustering key
Bytes spilled to remote storageSnowflake profileworking set over memory and local disklarger warehouse or smaller batches
Long queue, short runSnowflake query historytoo many concurrent queriesmulti-cluster warehouse
computeRatioMax far above computeRatioAvgBigQuery planskewhandle the hot or null key
shuffleOutputBytesSpilled above 0BigQuery planshuffle over its memoryfewer rows and columns first
DSBCASTINNER or DSDISTBOTH, big tablesRedshift EXPLAINjoin key is not the DISTKEYcollocate on the join key

Numbers to remember

WhatThe number
Micro-partition50 to 500 MB uncompressed, stored by column
Redshift zone mapsmin and max per 1 MB block; BigQuery prunes partitions and clustered blocks
Redshift slices per node2 on an ra3.xlplus, 16 on an ra3.16xlarge, each with its own memory and disk
Snowflake result cache24 hours, reset by each reuse, up to 31 days
BigQuery result cacheabout 24 hours, best effort and free; not for queries with a destination table, a function such as CURRENTTIMESTAMP(), changed tables or recent streaming inserts

What changed at SwiftKart

The rebuild's date filter took its value from a subquery, so Snowflake pruned nothing. In May it still fit. By June the table had outgrown the memory of a Medium warehouse, and the join spilled to remote storage.

You compute the date first and pass it as a literal. The rebuild prunes again and stops spilling.

Walk any slow query in the order of the table above: pruning, spilling, queueing, skew, data movement, caches. Name a number at each step, then the cause and the fix. Never "a bigger warehouse" before the evidence.

Next, Module 15 leaves the nightly batch behind, starting with Lesson 15.1, Events and logs.

In one line

A cloud warehouse runs a query on many nodes at once, and its profile tells you why it is slow: partitions scanned against total, bytes spilled, time queued, rows moved for a join, and one worker far above the average.

Interview corner

What is the difference between shared-nothing MPP and separated storage and compute?

In shared-nothing (classic Redshift, Synapse dedicated pools) every node owns a slice of each table on local disk, so work runs where the rows are; joins on a non-distribution key move rows between nodes, and resizing redistributes data. With separated storage and compute (Snowflake, BigQuery, Redshift RA3 with managed storage) one copy lives in object storage and compute clusters read and cache what they need, so you can resize, pause or add clusters without moving data. Both still shuffle inside a query; the difference is where data starts and how cheaply compute scales. Snowflake describes itself as a hybrid of shared-disk and shared-nothing.

A Snowflake query got five times slower with no SQL change. How do you investigate?

Open the query profile and compare it with a fast run. Partitions scanned against partitions total tells me whether pruning broke, for example new data arriving out of order or a filter that became a subquery. Bytes spilled to local and remote storage tell me whether the working set outgrew the warehouse; remote spilling is the slow case, fixed with a larger warehouse or smaller batches. Then queued time for concurrency, the most expensive operator for a join that exploded, and whether yesterday's run was a result-cache hit. I fix the one the numbers point at and measure again.

How do you choose distribution and sort keys in Redshift?

Distribute the largest, most-joined tables on their common join key, so those joins are collocated (DS_DIST_NONE), and give small dimensions DISTSTYLE ALL so every join to them is DS_DIST_ALL_NONE; leave it to AUTO when unsure. Avoid a skewed distribution key, because one slice then does most of the work. Choose a sort key on the column most queries filter by, usually a date, so zone maps skip 1 MB blocks. Then confirm with EXPLAIN: DS_BCAST_INNER or DS_DIST_BOTH on big tables means the keys are wrong.

What is a BigQuery slot, and how do you tell skew from a merely large query?

A slot is a virtual compute unit; a query runs as stages of workers on slots, connected by an in-memory shuffle, and on demand a project shares up to 2,000 concurrent slots. A large but balanced query has high slot-milliseconds and similar average and maximum compute ratios in every stage: it simply needs more slots or fewer bytes. A skewed one has a stage whose computeRatioMax is far above computeRatioAvg, often with shuffleOutputBytesSpilled, meaning a few workers got most rows. The fix for skew is in the data, a hot or null key, not in more capacity.