Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 2

Lab: Cost Attribution and a Measured Cost Cut

Attribute a day of warehouse cost to pipelines and teams from a tagged query history, find the most expensive job and why, then cut its cost with partition pruning and a schedule that matches when the data changes, and prove the results are unchanged. Finish with auto-suspend and storage tiering, measured on the same history.

Contentsand lesson path

What you will learn

  • Attribute warehouse and cluster cost to pipelines and teams with tags and query history, and cut it with pruning, scheduling, right-sizing and retention policies.

01. Goal and setup

Cloud warehouses bill for what you use: data scanned or compute time, plus storage. That makes cost a property of each pipeline, and it can grow quietly as data grows or as someone adds an hourly schedule. You cannot cut what you cannot attribute, so this lab starts with cost attribution: every query carries a query tag naming its pipeline and team, and the warehouse's query history records what each query read. Summing the history by tag gives a cost report per pipeline and team.

Real warehouses do this for you. Snowflake has the QUERY_TAG session parameter and the ACCOUNT_USAGE.QUERY_HISTORY view; BigQuery has job labels and INFORMATION_SCHEMA.JOBS, with bytes billed per job. Spark clusters are attributed the same way, one level up: tag each cluster or job (Databricks calls them custom_tags; cloud providers have resource tags) and group the billing export by those tags. DuckDB has neither, so warehouse.py builds a small stand-in. Each query runs with DuckDB's profiler on; the profile names the Parquet files that the scan had to read, and every row of those files is billed at a made-up price of £0.50 per million rows. That models engines that bill by data read; a columnar engine would read only the needed columns, so real bills are smaller, but the comparison works the same way.

Work in the poc-lab folder from lesson 1, with its .venv (DuckDB 1.5.6, Python 3.10 or newer). The warehouses lesson on pruning and clustering goes deeper into table layout; this lab is about finding which pipeline to fix and proving the saving.

02. Step 1: Create the event data

The script writes 180 days of app events, 3,000 a day, into one Parquet file in arrival order. An append-only ingest job leaves files like this: late events are mixed in, so every row group holds dates from the whole period.

Python · make_events.py
"""Write 180 days of app events (3,000 a day) to events.parquet, in arrival order
with late events mixed in, the way an append-only ingest job leaves them."""
import duckdb

duckdb.sql("""
COPY (
  SELECT DATE '2026-05-13' + ((i * 7919) % 180)::INT AS event_date,
         'u' || (i * 7907 % 20000) AS user_id,
         ['GB', 'IE', 'FR', 'DE'][1 + (i // 180) % 4] AS country,
         ['view', 'click', 'buy'][1 + (i // 7) % 3] AS action,
         ((i % 500) / 10)::DECIMAL(6, 2) AS value
  FROM range(540000) t(i)
) TO 'events.parquet' (FORMAT parquet)""")
print(duckdb.sql("SELECT count(*) AS events, min(event_date) AS first_day, "
                 "max(event_date) AS last_day FROM 'events.parquet'"))
Terminal
.venv/bin/python make_events.py
Expected output
┌────────┬────────────┬────────────┐
│ events │ first_day  │  last_day  │
│ int64  │    date    │    date    │
├────────┼────────────┼────────────┤
│ 540000 │ 2026-05-13 │ 2026-11-08 │
└────────┴────────────┴────────────┘

03. Step 2: A query history with tags

Read warehouse.py. The run function opens a fresh DuckDB connection with profiling switched on, runs the query, reads the profile, and finds the files each table scan read. It then adds a row to query_history in costs.duckdb with a label for the scenario, the hour the query ran, the pipeline and team tags, the files read and the rows in them. A query without tags is still recorded, with empty tags. That matters: cost you cannot attribute is a finding in itself. start clears earlier rows with the same label, so you can re-run a scenario without counting it twice.

Python · warehouse.py
"""A stand-in for a warehouse's query history. Each query runs with DuckDB's
profiler on; the profile says which Parquet files the scan had to read, and every
row in those files is billed, much as an on-demand engine bills the data it reads."""
import glob
import json
import os

import duckdb

history = duckdb.connect("costs.duckdb")
history.execute("""CREATE TABLE IF NOT EXISTS query_history (label VARCHAR,
    hour INT, pipeline VARCHAR, team VARCHAR, files_read INT, rows_read BIGINT)""")


def files_read(node):
    """Yield the Parquet files that each table scan in a profile read."""
    info = node.get("extra_info", {})
    if node.get("operator_type") == "TABLE_SCAN":
        names = info["Filename(s)"].split(", ")
        if names[-1] == "...":                   # long lists are cut: keep the glob
            names = sorted(glob.glob(names[0]))[: int(info["Total Files Read"])]
        yield from names
    for child in node.get("children", []):
        yield from files_read(child)


def start(label):
    """Forget earlier runs with this label, so a scenario can be re-run safely."""
    history.execute("DELETE FROM query_history WHERE label = ?", [label])


def run(sql, *, label, hour, tags=None):
    """Run one query; `tags` such as {'pipeline': ..., 'team': ...} is its query tag."""
    con = duckdb.connect()
    con.execute("PRAGMA enable_profiling = 'json'")
    con.execute("PRAGMA profiling_output = 'profile.json'")
    result = con.execute(sql).fetchall()
    con.close()                                  # writes the profile file
    with open("profile.json") as f:
        files = sorted(set(files_read(json.load(f))))
    os.remove("profile.json")
    rows = sum(duckdb.execute("SELECT num_rows FROM parquet_file_metadata(?)",
                              [name]).fetchone()[0] for name in files)
    tags = tags or {}
    history.execute("INSERT INTO query_history VALUES (?, ?, ?, ?, ?, ?)",
                    [label, hour, tags.get("pipeline"), tags.get("team"), len(files),
                     rows])
    return result

04. Step 3: Run one day and attribute its cost

schedule.py runs one day of the current schedule. Finance builds daily revenue once at 06:00. Product recomputes daily active users for the last 7 days every hour. Marketing exports yesterday's counts by country four times a day. Two analysts run untagged ad-hoc queries. The script prints a short hash of each pipeline's result, so you can check later that a cheaper version returns the same answer. Then report.py sums the history by team and pipeline.

Python · schedule.py
"""Run one day of scheduled queries and record them in the query history.
Usage: python schedule.py before | after"""
import hashlib
import sys

from warehouse import run, start

label = sys.argv[1]
start(label)
if label == "before":                  # one big file, every job reads all of it
    events = "'events.parquet'"
    recent, hours = "event_date >= DATE '2026-11-02'", list(range(24))
    yesterday = "event_date = DATE '2026-11-08'"
else:                                  # month partitions, filters on the partition key
    events = "read_parquet('events_by_month/*/*.parquet', hive_partitioning = true)"
    recent = "month >= '2026-11' AND event_date >= DATE '2026-11-02'"
    yesterday = "month = '2026-11' AND event_date = DATE '2026-11-08'"
    hours = [7]                        # the input changes once a day, after 06:00
QUERIES = {   # pipeline -> (team, hours it runs, SQL)
    "finance_daily": ("finance", [6], f"""SELECT event_date, sum(value) FROM {events}
        WHERE action = 'buy' GROUP BY ALL"""),
    "product_dau": ("product", hours, f"""SELECT event_date, count(DISTINCT user_id)
        FROM {events} WHERE {recent} GROUP BY ALL"""),
    "marketing_export": ("marketing", [7, 12, 17, 22], f"""SELECT country, count(*)
        FROM {events} WHERE {yesterday} GROUP BY ALL"""),
}
for pipeline, (team, run_hours, sql) in QUERIES.items():
    for hour in run_hours:
        rows = run(sql, label=label, hour=hour,
                   tags={"pipeline": pipeline, "team": team})
    digest = hashlib.sha256(repr(sorted(rows)).encode()).hexdigest()[:8]
    print(f"{label} {pipeline}: {len(run_hours)} runs, {len(rows)} result rows,"
          f" result hash {digest}")
for hour in (10, 15):                            # two ad-hoc queries, with no tag
    run(f"SELECT action, avg(value) FROM {events} GROUP BY ALL", label=label, hour=hour)
Python · report.py
"""Cost per team and pipeline from the query history.
Usage: python report.py BEFORE [AFTER]   (labels written by schedule.py)"""
import sys

import duckdb

PRICE = 0.50                         # pounds per million rows read (made up)
before = sys.argv[1]
after = sys.argv[2] if len(sys.argv) > 2 else before
con = duckdb.connect("costs.duckdb", read_only=True)
con.sql(f"""
WITH by_pipeline AS (
  SELECT coalesce(team, 'untagged') AS team, coalesce(pipeline, '(ad hoc)') AS pipeline,
    count(*) FILTER (label = '{before}')::INT AS runs,
    (sum(rows_read) FILTER (label = '{before}') / 1e6 * {PRICE})::DECIMAL(8, 3) AS cost,
    count(*) FILTER (label = '{after}')::INT AS runs_new,
    (sum(rows_read) FILTER (label = '{after}') / 1e6 * {PRICE})::DECIMAL(8, 3)
      AS cost_new
  FROM query_history GROUP BY ALL)
SELECT * FROM (SELECT * FROM by_pipeline ORDER BY cost DESC)
UNION ALL SELECT 'all', 'total', sum(runs), sum(cost), sum(runs_new), sum(cost_new)
FROM by_pipeline""").show(max_width=88)
Terminal
.venv/bin/python schedule.py before
.venv/bin/python report.py before
Expected output
before finance_daily: 1 runs, 180 result rows, result hash 1e49ce52
before product_dau: 24 runs, 7 result rows, result hash 958f8391
before marketing_export: 4 runs, 4 result rows, result hash 676c1672
┌───────────┬──────────────────┬────────┬───────────────┬──────────┬───────────────┐
│   team    │     pipeline     │  runs  │     cost      │ runs_new │   cost_new    │
│  varchar  │     varchar      │ int128 │ decimal(38,3) │  int128  │ decimal(38,3) │
├───────────┼──────────────────┼────────┼───────────────┼──────────┼───────────────┤
│ product   │ product_dau      │     24 │         6.480 │       24 │         6.480 │
│ marketing │ marketing_export │      4 │         1.080 │        4 │         1.080 │
│ untagged  │ (ad hoc)         │      2 │         0.540 │        2 │         0.540 │
│ finance   │ finance_daily    │      1 │         0.270 │        1 │         0.270 │
│ all       │ total            │     31 │         8.370 │       31 │         8.370 │
└───────────┴──────────────────┴────────┴───────────────┴──────────┴───────────────┘

Product's hourly job is 77% of the day's cost (£6.48 of £8.37), though it only needs the last 7 days. Every one of its 24 runs reads all 540,000 rows, because the single file gives the engine no way to skip old data. The untagged ad-hoc queries cost more than finance's job: in a real account, make tags mandatory, for example by setting a default tag per user role or tool, so that this line stays small.

05. Step 4: Cut the cost and check the answers

Two changes address the two causes. First, pruning: rewrite the events sorted (by date first) and partitioned by month, so each month is a separate folder (month=2026-11/). An engine skips whole partitions only when the query filters on the partition column, so the queries that need recent data add month >= '2026-11' next to their date filter. Second, scheduling: the events land once a day, so running product's query every hour returns the same answer 24 times. It now runs once, at 07:00, after the daily load; product needs yesterday's numbers by 08:00, so the job still meets its freshness SLO. The after branch of schedule.py contains both changes.

Python · relayout.py
"""Rewrite the events sorted by date and partitioned by month, so a query that
filters on recent dates can skip the files and row groups it does not need."""
import duckdb

duckdb.sql("SET threads = 1")         # one writer thread: the same files on every run
duckdb.sql("""
COPY (SELECT *, strftime(event_date, '%Y-%m') AS month
      FROM 'events.parquet' ORDER BY ALL)
TO 'events_by_month' (FORMAT parquet, PARTITION_BY (month), OVERWRITE)""")
print(duckdb.sql("""SELECT month, count(*) AS events, count(DISTINCT filename) AS files
    FROM read_parquet('events_by_month/*/*.parquet', hive_partitioning = true,
                      filename = true) GROUP BY ALL ORDER BY month"""))
Terminal
.venv/bin/python relayout.py
.venv/bin/python schedule.py after
.venv/bin/python report.py before after
Expected output
┌─────────┬────────┬───────┐
│  month  │ events │ files │
│ varchar │ int64  │ int64 │
├─────────┼────────┼───────┤
│ 2026-05 │  57000 │     1 │
│ 2026-06 │  90000 │     1 │
│ 2026-07 │  93000 │     1 │
│ 2026-08 │  93000 │     1 │
│ 2026-09 │  90000 │     1 │
│ 2026-10 │  93000 │     1 │
│ 2026-11 │  24000 │     1 │
└─────────┴────────┴───────┘

after finance_daily: 1 runs, 180 result rows, result hash 1e49ce52
after product_dau: 1 runs, 7 result rows, result hash 958f8391
after marketing_export: 4 runs, 4 result rows, result hash 676c1672
┌───────────┬──────────────────┬────────┬───────────────┬──────────┬───────────────┐
│   team    │     pipeline     │  runs  │     cost      │ runs_new │   cost_new    │
│  varchar  │     varchar      │ int128 │ decimal(38,3) │  int128  │ decimal(38,3) │
├───────────┼──────────────────┼────────┼───────────────┼──────────┼───────────────┤
│ product   │ product_dau      │     24 │         6.480 │        1 │         0.012 │
│ marketing │ marketing_export │      4 │         1.080 │        4 │         0.048 │
│ untagged  │ (ad hoc)         │      2 │         0.540 │        2 │         0.540 │
│ finance   │ finance_daily    │      1 │         0.270 │        1 │         0.270 │
│ all       │ total            │     31 │         8.370 │        8 │         0.870 │
└───────────┴──────────────────┴────────┴───────────────┴──────────┴───────────────┘

The result hashes from step 3 and step 4 are identical, so every pipeline returns the same answers. Product's daily cost fell from £6.48 to £0.012: one run instead of 24, reading 24,000 rows instead of 540,000. Marketing's export now reads one partition too. Finance and the ad-hoc queries still read everything, because they need the whole history; for finance, a daily summary table that is updated incrementally would be the next step. The total fell from £8.37 to £0.87 a day. Report it with that evidence: the measurement before and after, the unchanged result hashes and the SLO that still holds.

06. Step 5: Auto-suspend for compute time

Warehouses that bill compute time, such as Snowflake virtual warehouses, charge while the warehouse is running, busy or not. Auto-suspend stops it after a set number of idle minutes and resumes it when the next query arrives. uptime.py reads the same history and compares an always-on warehouse with auto-suspend after 10 minutes and after 1 minute. It assumes each query keeps the warehouse busy for 5 minutes; with a real history you would use each query's start and end times.

Python · uptime.py
"""Billed warehouse time for one day of the query history, for an always-on
warehouse and for auto-suspend after a few idle minutes.
Usage: python uptime.py LABEL   Assumes each query keeps the warehouse busy for
5 minutes, starting on the hour; a real history gives start and end times."""
import sys

import duckdb

RUN_MINUTES, CREDITS_PER_HOUR = 5, 2           # assumed duration; a "medium" size
label = sys.argv[1]
con = duckdb.connect("costs.duckdb", read_only=True)
hours = [h for (h,) in con.execute("SELECT hour FROM query_history WHERE label = ?"
                                   " ORDER BY hour", [label]).fetchall()]
busy, end = [], -1                              # queries in one hour run back to back
for h in hours:
    start = max(h * 60, end)
    end = start + RUN_MINUTES
    busy.append((start, end))


def billed(idle_minutes):
    """Minutes billed if the warehouse suspends after `idle_minutes` with no work."""
    total, awake_until = 0, -1
    for start, stop in busy:
        if start > awake_until:                 # it had suspended: resume now
            total += stop - start + idle_minutes
        else:                                   # still awake from the last query
            total += max(stop + idle_minutes, awake_until) - awake_until
        awake_until = max(awake_until, stop + idle_minutes)
    return total


print(f"{label}: {len(hours)} queries, {len(busy) * RUN_MINUTES} busy minutes")
for name, minutes in [("always on", 24 * 60), ("suspend after 10 min", billed(10)),
                      ("suspend after 1 min", billed(1))]:
    print(f"  {name:<21} {minutes:5} min billed = "
          f"{minutes / 60 * CREDITS_PER_HOUR:5.1f} credits")
Terminal
.venv/bin/python uptime.py before
.venv/bin/python uptime.py after
Expected output
before: 31 queries, 155 busy minutes
  always on              1440 min billed =  48.0 credits
  suspend after 10 min    395 min billed =  13.2 credits
  suspend after 1 min     179 min billed =   6.0 credits
after: 8 queries, 40 busy minutes
  always on              1440 min billed =  48.0 credits
  suspend after 10 min    110 min billed =   3.7 credits
  suspend after 1 min      47 min billed =   1.6 credits

An always-on warehouse bills 24 hours whatever happens. With auto-suspend, the bill follows the work: 13.2 credits with a 10-minute idle timeout, 6.0 with 1 minute, and less again with the new schedule. The shorter timeout is not free: each resume starts with an empty cache, so the first queries run slower, and some warehouses charge a minimum time on every resume (Snowflake bills at least 60 seconds). Right-sizing is the other compute lever, and it is measured from the same history: if queries rarely wait in a queue and the warehouse is idle most of its billed time, try one size smaller for a week and check that every job still meets its deadline; if queries queue in a busy window, use a larger size or more clusters only for that window.

07. Step 6: Storage tiering and retention

Storage is billed per byte per month. Many platforms offer cheaper tiers for data that is rarely read, and retention rules delete data that nobody is allowed or needs to keep. The script lists each month partition with its size and applies one rule: partitions whose newest day is more than 90 days old move to an archive tier. Prices are made up; read yours from your provider's price list.

Python · storage.py
"""Storage cost per month partition, now and with a tiering rule: partitions whose
newest day is more than 90 days old move to a cheaper archive tier."""
import datetime as dt
from pathlib import Path

HOT, ARCHIVE = 20.0, 4.0               # pounds per TB-month (made-up list prices)
today = dt.date(2026, 11, 9)
sizes = {"hot": 0, "archive": 0}
for part in sorted(Path("events_by_month").iterdir()):
    month = dt.date.fromisoformat(part.name.split("=")[1] + "-01")
    newest = (month.replace(day=28) + dt.timedelta(days=4)).replace(day=1)
    newest -= dt.timedelta(days=1)                       # last day of that month
    size = sum(f.stat().st_size for f in part.glob("*.parquet"))
    tier = "archive" if (today - newest).days > 90 else "hot"
    sizes[tier] += size
    print(f"{part.name}  newest day {newest}  {size / 1e6:.3f} MB  -> {tier}")
share = sizes["archive"] / sum(sizes.values())
new_price = HOT * (1 - share) + ARCHIVE * share
print(f"{share:.0%} of the bytes move to archive")
print(f"per TB of data like this: £{HOT:.2f} -> £{new_price:.2f} a month")
Terminal
.venv/bin/python storage.py
Expected output
month=2026-05  newest day 2026-05-31  0.153 MB  -> archive
month=2026-06  newest day 2026-06-30  0.238 MB  -> archive
month=2026-07  newest day 2026-07-31  0.247 MB  -> archive
month=2026-08  newest day 2026-08-31  0.246 MB  -> hot
month=2026-09  newest day 2026-09-30  0.238 MB  -> hot
month=2026-10  newest day 2026-10-31  0.246 MB  -> hot
month=2026-11  newest day 2026-11-30  0.058 MB  -> hot
45% of the bytes move to archive
per TB of data like this: £20.00 -> £12.85 a month

Partitioning by month makes the rule cheap to apply: moving a whole folder is one operation. Check the consumers first: finance's job reads the full history, so archive only after it reads a summary instead, or the job gets slower and more expensive. Deleting is different from archiving: keep data as long as a law, a contract or a real consumer needs it, and no longer.

08. Check your understanding

Practice check · 3 questions

Attribution and cuts

Each question changes one detail of the lab.

Q1. You keep the month layout but remove `month >= '2026-11' AND` from product's filter. How many files does each of its runs read?
Q2. In the report, untagged ad-hoc queries cost more than finance's daily job. What is the best next step?
Q3. With auto-suspend after 1 minute, why can a real warehouse bill more than `uptime.py` reports?
Practice only: not graded, not saved, not evidence.

09. Apply it

This completes the skill practice. Produce a per-pipeline cost report for your own pipeline from your warehouse's query history (or from this stand-in), grouped by tags. Pick the most expensive pipeline, implement one change (partition pruning, a schedule that follows data arrival, right-sizing, auto-suspend or retention), and show before and after costs together with evidence that the results are unchanged and the freshness and volume SLOs from lesson 2 are still met.

10. Review prompt

Without looking back, explain: why attribution comes before cutting; what a query tag is and where query history comes from in a real warehouse; why the hourly job was the most expensive; why partition pruning needs a filter on the partition column; how to prove that a cheaper pipeline still gives the same answers and meets its SLO; how auto-suspend changes compute cost and what it costs in return; and when to archive or delete old data.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check