cancel
Showing results forย 
Search instead forย 
Did you mean:ย 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Propagating SCD2 History from Silver to Gold with AUTO CDC FLOW and Handling Full Refresh

yit337
Contributor III

I have a streaming SCD2 table in the Silver layer, and I need to propagate all historical and future SCD2 events into another SCD2 streaming table in the Gold layer.

The Gold table is maintained through a DLT pipeline using two AUTO CDC FLOWs:

  1. Initial history load

    • Uses once=True.
    • Copies the entire Silver table into Gold.
    • This is required because the source table's CDF does not contain the complete historical event history.
  2. Incremental updates

    • Continuously reads from the Silver table's Change Data Feed (CDF).
    • Captures new changes as they occur.

This setup works fine during the initial deployment:

  • The Silver table already contains historical SCD2 records.
  • The CDF is empty
  • The once=True flow loads all existing records into Gold.
  • The second flow then keeps Gold synchronized using CDF going forward.

 

The challenge appears when performing a full refresh of the Gold table.

At that point:

  • The Silver table still contains the complete SCD2 history.
  • The Silver table's CDF now also contains some historical change events (not empty, but it does not contain full history because it has retention period).
  • If both flows are executed again:
    • The once=True flow reloads the entire Silver table.
    • The incremental CDC flow replays changes from CDF.
  • As a result, duplicate historical events are written into the Gold table.

Although full refreshes are expected to be rare, I'd like to have a robust solution before moving this design to production.

 

Is there a recommended Databricks pattern for handling this scenario? Have you implemented a similar architecture using AUTO CDC FLOW / Lakeflow Declarative Pipelines, and if so, what approach did you take?

4 REPLIES 4

SumeshKashyap
Valued Contributor III

Good on you for sorting this out before production. Full refresh is exactly where the two-flow backfill pattern goes wrong.

 

Why the duplicates happen

 

The two flows don't agree on where the history ends and the changes begin. On the first deployment the CDF happened to be empty, so the "full snapshot" and "changes since" covered different ranges without anyone setting it up that way. After a full refresh, both flows start from scratch. The once=True flow reads the whole current table. The CDF flow has a new checkpoint and replays everything still in retention. The ranges overlap and events land twice.

 

The fix: pin both flows to the same Silver table version

 

Read the Silver version once when the pipeline graph is defined, and use it as the boundary for both flows:

 

- The once flow reads Silver as of version V (time travel), not "whatever is current".

- The CDF flow starts at version V and drops anything with _commit_version <= V.

 

The CDF flow's starting position only matters when its checkpoint is new. So on normal updates the once flow doesn't run again, and the CDF flow ignores the starting version and keeps going from its checkpoint. On a full refresh, both reset together and line up at the same V. Nothing overlaps and nothing goes missing, even if Silver gets writes while the refresh is running.

 

import dlt

from delta.tables import DeltaTable

 

SILVER = "main.silver.customer_scd2"

GOLD = "main.gold.customer_scd2"

 

# Boundary version, resolved each time the graph is built.

# It only takes effect when the flows below start from a fresh checkpoint.

V = DeltaTable.forName(spark, SILVER).history(1).select("version").first()[0]

 

dlt.create_streaming_table(GOLD)

 

@Dlt.view

def silver_snapshot():

    return spark.read.option("versionAsOf", V).table(SILVER)

 

@Dlt.view

def silver_changes():

    return (

        spark.readStream

        .option("readChangeFeed", "true")

        .option("startingVersion", V)

        .table(SILVER)

        .where(f"_commit_version > {V}")

        .where("_change_type IN ('insert', 'update_postimage')")

    )

 

common = dict(

    target=GOLD,

    keys=["customer_id"],

    sequence_by="__START_AT",  # whatever you sequence on today

    stored_as_scd_type=2,

)

 

dlt.create_auto_cdc_flow(name="gold_backfill", source="silver_snapshot", once=True, **common)

dlt.create_auto_cdc_flow(name="gold_incremental", source="silver_changes", **common)

 

A few notes:

 

- I start the stream at V and filter with _commit_version > V rather than using startingVersion = V + 1, because V + 1 may not exist yet when the refresh starts.

- Keep your existing _change_type filtering and sequencing logic. The only change here is the shared boundary V.

- This assumes Silver is written by a different pipeline, which it sounds like it is. If Silver is in the same pipeline, you can't read its history while the graph is being built, and you'd need to pass V in as a pipeline parameter instead.

- Full refresh will also need the Silver snapshot at V to be readable with time travel. Since V is always the latest version, VACUUM on Silver won't get in the way.

 

Two extra safeguards worth adding

 

- Set pipelines.reset.allowed = false on the Gold table so nobody can full-refresh it by accident. You can still remove the property on purpose when you really do need a rebuild.

- If Gold uses the same keys as Silver and only changes columns row by row, you might not need a second SCD2 engine at all. Silver already has __START_AT/__END_AT, so a materialized view or plain streaming projection over Silver keeps the history without a backfill/CDF handoff to manage. A second AUTO CDC is only worth it when Gold changes the grain or the key.

 

Hope that helps. Feel free to share your sequence_by and _change_type handling if you'd like a second pair of eyes on the steady-state part too.

adnan_alvee
Databricks Employee
Databricks Employee

Hi @yit337 ,

The behavior you are seeing is expected. ONCE means โ€œrun once for the current pipeline state,โ€ not โ€œnever run again.โ€ A full refresh clears the Gold table and its flow checkpoints, so the ONCE flow runs again and the CDF flow can replay retained changes that are already included in the full snapshot.

That is why the current design can duplicate history:

Silver snapshot  -> historical rows
Silver CDF       -> some of the same changes again
                         |
                       Gold SCD2



The path I would recommend:

Preserve the original CDC events before Silver turns them into an SCD2 table.

The Bronze event table is not another SCD2 table and is not just a copy of Silver. It is an append-only log of changes, for example:

 

sequence

customer_id

operation

city

1

101

INSERT

New York

2

101

UPDATE

San Francisco

3

101

UPDATE

Los Angeles

Each event should include:

  • The business key, such as customer_id

  • The operation, such as INSERT, UPDATE, or DELETE

  • The full after-image or the changed columns

  • A source sequence, LSN, or event timestamp used to order changes

  • Ingestion metadata

The important point is that Bronze retains all events and does not rewrite the old events. Silver and Gold can then both process the same complete event.

For example:

CREATE OR REFRESH STREAMING TABLE silver_customer_history;

CREATE FLOW silver_cdc AS AUTO CDC INTO silver_customer_history
FROM STREAM(bronze_customer_events)
KEYS (customer_id)
SEQUENCE BY sequence
APPLY AS DELETE WHEN operation = 'DELETE'
COLUMNS * EXCEPT (operation, sequence)
STORED AS SCD TYPE 2;
CREATE OR REFRESH STREAMING TABLE gold_customer_history;

CREATE FLOW gold_cdc AS AUTO CDC INTO gold_customer_history
FROM STREAM(bronze_customer_events)
KEYS (customer_id)
SEQUENCE BY sequence
APPLY AS DELETE WHEN operation = 'DELETE'
COLUMNS * EXCEPT (operation, sequence)
STORED AS SCD TYPE 2;

 

There is no separate ONCE=True snapshot flow in this design. A full refresh replays the complete Bronze event log once, and future updates continue from the same source. AUTO CDC is intended to process CDC feeds into SCD Type 1 or SCD Type 2 targets.

CDF should not be treated as the permanent event history because it is retention-bound and may not contain the complete historical record. If CDF is the only available source, archive it continuously into a durable append-only table before retention removes it.



 

If Gold does not need independent SCD2 logic

If Gold only needs a projection or enrichment of Silverโ€™s existing SCD2 rows, do not apply SCD2 a second time. Use a materialized view instead:

CREATE OR REFRESH MATERIALIZED VIEW gold_customer AS
SELECT
  customer_id,
  city,
  __START_AT,
  __END_AT
FROM silver_customer_history;

This avoids creating โ€œhistory of historyโ€ from Silverโ€™s CDF, which contains physical table changes such as inserts, update preimages, update postimages, and deletes, rather than necessarily representing the original business events.

One correction to the earlier example: the first SQL block should define silver_customer_history; the second should define gold_customer_history. Both should not define Gold.

If the original CDC events are not available today, this architecture requires an upstream change. The existing Silver snapshot can be used for the initial migration, but a safe full-refresh design then needs a consistent Silver version boundary so that CDF events already represented in the snapshot are not replayed.


 

anuj_lathi
Databricks Employee
Databricks Employee

The cleanest fix I know is to stop treating this as two overlapping SCD2 loads. Make the two flows idempotent against each other by giving them a shared ordering domain, so a full refresh can replay both without producing duplicates.

Why you get duplicates

On a full refresh, the once flow re-runs and reloads the whole Silver table [1][2]. The streaming checkpoint for the CDF flow is also reset, so it re-reads whatever CDF is still retained. Those retained events describe changes already present in the snapshot, but nothing tells Gold that. On top of that, SCD2 AUTO CDC derives its own __START_AT/__END_AT and its own primary key (business key plus coalesce(__START_AT, __END_AT)) [3]. Feeding it data that already contains SCD2 intervals makes the same logical row land in two different shapes.

Recommended pattern: model Gold as an SCD1 table on the natural SCD2 key

A Silver SCD2 row is already uniquely identified by (business_key, __START_AT). The only thing that ever mutates on it is __END_AT, when the row is closed. So you don't need AUTO CDC to build history again. Make Gold an SCD Type 1 target keyed on (id, __START_AT), which gives you the same table shape with Silver's validity columns carried through as ordinary columns.

SCD1 targets support exactly the combination you need: one AUTO CDC FROM SNAPSHOT flow for the backfill, plus one or more AUTO CDC flows for the live feed [4]. The snapshot version and the CDC sequencing column form a single ordering domain [4]:

  • A newer snapshot takes precedence over older CDC events.
  • A CDC event newer than the snapshot wins over the snapshot.
  • A full refresh re-runs the one-time snapshot flow [5][4].

So if you set the snapshot version to the Silver table version you read, and sequence the CDF flow by _commit_version, then replayed CDF events at or below the snapshot version are treated as already applied and ignored. Anything committed after it is applied on top.

from pyspark import pipelines as dp

dp.create_streaming_table("gold_dim")

# 1) One-time history backfill, versioned by the Silver table version
def silver_snapshot(latest_version):
    if latest_version is not None:
        return None   # only ever one snapshot
    v = spark.sql("DESCRIBE HISTORY silver.dim LIMIT 1").collect()["version"]
    df = spark.read.option("versionAsOf", v).table("silver.dim")
    return df, v

dp.create_auto_cdc_from_snapshot_flow(
    target="gold_dim",
    source=silver_snapshot,
    keys=["id", "__START_AT"],
    stored_as_scd_type=1,
    once=True,
)

# 2) Live changes from Silver's CDF
@dp.view
def silver_cdf():
    return (
        spark.readStream
             .option("readChangeFeed", "true")
             .table("silver.dim")

References

[1] Load and process data incrementally with Lakeflow pipeline flows | Databricks on AWS โ€” https://docs.databricks.com/aws/en/ldp/concepts/flows
[2] AUTO CDC INTO (pipelines) | Databricks on AWS โ€” https://docs.databricks.com/aws/en/ldp/developer/ldp-sql-ref-apply-changes-into
[3] Advanced AUTO CDC topics | Databricks on AWS โ€” https://docs.databricks.com/aws/en/ldp/cdc-advanced
[4] The AUTO CDC APIs: Simplify change data capture with pipelines | Databricks on AWS โ€” https://docs.databricks.com/aws/en/ldp/cdc
[5] create_auto_cdc_from_snapshot_flow | Databricks on AWS โ€” https://docs.databricks.com/aws/en/ldp/developer/ldp-python-ref-apply-changes-from-snapshot



Anuj Lathi
Solutions Engineer @ Databricks

anuj_lathi
Databricks Employee
Databricks Employee

I have made a few errors in my previous response. Here's the corrected version.

What's documented about the ordering behavior

For SCD Type 1 targets, you can combine one AUTO CDC FROM SNAPSHOT flow with one or more AUTO CDC flows. The snapshot version and the CDC sequencing column form one ordering domain [1]:

  • A newer snapshot takes precedence over older CDC events.
  • A CDC event newer than the latest snapshot takes precedence over the snapshot.
  • Keys absent from the snapshot are treated as deleted at the snapshot version, though newer CDC events can restore them [1].

So the guarantee is precedence by version, not a separate dedup step. On a full refresh the one-time snapshot flow re-runs [1], and replayed CDF events with _commit_version below the snapshot version lose to the snapshot. That is the behavior you want, because a stale "row opened, __END_AT null" event must not overwrite the closed version of that row. Events at exactly the snapshot version carry the same values the snapshot already holds, so a tie is harmless under SCD1 upsert semantics.

Corrections to my earlier code

  • sequence_by belongs on the CDC flow, not the snapshot flow. The snapshot flow's version is its ordering value.
  • The CDF view was never connected to a flow. It needs create_auto_cdc_flow.
  • .collect()["version"] was a bug. It should be .collect()["version"].
  • The CDF needs cleanup. Filter out update_preimage, map deletes, and drop the CDF metadata columns.
  • __START_AT/__END_AT become ordinary columns because SCD1 doesn't generate or manage them. Gold just carries the values Silver computed. If you hit a naming conflict with reserved system columns (the docs flag this when adding AUTO CDC flows to an existing snapshot target [1]), rename them to valid_from/valid_to in the source views.
from pyspark import pipelines as dp
from pyspark.sql import functions as F

dp.create_streaming_table("gold_dim")

# One-time backfill; the snapshot version is the Silver Delta version we read
def silver_snapshot(latest_version):
    if latest_version is not None:
        return None
    v = spark.sql("DESCRIBE HISTORY silver.dim LIMIT 1").collect()["version"]
    return spark.read.option("versionAsOf", v).table("silver.dim"), v

dp.create_auto_cdc_from_snapshot_flow(
    target="gold_dim",
    source=silver_snapshot,
    keys=["id", "__START_AT"],
    stored_as_scd_type=1,

 

Anuj Lathi
Solutions Engineer @ Databricks