Cloud warehouses

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 8:30 on the first working day of the month. Tess forwards the warehouse bill: it has tripled since last month. Nothing failed. One dashboard runs SELECT * on the five-year events table every 15 minutes, and the warehouse behind the finance dashboards has not slept once. Nora's reply is one line: "Every query is metered. Find the meters."

You'll learn to

  • Explain why warehouses keep storage apart from compute
  • Estimate Snowflake credits from size, run time and auto-suspend
  • Show how micro-partitions, partitions and clustering skip data
  • Price BigQuery on demand and on capacity, and cap the bill

Learn

The bill tripled. Nothing broke.

A classic database keeps the data and the machine that queries it in one box. More data means a bigger box, and one heavy report slows everyone down.

Cloud warehouses split the two:

  • Storage is columnar files in the cloud's object storage: cheap, and shared.
  • Compute starts on demand, is sized per workload, and stops when idle.

So finance and data science query the same tables on separate compute, and neither slows the other. You pay for storage by the GB, and for compute by the second or by the bytes scanned. Snowflake, BigQuery, Redshift Serverless and Databricks SQL all work this way.

That gives every warehouse two meters: time and bytes. Tess's bill ran up on both.

Snowflake's three layers

Three stacked boxes: cloud services with the optimiser, metadata, result cache and access control; compute with three independent virtual warehouses; and database storage holding micro-partitions in the cloud provider's object storage.

Read it top to bottom. Snowflake calls this "a hybrid of traditional shared-disk and shared-nothing database architectures": one copy of the data for every warehouse, as in shared disk; each warehouse an MPP cluster with local storage, as in shared nothing (Lesson 14.5).

A warehouse that never sleeps

Start with the first meter: time. In Snowflake, compute is a virtual warehouse: a cluster you name and size. Think of a taxi with the meter running. It charges while it waits, too.

The unit is the credit. Credits per hour double with each size: X-Small 1, Small 2, Medium 4, Large 8, X-Large 16. Billing is per second, with a 60-second minimum each time a warehouse starts or resumes.

Two settings decide how long the meter runs. AUTO_SUSPEND stops the warehouse after so many idle seconds. AUTO_RESUME starts it on the next query. A warehouse that never suspends bills around the clock.

The finance dashboard refreshes for 20 seconds, once an hour, from 08:00 to 17:00. Look at one of those hours.

One hourly refresh on a Medium warehouse

Three timelines over one hour: each runs a 20-second query, then stays on and billed for 60 seconds, for 600 seconds, or for the rest of the hour when it never suspends.

Each lane is one setting: blue is the 20-second query, amber and red are seconds billed with nothing running.

Count the credits

CREDITS_PER_HOUR = {'XS': 1, 'S': 2, 'M': 4, 'L': 8, 'XL': 16}

def credits(size, busy_periods, auto_suspend_s=60):
    """Credits for a day. busy_periods: (start_s, end_s) when queries ran. The warehouse
    stays on auto_suspend_s after each period; every start bills at least 60 seconds."""
    total_s = 0
    for start, end in busy_periods:
        total_s += max(60, (end - start) + auto_suspend_s)
    return total_s / 3600 * CREDITS_PER_HOUR[size]

hourly_refresh = [(h * 3600, h * 3600 + 20) for h in range(8, 18)]   # a 20 s dashboard refresh, hourly 08:00 to 17:00
print('auto-suspend 60 s :', round(credits('M', hourly_refresh, 60), 2), 'credits')
print('auto-suspend 600 s:', round(credits('M', hourly_refresh, 600), 2), 'credits')
print('never suspends    :', 24 * CREDITS_PER_HOUR['M'], 'credits')

Two hundred seconds of real work a day. With a 60-second auto-suspend it costs under one credit; left running, 96. That gap is most surprise warehouse bills.

Credits a day for ten refreshes

Bars compare 0.89 credits a day with a 60-second auto-suspend, 6.89 with 600 seconds, and 96 for a warehouse that never suspends.

Compare the three bars, then note that short suspends have a cost too: the warehouse cache (table data a running warehouse keeps) is dropped on suspend, so the first query after a resume reads from storage again. For a dashboard every hour, 60 seconds wins; for a burst of queries a minute apart, a little longer can be faster and no dearer.

Remember: a Snowflake warehouse bills for the seconds it is on, not the seconds it works.

Bigger, or more of them?

Size is the other dial. A size up doubles the credits per hour, but it often roughly halves a big query's run time, so the query can cost the same and finish sooner. Each resize up starts a new 60-second minimum.

A bigger warehouse does not help when many small queries wait in a queue. For that, a multi-cluster warehouse (Enterprise Edition) adds same-size clusters while queries queue. The rule: scale up for one big query, scale out for many users.

One more line on the bill is the cloud services layer, which plans queries and keeps metadata. It is billed only for what exceeds 10% of the day's warehouse credits.

A credit's price depends on edition and region.

Skip the files that cannot match

Now the second meter: how much data a query reads. Snowflake stores every table as micro-partitions: immutable columnar files, made automatically as rows arrive. For each one it keeps the min and max of every column, like the label on a filing box: "invoices, March to May".

A filter is checked against those labels first. A micro-partition whose range cannot contain the value is never read. That is pruning, the same idea as Delta's data skipping.

Pruning works when the data sits roughly sorted by what you filter on. That is usually time, because rows arrive in time order. For a huge table filtered by something else, you define a clustering key, and Snowflake re-sorts the table (reclusters) in the background, for a fee.

Find customer 7 in eight files

The 80 orders stored as eight files of ten rows in two layouts, each file labelled with its lowest and highest customer id: in arrival order all eight ranges contain customer 7, clustered by customer only one does.

  1. Eight files, eight labels. The 80 orders sit in 8 files of 10 rows, in two layouts. For each file the warehouse keeps the lowest and highest customer_id inside, and reads those labels before any data.

  2. Arrival order, customer_id = 7. Customers buy on any day, so every file holds a wide range, and 7 falls inside all eight. Nothing can be skipped: 8 of 8 scanned.

  3. Clustered by customer, the same filter. Now each file holds a narrow band of customers, and only the range 5 to 9 can contain 7. One file is read and seven are skipped: 1 of 8 scanned.

Blue files are read, grey ones are skipped. A Snowflake query profile reports the same two numbers: partitions scanned out of partitions total.

Pruning, measured on real Parquet footers

import duckdb

def write_partitions(name, order_by, rows_per_file=10):
    """The 80 orders as 8 small Parquet files, like micro-partitions, in the given order."""
    for i in range(8):
        duckdb.sql(f"""
            COPY (SELECT * FROM 'data/orders.csv' ORDER BY {order_by}
                  LIMIT {rows_per_file} OFFSET {i * rows_per_file})
            TO 'mp_{name}_{i}.parquet' (FORMAT PARQUET)
        """)

def scanned(name, column, value):
    """(partitions whose min/max could hold value, partitions in total)."""
    stats = duckdb.sql(f"""
        SELECT file_name, MIN(stats_min_value), MAX(stats_max_value)
        FROM parquet_metadata('mp_{name}_*.parquet')
        WHERE path_in_schema = '{column}'
        GROUP BY file_name
    """).fetchall()
    return sum(1 for _, lo, hi in stats if int(lo) <= value <= int(hi)), len(stats)

write_partitions('arrival', 'order_ts, order_id')        # rows as they arrived, in time order
write_partitions('clustered', 'customer_id, order_id')   # the same rows, clustered by customer

for column, value in [('order_id', 1050), ('customer_id', 7)]:
    print(f'{column} = {value}:  arrival order scans', scanned('arrival', column, value),
          ' clustered by customer scans', scanned('clustered', column, value))

Each pair is (partitions scanned, partitions total), worked out from the min/max in each file's footer before reading any data, as a warehouse does. The second line is the walkthrough you stepped through.

Partitions scanned, out of 8

FilterRows in arrival orderClustered by customerid
orderid = 105028
customerid = 781

Order ids grow with time, so arrival order already prunes them well; customers are spread across every file. Clustering by customer fixes customer filters and ruins order-id filters. A clustering key is a choice for the queries that matter most.

Snowflake: size, suspend, cluster, cap

Runs in the cloud:

CREATE WAREHOUSE reporting_wh
  WAREHOUSE_SIZE = 'XSMALL'
  AUTO_SUSPEND = 60
  AUTO_RESUME = TRUE;

ALTER TABLE events CLUSTER BY (event_date, user_id);
SELECT SYSTEM$CLUSTERING_INFORMATION('events', '(event_date)');

CREATE RESOURCE MONITOR monthly_cap WITH CREDIT_QUOTA = 100
  TRIGGERS ON 80 PERCENT DO NOTIFY
           ON 100 PERCENT DO SUSPEND;
ALTER WAREHOUSE reporting_wh SET RESOURCE_MONITOR = monthly_cap;
-- SYSTEM$CLUSTERING_INFORMATION (trimmed)
{
  "cluster_by_keys" : "LINEAR(event_date)",
  "total_partition_count" : 1840,
  "average_overlaps" : 0.42,
  "average_depth" : 1.31
}

A low average depth means a value of event_date lives in very few micro-partitions: good pruning. The resource monitor warns at 80% of the monthly credits and suspends the warehouse at 100%.

BigQuery: the meter is bytes

BigQuery has nothing to start or stop. You send a query and Google runs it on shared workers called slots. Storage is billed separately.

One way to pay is on demand: per TiB the query scans. Then a table's layout is its price:

  • A partitioned table splits rows by a date or timestamp column (or ingestion time, or an integer range). A filter on that column skips whole partitions.
  • A clustered table sorts data inside each partition by up to four columns, so filters on them read fewer blocks.

The events dashboard filters on nothing, so every refresh scans all five years. With require_partition_filter, a query that forgets the date filter is refused instead.

BigQuery: build it right, then guard the bill

Runs in the cloud:

bq query --use_legacy_sql=false '
CREATE TABLE swiftkart.events
PARTITION BY DATE(event_ts)
CLUSTER BY user_id, event_type
OPTIONS (require_partition_filter = TRUE)
AS SELECT * FROM swiftkart.events_raw'

bq query --use_legacy_sql=false --maximum_bytes_billed=1000000 \
  'SELECT * FROM swiftkart.events WHERE DATE(event_ts) >= "2021-01-01"'
Query exceeded limit for bytes billed: 1000000. 1786706395136 or higher required.

--maximum_bytes_billed makes a query fail instead of running when it would bill more than the limit: this one would have billed about 1.6 TiB, so it never ran. Projects can also have daily quotas. Together with dry runs, they stop a runaway query before it costs anything.

LIMIT does not lower the bill. On BigQuery on demand, SELECT * FROM events LIMIT 10 on a table that is not clustered reads every column of the whole table and bills for it; the LIMIT only trims what you see. Use the table preview to look at data, select only the columns you need, and filter on the partition column.

Two ways to pay for slots

On demand is one of two ways to pay BigQuery.

  • On demand: $6.25 per TiB scanned in the US multi-region, with the first TiB each month free. A project gets up to 2,000 concurrent slots, shared by all its queries.
  • Capacity: you pay for slot-hours, in one of three editions. A reservation keeps a baseline of slots always allocated and autoscales above it.

On demand rewards fewer bytes. Capacity rewards fewer slot-seconds. A query that scans little but joins and sorts a lot is cheap on demand and dear on capacity. A wide scan with little work is the reverse. The job history records both: total_bytes_billed and total_slot_ms.

Two bills worked out

def snowflake_billed(warehouse_credits, cloud_services_credits):
    """Cloud services are billed only for what exceeds 10% of the day's warehouse credits."""
    adjustment = min(float(cloud_services_credits), 0.1 * warehouse_credits)
    return round(warehouse_credits + cloud_services_credits - adjustment, 2)

def bigquery_on_demand(tib_scanned, price_per_tib=6.25, free_tib=1.0):
    return round(max(0.0, tib_scanned - free_tib) * price_per_tib, 2)

for wh, cs in [(100, 20), (120, 10), (80, 5), (100, 13)]:
    print('Snowflake day:', wh, 'warehouse +', cs, 'cloud services ->', snowflake_billed(wh, cs), 'billed')
print('BigQuery month, 41 TiB scanned: $', bigquery_on_demand(41))

The four Snowflake days are the example in Snowflake's own documentation: 110, 120, 80 and 103 credits billed. The BigQuery month pays for 40 TiB: the first is free.

Who is spending? Query the job history

SELECT user_email,
       COUNT(*) AS queries,
       ROUND(SUM(total_bytes_billed) / 1024.0 ^ 4, 4) AS tib_billed
FROM jobs
GROUP BY user_email
ORDER BY tib_billed DESC, user_email;

In BigQuery this table is INFORMATION_SCHEMA.JOBS; in Snowflake, SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY and WAREHOUSE_METERING_HISTORY. The same GROUP BY over the real view is the first step of every cost review.

Numbers to remember

WhatThe number
Snowflake sizescredits per hour double with each size: X-Small 1, up to 512 for a 6X-Large (standard Gen1 warehouses)
Snowflake billingper second, with a 60-second minimum on each start, resume and resize up
Cloud servicesbilled only above 10% of the day's warehouse credits
Micro-partitionroughly 50 to 500 MB of uncompressed data
BigQuery on demand$6.25 per TiB (US multi-region), first TiB a month free; at least 10 MB billed per table referenced and per query; up to 2,000 concurrent slots per project, with temporary bursts above that
BigQuery capacityeditions Standard, Enterprise and Enterprise Plus; autoscales in multiples of 50 slots, billed per second with a one-minute minimum
BigQuery clusteringup to four columns

What changed at SwiftKart

Two fixes, one per meter. The finance warehouse gets AUTO_SUSPEND = 60: 96 credits a day become 0.89. The events dashboard stops running SELECT * on five years. It reads a small gold table that pre-aggregates what it asks for every 15 minutes, so it scans kilobytes instead of terabytes.

Teams that keep bills flat add a few habits: a warehouse (or reservation) per workload so costs are visible, the smallest size that meets the deadline, resource monitors or budgets with alerts, and required partition filters.

"Snowflake or BigQuery?" has no single right answer. On Snowflake you control idle time. On BigQuery you control bytes. Both separate storage from compute and prune with metadata.

Next, Lesson 14.5 opens the engine: what a warehouse does inside when a query runs slow.

In one line

A cloud warehouse keeps storage apart from compute and has two meters: Snowflake bills the seconds a sized warehouse is on, BigQuery bills the bytes a query scans, and both skip data using min and max metadata.

Interview corner

How does Snowflake bill compute, and how do you keep it down?

Virtual warehouses use credits per hour by size, doubling with each size, billed per second with a 60-second minimum per start. Keep it down with short AUTO_SUSPEND and AUTO_RESUME, the smallest size that meets the deadline, separate warehouses per workload to see who spends, resource monitors with quotas, and good pruning so queries finish sooner.

What are micro-partitions and clustering keys in Snowflake?

Snowflake stores tables as small immutable columnar micro-partitions, about 50 to 500 MB uncompressed, with min/max metadata per column. Queries prune micro-partitions whose ranges cannot match. Data arriving in time order prunes well on time; for very large tables filtered on other columns, a clustering key makes Snowflake recluster in the background so those filters prune too, at an extra compute cost.

Partitioning versus clustering in BigQuery?

Partitioning splits a table into partitions by a date, timestamp, ingestion time or integer range column, and filters on it skip whole partitions; it can require a partition filter. Clustering sorts data within partitions by up to four columns, so filters on them read fewer blocks. Typically partition by date and cluster by the most common filter columns, such as customer or event type.

Snowflake or BigQuery: how do the billing models change the way you tune?

Snowflake bills credits per second while a sized warehouse runs, 1 credit an hour for X-Small doubling to 512 for 6X-Large, with a 60-second minimum per start or resize up, plus cloud services above 10% of daily warehouse credits. So you tune idle time (auto-suspend), the size per workload, and concurrency with multi-cluster warehouses. BigQuery on demand bills $6.25 per TiB scanned in the US with 2,000 concurrent slots per project, so you tune bytes: partitions, clustering, column choice, required partition filters; on editions you pay slot-hours with a baseline and autoscaling in steps of 50, so slot-milliseconds become the number to cut.