FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Star and Snowflake Warehousing with SCD Type 2

Fact grain, star versus snowflake dimensions, and Type 2 surrogate-key history preserve the attributes a business event had at its effective time.

Freshness: current•9 min read•Data Engineering and Databases
Full Technical Reference Document

Mental model

A warehouse fact records a business event at a defined grain, while dimensions describe the people, products, or places involved. Slowly changing dimension Type 2 (SCD2) adds a new dimension row when tracked attributes change, assigning a new surrogate key and a validity interval. A fact can then join to the version that was true when its event occurred.

Learning outcomes

  • Declare fact grain and distinguish a stable natural key from a version-specific surrogate key.
  • Explain how star and snowflake dimension shapes affect joins and attribute maintenance.
  • Use half-open validity intervals to resolve a fact to its dimension version at event time.
  • Choose between scheduled dbt snapshots and change capture from Snowflake Streams for a source's change pattern.

Theory

Begin with grain: one row in a sales fact might mean one order line, not one order and not one daily customer total. Measures such as quantity and net amount belong at that grain; descriptive attributes belong in dimensions. A surrogate key identifies a particular dimension row, while the natural key (for example, customer_id) identifies the real customer across versions. Keeping both lets a warehouse preserve business identity while facts point to historical descriptions.

In a star schema, a fact table joins directly to comparatively wide dimensions. BI queries are simple and usually need fewer joins, but repeated labels can consume space and should be updated consistently. A snowflake schema normalizes a dimension into related tables, such as customer, city, and region. That can reduce duplicated hierarchy values, while adding joins and making self-service queries less direct. The choice is about query shape and stewardship; neither layout changes the requirement that a fact's grain and key semantics stay stable.

SCD2 represents each tracked attribute state as a row with valid_from and valid_to timestamps. Treat intervals as half-open: the start is included and the end excluded. For one natural key, versions can then meet at a boundary without both rows matching an event. Store a distinct surrogate key for each version and let a current version use a null end or a documented far-future sentinel. An event-time lookup chooses exactly the version whose interval contains the event timestamp:

SK⁡(k,t)=surrogate_key⁡(d),d.customer_id=k,d.valid_from≤t<d.valid_to\operatorname{SK}(k,t)=\operatorname{surrogate\_key}(d),\quad d.customer\_id=k,\quad d.valid\_from \le t < d.valid\_to

Here kk is the stable customer natural key, tt is the fact's UTC event time, and dd is the unique dimension version whose half-open interval contains tt. If valid_to is null for current rows, query logic must substitute the chosen current-row convention consistently. The warehouse should test that intervals for a natural key do not overlap and that at most one current version exists.

Suppose customer 481 changes from Basic to Pro at 2026-03-17 09:00 UTC. The Basic version has surrogate key 2104 and interval [2025-12-01 00:00, 2026-03-17 09:00); the new Pro version receives key 2379 and interval [2026-03-17 09:00, infinity). An order at 08:59 resolves to 2104, while an order at 09:02 resolves to 2379. Exactly 09:00 maps to the Pro row because the old interval excludes its end. If three million orders arrive per day and 0.4% are replayed, 12,000 replayed rows must still resolve to the same version rather than create extra dimension history.

Declare event grain and natural key
Capture source-row changes with snapshot or stream
Close the prior dimension validity interval
Insert a new surrogate-key version
Resolve each fact against event time
Conceptual teaching model synthesized from:dbt-snapshots-scd2,snowflake-streams-cdc

dbt snapshots compare a mutable query result with the previous snapshot and record changed versions. The timestamp strategy uses a trustworthy updated_at column, which is usually more resilient to source-column additions and removals than maintaining a list of checked fields. Snowflake Streams instead expose row-level change records between transactional offsets; a task or DML consumer can process inserts, updates, and deletes. The stream is a change feed, not an SCD2 dimension by itself: the consumer still has to deduplicate changes, preserve effective-time ordering, close the old interval, and create the new version. dbt's dbt_scd_id metadata field uniquely identifies a snapshot version; a downstream dimension can expose it as the surrogate key or assign a separate warehouse key.

Trade-offs

SCD2 gives historical reporting a stable answer to “what was true when the sale happened,” but it increases dimension rows and makes lookups temporal. A normal surrogate-key equality join is faster when the fact is assigned its dimension key during ingestion; if key assignment is delayed, an interval join is needed. Partition or cluster strategy should follow the actual fact query pattern, and tests should catch missing or multiple matching versions before metrics are published.

Use SCD1 overwrite for attributes whose past values are intentionally irrelevant, such as a corrected spelling when reports should always show the latest name. Use SCD2 for attributes whose history changes business interpretation, such as account segment or shipping territory. A star dimension simplifies the downstream model but can repeat hierarchy data; a snowflake normalizes it at the cost of joins. Streaming changes can reduce capture delay, but require offset, task-failure, and schema-evolution operations. Periodic snapshots are easier to reason about but only observe changes present at snapshot time.

Failure modes and misconceptions

An updated_at column that changes late or is not maintained can make a timestamp snapshot miss a real change. If no reliable update timestamp exists, use dbt's check strategy with an explicit set of columns or another source of change evidence; adding a field later may otherwise change behavior unexpectedly. A scheduled snapshot also cannot record an intermediate state that was created and overwritten between runs. A stream can capture committed row changes, but a consumer must process its offset deliberately: when DML that consumes the stream commits, the stream offset advances with that transaction. Keep the destination write in the same transaction where possible, or stage the change durably so retries cannot skip an offset or apply a change twice.

Backdated source corrections are another trap. Appending a new row with an earlier valid_from can overlap existing intervals and produce duplicate fact matches. Route late corrections through an interval-repair process that closes and reinserts affected versions in effective-time order, then restates facts if surrogate assignments change. Replayed CDC events should be idempotent by source change identity and natural key; otherwise retries can create duplicate versions. Deletes need a declared policy too: close the current row, create a tombstone, or retain the last known state. Validate one current row per natural key, no overlapping intervals, unique surrogate keys, and representative fact-to-dimension match counts.

Decision scenario

A retail mart has 80 million order lines and receives customer changes from a CRM about every five minutes. Analysts need the tier that applied when each order was placed, while corrections may arrive a day late. Capture the low-latency change stream into a durable staging table, apply ordinary changes by effective timestamp in an idempotent transaction, and keep a repair path for late events. Materialize the customer version key on each fact during ingestion when the correct interval is known; retain natural key and event time for audit and repair. Use dbt snapshots for sources with reliable timestamps but no CDC feed. Compare the star and snowflake representations against the mart's common queries before normalizing attributes that analysts frequently group by.

Implementation pattern

This dbt snapshot configuration uses the timestamp strategy available in dbt v1.9 and later. Declare the crm.customers source in the project and make sure its updated_at column reflects every tracked change.

yaml
snapshots:
- name: customer_history
relation: source('crm', 'customers')
config:
schema: snapshots
unique_key: customer_id
strategy: timestamp
updated_at: updated_at
hard_deletes: new_record
tags:
- dimensional-history

After the snapshot is materialized as a dimension, an as-of join can assign each fact to one version. This query exposes dbt's per-version dbt_scd_id as a surrogate key and assumes non-overlapping intervals with a null dbt_valid_to for the current row.

sql
SELECT
f.order_id,
f.ordered_at,
d.dbt_scd_id AS customer_sk,
d.tier
FROM analytics.fct_order AS f
JOIN analytics.snapshots.customer_history AS d
ON d.customer_id = f.customer_id
AND f.ordered_at >= d.dbt_valid_from
AND f.ordered_at < COALESCE(
d.dbt_valid_to,
'9999-12-31 00:00:00'::TIMESTAMP_NTZ
);
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next