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 2 of 6 · Worked example · 25 min · revision 2

One Definition per Metric: Building a Semantic Layer

Two teams report different revenue for the same month. Fix it by defining revenue, orders, average order value and active customers once in a MetricFlow semantic layer on a dbt project, then query them at different grains and from a second consumer and get the same numbers.

Contentsand lesson path

What you will learn

  • Define business metrics once in a semantic layer (for example MetricFlow or Cube) with measures, dimensions and time grains, and get identical numbers from two different consumers.

01. The problem

An online shop has one orders table. Finance says January revenue was 24,959.00. The product team's notebook says 27,329.00. Both ran SQL against the same table, so the data is not the problem: the definition is. Finance leaves out refunded orders and the product team does not. When every tool and every person writes their own SQL for a metric, small differences like this are unavoidable, and meetings turn into arguments about whose number is right.

A semantic layer solves this by moving metric definitions out of dashboards and notebooks into one shared, version-controlled place. Consumers ask the layer for "revenue by month" or "revenue by region", and the layer writes the SQL. The vocabulary is small:

  • A measure is an aggregation of a column, such as the sum of amount or the count of orders. In dbt 1.12 and later, measures are written as simple metrics.
  • A dimension is something you group or filter by, such as region or status. A time dimension can be grouped at different grains: day, week, month, quarter or year.
  • An entity is a key, such as order_id or customer_id, that tells the layer what each row is and how tables join.
  • A metric is what people ask for. It can be a simple aggregation, or built from other metrics, like a ratio.

In this worked example you build that layer with MetricFlow, the open-source (Apache 2.0) engine behind the dbt Semantic Layer, on a dbt project that uses DuckDB. Tools such as Cube use the same ideas with different syntax.

02. Step 1: Set up the project and the data

You need Python 3.10 or later. This example was tested with Python 3.12, dbt-core 1.12.7, dbt-duckdb 1.11.1, dbt-metricflow 0.15.0 (MetricFlow 0.213.0) and DuckDB 1.5.6. The dbt-metricflow package installs dbt Core and the mf command line. When you run dbt you may see a note that dbt v2 is available; this lesson uses dbt Core v1, the line that dbt-metricflow 0.15 supports.

The data is 600 orders from the first quarter of 2026, generated with a fixed seed so your numbers match. Create the files, then build the seed and the model.

Terminal
mkdir -p shop/seeds shop/models && cd shop
python3 -m venv .venv && source .venv/bin/activate
pip install "dbt-metricflow[dbt-duckdb]==0.15.0" "duckdb==1.5.6"
export DBT_PROFILES_DIR="$PWD"
Python · make_seed.py
"""Write seeds/raw_orders.csv: 600 orders in Q1 2026, the same on every run."""
import csv
import random
from datetime import date, timedelta

rng = random.Random(7)
with open("seeds/raw_orders.csv", "w", newline="") as f:
    out = csv.writer(f)
    out.writerow(["order_id", "customer_id", "order_date",
                  "region", "status", "amount"])
    for order_id in range(1, 601):
        day = date(2026, 1, 1) + timedelta(days=rng.randrange(90))
        out.writerow([order_id, rng.randint(1, 120), day.isoformat(),
                      rng.choice(["North", "South"]),
                      "refunded" if rng.random() < 0.1 else "paid",
                      f"{rng.uniform(5, 250):.2f}"])
YAML · dbt_project.yml
name: shop
version: "1.0.0"
profile: shop
YAML · profiles.yml
shop:
  target: dev
  outputs:
    dev:
      type: duckdb
      path: shop.duckdb
SQL · models/fct_orders.sql
select order_id, customer_id, cast(order_date as date) as order_date,
       region, status, amount
from {{ ref('raw_orders') }}
Terminal
python make_seed.py
dbt --quiet build; echo "dbt exit code: $?"
Expected output
dbt exit code: 0

03. Step 2: Reproduce the disagreement

Before fixing anything, reproduce the problem. Each team's query is reasonable on its own, and nothing in the table says which rule is right.

Python · two_teams.py
"""Two teams compute January revenue with their own SQL."""
import duckdb

con = duckdb.connect("shop.duckdb", read_only=True)
finance = con.sql("""
    select sum(amount) from fct_orders
    where status = 'paid' and order_date < date '2026-02-01'
""").fetchone()[0]
product = con.sql("""
    select sum(amount) from fct_orders
    where order_date between date '2026-01-01' and date '2026-01-31'
""").fetchone()[0]
print(f"finance: {finance:,.2f}")
print(f"product: {product:,.2f}")
Terminal
python two_teams.py
Expected output
finance: 24,959.00
product: 27,329.00

The fix is a decision as much as code: the business agrees that revenue means paid orders only, writes that down once, and every consumer reads it from there.

04. Step 3: Define the semantic model and the metrics

In dbt 1.12 the semantic model sits inside the model's own YAML entry. Read the file below with the vocabulary from the problem statement in mind.

  • semantic_model: enabled: true turns fct_orders into a semantic model named orders.
  • agg_time_dimension: order_date says which date to use when someone asks for a metric "by month". MetricFlow calls that requested time metric_time.
  • Under columns, order_id is the primary entity (one row per order) and customer_id a foreign entity. order_date is a time dimension with granularity: day, its finest grain. region and status are categorical dimensions.
  • revenue, paid_orders and active_customers are simple metrics, the measures. The business rule "paid orders only" lives in their expr. average_order_value is a ratio metric: revenue divided by paid orders.

MetricFlow also needs a time spine, a table with one row per day, so that it can fill gaps and handle cumulative metrics. The time_spine block marks time_spine_daily as that table.

SQL · models/time_spine_daily.sql
select cast(d as date) as date_day
from range(date '2025-01-01', date '2027-01-01', interval 1 day) as t(d)
YAML · models/semantic.yml
models:
  - name: time_spine_daily
    time_spine:
      standard_granularity_column: date_day
    columns:
      - name: date_day
        granularity: day

  - name: fct_orders
    semantic_model:
      enabled: true
      name: orders
    agg_time_dimension: order_date
    columns:
      - name: order_id
        entity: {type: primary, name: order}
      - name: customer_id
        entity: {type: foreign, name: customer}
      - name: order_date
        granularity: day
        dimension: {type: time}
      - name: region
        dimension: {type: categorical}
      - name: status
        dimension: {type: categorical}
    metrics:
      - name: revenue
        description: Paid order value. Refunded orders do not count.
        type: simple
        agg: sum
        expr: "case when status = 'paid' then amount else 0 end"
      - name: paid_orders
        type: simple
        agg: sum
        expr: "case when status = 'paid' then 1 else 0 end"
      - name: active_customers
        description: Customers with at least one paid order in the period.
        type: simple
        agg: count_distinct
        expr: "case when status = 'paid' then customer_id end"
      - name: average_order_value
        type: ratio
        numerator: revenue
        denominator: paid_orders
Terminal
dbt --quiet build; echo "dbt exit code: $?"
mf list metrics | grep '^•'
Expected output
dbt exit code: 0
• active_customers: metric_time, order__order_date, order__region, order__status
• average_order_value: metric_time, order__order_date, order__region, order__status
• paid_orders: metric_time, order__order_date, order__region, order__status
• revenue: metric_time, order__order_date, order__region, order__status

Dimensions are named after the entity they belong to: order__region is the region of an order. A double underscore separates the parts, which is why names in the semantic layer must not contain one.

05. Step 4: Ask for metrics by month and with a filter

Ask for three metrics by month. January revenue is 24,959.00, the finance number, because the rule is now part of the definition. Nobody can forget it in a new dashboard.

Terminal
mf query --metrics revenue,paid_orders,average_order_value \
  --group-by metric_time__month --order metric_time__month --decimals 2 --quiet
Expected output
metric_time__month      revenue    paid_orders    average_order_value
--------------------  ---------  -------------  ---------------------
2026-01-01T00:00:00    24959.00            198                 126.06
2026-02-01T00:00:00    21448.42            164                 130.78
2026-03-01T00:00:00    23079.84            187                 123.42

Filters name dimensions with the Dimension() wrapper, so the layer can check that the dimension exists and add any joins it needs.

Terminal
mf query --metrics revenue --group-by metric_time__month \
  --where "{{ Dimension('order__region') }} = 'North'" \
  --order metric_time__month --decimals 2 --quiet
Expected output
metric_time__month      revenue
--------------------  ---------
2026-01-01T00:00:00    14508.17
2026-02-01T00:00:00    10018.68
2026-03-01T00:00:00    10107.33

06. Step 5: A ratio that is right at every grain

Now ask for average order value for the whole quarter. A tempting shortcut is to average the three monthly values from step 4: (126.06 + 130.78 + 123.42) / 3 = 126.75. That is wrong, because the months have different numbers of orders, and a plain average gives a quiet month as much weight as a busy one. The layer gets 126.57: total revenue divided by total paid orders.

Terminal
mf query --metrics average_order_value --group-by metric_time__quarter \
  --decimals 2 --quiet
Expected output
metric_time__quarter      average_order_value
----------------------  ---------------------
2026-01-01T00:00:00                    126.57

--explain prints the SQL instead of running it. The inner query sums revenue and paid orders at the requested grain, and only the outer query divides. A ratio metric always divides its parts at the grain of the query, whatever grain that is.

Terminal
mf query --metrics average_order_value --group-by metric_time__quarter \
  --quiet --explain | fold -s -w 80
Expected output
SELECT
  metric_time__quarter
  , CAST(revenue AS DOUBLE) / CAST(NULLIF(paid_orders, 0) AS DOUBLE) AS 
average_order_value
FROM (
  SELECT
    metric_time__quarter
    , SUM(__revenue) AS revenue
    , SUM(__paid_orders) AS paid_orders
  FROM (
    SELECT
      DATE_TRUNC('quarter', order_date) AS metric_time__quarter
      , case when status = 'paid' then amount else 0 end AS __revenue
      , case when status = 'paid' then 1 else 0 end AS __paid_orders
    FROM "shop"."main"."fct_orders" orders_src_10000
  ) subq_3
  GROUP BY
    metric_time__quarter
) subq_5

07. Step 6: Distinct counts do not add up

active_customers counts distinct customers with a paid order. Ask for it by month and by quarter.

Terminal
mf query --metrics active_customers --group-by metric_time__month \
  --order metric_time__month --quiet
mf query --metrics active_customers --group-by metric_time__quarter --quiet
Expected output
metric_time__month      active_customers
--------------------  ------------------
2026-01-01T00:00:00                   97
2026-02-01T00:00:00                   86
2026-03-01T00:00:00                   90
metric_time__quarter      active_customers
----------------------  ------------------
2026-01-01T00:00:00                    117

The months add up to 273, but the quarter has 117 customers. Both are correct: a customer who ordered in January and in March is one customer in the quarter but appears in two months. A sum is additive, so monthly sums can be rolled up to a quarter; a distinct count is non-additive, so it must be computed again from the rows at each grain. A pre-computed table of monthly active customers cannot answer the quarterly question, while the semantic layer can, because it computes from the rows each time.

08. Step 7: A second consumer gets the same numbers

A semantic layer pays off when every consumer goes through it. Here the second consumer is a Python job, the kind of code that feeds an internal app or a scheduled report. It asks the layer for revenue by month and region, then adds up each region in Python. Self-hosted MetricFlow is reached through its command line, as here; on the dbt platform, BI tools and applications reach the same definitions through the Semantic Layer APIs.

Python · app_report.py
"""A second consumer: a Python job that asks the semantic layer, not the tables."""
import csv
import subprocess
from collections import defaultdict


def metric_query(metrics, group_by):
    subprocess.run(["mf", "query", "--metrics", metrics, "--group-by", group_by,
                    "--csv", "result.csv", "--quiet"], check=True)
    with open("result.csv", newline="") as f:
        return list(csv.DictReader(f))


rows = metric_query("revenue", "metric_time__month,order__region")
by_region = defaultdict(float)
for row in rows:
    by_region[row["order__region"]] += float(row["revenue"])
for region, revenue in sorted(by_region.items()):
    print(f"{region}: {revenue:,.2f}")
Terminal
python app_report.py
mf query --metrics revenue --group-by order__region --order order__region \
  --decimals 2 --quiet
Expected output
North: 34,634.18
South: 34,853.08
order__region      revenue
---------------  ---------
North             34634.18
South             34853.08

The job's totals, added up from month-and-region rows, match the layer's direct answer by region to the cent. Revenue is a sum, so rolling it up is safe; the job would be wrong if it rolled up active_customers the same way, which is why consumers should ask the layer for each grain they need.

09. Check your understanding

Practice check · 3 questions

Definitions, grains and additivity

Each question builds on this worked example. Pick the best answer.

Q1. Finance decides that revenue should leave out orders under 10.00 from next month. Where should that change go?
Q2. You run `mf query --metrics paid_orders --group-by metric_time__quarter`. Using the monthly results from step 4, what does it return?
Q3. A colleague defines average order value as a simple metric with `agg: average` and `expr: amount`. How does it compare with the ratio metric in this example?
Practice only: not graded, not saved, not evidence.

10. Apply it

This is the semantic layer part of the skill practice. On the star schema from your batch project:

  • Define five metrics, including at least one ratio and one distinct count, with descriptions that state the business rule in plain words.
  • Query each metric at two grains and by one dimension, and keep the outputs as evidence.
  • Make a dashboard and a Python client read the same metric through the layer, and show that their totals match.
  • Add a CI step that runs mf validate-configs, so a broken definition fails the pull request.

11. Review prompt

Without looking back, explain: why two correct-looking queries can disagree; what measures, dimensions, entities, time grains and metrics are; why a ratio must divide its parts at the grain of the query; why monthly active customers do not add up to quarterly active customers; and what changes for consumers once metrics come from a semantic layer.

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