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
On this page
- The problem
- Step 1: Set up the project and the data
- Step 2: Reproduce the disagreement
- Step 3: Define the semantic model and the metrics
- Step 4: Ask for metrics by month and with a filter
- Step 5: A ratio that is right at every grain
- Step 6: Distinct counts do not add up
- Step 7: A second consumer gets the same numbers
- Check your understanding
- Apply it
- Review prompt
Lessons of Data Serving & BI
- Who Consumes Data and How It Reaches Them Concept · 20 min
- One Definition per Metric: Building a Semantic Layer Worked example · 25 min
- Lab: A Fast Dashboard That Respects Access Rules Lab · 30 min
- Lab: Reverse ETL from a Mart to an Operational Tool Lab · 25 min
- Low-Latency Serving: Caches, Data APIs and Real-Time OLAP Worked example · 20 min
- Check: Choose and Defend a Serving Path Knowledge check · 8 questions
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
amountor 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_idorcustomer_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.
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""""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}"])name: shop
version: "1.0.0"
profile: shopshop:
target: dev
outputs:
dev:
type: duckdb
path: shop.duckdbselect order_id, customer_id, cast(order_date as date) as order_date,
region, status, amount
from {{ ref('raw_orders') }}python make_seed.py
dbt --quiet build; echo "dbt exit code: $?"dbt exit code: 003. 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.
"""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}")python two_teams.pyfinance: 24,959.00
product: 27,329.00The 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: trueturnsfct_ordersinto a semantic model namedorders.agg_time_dimension: order_datesays which date to use when someone asks for a metric "by month". MetricFlow calls that requested timemetric_time.- Under
columns,order_idis the primary entity (one row per order) andcustomer_ida foreign entity.order_dateis a time dimension withgranularity: day, its finest grain.regionandstatusare categorical dimensions. revenue,paid_ordersandactive_customersare simple metrics, the measures. The business rule "paid orders only" lives in theirexpr.average_order_valueis 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.
select cast(d as date) as date_day
from range(date '2025-01-01', date '2027-01-01', interval 1 day) as t(d)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_ordersdbt --quiet build; echo "dbt exit code: $?"
mf list metrics | grep '^•'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__statusDimensions 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.
mf query --metrics revenue,paid_orders,average_order_value \
--group-by metric_time__month --order metric_time__month --decimals 2 --quietmetric_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.42Filters name dimensions with the Dimension() wrapper, so the layer can check that the dimension exists and add any joins it needs.
mf query --metrics revenue --group-by metric_time__month \
--where "{{ Dimension('order__region') }} = 'North'" \
--order metric_time__month --decimals 2 --quietmetric_time__month revenue
-------------------- ---------
2026-01-01T00:00:00 14508.17
2026-02-01T00:00:00 10018.68
2026-03-01T00:00:00 10107.3306. 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.
mf query --metrics average_order_value --group-by metric_time__quarter \
--decimals 2 --quietmetric_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.
mf query --metrics average_order_value --group-by metric_time__quarter \
--quiet --explain | fold -s -w 80SELECT
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_507. 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.
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 --quietmetric_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 117The 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.
"""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}")python app_report.py
mf query --metrics revenue --group-by order__region --order order__region \
--decimals 2 --quietNorth: 34,634.18
South: 34,853.08
order__region revenue
--------------- ---------
North 34634.18
South 34853.08The 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
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.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.