Skip to content
Tech Interview Prep
Technical interview guide

Semantic Data Modeling for BI

The metrics layer that defines business terms consistently, so 'revenue' means the same thing in every report.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v5
Editorial status
Reviewed

Scope: Current dbt MetricFlow, LookML, Power BI, Tableau, Cube, OpenMetadata, BigQuery, and Snowflake guidance reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Define grain for an orders semantic model.

Answer

Grain is what one row in a fact table represents. For an orders model, the first decision is whether that row is an order header, an order line, a shipment, a payment, or a daily snapshot. I'd pick order line as the base grain for sales, because price, discount, tax, and product are determined at the line. Order header becomes a dimension or a separate fact at order grain. Shipments and payments get their own facts at their own grains.

Assume a retail domain: one order has many lines, lines can ship in separate shipments, payments can be partial, refunds can be partial. We need order count, units sold, gross revenue, net revenue, and on-time delivery.

Worked example, hypothetical order #1001:

entitygrainrows for #1001key
order headerone row per order1order_id
order lineone row per line3order_id, line_id
shipmentone row per shipment2shipment_id
paymentone row per payment1payment_id

Metrics at line grain: order count = COUNT(DISTINCT order_id) = 1. Units sold = SUM(quantity) = 5 (lines: 2, 2, 1). Gross revenue = SUM(line_amount) = $120. If you used order grain and stored order_total = $120, you get the same revenue, but you cannot get units by product. If you used line grain and did COUNT(*) for orders, you get 3, which is wrong.

Trade-offs. Order grain is simpler, fewer rows (1x), faster for order dashboards, but cannot answer product or fulfillment questions. Line grain is 3.2x rows on average (hypothetical), more storage, but supports product margin and returns. Shipment grain is needed for on-time delivery; if you only have order grain, you cannot compute partial shipment delays. Deciding criteria: what is the most granular question you must answer? If you need product-level returns, line grain. If you only need daily order counts, order grain. When wrong: using order grain for line-level metrics forces a join to a line table and aggregation, which can double-count if the join fans out; using line grain for order count without DISTINCT overcounts by lines per order.

Failure modes. Duplicate rows from retries or late-arriving updates. Detection: uniqueness test on (order_id, line_id) should return zero duplicates. If it fails, you have a fan-out or duplicate load. Operational cost: a 2x duplicate on 320M rows doubles reported revenue until backfilled. Another failure: mixing grains in one table causes metric reconciliation failures. Order count from line fact vs order fact differ by lines per order. Detection: reconcile order count between facts; if line fact count is 3.2x order fact, that's expected, but if you expected 1:1, you have a grain mismatch.

Event and processing times: at line grain, event time is the order-placed timestamp, processing time is ingestion timestamp. Late updates: if a line is added after order placement, you need to handle it; at order grain, you might miss it. That is a grain choice consequence, not a test checklist.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-11

Handle null, unknown, and not-applicable dimensions.

Answer

First, clarify what 'null' means here. In a dimensional warehouse, a null dimension foreign key can mean the source didn't provide it, it's late, it's redacted, it's truly unknown, or it's not applicable. Each has different handling. Assume we're in a star schema with fact and dimension tables, and we need to preserve facts for accurate totals and allow filtering.

The standard approach is to use explicit unknown members in dimension tables with stable surrogate keys. For example, a customer dimension might have customer_key = -1 for 'Unknown', -2 for 'Not Applicable', -3 for 'Redacted'. Never use NULL as a foreign key in the fact table. For late-arriving dimensions, load the fact with the unknown key, then backfill when the dimension arrives, updating the fact and keeping an audit trail.

Why? In SQL, NULL != NULL, so a fact with NULL dimension key won't match any dimension row in an inner join. That silently drops the fact from totals. In an outer join, it produces a row with NULL attributes, which can break filters and aggregations. A surrogate key like -1 matches a real row, so the join succeeds and the fact is included under 'Unknown'.

Hypothetical example: fact table has 1,000 rows. 50 rows have dim_key = NULL. Query: SELECT d.category, SUM(f.amount) FROM fact f JOIN dim d ON f.dim_key = d.dim_key GROUP BY d.category. With NULL, the 50 rows are excluded, so total sum is 950. With dim_key = -1 and a dimension row (-1, 'Unknown'), the sum is 1,000 and 'Unknown' appears as a category.

Trade-offs: Three options. (1) NULL in fact: simple ETL, but breaks joins and aggregates. Wrong when you need to join or aggregate. (2) Dedicated UNKNOWN row in dimension: preserves joins, allows attributes, but requires governance to prevent misuse (e.g., analysts filtering out unknown). Best for most cases. (3) Separate fact table for unknowns: avoids polluting dimension, but complicates queries and totals. Wrong when unknowns are a small fraction or when you need to join to dimension for attributes.

Failure modes: Unknown rate grows silently. Detection: monitor percentage of facts with unknown key per dimension. Alert if it exceeds a threshold (e.g., 5% for a week). Symptom: reports show 'Unknown' category growing, totals shift. Cost: analysts lose trust, backfill becomes expensive. Not-applicable misclassified as unknown. Detection: audit sample of unknown facts, check source. Symptom: incorrect filtering (e.g., 'Not Applicable' included in 'Unknown' totals). Late-arriving dimension not backfilled. Detection: compare fact load date vs dimension load date, alert on aging unknowns (e.g., > 7 days). Symptom: unknown persists, reports stale.

Table: Option | Join behavior | Aggregation | Governance | When to use NULL | Inner join drops rows; outer join gives NULLs | Breaks SUM, COUNT | None | Never for dimensions Dedicated UNKNOWN row | Inner join works | Works | Requires policy | Most cases Separate fact table | No join to dimension | Requires union | Complex | When unknowns are large and distinct

Use dedicated unknown members with surrogate keys. Decide whether unknown members are included in totals and filters: typically include them in totals to avoid undercounting, but allow filtering them out for specific analyses. Monitor unknown rates, backfill late arrivals, and preserve audit. Test outer-join behavior, default filters, localization, and row-security interaction.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Define metric time, calendar, and incomplete-period behavior.

Answer

Core answer

Metric time is the single timestamp a metric is bucketed by, and it is a business event time, not a system time. Pick it per metric and write it down: revenue uses settlement time, bookings use booking time, shipments use ship time. Store it as UTC (timestamptz in Postgres, TIMESTAMP in BigQuery) and keep the source zone name (America/New_York, not -05:00) plus ingestion and processing timestamps as separate columns. The zone name matters because offsets are political: US Eastern is UTC-5 in winter and UTC-4 in summer, and tzdata changes it by law.

Calendar behavior is the mapping from that instant to the buckets you report on. It is a conformed dimension, one row per day, with columns for calendar date, ISO week, month, quarter, fiscal period, and a holiday flag. Declare four things: week start (ISO is Monday; US retail often Sunday), the reporting timezone used to cut the day, fiscal year start, and how the fiscal calendar is built (4-5-4 retail, or a 52/53-week year).

Incomplete-period behavior is what you do when the current bucket is partial. A month-to-date figure compared against a full prior month is not a comparison; it is a smaller window. Two accepted fixes: compare period-to-date against the same day-count of the prior period, or show the partial bucket with an explicit "in progress" label and suppress period-over-period deltas until close.

Trade-offs

Event time vs processing time: event time gives stable, restatable numbers but late data forces backfills; processing time is simple but a re-run changes history. Choose event time for anything financial or contractual; processing time only for operational monitoring where "when we saw it" is the question.

Booking vs settlement: booking time measures demand, settlement measures realized revenue. They diverge by refunds and cancellations, so a metric must name which one and never mix them in one series.

Zone name vs fixed offset: fixed offsets are cheap and wrong across DST; zone names cost a tzdata dependency but survive it.

Failure modes

  • DST spring-forward: 2025-03-09 in America/New_York has no 02:00–02:59. A daily job keyed on local midnight can drop or double a day. Detect by asserting 365/366 distinct local dates per year.
  • Fall-back: 2025-11-02 01:00–01:59 occurs twice; naive local timestamps collide. Detect by counting duplicate local timestamps.
  • Cutoff race: a batch that closes at 00:05 UTC catches events that landed at 23:58 but misses a 00:02 late arrival, so yesterday's number changes tomorrow. Detect by tracking row counts per event date across runs.
  • Fiscal boundary: ISO week 1 of 2021 starts 2021-01-04; 2021-01-01 belongs to ISO week 53 of 2020. A calendar-year join silently mislabels it.

Artefacts

conceptwhat it isthe decision it forces
metric timebusiness event instant, UTC + zone namebooking vs settlement
calendarconformed day dimensionweek start, fiscal rule
incomplete periodpartial current bucketPTD vs full-period compare
SQL
-- Postgres: bucket by event time in the reporting zone
SELECT date_trunc('week', booked_at AT TIME ZONE 'America/New_York') AS wk,
       count(*)
FROM bookings
GROUP BY 1;

Arithmetic: a US Eastern day is 23 hours on 2025-03-09 and 25 hours on 2025-11-02, so a "daily average per hour" metric shifts by roughly 4% on those days unless you divide by actual hours.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Model a many-to-many attribution relationship.

Answer

Core answer (first 90 seconds)

Assume the case is orders credited to several campaigns, and I need revenue per campaign plus "how many orders touched this campaign" without double counting. I model it as a bridge table between the fact and the dimension, with an explicit allocation weight on the bridge. Grain is one row per (order, campaign, validity window). The weight is the semantic contract: it states how much of the order's additive measures belong to that campaign.

SQL
CREATE TABLE campaign_attribution (
  order_id    bigint       NOT NULL REFERENCES orders(order_id),
  campaign_id int          NOT NULL REFERENCES campaign(campaign_id),
  weight      numeric(5,4) NOT NULL CHECK (weight > 0 AND weight <= 1),
  valid_from  date         NOT NULL,
  valid_to    date         NOT NULL DEFAULT '9999-12-31',
  PRIMARY KEY (order_id, campaign_id, valid_from)
);

The primary key is the bridge grain. valid_from/valid_to make restatements append-only instead of overwriting history.

Why the weight exists: the fan-out mechanism

Joining a fact to a bridge multiplies fact rows by the number of matching bridge rows. Order 4471 is $300 and is credited to three campaigns at 0.5/0.3/0.2. A naive SUM(o.amount) over the join counts 4471 three times:

100 orders, source total $50,000
naive join:     50,000 + 2 x 300 = 50,600   -- 4471 counted 3x
weighted:       SUM(amount * weight) = 50,000
per campaign:   150 / 90 / 60

The weight is what makes the join additive-safe: it redistributes the order's revenue instead of replicating it.

Trade-offs: pick by whether the metric must reconcile

AllocationSums to source total?Use whenWrong when
Full credit (each campaign gets 100%)NoReach/awareness counting, overlap analysisAny revenue or ROAS number
Fractional (weights sum to 1)YesRevenue, spend, ROAS attributionYou need per-campaign counts of distinct orders
Distinct entity (COUNT DISTINCT order_id)N/A: no additive fact summed"How many orders touched campaign X"You need a dollar figure

Deciding rule: if the metric has a source total it must tie back to, use fractional or distinct. If you are measuring overlap, full credit is fine because you never sum the additive fact.

Failure modes, with detection

  1. Fan-out double counting. Symptom: totals inflate by exactly the extra attribution count. Detect with a reconciliation query:
SQL
SELECT
  (SELECT SUM(amount) FROM orders) AS source_total,
  (SELECT SUM(o.amount * a.weight) FROM orders o
     JOIN campaign_attribution a USING (order_id)) AS attributed_total;

Cost: overstated ROAS, budget shifted to campaigns that did not earn it.

  1. Weights that do not sum to 1. Symptom: fractional totals drift from source. Detect:
SQL
SELECT order_id, SUM(weight) FROM campaign_attribution
GROUP BY order_id HAVING SUM(weight) <> 1;
  1. Unattributed orders vanish. An inner join silently drops orders with no bridge row. Detect by comparing COUNT(*) from orders against COUNT(DISTINCT order_id) in the bridge; the gap is your unknown bucket.

  2. Late corrections. A restatement that overwrites valid_to changes historical reports retroactively. Detect by snapshotting as-of totals and diffing; keep the append-only window so the old answer is still reproducible.

Close

State the allocation contract up front, put the weight on the bridge, and guard every additive query with the reconciliation check. That is the whole model: grain, weight, validity, and one query that proves the totals still tie out.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Design and validate semantic relationships.

Answer

Assume a warehouse-backed semantic layer (dbt, LookML, or Cube style) over a multi-tenant warehouse, where the model is the contract that both BI and the metrics API read from. The answer I'd give: every relationship is a four-clause contract (grain, integrity, direction, scope) and each clause gets a SQL assertion that runs on every model build. If an assertion fails, the model does not publish. Validation is not a review of today's sample; it is a gate that runs tomorrow too.

The four clauses:

  • Grain. The one side is unique at its declared key, per tenant. State the key explicitly; customer_id alone is not unique if tenants share a sequence.
  • Integrity. Every many-side key resolves to exactly one one-side row, or maps to an explicit unknown member. Decide which, and encode it.
  • Direction. Filter propagation is declared, not inferred. A filter on the dimension either does or does not restrict the fact, and the model says which.
  • Scope. Tenant predicate and temporal predicate are part of the join condition, not the caller's responsibility.
SQL
-- grain: one side unique per tenant
select tenant_id, customer_id, count(*)
from dim_customers group by 1,2 having count(*) > 1;

-- integrity: many side resolves, tenant-scoped
select count(*) from fct_orders o
left join dim_customers c
  on c.tenant_id = o.tenant_id and c.customer_id = o.customer_id
where c.customer_id is null;

-- temporal: SCD2 join must hit exactly one version
select count(*) from fct_orders o
join dim_customers c
  on c.customer_id = o.customer_id
 and o.ordered_at >= c.valid_from
 and o.ordered_at <  c.valid_to
group by o.order_id having count(*) <> 1;

Why fanout happens, with numbers. Take 1,000 orders totalling $180,000 and 2,400 order items. SUM(orders.amount) alone is $180,000. Join orders to order_items and sum the same column: each order's amount repeats once per item, so you get $432,000. The inflation ratio, 2.4, is exactly 2,400/1,000: the average items per order. That is the test: compare the aggregate with and without the join, and assert the ratio is 1.0 for any relationship declared many-to-one. A ratio of 2.4 means the model declared the wrong cardinality, not that the data is dirty.

Trade-offs, and when each choice is wrong.

choiceright whenwrong when
Physical FK constraintwarehouse is the system of record, writes are low-volumebulk loads and late-arriving facts: the constraint blocks the load and you cannot backfill orphans
Declared-only + CI assertionwarehouse is a load target, ELT owns integritynothing runs the assertion, so drift is invisible until a dashboard is wrong
Inner join to dimensionorphan facts are a bug you want surfaced loudlyit silently drops fact rows; revenue stops reconciling to finance
Left join + unknown memberfact totals must reconcilethe null member pollutes "top customers" and any grouped report
Symmetric aggregate at fact grainad-hoc joins, unknown query pathsslower, and unnecessary if the model exposes one pre-defined path

Failure modes and how each is detected.

  • Fanout: the ratio test above fires; symptom is revenue reading 2.4x finance; cost is a quarter of decisions made on inflated numbers.
  • Cardinality drift: a backfill introduces a duplicate customer_id; the nightly uniqueness assertion fires; symptom is fanout appearing with no model change.
  • Ambiguous path: two FKs from orders to customers (customer_id, billing_customer_id); assert exactly one declared path per fact-dimension pair; symptom is two analysts getting different revenue from the same metric name.
  • Cross-tenant match: the join omits tenant_id; assert zero joined rows where tenants differ; symptom is one customer seeing another's rows. A security incident, not a data-quality one.
  • Temporal: SCD2 join without valid_from/valid_to; assert every fact matches exactly one version; symptom is historical reports restated with today's attributes.

If pushed on which single check matters most, I'd say the fanout ratio: it is the one that catches a wrong cardinality declaration, a drifted key, and an ambiguous path with the same assertion.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Resolve ambiguous and bidirectional relationships.

Answer

Core answer (first 90 seconds)

Ambiguity is a counting problem, not a modelling preference. Before I touch a relationship I count the distinct join paths from each fact to each dimension. Zero paths: the dimension is unreachable and its fields are decoration. One path: single-direction filter, done, no decision to make. Two or more: I have to name them, because the engine will otherwise pick one for me, and the pick can change when the query changes.

So the answer is: pick one path active per explore, expose the others as separate explores or activate them per measure. In Power BI, a second relationship between the same pair of tables lands inactive (dashed) and you opt in per measure with USERELATIONSHIP(dim_order_date[date], fct_sales[order_date]). In Looker you do the same thing with a role-playing alias in sql_on, or a separate explore.

Bidirectional filtering (Both cross-filter direction in Power BI, relationship: many_to_many in Looker) is the right call in exactly one situation: a bridge table between a fact and a dimension where the bridge is the only path and the filter genuinely has to travel both ways. Everywhere else it is a shortcut that hides a second path.

Why ambiguity produces wrong totals

Two paths from fct_sales to dim_region: one via dim_customer.region_key, one via dim_store.region_key. With both active and bidirectional, a query grouping revenue by region joins through both. That join is an inner join on region, so a sales row survives only if the customer's region and the store's region agree. Rows where they disagree disappear.

Trace (hypothetical, 1M-row fact):

  • Total revenue, customer path only: $12,400,000
  • Total revenue, store path only: $12,400,000
  • Both paths active, grouped by region: $11,900,000
  • Missing: 4% of rows, $500,000. Customers whose billing region differs from the store's region

Same query, three totals, no error message. That is the failure signature: the total moves when you add a field from the other path, and it moves silently.

Fan-out is the other half

Joining a fact to two one-to-many tables multiplies rows. 1,000,000 order lines × 1.8 shipments per line = 1,800,000 rows, and SUM(revenue) returns $22.3M instead of $12.4M. Looker's symmetric aggregates (on by default) prevent this by packing the primary key into the aggregate so DISTINCT dedupes the fan-out; a many_to_many relationship needs a sql_distinct_key on the measure to stay correct. Power BI has no equivalent, so the fix is structural: keep the shipment measure in its own table, or use a measure that does not traverse the fan-out.

Failure modes and how I detect them

failuresymptomdetection
ambiguous pathtotal changes when an unrelated dimension is addedrun the measure with each path's dimension, compare
fan-outmeasure scales with the row count of the joined tablecompare measure at fact grain vs. aggregated
bidirectional leakfiltering dim A silently filters dim Bremove the filter, compare row counts of B
RLS gapa user sees rows on one path they cannot see on the otherrun the same user against both paths
planner costquery time jumps when the second path is activecompare timings with the path on and off

When bidirectional is right

Bridge tables. A many-to-many between fct_sales and dim_promotion through bridge_sale_promotion needs both directions or the filter never reaches the fact. Also when a conformed dimension serves two facts and one filter must reach both, but only if there is exactly one path to it. If there are two, you do not have a bidirectional problem, you have an ambiguity problem, and Both will paper over it until someone adds a field.

Decision rule: count paths first. One path, single direction. Two or more, name them, one active per explore, the rest via USERELATIONSHIP or a role-playing alias. Reach for Both only when the bridge is the only path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Prevent metric fanout across semantic joins.

Answer

The 90-second answer

Fanout is a row-multiplication bug, not an aggregation bug. Join a fact table to a table at a finer grain, orders to order_items, and each order row is repeated once per matching item. SUM(order_total) then adds the same order's total N times. COUNT(DISTINCT order_id) is unaffected because the key is still distinct; COUNT(*) is inflated; MIN/MAX are unaffected; AVG silently becomes a row-weighted average instead of an order-weighted one.

So: declare the grain of every model and the cardinality of every join, validate that the "one" side is actually unique, and either aggregate the fact-grain measure before the join or let the semantic layer deduplicate by the fact's primary key.

Trace

orders: grain: one row per order

order_idorder_total
1100
250

order_items: grain: one row per item

order_iditem_iditem_price
1a60
1b40
2c50
SQL
SELECT SUM(o.order_total)        AS revenue,
       COUNT(*)                  AS rows_,
       COUNT(DISTINCT o.order_id) AS orders_
FROM orders o JOIN order_items i USING (order_id);

→ revenue = 250, rows_ = 3, orders_ = 2. True revenue is 150. Order 1's total was counted twice because it has two items. SUM(i.item_price) = 150 is correct: that measure lives at the item grain, so the join does not multiply it. AVG(o.order_total) returns (100+100+50)/3 = 83.33 instead of the order-weighted (100+50)/2 = 75.

Fix: pre-aggregate at the originating grain:

SQL
WITH order_rev AS (
  SELECT order_id, SUM(order_total) AS revenue
  FROM orders GROUP BY order_id
)
SELECT SUM(revenue) FROM order_rev;  -- 150

Alternatives

  • Symmetric aggregates (Looker): declare primary_key: yes on the fact view and relationship: many_to_one on the join. Looker then generates SQL that deduplicates fact rows by that key before summing, so SUM(order_total) returns 150 even with item dimensions in the query. Without the primary key it falls back to plain SUM and you get 250.
  • Semantic-layer join declarations (dbt Semantic Layer / MetricFlow): entities typed primary, unique, foreign plus a declared join relationship give the planner the grain information it needs to aggregate at the right level.
  • Tableau relationships (2020.2+) keep each table at its own grain and join at query time, so a measure defined in orders is not multiplied by order_items rows.
  • Bridge tables: when the many-to-many is real (orders ↔ promotions), model a bridge with an allocation factor and aggregate the allocated amount rather than joining directly.

Failure modes

  • Ratio metrics hide it: if numerator and denominator fan out by the same factor, SUM(a)/SUM(b) is unchanged while both components are wrong. Check the components, not the ratio.
  • The bug is invisible until a dimension from the many side is added. Test every metric's total with and without each supported joined dimension.
  • Missing keys: an inner join silently drops facts with no match; a left join keeps them but produces NULLs on the many side. Test both.
  • Duplicate keys on the "one" side: a supposedly unique order_id appearing twice multiplies everything. Assert uniqueness as a data test, SELECT order_id FROM orders GROUP BY 1 HAVING COUNT(*) > 1, not a one-off query.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design conformed customer, product, and calendar dimensions.

Answer

Conformed dimensions means one row per business entity, one surrogate key, and one agreed definition of every attribute, shared by every fact process that slices on it. The payoff is concrete: you can add revenue from orders and subtract returns on the same customer_sk and the number reconciles, because both facts point at the same row.

Assumptions: three fact processes. Orders at order-line grain, shipments at shipment grain, returns at return-line grain. CRM owns customer, PIM owns product, finance owns the fiscal calendar. Columnar warehouse, INT surrogate keys.

Start with the calendar, because it is the cheapest and it anchors the other two. One row per day, 2020-01-01 through 2039-12-31 is 7,305 rows. date_key is INT in yyyymmdd form (20240305), 4 bytes. Every fact joins on it, so "revenue and returns by fiscal week" is one group-by with no date arithmetic in the query. At 500M fact rows, a 4-byte date key instead of an 8-byte timestamp saves 2 GB on that column alone.

Customer and product need history, so use SCD Type 2 on the attributes whose past value must stay attached to past facts (customer segment, product category) and Type 1 overwrite on pure corrections like a misspelled name. The trace:

dim_customer: customer_sk, customer_bk, segment, valid_from, valid_to, is_current

Current row: sk=902, bk='C-4471', segment='SMB', valid_from=2023-01-01, valid_to=9999-12-31, is_current=1

2024-03-01 load, CRM now says segment='Enterprise':
  step 1  close old row  -> sk=902, valid_to=2024-02-29, is_current=0
  step 2  insert new row -> sk=1187, segment='Enterprise', valid_from=2024-03-01, valid_to=9999-12-31, is_current=1
  step 3  the 2024-03-05 order gets customer_sk=1187; the 2023-06 order keeps 902

So a 2023 revenue-by-segment report still shows SMB for that customer's 2023 orders. Under Type 1 it would retroactively read Enterprise and last year's numbers would move.

Many-to-many identity (a customer in several segments, a product in several price bands) does not go in the dimension. Use a bridge table with a weighting factor, or a mini-dimension if the combination set is small and stable. Arithmetic: customer 4471 sits in 3 segments with weights 0.5/0.3/0.2. The orders fact has 1,000,000 rows, 4,000 of them this customer. Joining through the bridge yields 12,000 rows; SUM(revenue * weight) returns the true total, while an unweighted sum triples it.

Failure modes and how you catch them:

  • Late-arriving dimension. Fact lands before the customer row exists. Detect: count fact rows with customer_sk = -1 (the unknown member) after each load; alert above 0.5% of daily rows. Cost: those rows are invisible to every segment rollup until backfilled.
  • Type 2 fan-out. A join to the dimension without is_current = 1 or a valid_from/valid_to range predicate multiplies rows. Detect: post-join row count exceeds fact row count.
  • Conformed drift. Two teams define "active customer" differently: 90 days vs 180. Detect: the same metric computed from two facts disagrees; that is the signal, not a rounding error.

Do not force conformity where meaning genuinely differs. If product "category" is a merchandising taxonomy in one process and a regulatory class in another, build dim_product_merch and dim_product_reg, both keyed on the same product_sk, rather than one column carrying two meanings. Conform the key and the grain; split the attribute.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do you handle role-playing dimensions and shared conformed dimensions across heterogeneous fact tables at different granularities?

Answer

To model role-playing dimensions and multi-fact conformed dimensions across heterogeneous granularities, isolate context through dimension aliasing and enforce grain-preserving aggregation boundaries.

1. Role-Playing Dimensions: Aliasing vs. Inactive Paths

A single physical dimension entity (e.g., dim_date or dim_location) playing multiple business roles (e.g., order_date, ship_date, fulfillment_date) must be disambiguated to prevent join ambiguity and circular paths.

  • In Semantic Engines & Code-first Layers (LookML, Cube, dbt MetricFlow): Instantiate explicit aliases or views of the dimension. In LookML, join the view under distinct join names: join: order_date { from: dim_date ... } and join: ship_date { from: dim_date ... }. In Cube, define distinct cube joins aliasing the dimension cube. This enables simultaneous filtering across multiple date roles on the same fact.
  • In Desktop BI Graph Engines (Power BI): Only one active relationship can exist between two tables. Secondary date roles use inactive relationships activated selectively via DAX (USERELATIONSHIP(fact_orders[ship_date_key], dim_date[date_key])). However, if users must cross-filter order_date and ship_date simultaneously in visual slicers, physical or calculated table aliasing (dim_ship_date = dim_date) is required.

2. Heterogeneous Granularities and Fact Drill-Across

When combining facts at different grains: such as daily transaction lines (fact_order_line at order_id + line_id, daily grain) and monthly marketing budget (fact_marketing_spend at channel_id + month_date_key, monthly grain): never join fact-to-fact directly across dimensions, which causes metric fanout.

Instead, use a conformed constellation model with drill-across behavior:

[dim_channel] <---(1:N)--- [fact_marketing_spend] (Grain: Channel + Month)
      ^                            |
      | (1:N)                      v (N:1 via month)
[fact_order_line] ---------> [dim_date] (Conformed: day_key, month_key)
 (Grain: OrderLine + Day)
  1. Conformed Grain Boundary: Dimensions joined to aggregate facts must conform at the target grain. dim_date provides month_date_key (first day of month), acting as the conformed key for fact_marketing_spend, while day_date_key joins to fact_order_line.
  2. Independent Subqueries (Symmetric Aggregation / Drill-Across): The query engine must aggregate each fact table independently to the shared grain before joining. Looker achieves this via symmetric aggregates (SUM(DISTINCT ...) using primary keys) or federated subqueries; Tableau leverages multi-table logical relationships that aggregate measures at their native level before combining.

Comparison of Grain Alignment Approaches

PatternImplementationProsCons / Risks
Pre-aggregated RollupAggregate daily facts to monthly rollup table in ETLFastest runtime query; simple 1:N star schemaLoses line-item drill-down capability in the same report view
Engine Split-Query (Drill-Across)Independent queries joined on conformed keysPreserves native line grain; single unified metric layerSlower SQL; requires strictly defined primary keys on all facts
Dimension AliasingSeparate physical/logical views per roleAllows simultaneous visual slicing on distinct rolesMultiplies dimension catalog objects and cache memory

Concrete Failure Mode

Failing to alias a role-playing dimension while joining two facts creates a chasm trap or circular dependency: querying Spend and Revenue by Date can silently filter spend by order_date instead of spend allocation date, distorting marketing ROI metrics by 10%–50% due to dropped records or multi-counted sums.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Model current-state and historical dimensional analysis.

Answer

First 90 seconds. I'd pin down two assumptions before answering: the source sends one row per business key as it stands right now, with an updated_at timestamp or a set of columns I can diff; and the warehouse is the only place history will live. Facts arrive carrying the customer's business key and their own event timestamp. Then the answer: there are two different questions hiding in 'current-state and historical', who was this customer when the order was booked and who is this customer now, and they must not be served by the same query. One versioned dimension table, a surrogate key per version, an explicit validity interval, plus a per-fact-table decision about whether the fact stores that surrogate or resolves the version at read time.

Store the surrogate on the fact when the report must reproduce as booked: finance close, published dashboards. Keep the business key on the fact when a row can be re-attributed after a source correction and you want the correction to flow through. Normally you do both: surrogate for the close, business key for the correction path.

The table.

SQL
create table dim_customer (
  cust_sk    bigint       not null,  -- hash(cust_id, valid_from) truncated to 64 bits
  cust_id    bigint       not null,  -- durable business key
  tier       varchar(16)  not null,
  valid_from timestamp_tz not null,
  valid_to   timestamp_tz,           -- null = open
  is_current boolean      not null,
  primary key (cust_sk)              -- informational on Snowflake/Redshift, enforced on Postgres
);

Hash rather than a sequence so a full refresh reproduces the same surrogate and fact rows never need rewriting. The cost is that you can't cheaply renumber, and a 64-bit hash collision, while negligible, is unrepairable in place.

A worked trace. Customer 4471 changes tier three times:

cust_skcust_idtiervalid_fromvalid_tois_current
910044471Silver2024-03-01 00:00Z2024-11-15 00:00Zfalse
910774471Gold2024-11-15 00:00Z2025-02-03 00:00Zfalse
912304471Platinum2025-02-03 00:00Znulltrue

Order 88321, $1,240, booked 2024-12-02 14:20Z with cust_sk = 91077:

readpredicatetier returned
event-time (as booked)f.cust_sk = d.cust_skGold
current-statef.cust_id = d.cust_id and d.is_currentPlatinum
point-in-time at 2024-12-31cust_id = 4471 and valid_from <= '2024-12-31' and (valid_to > '2024-12-31' or valid_to is null)Gold

That single order lands in Gold for a Q4-2024 revenue-by-tier report and Platinum for a live pipeline report. The 1,240 is a legitimate difference, not a bug: the bug is a query that mixes the two predicates in one WHERE.

The two diverge when a correction is backdated. If on 2025-06-01 the source says 4471 was Gold from 2024-09-01, the right write is to insert the version at the true effective time and re-close the following version to 2024-09-01, not to append a version stamped 2025-06-01. Facts still carrying 91077 keep pointing at the November Gold row until you rewrite them, which is exactly why the business-key path exists.

Failure modes, and how each is caught.

  1. Overlaps. Postgres can enforce this: EXCLUDE USING gist (cust_id WITH =, tstzrange(valid_from, valid_to) WITH &&) with the btree_gist extension. Snowflake and Redshift declare primary keys but don't enforce them, so it's a scheduled test:
SQL
-- pass = zero rows
select a.cust_id
from dim_customer a
join dim_customer b
  on a.cust_id = b.cust_id
 and a.cust_sk < b.cust_sk
 and a.valid_from < coalesce(b.valid_to, '2999-12-31'::timestamp)
 and b.valid_from < coalesce(a.valid_to, '2999-12-31'::timestamp);
  1. Mixing the open marker with a sentinel. A null valid_to makes valid_to > ts false for the current row, so a point-in-time query silently drops today. dbt's snapshot writes NULL for the open row unless you set its dbt_valid_to_current config to a sentinel like 9999-12-31, which trades IS NULL for working range predicates. Pick one convention; assert sum(case when is_current then 1 else 0 end) = 1 per cust_id.

  2. Unknown member. A null surrogate in the fact inner-joins to nothing and those rows vanish from every report. Keep a cust_sk = -1 row per dimension, make the fact FK NOT NULL DEFAULT -1, and test select count(*) from fact f left join dim_customer d using (cust_sk) where d.cust_sk is null is zero.

  3. Rekeys and merges. When two source IDs merge, a crosswalk with (old_id, new_id, effective_from) keeps the chain intact; without it history splits and the merged entity's revenue halves.

  4. Read-time join cost. An equality join hashes; an interval join is non-equi and most engines fall back to a nested loop unless the dimension is small enough to broadcast. Rough back-of-envelope: 240M fact rows against ~4 versions per key is 240M hash probes for the surrogate path versus up to 960M interval comparisons for the point-in-time path.

When not to. If only 'now' matters, an SCD1 overwrite plus the source's own CDC stream is enough. SCD2 costs a row per change and a version chain per key, and on a high-churn feed that storage is real.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Model balances, ratios, and distinct counts correctly.

Answer

What I'd say first

Three measure classes, three different rules, and the rule falls out of the grain you're aggregating over. Additive measures (units sold, revenue) sum over any dimension. Semi-additive measures (account balance, headcount, inventory on hand) sum across entities but not across time: you have to pick a time operator before any total means anything. Non-additive measures (ratios, distinct counts, medians) are never summed or averaged at row level; they're recomputed from components.

classexamplevalid across entitiesvalid across time
additiveunits soldsumsum
semi-additiveaccount balancesumlast non-empty (period-end), or first / avg
non-additiveconversion rate, DAUrecompute from numerator + denominatorrecompute from numerator + denominator

Balances. A balance is a snapshot, so summing it across dates double-counts the same money. In dbt's MetricFlow you declare this with non_additive_dimension: {name: date_day, window_choice: max}: max gives period-end, min gives period-start. Without that declaration the semantic layer will happily sum 30 daily balances and report 30× the real book.

Ratios. Average the row percentages and you get a number that depends on how you sliced, not on the business. Two days: day 1 is 1 conversion / 10 sessions = 10%, day 2 is 90 / 100 = 90%. Mean of the daily rates is 50%. Pooled, it's 91 / 110 = 82.7%. A 32.7-point gap, and it widens as the traffic mix shifts between segments. So store numerator and denominator as separate additive measures and divide at query time; the ratio is then correct at every grain.

Distinct counts. Specify entity, scope, window, and merge behavior. The merge rule is the part that bites: exact COUNT(DISTINCT user_id) is not mergeable. Two shards each containing user A give 1 + 1 = 2. HyperLogLog sketches are mergeable, union of registers, which is why they survive partitioning.

SQL
-- BigQuery, HLL precision 15 (range 10-24, default 15)
WITH daily AS (
  SELECT event_date, HLL_COUNT.INIT(user_id, 15) AS sketch
  FROM events GROUP BY event_date
)
SELECT HLL_COUNT.EXTRACT(HLL_COUNT.MERGE(sketch)) AS dau_30d
FROM daily;

Relative error is 1.04 / sqrt(2^precision): 0.57% at precision 15, 1.6% at precision 12. Redis HyperLogLog uses 16,384 registers for a 0.81% standard error. Merging sketches of different precision fails outright in BigQuery, so pin the precision in the model, not at the call site.

Failure modes and how you catch them. An averaged ratio shows up as a dashboard number that moves when you add a filter but not when the underlying events change: reconcile it against a pooled recompute on the same window. A summed distinct count overcounts silently; compare sum-of-partials against exact on one small partition. A semi-additive measure summed across time inflates roughly linearly with the window length, so a 30-day total near 30× a single day is the tell.

When not to approximate. Exact when the number is contractual (billing, per-tenant quotas, regulatory counts) or when cardinality is small enough that exact is cheap. Approximate when you're scanning billions of rows and sub-1% error is fine for a dashboard. Don't mix the two in one metric: a ratio whose denominator is approximate inherits the sketch's error and can't be reconciled against an invoice.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Define a governed conversion-rate metric.

Answer

Core answer (first 90 seconds)

A governed conversion rate is a ratio with a written contract, not a dashboard formula. The contract fixes five things: the eligible-opportunity event, the conversion event, identity and dedup, the attribution window, and the time basis. Segmentation and exclusions hang off those.

Concretely, I'd define it as conversions ÷ eligible opportunities, both counted as additive integers at the grain of the decision (say, per account per day) attributed on a 7-day click-through / 1-day view-through window, deduplicated on user_id, excluding internal IPs and refunded orders, timestamped in UTC on event time. The numerator and denominator live as two integer columns in one table. The rate is always derived by dividing summed columns, never by averaging a stored percentage.

The choices that are actually trade-offs

Window length. A 7-day click window credits more conversions than 1-day, but it also credits purchases that would have happened anyway. The deciding criterion is whether you can run a holdout: if you can measure incremental lift, report on the longer window and decide on the holdout; if you can't, keep the window short enough that the sales cycle dominates it.

Identity. Session ID splits one journey across three sessions and undercounts; user ID merges a shared family device and overcounts. Pick per-session identity when the decision is UX (which page converts), per-account identity when the decision is revenue.

Exclusions. Dropping refunds lowers the numerator and makes the rate incomparable to last quarter unless you restate history. Version the definition and backfill, or don't exclude.

Worked check: why you never average percentages

Three segments, one week:

segmenteligibleconversionsrate
Desktop1,000505.0%
Mobile9,0004505.0%
Tablet1002020.0%

Equal-weight average of the three rates: (5.0 + 5.0 + 20.0) / 3 = 10.0%. Weighted from the additive columns: (50 + 450 + 20) / (1,000 + 9,000 + 100) = 520 / 10,100 = 5.15%. The naive rollup is nearly double the truth because Tablet's 100 opportunities carry the same weight as Mobile's 9,000. When Growth reports 10% and Finance reports 5.15% for the same week, this is almost always the disagreement.

Failure modes and how I'd catch them

Late arrival. If 4% of conversions land more than 48 hours after the event, a T+24h snapshot reads low and drifts as backfill lands. Detect by computing the same day's rate at T+24h and T+7d; if the relative delta exceeds 0.5%, the pipeline is reading a partial partition.

Zero denominator. A segment with zero eligible opportunities must return NULL, not 0: a 0 drags any weighted rollup down and hides the fact that there's no data. Detect with a not_null test on the denominator plus a row-count check per segment.

Double counting. Dedup on user_id fails when one purchase fires two conversion events. Detect by asserting one conversion per opportunity_id; alert when the duplicate ratio exceeds 0.1%.

Definition drift. Someone edits the eligibility filter and the denominator jumps 12% week over week with no traffic change. Detect by versioning the metric definition and diffing cohort counts against the prior version.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

Design a governed multi-currency revenue metric.

Answer

Core answer (first 90 seconds)

Clarify three things before designing: which currency is the reporting currency, what grain revenue lands at, and whether finance needs as-reported or as-restated numbers. Assume facts land at transaction grain in a warehouse, reporting currency is USD, and the monthly close reconciles to the GL.

Keep the fact table in native currency, native_amount plus currency_code (ISO 4217), and never store a converted amount there. Put rates in a separate dimension keyed by (base_ccy, quote_ccy, rate_type, effective_from, effective_to). Convert in a view. Restating then becomes a rate-table swap, not a fact rewrite, and native and converted measures stay distinct columns a consumer can pick between.

SQL
select f.revenue_id, f.native_amount, f.currency_code,
       f.native_amount * r.rate as revenue_usd
from fact_revenue f
join fx_rate r
  on r.base_ccy = f.currency_code
 and r.quote_ccy = 'USD'
 and r.rate_type = 'spot'
 and f.booked_at >= r.effective_from
 and f.booked_at <  r.effective_to

The half-open interval is the whole trick: it prevents fanout (two rows matching one fact) and gaps (no row matching) at the same time.

The decisions, with alternatives

DecisionOption AOption BDeciding criterion
Rate typeDaily spot at transaction datePeriod averageIAS 21.22 permits an average rate for a period only if rates don't fluctuate significantly; use spot when a currency moved materially in the period
RestatementAs-reported: freeze the rate used at closeAs-restated: recompute with the latest rate tableGL reconciliation needs frozen; trend analysis needs a comparable series. Store both via a rate_version column
Where to convertStore converted amount in the factConvert in a viewStorage and query cost vs the cost of rewriting facts on every restatement
Missing rateFail the loadCarry forward the last known rateMateriality; carry-forward hides stale rates, so only use it with an age alert

Failure modes and how you catch them

  • Fanout. A rate join that isn't unique on the pair multiplies facts. Detect by asserting the joined row count equals the fact row count, and that sum(native_amount * rate) per row equals the converted total.
  • Silent nulls. A missing rate nulls revenue_usd and the total quietly drops. Detect with a count of facts where revenue_usd is null; alert on anything above zero.
  • Stale carry-forward. Detect by comparing max(effective_from) to the transaction date and flagging rates older than your cutoff (e.g. 7 days).
  • Currency mismatch. A pair quoted the wrong way round (USD/EUR vs EUR/USD) inverts the number. Detect by reconciling the converted total to the GL within tolerance: 0.1% or $1, whichever is larger.

Precision and rounding

Store rates at DECIMAL(38,12) and amounts at DECIMAL(38,6) or as minor-unit integers. Minor units differ: JPY has 0 decimals, USD 2, KWD 3. Round at the aggregate, not per row: rounding 10,000 rows to the cent drifts by up to 10,000 × $0.005 = $50.

Worked example (illustrative figures)

1,000 EUR booked 2024-03-15, spot rate 1.0889 → 1,088.90 USD. If the period average is 1.0850, the as-restated figure is 1,085.00 USD: a $3.90 gap on one row, which is why the restatement policy has to be explicit rather than implied.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Model late facts, corrections, and period close.

Answer

Assume a payments fact table. Event time is the business timestamp on the transaction; ingestion time is when the record lands in the warehouse. I'd model three things: a watermark that separates on-time from late, a period status that is provisional until a close job runs, and a correction path that either restates the open period or posts an adjustment to the current period once closed. The deciding rule: if the period is open, restate; if closed, adjustment. Approval threshold: any restatement over $10k or 0.5% of period revenue needs finance sign-off.

Mechanism: in Flink, WatermarkStrategy.forBoundedOutOfOrderness(Duration.ofMinutes(5)) sets the watermark to maxEventTime − 5min. A tumbling window [H, H+1h) fires when the watermark passes H+1h, i.e. once an event with event time ≥ H+1h+5min has arrived. So the grace is 5 minutes past the window end, not past the window start. Events arriving after the window fired go to a side output: that side output is the correction feed. Correction lineage columns: original_event_id, correction_id, reason, corrected_at, corrected_by, so any number traces back to its source.

Worked trace, hourly window [23:00, 00:00), 5-minute bounded out-of-orderness:

event_idevent_timeingestedmaxEventTime afterwatermarkwindow stateaction
e123:5823:5823:5823:53openbuffered
e200:0300:0300:0323:58openbuffered
e300:0600:0600:0600:01firesemits e1
e423:5900:0700:0600:01already firedside output → correction

e4 is late by one minute of event time relative to the watermark, so it never joins the window; it lands in the correction feed.

Trade-offs: restatement rewrites history, simpler for consumers, but breaks audit unless every version is kept. Adjustment keeps history immutable, but consumers must sum across periods. Choose restatement for open periods (current month, no external reports filed); choose adjustment for closed periods (prior quarters, auditors require immutability). Deciding criteria: regulatory filing deadline, materiality threshold, and whether downstream consumers can absorb a restated number.

Failure modes: duplicates from at-least-once delivery → dedup on event_id, monitor duplicate_rate, alert above 0.01%. Reversal (negative amount) → sign check, route to manual review if abs(amount) > $1k. Corrected dimension (customer region changed) → compare dim_customer.version at event time against current, flag for restatement. Close boundary → assign period by event_time, not ingestion_time; test with events at ±1ms around midnight.

Close job, runs 02:00 UTC daily:

SQL
UPDATE fact_revenue
SET period_status = 'closed', closed_at = CURRENT_TIMESTAMP
WHERE event_date = CURRENT_DATE - 1
  AND period_status = 'provisional';

INSERT INTO fact_revenue_adjustments
  (event_id, original_event_id, amount, adjustment_for_period, posted_period, reason)
SELECT event_id, original_event_id, amount, event_date, CURRENT_DATE, 'late_event'
FROM late_events
WHERE event_date < CURRENT_DATE - 1;

Detection: monitor late_event_count per day, alert above 0.1% of daily event volume; monitor adjustment_total per period, and above 0.5% of period revenue trigger finance review. Keep raw events in an immutable store (S3 object lock, or Snowflake Time Travel set to 90 days) so corrections can be replayed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Create metric governance and certification.

Answer

What I'd say first

Before designing anything I'd ask three things: how many metrics are in the semantic layer, who consumes them (internal dashboards only, or do numbers leave the company in board or regulatory reporting), and what the current pain is. Usually two dashboards disagreeing on the same name.

Assume ~800 metrics in a dbt + Looker stack over Snowflake, ~40 analysts, exec reporting plus one regulatory filing. That assumption drives the design: I certify the ~60 metrics feeding exec or external reporting and leave the rest on automated tests.

The answer

Governance is two named roles and one enforced state machine.

Business owner: accountable for what the metric means, who may use it, and approving changes. Technical steward: owns the model, lineage, tests, freshness, and incidents. On a small team one person holds both; splitting them is what stops "the data team" from being the owner of everything.

Certification is a state, not a document. Five states, each with an entry criterion and an approver:

stateentry criterionapproverexit
draftmetric exists in the semantic layerauthorverified or retired
verifiedformula, grain, unit and tests pass in CI; owner namedstewardcertified or retired
certifiedowner signs the definition; lineage traced to source; used by at least one tier-1 consumerbusiness ownerdeprecated
deprecatedsuperseded or source retired; consumers notifiedownerretired
retiredno consumers for 90 dayssteward—

Enforcement is what makes it real. In dbt the certification flag lives in meta on the metric, and CI fails the build if a certified metric's SQL changes without a linked change record. Looker shows the certified badge on the field and the dashboard. A nightly job diffs the certified list against the catalog and opens a ticket on drift.

Trade-offs

Certifying everything is the common mistake. Each certification costs roughly 2–4 hours of owner plus steward time; 800 metrics is 1,600–3,200 person-hours for reviews most consumers never needed. Certifying only tier-1 while testing everything costs about 200–300 hours and covers the numbers people actually argue about. Decide by blast radius: does the number leave the company, or drive a decision with money attached? If neither, verified is enough.

Failure modes

  • Certification theater: everything certified, nothing trusted. Detect by counting disputes on certified metrics per quarter; non-zero means the bar was too low.
  • Owner rot: the owner left. Detect with quarterly attestation; no attestation for two quarters auto-demotes to verified.
  • Duplicate names: two teams certify active_users differently. Detect with a CI uniqueness check on certified names; escalate to the governance council, which decides within five business days.
  • Stale certification: the source table changed under a certified metric. Detect via lineage: an upstream model change suspends certification until re-review.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Resolve competing metric definitions across teams.

Answer

"Resolve" here doesn't mean getting everyone to agree in a meeting. It means making one definition executable and versioned, then moving consumers onto it. I'd assume a warehouse, a BI tool, and a metric layer (dbt's semantic layer, LookML, or Cube) with one team owning that layer. If nobody owns it, that's the first fix.

The conflict is almost never about the number. It's about grain, population, time semantics, and exclusions. Two teams saying "active user" can both be right and differ by 30% because one counts any login in 30 days and the other counts a session with a core action in 7 days.

So: for each contested metric, decide whether the two meanings answer the same decision. If yes, converge on one definition. If no, qualify them with distinct names and document the mapping. Then migrate.

Why they diverge

Hypothetical: "monthly active user" for a B2B SaaS product.

Team A (Growth)Team B (Finance)
Grainuser-day, deduped to useraccount-month
Populationall users, incl. free trialpaying accounts only
Windowany login in 30 daysany login in calendar month
Exclusionsnoneinternal, test, churned-before-billing
Result1.2M840k

Same word, 360k gap. Neither is wrong. Growth wants reach; Finance wants billable engagement.

How a step resolves it

Write the definition as code, not prose. Code is the arbiter because it can be tested.

SQL
-- models/metrics/mau.sql  (dbt 1.7, Snowflake)
-- grain: account-month; population: paying accounts; window: calendar month
select
  date_trunc('month', e.event_at) as month,
  e.account_id,
  count(distinct e.user_id) as mau
from analytics.fct_events e
join analytics.dim_accounts a using (account_id)
where a.is_paying
  and e.event_name = 'login'
  and not a.is_internal
group by 1, 2

Then a singular dbt test that fails if the number moves more than 5% week over week without a version bump. That test is what turns "we agreed" into "it can't silently drift." In dbt's semantic layer you'd expose this as a metric on top of the model; the SQL is the same.

Converge or qualify

ConditionCall
Same decision, same grainConverge, one certified metric
Different decisions (comp vs GAAP)Qualify: revenue_booked vs revenue_recognized
Regulatory or contractual definitionQualify, never override
Migration cost > discrepancy costQualify and document the delta

One certified metric is the wrong call when consumers have a contractual definition: you can't converge sales comp onto GAAP revenue.

Failure modes

  • Two dashboards drift after someone edits a filter. Detected by a reconciliation test between the certified metric and the legacy query; cost is a week of exec reviews on numbers that don't match.
  • Forced convergence where meanings differ. Detected when Finance restates; cost is a restatement and lost trust.
  • Migration without a deprecation window. Detected by query logs still hitting the old table after the cutoff; cost is stale dashboards in the board deck.

Migration

Version the definition, publish old vs new side by side for one cycle, then flip consumers. Keep the rationale and an escalation path for the next conflict.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Build useful semantic lineage and impact analysis.

Answer

What I'd say first. Lineage is worth building only if it answers two questions faster than a human can: what breaks if I change this? and where did this number come from? Assume a warehouse (Snowflake or BigQuery), dbt for transforms, and a BI layer (Looker or Tableau). I'd build two graphs, declared and observed, merge them, and make impact analysis a reverse traversal that carries confidence. I would not try to make the graph complete; I'd make it honest about what it cannot see.

Declared lineage comes from artifacts you already have. dbt manifest.json gives model→model and column→column edges for anything dbt compiled; a few thousand models produce a manifest in the tens of megabytes and it parses in seconds. LookML and Tableau .twb files give the BI layer. For raw SQL outside dbt, parse with sqlglot and emit edges. Declared lineage is complete for code that exists, including models that never ran, and blind to everything that is not in a repo.

Observed lineage comes from query logs. Snowflake's ACCOUNT_USAGE.ACCESS_HISTORY gives column-level reads and writes with 365-day retention; BigQuery's INFORMATION_SCHEMA.JOBS_BY_PROJECT gives table-level with 180 days. This is ground truth for what actually ran, including ad-hoc queries and BI extracts, and blind to anything outside the retention window or never executed.

The two disagree in a specific, useful way: a table read in the logs with no declared upstream edge is an invisible consumer. That check is what catches dynamic SQL, EXECUTE IMMEDIATE, and hand-written BI SQL. Run it weekly and alert on new gaps.

Impact analysis is a reverse traversal from the changed node, column-level where you have it and table-level where you do not:

SQL
WITH RECURSIVE impact AS (
  SELECT downstream_node, downstream_column, 1 AS depth, confidence
  FROM lineage_edge
  WHERE upstream_node = 'raw.orders' AND upstream_column = 'id'
  UNION ALL
  SELECT e.downstream_node, e.downstream_column, i.depth + 1,
         LEAST(i.confidence, e.confidence)
  FROM lineage_edge e
  JOIN impact i
    ON e.upstream_node = i.downstream_node
   AND e.upstream_column = i.downstream_column
  WHERE i.depth < 10
)
SELECT * FROM impact ORDER BY depth;

Edges carry confidence: 1.0 declared, 0.8 observed, 0.5 inferred from a parse that could not resolve a column. LEAST propagates the weakest link, so a path through an opaque Python transform surfaces as low-confidence rather than as a confident wrong answer. depth < 10 caps cycles.

Trace for a type change on raw.orders.id:

depthnodecolumnconfidence
1stg_ordersorder_id1.0
2fct_ordersorder_id1.0
3dim_customer_ordersorder_id1.0
3looker:customer_ltvorder_id0.8

The Looker view appears only because observed edges are in the graph. Declared-only lineage would have reported three consumers and missed the dashboard someone actually looks at.

When not to build this. Under ~50 models and one team, dbt ls --select source:raw.orders+ gives table-level impact for free, and a graph you have to maintain is worse than a command you have to remember. Buy (DataHub, OpenMetadata) before you build a parser; build only the merge and the traversal, which is where your semantics live.

Failure modes. Stale graph after a rename → false "no impact"; stamp every edge with the commit it came from and block merges when the graph is older than the branch. SELECT * resolved to every column → over-broad impact that people learn to ignore; mark those edges table-level. Lineage leaking PII column names to everyone → apply the same access rules to the graph as to the data.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Build a semantic-layer test strategy.

Answer

A semantic layer is metric and dimension definitions compiled to SQL against a warehouse. Assume dbt-style definitions in version control (MetricFlow or a BI model), warehouse SQL, and the ability to seed fixture rows. The strategy is three tiers, and the deciding criterion between them is cost per run against how precisely a failure localizes.

Tier 1: contract tests, every build. These run on the model, not the metric. Unique and not_null on the declared grain key, accepted_values on every enum, relationships on every foreign key. They're cheap, they run in seconds, and they catch the failures that make every downstream metric wrong at once.

YAML
# dbt 1.8+ schema YAML
models:
  - name: fct_orders
    columns:
      - name: order_id
        data_tests: [unique, not_null]
      - name: status
        data_tests:
          - accepted_values:
              values: ['placed','shipped','cancelled','refunded']
      - name: customer_id
        data_tests:
          - relationships:
              to: ref('dim_customers')
              field: customer_id

Tier 2: metric fixtures, on definition change. Seed deterministic rows covering eligibility, exclusions, cancellation, refund, duplicate, late event, unknown member, zero denominator, time and fiscal boundaries, currency, and dimensions. Assert the exact metric output. This is the only tier that localizes a bug to a specific rule, and it's the expensive one to author, so it gates metric definition changes, not every commit.

Tier 3: reconciliation, on a schedule. Compare the metric total to an independent trusted query (finance extract, legacy report) with a stated tolerance. Coarse, can't localize, but it's the only tier that catches unknown-unknowns.

Trade-off: fixtures are precise and brittle; reconciliation is robust and blunt. Don't run fixtures on every build: they're slow and they fail on unrelated data drift. Don't rely on reconciliation alone: it tells you something is wrong, never what.

Failure modes and detection:

  • Join fanout. A metric joins a one-to-many table without dedup. Say 1,000 orders with 3 items each: summing over the joined result gives 3× revenue. Detect by asserting the metric equals the sum over the fact table at the declared grain, and counting rows per key before and after the join.
  • Late events. A restatement changes a closed period. Detect by running the metric for a past period twice with a fixed as-of timestamp and diffing.
  • Unknown member. An inner join to a dimension silently drops rows. Detect with a relationships test plus a row-count reconciliation between fact and joined result.
  • Zero denominator. A ratio returns null or errors. Detect with a fixture whose denominator is zero, asserting null rather than a division error.
  • Duplicate grain. Detect with a unique test on the grain key.

Differential tests (same frozen data, metric output before and after a change) are the cheapest regression net, but they only cover changes you make. Query compilation tests catch a definition that won't compile; access negatives catch a metric leaking a restricted dimension.

Deciding criterion: contract tests gate every merge, fixtures gate metric definition changes, reconciliation runs nightly. If you can only afford one, run contract tests: cheapest, widest blast radius.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Implement secure multi-tenant semantic queries.

Answer

Let me clarify the setup. I'm assuming a multi-tenant SaaS where tenants share tables with a tenant_id column, users authenticate via an IdP (e.g., Okta, Auth0) and get a JWT with tenant and role claims. A semantic layer (Looker, Cube, or custom) sits over a warehouse (Snowflake, BigQuery, Databricks). The question is how to enforce tenant isolation for semantic queries: interactive, API, cache, exports.

The core answer: derive tenant and policy attributes server-side from the verified JWT, never from client input. Then enforce at two layers: the warehouse and the semantic layer. The warehouse is the backstop because it catches direct SQL and any path that bypasses the semantic layer. The semantic layer handles metric and dimension permissions that are business-specific.

For the warehouse, use row-level security (RLS) and column masking. In BigQuery, create a row access policy that filters on a mapping table:

SQL
CREATE ROW ACCESS POLICY tenant_policy
ON fact_sales
GRANT TO ('role:analyst')
FILTER USING (
  tenant_id IN (
    SELECT tenant_id FROM tenant_user_map WHERE user_email = SESSION_USER()
  )
);

This rewrites every query to add the predicate. For column-level, use policy tags to mask PII. In Snowflake, use row access policies and masking policies. The semantic layer sets a session variable or passes the user identity so the warehouse can evaluate the policy.

For the semantic layer, use user attributes (e.g., tenant_id, region) and access filters. In Looker, access filters inject WHERE tenant_id = '{{ _user_attributes['tenant_id'] }}' into generated SQL. In Cube, you define a security context and apply it in the query rewrite. This handles dimension and metric permissions: e.g., a user can see revenue but not cost.

Now tradeoffs. Warehouse RLS is centralized and works for all consumers, but it can add latency: for instance, a policy that joins to a mapping table might add 5–15 ms per query, and it can prevent partition pruning if the policy is not written carefully. Semantic layer enforcement is easier to iterate and can express complex rules, but it only protects queries through that layer; a user with direct warehouse credentials bypasses it. So use both: warehouse RLS as the hard boundary, semantic layer for fine-grained business logic.

Failure modes. Cache poisoning: if the cache key omits tenant_id or user attributes, one tenant sees another's results. Detect by auditing cache keys and running cross-tenant tests. Small-group inference: even with RLS, a user can infer sensitive data by aggregating over small groups. Mitigate with a minimum group size (e.g., suppress results with count < 5) or differential privacy. Stale permissions: if a user's role changes, cached results or pre-aggregations may still be served. Reauthorize on every read, or invalidate cache on permission change. Error leakage: error messages may reveal table names or the existence of other tenants. Return generic errors and log details server-side.

For exports and subscriptions, re-run authorization at delivery time, not just at creation. For pre-aggregations, partition by tenant_id and security attributes, and never serve a pre-aggregation that crosses tenants.

A quick test matrix:

PathEnforcementTest
InteractiveWarehouse RLS + semantic filtersQuery as tenant A, try to see tenant B
APISame, plus token validationTamper with tenant_id in request
CachePartition by tenant_id + attributesPoison cache with tenant A, read as B
ExportReauthorize at deliveryChange role after export created

That covers the main mechanisms, tradeoffs, and failure modes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Protect sensitive aggregates and dimensions.

Answer

Core answer (first 90 seconds)

Assume the release is a query interface over a fact table with sensitive measures, and the attacker can issue many queries. Then cell suppression alone is not a control: it is a speed bump. The property you actually need is a bound on how much any one person can change any released output. Say that first, then pick the mechanism: exact suppression with complementary cells for a fixed, published table; noise with a privacy budget for anything queryable or repeatedly released.

Why suppression alone fails: differencing

querypredicaterowsresult
Aregion = 'EMEA'121,000,000
Bregion = 'EMEA' AND segment = 'SMB'11940,000

Both cells pass a k ≥ 5 rule. A − B = 60,000, which is the revenue of the single enterprise customer in EMEA. The rule has to be applied to the query set, not to the cell. That is what complementary suppression does: when you suppress a cell, you suppress at least one more in the same row or column so the first is not recoverable from the marginals. CMS's cell suppression policy for Medicare data suppresses cells with counts of 1–10 and applies complementary suppression for exactly this reason.

When suppression is the wrong tool

A fixed published table with few dimensions: suppression is exact, cheap and auditable. A query interface with unbounded filters, or repeated releases under different groupings: suppression cannot track accumulated disclosure, because each release looks fine on its own. Then you need a privacy budget: differential privacy, where each query spends ε and the total is capped. The 2020 US Census used the TopDown Algorithm with a published privacy-loss budget of ε = 19.61, and the documented cost is real: small-place counts got noisy enough that some jurisdictions could not use them for redistricting. That is the trade. DP gives a provable bound on individual influence; suppression gives exact totals but no bound under composition.

Failure modes and how you detect them

  • Differencing across overlapping cohorts. Log every query's predicate, compute the symmetric difference between query pairs, alert when it drops below k rows.
  • Drill-down. The dashboard suppresses the cell but the filter path reaches a sub-cohort. Audit the tool's generated SQL, not the rendered view.
  • Export and cache paths. The UI suppresses; the CSV endpoint does not. Diff the API response against the rendered cell.
  • Existence leaks. "No results" versus "1 result" reveals a person. Fuzz with a predicate you know matches exactly one row.
  • Joins with public data. Narayanan and Shmatikov re-identified Netflix Prize records by linking them to IMDb ratings (2008). Run re-identification tests against the public datasets your users can reach.

Rate limiting helps but is not a bound: it raises attacker cost, it does not cap disclosure. Pair it with a per-user query budget.

If pushed

"Why not just encrypt the derived values?" Encryption protects data at rest, not the released aggregate; the attacker sees the plaintext answer. "What about truthful totals?" Publish the total, suppress the cell, and say so in the metadata, "suppressed: fewer than 11 records", but the suppression notice itself must not narrow the range below k.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design semantic pre-aggregations safely.

Answer

Core answer (first 90 seconds)

Assume a star schema in a columnar warehouse, row-level security keyed on tenant_id, and a freshness SLO of a few minutes. A pre-aggregation is safe only when the planner can prove the query's grain, filters, security predicate and metric definitions are implied by the materialization's contract. Name matching is not proof. So the materialization declares grain, measures with a rollup class, dimensions, filters, time zone/calendar, a semantic version hash, the source watermark, the security partition, and the refresh policy. The planner rewrites only on implication; otherwise it falls back to base.

Why each field exists

Measures need a rollup class, because not all aggregates compose:

classexamplerolls up?how
additiveSUM(revenue)yessum of partials
semi-additiveend-of-day balancenot over timelast value per period
non-additiveA/B ratio, AVGnostore numerator and denominator, divide at query time
distinctCOUNT(DISTINCT user_id)noHLL sketch, ~0.8% error at 2^14 registers (1.04/√m)

COUNT(DISTINCT) over a union of partials overcounts: two days with 1,000 distinct users each can union to 1,400, not 2,000. Store a mergeable sketch or leave that metric on base.

The watermark is what makes fallback safe. If base MAX(updated_at) is T and the pre-agg covers up to T, any query whose window ends after T must go to base. You also hold a grace period: don't materialize the last 3 days, because late events still land. Druid exposes this as lateMessageRejectionPeriod; BigQuery's max_staleness lets a query read the MV only if it is within the bound, and otherwise silently falls back.

The version hash covers metric SQL, grain, filters and time zone. Change any of them and the hash changes, so the planner refuses the old materialization. Time zone matters because a UTC-day rollup cannot answer "yesterday in America/Los_Angeles" without re-aggregating, and a DST day is 23 or 25 hours.

Security is the one that leaks. If RLS is tenant_id = current_tenant(), the pre-agg must be grouped by tenant_id, and the planner must verify the query predicate is implied by that partition. A pre-agg built without the tenant column will serve cross-tenant rows.

A Cube rollup carries most of this contract directly:

YAML
pre_aggregations:
  - name: daily_tenant
    type: rollup
    measures: [revenue, users]
    dimensions: [tenant_id]
    timeDimension: created_at
    granularity: day
    partitionGranularity: month
    refreshKey:
      every: 1 hour
      sql: SELECT MAX(updated_at) FROM orders

Trade-offs

Pre-aggregation buys latency with storage and staleness. A 2 TB fact table rolled to day grain over 20 dimensions lands near 40 GB (2%); p95 drops from ~12 s to ~300 ms. Incremental refresh from the watermark takes ~90 s; a full rebuild ~20 min. Don't materialize when the dominant filter is a high-cardinality key like user_id (the rollup cannot prune), when query volume is a few per day (refresh cost exceeds the savings), or when the freshness SLO is under ~5 minutes (base plus a result cache wins). Looker's symmetric aggregates and Cube's rollupJoin are the alternatives when fan-out, not scan volume, is the problem.

Failure modes and detection

  • Fan-out double counting (order→items): compare pre-agg SUM to base SUM on a sampled partition nightly.
  • Stale pre-agg serving "today": alert when watermark lag exceeds the refresh interval.
  • Cross-tenant leak: CI canary query as tenant B against tenant A's pre-agg.
  • Non-additive measure summed: equivalence test on ratio metrics across filters.
  • DST drift: compare day-boundary counts in two zones.

What would change the decision: if late arrivals exceed ~1% of rows past the grace period, widen the grace period or drop the pre-agg for that metric.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Cache semantic query results correctly.

Answer

Assumptions I'd state first. A semantic layer (Cube, dbt MetricFlow, or Looker) sits in front of a warehouse; dashboards issue the same metric with different filter orders, grains and timezones; row-level policies are per tenant; the freshness SLA is "a dashboard reflects source data within 15 minutes." The question is how to key, expire and invalidate that cache without ever serving one tenant another's rows.

Core answer. The cache key must be a canonical form of everything that changes the result, and nothing else. That set is: metric definitions and their version, the measure set, dimensions, filter predicates, grain, the time window in UTC plus the display timezone (DST moves day boundaries), currency or unit, approximation mode, the row/column policy identity, and the data version of the sources. Everything else (filter order, dimension order, IN (a,b) vs IN (b,a), whitespace) has to be normalized away, or semantically identical queries miss each other and the hit rate collapses.

Python
import hashlib, json

def cache_key(req, *, tenant, policy_version, data_version, model_version):
    canon = {
        "model": model_version,                       # e.g. "metrics@9f3c1a"
        "metrics": sorted(req["metrics"]),
        "dimensions": sorted(req["dimensions"]),
        "filters": sorted(
            (f["field"], f["op"], tuple(sorted(map(str, f["values"]))))
            for f in req["filters"]
        ),
        "grain": req["grain"],                       # "day"
        "window": [req["start_utc"], req["end_utc"]],  # already UTC ISO-8601
        "tz": req["tz"],                             # display tz, affects bucketing
        "currency": req.get("currency", "USD"),
        "approx": req.get("approx", False),
        "policy": f"{tenant}:{policy_version}",
        "data": data_version,                         # max(updated_at) of sources
    }
    blob = json.dumps(canon, sort_keys=True, separators=(",", ":"))
    return "sq:" + hashlib.sha256(blob.encode()).hexdigest()[:32]

Trace it: a request filtering region in ["us","eu"] and one filtering region in ["eu","us"] both canonicalize to ("region","in",("eu","us")), so they produce the same blob and the same key. That is the collision you want. Change tenant and the policy field changes, so the keys diverge: that is the collision you must never allow.

TTL comes from the SLA, not from a default.

SurfaceTTLWhy
Exec dashboard over hourly-loaded facts5 minSLA is 15 min; 5 min leaves room for a late load
On-call ops dashboard over a streaming source60 sstaleness is visible to the responder
Metric with a restatement feednone: invalidate on watermark changea corrected number must never be served from cache

Trade-off: cache above or below the row filter. Above security means the key carries tenant and policy version, so each tenant gets its own entry. Below security means one shared entry with the filter applied on read; it wins only when the row filter is a pure predicate over columns already present in the cached result and the policy version is still in the key. It saves memory, 200 tenants × 50 MB of hot results is 10 GB you don't spend, but any policy that needs a join to a permissions table breaks it, and every read pays the filter cost. Default to above security.

Failure modes and how you catch them.

  1. Cross-tenant leak from a key that omits policy identity. Detect with a CI canary that runs the same query as tenant A and tenant B, asserts the result sets differ and that the keys differ. Cost is a security incident, not a bug.
  2. Stale after a restatement. Compare the entry's data version against the source watermark on read; a mismatch forces recompute. Cost is one extra metadata read per hit, roughly 1 ms against Redis.
  3. Timing leakage. A hit returns in 2 ms and a miss in 400 ms, so an attacker infers whether a filter matched rows for another tenant. Measure p50 hit vs miss latency per endpoint; pad misses or don't cache existence checks at all.
  4. Near-miss keys. >= 2024-01-01 vs > 2023-12-31, or America/New_York vs UTC at day grain. Property-test equivalent query pairs for equal keys and a near-miss set for unequal keys.

Also single-flight the miss: 200 concurrent dashboard loads of the same tile should trigger one recompute, not 200.

Decision criteria. If the semantic layer already versions metric definitions and exposes a data watermark, key on those and put the cache there. If it doesn't, build the canonical key at the API edge and treat policy version as a first-class input. The one call that matters is above vs below the row filter: above unless the filter is provably a pure predicate over cached columns.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design an approximate metric responsibly.

Answer

Core answer (first 90 seconds)

"Responsibly" means the approximation is part of the contract, not a hidden implementation detail. Pick the sketch from the operation the metric must support, then publish the error bound next to the number.

Assume: distinct users per feature-flag variant per day, ~40M events/day, ~5M DAU, 500 flags × 3 variants = 1,500 groups. The dashboard must union groups (all variants of one flag) but never intersect them.

Exact counting costs a hash set per group: 5M IDs × 8 bytes = 40 MB, ×1,500 = 60 GB of state per day, and every merge ships IDs. HyperLogLog at p=14 uses 2^14 = 16,384 registers × 6 bits = 12 KB per group, 18 MB total, and merges by register-wise max, so union is free.

Standard error is 1.04/√m = 1.04/128 ≈ 0.81%. At 5M DAU that is ±40k at 1σ, so publish "5.0M ±1.6% (95%)" and name the column dau_approx.

Mechanism

HLL hashes each user ID to 64 bits, uses the first p bits to choose a register, and stores the position of the leftmost 1-bit in the remainder. The estimate is a bias-corrected harmonic mean of 2^register. Each register only records "the rarest hash pattern I have seen," so two sketches union by taking the max per register: that is the whole reason it is mergeable. Below ~40k (2.5m) it switches to linear counting, m·ln(m/V) over the V zero registers, because the raw estimator is biased at low cardinality.

Count-Min Sketch covers the other shape: frequency per key, e.g. top error codes. Width w = ⌈e/ε⌉, depth d = ⌈ln(1/δ)⌉; with ε=0.001, δ=0.01 that is w=2,719, d=5, ~13.6k counters. It only overestimates: est ≤ true + εN with probability 1−δ. It merges by counter-wise addition.

When not to use a sketch

  • Need the actual IDs (retargeting, dedup list) → exact set.
  • Need intersection or difference ("users who saw A and B") → HLL cannot; use a Theta sketch (Apache DataSketches) or exact.
  • Cardinality under ~10k → exact is cheaper than the operational cost of explaining error.

Failure modes and detection

failuresymptomdetectionfix
summing per-group HLLsdaily total exceeds union estimate by >2σcompare Σ group estimates against the union sketchunion by register max
weak or truncated hasherror grows with n, exceeds 0.81%benchmark vs exact on 1M known IDs64-bit hash (xxHash / MurmurHash3)
merging different pgarbage estimatep in the sketch headerreject mismatched merges
small-n bias3–8% error under 10knightly exact-vs-sketch difflinear counting or exact fallback

Expose the event watermark and sketch build time; a stale sketch reads as a drop. Version the algorithm (p, hash, correction) in the sketch header: a change is a new column, not a silent swap. Nightly, compare a 1% exact sample against the sketch and alert if deviation exceeds 2σ.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

How do you evaluate whether to model business logic in a decoupled headless semantic layer versus directly within a BI platform's native modeling layer?

Answer

Decoupling business semantics into a headless semantic layer (e.g., dbt MetricFlow, Cube) versus embedding them inside a BI-native engine (e.g., Power BI VertiPaq semantic models) turns on three architectural axes: consumer diversity, engine pushdown requirements, and report-level calculation intimacy.

Evaluation Axes

  1. Consumer Diversity & Multi-Tool Parity: If downstream consumption spans multiple BI surfaces (e.g., Power BI dashboards, Tableau workbooks, Jupyter notebooks, reverse-ETL triggers, and custom operational apps), a headless layer is necessary. Defining metrics like gross_margin upstream prevents divergence across DAX measures, Tableau calculated fields, and ad-hoc SQL. If consumption is strictly homogenous (e.g., 95%+ of reporting lives in Power BI), native models minimize operational complexity.

  2. Execution Engine & Pushdown Semantics: Headless tools compile logical definitions into dialect-specific SQL executed directly against the warehouse (e.g., Snowflake, BigQuery) or leverage managed pre-aggregations (Cube). They excel when data remains at warehouse scale and central governance (e.g., row-level security policies at the warehouse tier) must be preserved. BI-native layers often ingest or cache data into in-memory tabular engines (e.g., VertiPaq), which can yield single-digit millisecond query performance on complex matrix visuals but duplicate storage and incur data transfer/refresh lags.

  3. Calculation Intimacy & Visual Context: Headless layers operate best on deterministic aggregations: cumulative metrics, additive sums, simple dimensional slices, and symmetric join graphs. BI-native engines excel at visual-context-dependent logic: dynamic parent-child hierarchy navigation, dynamic formatting, asymmetric matrix row/column visibility, and visual-level rank calculations requiring iterative engine evaluation.

Comparison

CapabilityHeadless Semantic Layer (e.g., MetricFlow, Cube)BI-Native Model (e.g., Power BI Dataset)
Single Source of TruthUniversal API (SQL, REST, GraphQL) across BI, notebooks, and apps.Siloed to the BI tool and clients supporting its native protocol (e.g., XMLA).
Query ExecutionCompiles to warehouse dialect or queries managed pre-aggregations.In-memory columnar cache (VertiPaq) or direct DirectQuery/dual-mode pushdown.
Version Control & CI/CDPure code (YAML/Jinja/JS), native Git workflows, warehouse-level unit tests.PBIP/TMDL/BIM formats; viable CI/CD, but merges can conflict on layout/visual metadata.
Complex Visual LogicPoor fit for asymmetric report layouts, visual-context matrix pivots.First-class support for visual context, dynamic formatting, and context transition.

Failure Modes & Boundaries

  • Double Modeling Trap: Teams build dimensions in the headless layer, but report authors rebuild measures in DAX or Tableau to support dynamic visuals, reintroducing metric drift.
  • DirectQuery / Pushdown Latency Wall: A headless layer generating complex subqueries across large snowflake schemas can result in multi-second dashboard renders compared to native in-memory caching. Cube pre-aggregations or warehouse clustering must be explicitly sized.
  • Security Granularity Mismatch: Warehouse-level row-level security (RLS) pushed through a headless layer using service account pooling loses end-user context unless proxy-user impersonation or custom session parameters are mapped end-to-end.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How do you design the semantic model so that natural-language and LLM-driven query interfaces resolve to certified metrics at the correct grain?

Answer

The semantic model is the API contract the LLM compiles against. The LLM never sees raw tables; it sees a catalog of certified metrics with typed signatures. Each metric declares canonical name, synonyms, description, default aggregation, base grain, allowed dimensions, certification status, owner, and default time grain. The NL layer retrieves over that catalog, then calls a query_metric tool that validates every argument against the declaration. If the metric or dimension is not in the catalog, the call fails and the layer asks a clarifying question instead of generating SQL.

yaml

dbt MetricFlow: certified metric with machine-readable contract

metrics:

  • name: net_revenue description: "Revenue after returns and discounts, USD, at order-line grain." type: simple type_params: measure: net_revenue filter: "{{ Dimension('order_line__is_cancelled') }} = false" meta: synonyms: ["net sales", "revenue after returns"] certified: true owner: "finance-analytics" allowed_dimensions: ["order_date", "customer_region", "product_category"] default_time_grain: month

The measure itself declares grain and aggregation:

yaml semantic_models:

  • name: order_lines model: ref('fct_order_lines') defaults: agg_time_dimension: order_date entities:
    • name: order_line_id type: primary
    • name: customer_id type: foreign dimensions:
    • name: order_date type: time type_params: { time_granularity: day }
    • name: customer_region type: categorical measures:
    • name: net_revenue agg: sum expr: net_amount agg_time_dimension: order_date

dbt does not enforce allowed_dimensions natively; the NL compiler reads meta and enforces it, or you scope the metric to a narrower semantic model. Looker declares synonyms directly on the field; Cube uses meta. Power BI's star schema enforces grain through one-to-many relationships from dimensions to facts, so a measure on the fact table can only be sliced by related dimensions.

DeclarationWhat the NL layer does
name + synonymsmaps "net sales" to net_revenue; rejects "revenue" if two certified metrics claim it
descriptionretrieval and ranking; disambiguates similar metrics
default aggregationif user says "average revenue", layer uses avg only if declared, else explains default is sum
base graincompiler aggregates measure at order-line grain before joining dimensions
allowed dimensionsrejects region if only customer_region is allowed; maps synonym
certificationonly certified metrics enter the LLM tool schema

Trace: user asks "Q3 net revenue by region." The LLM proposes {"metric":"revenue","dimensions":["region"],"time_range":"2025-07-01/2025-09-30"}. The semantic layer rejects revenue (not certified) and region (not in allowed_dimensions). It maps region to customer_region via synonym, rewrites to net_revenue, and generates SQL that aggregates net_revenue in a subquery at order-line grain, then joins dim_customer on customer_id and groups by customer_region, rolling up to month. No fanout because aggregation happens before the join: the same principle as Looker symmetric aggregates and MetricFlow's generated SQL.

Trade-offs: a tight allow-list raises clarification rate; a loose one lets the LLM slice a metric by a dimension that fans out. When exploratory analysis needs uncertified cuts, expose a separate, clearly labeled path that does not claim certification. Failure modes: synonym collision (two metrics both claim "revenue"), grain mismatch (user asks "by customer" when the metric is order-line grain and customer is many-to-many via a bridge), default aggregation mismatch, and hallucinated metric names. Detect by logging rejected metric and dimension names, tracking clarification rate, and running a golden set of NL questions against the catalog in CI.

Curated: · Written: · Reviewed:

Difficulty: Hard