Data Engineering for AnalyticsVol. 21 · Analytics
0 / 0

Shelves / Data Engineering for Analytics

DE·02

Modelling Data for Analysis

How to shape data so questions are easy, fast and right: facts and dimensions, choosing and declaring the grain, star schemas, conformed dimensions, slowly changing dimensions (types 1, 2 and 3) and point-in-time correctness, wide tables and when they're fine, the layers from raw to staging to marts, and the double-counting traps; with TiffinBox's order, delivery and subscription models and a lab in which overwriting a kitchen's area rewrites history and a careless join doubles revenue.

17 topics · ~8 min read · 16-question quiz
Updated Suggest a correction

Start here: shape decides answers

Raw data arrives in the shapes that were convenient for the systems that produced it: TiffinBox's normalised tables, Kafka events, a payment provider's export. Analysts need shapes that make questions easy and answers correct: "revenue by area by month", "repeat rate by kitchen", "delivery time by rider and hour". Dimensional modelling is the long-standing method for that:

  • Facts record measurable events at a declared grain (one row per order; one row per delivery attempt; one row per subscription per day), with numeric measures (amount, minutes) and keys to dimensions.
  • Dimensions describe the context (kitchen, customer, date, rider, area) with descriptive attributes used for filtering and grouping.
  • Arranged as a star: one fact table in the middle, dimensions around it, joined by keys.

Two ways to get it wrong, measured

The lab built three months of orders for four kitchens, one of which (kitchen 2) moved from Kondapur to Gachibowli on 1 April, and asked "revenue by area for January to March":

Kitchen dimension Kondapur Gachibowli
type 1: area overwritten with the new value ₹9,00,000 ₹9,00,000
type 2: history kept with validity dates ₹18,00,000 ₹0

The type 1 table rewrote history: Gachibowli got revenue earned before the kitchen moved there. And joining order-level payments to order items before summing doubled revenue (₹1,44,79,800 instead of ₹72,40,000), because each order had about two items. Both reports would have looked plausible.

How deep to go

Volume 17 defines six mastery levels. For analytical modelling:

Level What you can do
L1 Name facts, dimensions, grain and star schema
L2 Build a star schema for a business process
L3 Explain SCD types, additivity, conformed dimensions and point-in-time joins
L4 Find double counting, history rewrites and grain mismatches in real reports
L5 Design the modelling layers and standards for an organisation
L6 Evolve models as the business changes without breaking dashboards

Facts

Fact tables record events or snapshots at a grain:

Fact Grain Measures Dimensions
fct_orders one row per order amount, items, discount, delivery minutes date, customer, kitchen, rider, area, plan
fct_order_items one row per item in an order price, quantity order, dish, kitchen, date
fct_deliveries one row per delivery attempt minutes, distance rider, area, date, hour, outcome
fct_subscription_days one row per subscription per day (periodic snapshot) active (0/1), skipped (0/1), price customer, plan, kitchen, date
fct_payments one row per payment event amount, fee customer, method, date

Three kinds:

  • Transaction facts (orders, payments): one row per event.
  • Periodic snapshots (subscription days, daily balances): one row per entity per period, even if nothing happened, which makes "how many were active on each day?" a simple sum.
  • Accumulating snapshots (an order's journey: placed, accepted, cooked, picked up, delivered): one row per order, updated as milestones occur, with durations between them.

Additivity: amounts and counts are additive (sum across any dimension); balances and "active subscriptions" are semi-additive (sum across customers, not across days: take the value at the period end or average it); ratios and percentiles are non-additive (store numerator and denominator, compute the ratio last).

Dimensions

  • Date (and time of day): a table with one row per day and attributes like weekday, week, month, festival flags (Diwali, Sankranti), working day. Joining to it beats computing calendars in every query.
  • Customer, kitchen, rider, dish, plan, area: descriptive attributes, including hierarchies (dish → cuisine; area → city → state).
  • Surrogate keys (kitchen_key) separate the warehouse's identity from source IDs and allow several versions per entity.
  • Conformed dimensions mean the same thing in every fact table: one dim_kitchen used by orders, deliveries and subscriptions, so reports agree.

Slowly changing dimensions

Attributes change: kitchens move, customers change plans, dishes are reclassified. The choice per attribute:

Type What happens Use when
0 never changes (original value kept) date of first order
1 overwrite corrections, or history doesn't matter
2 add a new row with valid_from, valid_to (and is_current) history matters: area, plan, price tier
3 keep a "previous value" column only the last change matters (rare)

Point-in-time joins for type 2: join the fact to the dimension version valid at the event's time (o.order_date >= k.valid_from and o.order_date < k.valid_to), or store the dimension's surrogate key on the fact when it's loaded. The lab shows the difference: type 1 moved ₹9 lakh of January–March revenue to an area the kitchen wasn't in yet.

dbt snapshots implement type 2 by comparing each run's source rows with the previous ones (chapter 04).

Layers

Layer Contents Rules
raw exactly what arrived, append-only, with load metadata never edited; kept for reprocessing
staging one model per source table: renamed, typed, deduplicated, units fixed no joins across sources; no business logic
intermediate reusable building blocks (sessions, order journeys) internal
marts facts and dimensions for business processes; wide tables for specific uses documented, tested, owned

Wide tables and semantic layers

Columnar engines make wide, denormalised tables (one row per order with every attribute flattened in) cheap to query, and many analysts prefer them. They're fine as a convenience layer built from the star schema, for a clear use, with the grain stated. Don't let them replace the star: when two wide tables disagree about a definition, the shared dimensions are what settle it.

A semantic layer (dbt's metrics, LookML, Cube) defines metrics once ("revenue = sum of delivered order amounts, net of refunds") so every dashboard computes them the same way.

Double-counting traps

  • Fan-out joins: joining a table at a coarser grain (orders) to a finer one (items) and summing the coarse measure (the lab: 2×).
  • Many-to-many dimensions: a dish with several tags, a customer in several segments; summing across them counts once per tag.
  • Duplicate source rows: replayed webhooks or CDC duplicates (chapter 04's dbt test caught 37).
  • Mixing grains in one table: daily and monthly rows together.

The defences: state the grain in every model's documentation, test uniqueness of the grain's key, aggregate before joining, and reconcile totals against the source system.

TiffinBox's first models

Text
dim_date · dim_customer (type 2: plan, area) · dim_kitchen (type 2: area, rating tier) · dim_dish · dim_rider
fct_orders (order) · fct_order_items (order line) · fct_deliveries (attempt) · fct_subscription_days (subscription × day) · fct_payments (payment)

These are the marts chapter 04 builds with dbt and chapter 10's project extends.

Common traps

  • No declared grain.
  • Type 1 for attributes whose history matters.
  • Summing semi-additive or non-additive measures.
  • Wide tables as the only model.
  • Business logic in staging or raw data used directly in dashboards.

Lab: history rewritten, revenue doubled

Setup. DuckDB on the lab machine. 36,200 orders over the first 181 days of 2026, spread evenly over four kitchens (₹200 each). Kitchen 2 moved from Kondapur to Gachibowli on 1 April 2026.

  • dim_kitchen_t1: one row per kitchen, area overwritten with the current value (kitchen 2 → Gachibowli).
  • dim_kitchen_t2: one row per kitchen version: kitchen 2 has a Kondapur row valid until 1 April and a Gachibowli row from 1 April.

Then each order got 1–3 items (about 2 on average), and payments were stored at order level.

Experiment 1: revenue by area for January–March

Area Type 1 (overwrite) Type 2 (point-in-time join)
Ameerpet ₹9,00,000 ₹9,00,000
Gachibowli ₹9,00,000 — (no kitchen there yet)
Kondapur ₹9,00,000 ₹18,00,000
Madhapur ₹9,00,000 ₹9,00,000

Experiment 2: revenue after a fan-out join

Revenue
sum of payments ₹72,40,000
sum of payments after joining to items (1–3 items per order, mean 2.0) ₹1,44,79,800

What it shows

  • Type 1 silently rewrites history. Every past report changes when an attribute changes, and nothing warns you. If a question involves "as it was at the time", the dimension must keep versions.
  • Fan-outs inflate measures by the average multiplicity (here ~2×). The query ran without error and returned a believable number.
  • The fixes are structural: point-in-time joins (or surrogate keys captured at load), declared grains, uniqueness tests on grain keys, and aggregating to a common grain before joining.

Try it yourself

  1. Store kitchen_key on each order at load time (looking up the version valid that day) and rewrite the type 2 query without date ranges.
  2. Fix the fan-out two ways: aggregate items per order first; or compute revenue from the order table and item counts from the item table.
  3. Implement the type 2 dimension with a dbt snapshot in chapter 04's project, then change a kitchen's area and rerun.

Revision sheet: modelling data for analysis

Key ideas

  • Facts at a declared grain with measures; dimensions with descriptive attributes; star schemas; conformed dimensions; surrogate keys.
  • Transaction, periodic snapshot and accumulating snapshot facts.
  • Additive, semi-additive and non-additive measures.
  • SCD types 0/1/2/3; point-in-time joins for type 2.
  • Layers: raw → staging → intermediate → marts; wide tables and semantic layers built on top.
  • Double-counting traps: fan-out, many-to-many, duplicates, mixed grains.

Numbers to remember

  • Lab: type 1 moved ₹9 lakh of Q1 revenue to the wrong area; fan-out doubled revenue (₹72.4 lakh → ₹1.45 crore).

Glossary

  • Grain: what one fact row represents.
  • Star schema: a fact table joined to dimension tables.
  • SCD: slowly changing dimension.
  • Surrogate key: a warehouse-generated identifier for a dimension row/version.
  • Semantic layer: shared metric definitions.