donderdag 26 november 2026

Databricks series : Building a mediallion architecture with SCD Type 2 (step 2) (Part XIII)

Introduction

In this series, we're building a small but realistic data platform using Databricks, Python, Delta Lake, and Unity Catalog. The goal is to create a reusable data ingestion architecture that can handle different data sources, such as CSV files and REST APIs, while supporting incremental processing and historical data tracking. We'll use a Medallion-inspired architecture with four logical layers:

  • Raw : Original source files.

  • Base : Ingested data stored as Delta tables.

  • Prep  : Validated and transformed data, including historical tracking.

  • Gold : Business-ready data for reporting and analytics.

In this first part, we'll focus on preparing the Unity Catalog structure and creating the Raw storage location. We won't build the Python pipelines yet. First, let's get the foundation right.


We are building upon what we already have :


2. Creating the Unity Catalog schemas

We'll use an existing Unity Catalog catalog called main.

Instead of creating separate catalogs for every layer, we'll create four schemas inside the existing catalog:


main
│
├── raw
├── base
├── prep
└── gold

Open the Databricks SQL Editor and execute:


CREATE SCHEMA IF NOT EXISTS main.raw;
CREATE SCHEMA IF NOT EXISTS main.base;
CREATE SCHEMA IF NOT EXISTS main.prep;
CREATE SCHEMA IF NOT EXISTS main.gold;

This creates the logical structure for our data platform. Using schemas for the different layers keeps the data organized and makes access management easier.


3. Creating the Raw Volume

The Raw layer will store our original source files. In Unity Catalog, we'll use a Volume for file storage. Execute the following SQL statement:

CREATE VOLUME IF NOT EXISTS main.raw.files;

Our Raw storage location is now:

/Volumes/main/raw/files/

We'll use this location as the landing zone for incoming files. For example, our folder structure will eventually look like this:


/Volumes/main/raw/files/
│
├── customers/
│   ├── customers.csv
│   └── customers_update.csv
│
└── exchange_rates/
    └── exchange_rates.json


The important design principle is that the Raw layer preserves the original input. We don't apply business transformations or overwrite source files during ingestion. This gives us the possibility to reprocess the original data if something goes wrong in a downstream pipeline.


4. Verifying the Unity Catalog structure

After creating the schemas and Volume, we can verify the setup. To list the schemas we can use the following command :


SHOW SCHEMAS IN main;

Resulting in :




To inspect the Volume:


DESCRIBE VOLUME main.raw.files;



We should now have the following structure available:

main
│
├── raw
│   └── files (Volume)
│
├── base
│
├── prep
│
└── gold

At this stage, the schemas are empty except for the Raw Volume. That's exactly what we want. We're preparing the foundation before implementing the ingestion logic.


5. Moving existing source files

In our existing Python project, we already have two customer CSV files:


/Volumes/main/demo/raw/customers.csv
/Volumes/main/demo/raw/customers_update.csv

We'll move or copy these files into the new Raw Volume:


/Volumes/main/raw/files/customers/customers.csv
/Volumes/main/raw/files/customers/customers_update.csv

So this is the result :


We'll keep the original files until we've verified that the new locations work correctly. This gives us a clean separation between the original landing zone and the future Delta tables.


Conclusion

We've now established the foundation of our Databricks Medallion Architecture. By organizing Unity Catalog into Raw, Base, Prep, and Gold schemas, and creating a dedicated Volume for original source files, we've established a clear separation between file storage, data ingestion, preparation, and business consumption. The next step is to connect these layers with Python and Delta Lake. This is where the architecture starts to become a working data platform.

zondag 22 november 2026

Databricks series : Building a mediallion architecture with SCD Type 2 (Step 1) (Part XII)

Introduction

When building a data platform, simply loading files into Delta tables is rarely enough. As data pipelines grow, we need a structured approach to ingestion, data quality, change tracking, and historical data management.  In this blogpost and other blogposts, we'll build a small but practical data platform using Databricks, Unity Catalog, Delta Lake, Change Data Feed (CDF), and Slowly Changing Dimensions Type 2 (SCD2).


The goal is to create an architecture that can ingest data from different sources, preserve the original input, detect changes, and maintain historical versions of business entities. We'll use customer data as our example, but the same architecture can also support REST APIs and other data sources.



The architecture

We'll use a Medallion-inspired architecture with four logical layers:

  • Raw: Original source files.

  • Base: Ingested data stored as Delta tables.

  • Prep: Validated and transformed data, including historical tracking.

  • Gold: Business-ready data for reporting and analytics.


Each layer has a specific responsibility. This separation makes the platform easier to maintain, troubleshoot, and extend.


2. Raw – Preserve the original data

The Raw layer is our landing zone. Its responsibility is straightforward: store source files exactly as they arrive. For this implementation, we'll use a Unity Catalog Volume:


/Volumes/main/raw/files/

Our folder structure could look like this:


/Volumes/main/raw/files/
    customers/
        customers.csv
        customers_update.csv

    exchange_rates/
        exchange_rates.json


We deliberately avoid business transformations in this layer. The original files remain available for reprocessing, troubleshooting, and auditing. Using a Unity Catalog Volume also provides governed access to files through Databricks.


3. Base – Ingest files into Delta tables

The Base layer converts the files from Raw into Delta tables. For example:


main.base.customers
main.base.exchange_rates


During ingestion, we add technical metadata to each record:




We use append-based ingestion so that incoming records are preserved instead of overwriting previous data. An important feature of this layer is Delta Change Data Feed. We enable CDF on the Base table:


ALTER TABLE main.base.customers
SET TBLPROPERTIES (
    delta.enableChangeDataFeed = true
);


CDF allows downstream processes to read row-level changes made to a Delta table. It exposes metadata such as:

  • _change_type

  • _commit_version

  • _commit_timestamp

This provides an efficient mechanism for incremental processing. One important distinction: when we append records from CSV files, CDF reports those records as inserts. It does not automatically detect that a customer already exists in another batch. That comparison is part of our downstream processing.


Prep – Data quality and historical tracking

The Prep layer is where the actual data preparation takes place.

Here we:

  • Validate incoming data.

  • Apply data types.

  • Remove or handle duplicates.

  • Apply business rules.

  • Detect changes in customer records.

  • Maintain historical versions using SCD Type 2.


We'll use an ODCS Data Contract to describe the expected customer schema and required fields.

For example, a customer contract defines:


schema:
  - name: customers
    properties:
      - name: customer_id
        logicalType: string
        primaryKey: true
        required: true

      - name: first_name
        logicalType: string
        required: true

      - name: last_name
        logicalType: string
        required: true

      - name: country
        logicalType: string
        required: true


The contract describes the expected structure and quality requirements. Our PySpark validation code enforces the selected rules at runtime.


Implementing SCD Type 2

A key requirement in many data platforms is preserving historical changes.


Suppose customer 1002 initially lives in Belgium:

customer_idfirst_namecountry
1002PietBelgium

Later, the customer changes their name and country:

customer_idfirst_namecountry
1002Pieter  Netherlands


A conventional upsert would overwrite the existing record. With SCD Type 2, we preserve the old version and insert a new one. Our Prep table, main.prep.customers, will contain:




We use the following technical columns:

  • valid_from: Start of the record's validity.

  • valid_to: End of the record's validity.

  • is_current: Indicates the active version.

  • record_hash: Helps identify changes in tracked business attributes.


The processing logic compares incoming records with the current version in Prep. When tracked attributes change, the existing version is expired and a new version is inserted.

The result is a complete historical view of customer data.


How CDF and SCD Type 2 work together

CDF and SCD Type 2 solve different problems. Change Data Feed identifies which rows have changed in a Delta table.  SCD Type 2 determines how business history should be maintained.


In our architecture, the flow is:

  1. New files arrive in Raw.

  2. An ingestion job appends their records to Base.

  3. Delta CDF exposes the new records.

  4. A preparation job reads the changes incrementally.

  5. The incoming records are validated and compared with current customer records.

  6. SCD Type 2 expires old versions and inserts new versions.


We also maintain a durable processing checkpoint so that the CDF consumer knows which Delta version it has already processed. This is important for reliable incremental processing and recovery after job failures. CDF itself is not a permanent archive. Its availability is subject to Delta table retention and vacuum operations. If long-term change-event retention is required, we should persist the events in a separate Delta table.


Gold – Business-ready data

The Gold layer contains data models designed for consumption by reporting tools, dashboards, and analytical workloads.  For example:


main.gold.dim_customer
main.gold.fact_exchange_rates


We can create a current customer view:

CREATE OR REPLACE VIEW main.gold.dim_customer AS
SELECT *
FROM main.prep.customers
WHERE is_current = true;



This gives consumers a straightforward view of the current customer state.  Other Gold models can use the historical records in Prep to perform time-based analysis, such as customer segmentation or historical reporting.


7. Orchestrating the pipeline with Databricks Jobs and Asset Bundles

We'll use separate Databricks Jobs for each major stage:


Databricks Asset Bundles (DAB) allow us to define and deploy these jobs from a local development environment, such as Visual Studio Code. This keeps the project version-controlled and makes deployment repeatable across development and production environments.


Why this architecture?

This architecture provides several benefits:

  • Separation of responsibilities  : Each layer has a clear purpose, making the solution easier to understand and maintain.
  • Reprocessing :  Original files remain available in Raw, allowing us to replay ingestion or correct transformation logic.
  • Incremental processing : CDF avoids repeatedly processing the entire Base table when only a small number of records have changed.
  • Historical tracking : SCD Type 2 preserves previous versions of customer data instead of simply overwriting them.
  • Data governance :Unity Catalog provides centralized governance for tables, schemas, volumes, and access permissions.
  • Extensibility : The same ingestion framework can support CSV files, REST APIs, and additional source systems.


Conclusion

By combining Unity Catalog Volumes, Delta Lake, Change Data Feed, and SCD Type 2, we can build a practical and extensible data platform. The Raw layer preserves the original input, Base provides a reliable Delta ingestion layer, Prep manages data quality and historical changes, and Gold exposes business-ready datasets.


The most important design principle is that each technology has a distinct responsibility:

  • Raw preserves the source.

  • Base ingests the data.

  • CDF tracks Delta changes.

  • Prep validates and historizes the data.

  • SCD Type 2 maintains business history.

  • Gold serves analytical workloads.

This gives us a solid foundation for building more advanced Databricks data pipelines without making the ingestion process and business transformations tightly coupled.


Hennie

Data modelling series : Assertions

Introduction

In data modeling, assertions (also known as business rules or structural assertions) are short, unambiguous sentences written in plain language that define the cardinality between two entities. They serve as a direct translation from a diagram (such as an ERD) into clear agreements with the business.
A well-crafted assertion almost always follows a fixed pattern to capture both minimum (optional vs. mandatory) and maximum (one vs. many) cardinality, and is always read in both directions.


The formula


The Standard Formula for an Assertion : 

A/An [Entity A] [MUST / MAY] [relationship verb] [one / one or more] [Entity B].

MUST = Mandatory (Minimum = 1)
MAY = Optional (Minimum = 0)
one = Maximum = 1
one or more = Maximum = N (many)


Some examples


1. One-to-Many (1:N)  The Most Common Relationship

Scenario: An online store with customers and orders.

Direction 1 (Customer → Order): "A Customer may place one or more Orders." 
Optional, because someone can create an account without buying anything right away: 0..N

Direction 2 (Order → Customer): "An Order must be placed by exactly one Customer." 
Mandatory, an orphaned order without a customer cannot exist: 1..1



2. One-to-One (1:1) – Strict Pairing

Scenario: Employees and their company cars.

Direction 1 (Employee → Company Car): "An Employee may drive at most one Company Car." Optional, not everyone has a company car: 0..1

Direction 2 (Company Car → Employee): "A Company Car must be assigned to exactly one Employee." 
Mandatory, this company does not register unused pool cars: 1..1


3. Many-to-Many (M:N) – Mutual Multiplicity

Scenario: Students and courses at a university.

Direction 1 (Student → Course): "A Student must enroll in one or more Courses." 
Mandatory to maintain active enrollment: 1..N

Direction 2 (Course → Student): "A Course may be attended by one or more Students." 
Optional, a newly created course might still have 0 enrollments: 0..N


Assertions are the ultimate stress test for your data model. When a domain expert reads an assertion and says, "No, that's not how it works in reality" (for example: "An order may also be placed by a guest without an account"), you immediately know you need to adjust your data model and database constraints (NOT NULL vs. NULL) before writing a single line of code.



Hennie


vrijdag 20 november 2026

Data modelling series : Cardinality

Introduction

Data modeling remains essential because it transforms raw data into reliable, usable, and scalable information, regardless of how fast technologies like cloud storage, NoSQL, or AI evolve. Without a solid data model, organizations end up with data chaos : leading to flawed analytics, slow systems, and untrustworthy AI outputs.

 

Reasons

Reasons why data modelling is still important : 

  • Foundation for AI and Machine Learning: AI models and LLMs are only as good as the data feeding them (garbage in, garbage out). A clear data model provides context, clean relationships, and consistent definitions, enabling AI systems to make accurate predictions and hallucinate less.
  • Single Source of Truth: Within a company, terms like "active customer" or "revenue" often mean different things to marketing than they do to finance. Data modeling forces organizations to agree on and enforce clear business rules and definitions before building reports or dashboards.
  • Preventing High Cloud Costs and Technical Debt: Modern cloud data platforms (such as Snowflake or BigQuery) make it easy to dump massive amounts of unstructured data. However, without a proper model, complex queries become painfully slow and cloud compute costs skyrocket.
  • Data Governance and Privacy Compliance (GDPR): Privacy laws and security standards require organizations to know exactly what personal data they hold, where it lives, and how it connects. A data model makes data lineage and access control transparent and auditable.
  • Bridge Between Business and IT: A data model (especially at the conceptual and logical levels) acts as a shared language. It aligns domain experts and software engineers on business processes and expectations before a single line of code is written.


Cardinality

In this blogpost I want to go more in depth about cardinality between entities. Below an example of a Customer, order and product. It's not a perfect example but assume it is ;-). I borrowed this example from a youtube video from Lucidchart.



We have a minimum and maximum number that an entity instance(s) can have related to another entitiy instance(s). Lets understand the maximum and minimum cardinality.


Maximum cardinality rules :

  • One-to-One (1:1): One instance of Entity A connects to at most one instance of Entity B, and vice versa (e.g., a person and a passport). 
  • One-to-Many (1:N) / Many-to-One (N:1): One instance of A connects to many instances of B, while each instance of B connects to at most one instance of A (e.g., one customer places many orders).
  • Many-to-Many (M:N): Multiple instances of A connect to multiple instances of B and vice versa (e.g., students and courses). We also call this in datamodelling an associative entity.

Minimum cardinality (optionality) rules :

  • Mandatory (Minimum = 1): An entity instance must participate in the relationship.
  • Optional (Minimum = 0): An entity instance may participate without a matching record on the other side (e.g., a customer may have 0 orders). 

There is a difference between : and .. . If you say it is 1:N then we reason from maximum cardinality and if we say 0..N. Use a double dot (..) when defining the exact rules for one specific direction (minimum..maximum). 


How they fit together? Take a standard One-to-Many (1:N) relationship between a Customer and an Order:
  • Overall (maximum) relationship: 1:N (Customer to Orders).
  • Customer → Order (0..N): "A Customer may place zero, one, or many Orders."
  • Order → Customer (1..1): "An Order must belong to one and only one Customer."

So it's a bit confusing, when we say a relation is 1:N, because this the MAXIMUM relationship, and this gives only a specific view of the reality. 






So we have four options :




Now let's investigate this in more depth. So what does this mean? How many combinations can we create? As it seems we can create 10 combinations.





One to one (3 variants)

In a One-to-One relationship, a single record in Entity A links to at most one record in Entity B, and vice versa. Here are the variants with examples:





Why It Matters: 1:1 relationships are often used to separate sensitive data (like user credentials or medical records) from general profile data for security and performance.


One to many (4 variants)

The One-to-Many relationship is the most common building block in relational databases. One record in the "parent" entity can link to multiple records in the "child" entity, while each child record belongs to only one parent.



Why It Matters: Getting the direction of 1:N right prevents catastrophic reporting bugs : such as accidentally multiplying revenue numbers when joining customer and order tables in BI dashboards.

Many to Many (3 variants)

In a Many-to-Many relationship, multiple records in Entity A can link to multiple records in Entity B, and vice versa.



Why It Matters: N:M relations are often used in conceptual modelling. Relational databases cannot store a direct M:N link cleanly without duplicating data. To solve this, data modelers introduce a bridge table (such as Enrollment), splitting one M:N relationship into two clean 1:N relationships.

Hennie

dinsdag 17 november 2026

Databricks series : reading an API (Part XI)

Introduction

Next, lets create a pipeline that retrieves current exchange rates via a public API. We will use the free Frankfurter API. It provides both historical and recent exchange rates and does not require an API key for basic functionality.


What are we going to build?

  1. Python performs an HTTP GET request to the API.
  2. The API returns JSON data containing exchange rates.
  3. Python converts the JSON into a Spark DataFrame.
  4. We validate the data using an ODCS Data Contract.
  5. We write the data to a Delta table.
  6. A Databricks Job executes the pipeline using parameters.



Projectstructure  

We slightly change the project structure :

databricks-transfer/
│
├── databricks.yml
├── resources/
│   └── transfer_job.yml
│
├── src/
│   ├── main.py
│   └── transfer/
│       ├── config_loader.py
│       ├── contract_validator.py
│       ├── processor.py
│       └── api_client.py       <-- new
│
├── config/
│   └── entities.json
│
├── contracts/
│   ├── customers.yaml
│   └── exchange_rates.yaml     <-- new
│
└── requirements.txt


Lets create the API client

We use the Frankfurter API:

https://api.frankfurter.app/latest?from=EUR&to=USD,GBP,CHF


The API returns JSON. We convert this into a Spark DataFrame with one record per exchange rate.


{
    "amount":1.0,
    "base":"EUR",
    "date":"2026-11-16",
    "rates":{
        "CHF":0.9244,
        "GBP":0.8345,
        "USD":1.1014
    }
}


New file: src/transfer/api_client.py

Next we need to create a new file api_client.py. Create this file with the following content:


import requests

from pyspark.sql import Row


def read_api_data(spark, config):

    url = config["url"]
    base_currency = config["base_currency"]
    target_currencies = config["target_currencies"]

    print(f"Calling API: {url}")
    print(f"Base currency: {base_currency}")
    print(f"Target currencies: {target_currencies}")

    response = requests.get(
        url,
        params={
            "from": base_currency,
            "to": ",".join(target_currencies)
        },
        timeout=30
    )

    response.raise_for_status()

    data = response.json()

    exchange_date = data["date"]
    rates = data["rates"]

    rows = [
        Row(
            base_currency=base_currency,
            target_currency=currency,
            exchange_rate=float(rate),
            exchange_date=exchange_date
        )
        for currency, rate in rates.items()
    ]

    df = spark.createDataFrame(rows)

    print(f"Retrieved {len(rows)} exchange rates")

    return df


What is happening here?

  1. We read the API settings from the configuration.
  2. We perform an HTTP GET request.
  3. We check whether the API call was successful.
  4. We convert the JSON response into individual records.
  5. We return a Spark DataFrame.


Extending the configuration

Open config/entities.json and add a new entity : exchange_rates. Leave your existing customer configurations as they are.

{
  "customers": {
    "source": "/Volumes/main/demo/raw/customers.csv",
    "target": "main.demo.customers",
    "format": "csv",
    "mode": "overwrite",
    "contract": "contracts/customers.yaml"
  },
  "customers_update": {
    "source": "/Volumes/main/demo/raw/customers_update.csv",
    "target": "main.demo.customers",
    "format": "csv",
    "mode": "merge",
    "merge_key": "customer_id",
    "contract": "contracts/customers.yaml"
  },
  "exchange_rates": {
    "source_type": "api",
    "url": "https://api.frankfurter.app/latest",
    "base_currency": "EUR",
    "target_currencies": ["USD", "GBP", "CHF"],
    "target": "main.demo.exchange_rates",
    "mode": "append",
    "contract": "contracts/exchange_rates.yaml"
  }
}


Note: For the API, we use 'source_type' instead of 'format'. This allows our processor to distinguish between CSV and API.


Step 3 – Extending the processor

Open `src/transfer/processor.py` and replace the content: 


from delta.tables import DeltaTable
from transfer.contract_validator import validate_dataframe
from transfer.api_client import read_api_data

def transfer_data(spark, config, contract=None):

    target = config["target"]
    mode = config["mode"]
    source_type = config.get("source_type", "csv")

    print(f"Source type: {source_type}")
    print(f"Target table: {target}")
    print(f"Loading mode: {mode}")


    # Read everything as strings first
    source_type = config.get("source_type", "csv")

    if source_type == "csv":

        source = config["source"]
        file_format = config["format"]

        df = (
            spark.read
            .format(file_format)
            .option("header", "true")
            .option("inferSchema", "false")
            .load(source)
        )

    elif source_type == "api":

        df = read_api_data(spark, config)

    else:
        raise ValueError(
            f"Unsupported source type: {source_type}"
        )

    # Validate before writing

    if contract is None:
        raise ValueError(
            "No data contract configured for this entity"
        )

    df = validate_dataframe(df, contract)

    record_count = df.count()

    print(f"Validated records: {record_count}")

    # Apply loading strategy

    if mode == "overwrite":

        (
            df.write
            .format("delta")
            .mode("overwrite")
            .saveAsTable(target)
        )

    elif mode == "append":

        (
            df.write
            .format("delta")
            .mode("append")
            .saveAsTable(target)
        )

 
    elif mode == "merge":

        merge_key = config["merge_key"]

        # Read primary keys from the ODCS contract
        primary_keys = [
            item["name"]
            for item in contract["schema"][0]["properties"]
            if item.get("primaryKey") is True
        ]

        print(f"ODCS primary keys: {primary_keys}")
        print(f"Configured merge key: {merge_key}")

        if merge_key not in primary_keys:
            raise ValueError(
                f"Merge key {merge_key} is not defined "
                f"as a contract primary key. Found: {primary_keys}"
            )

        if spark.catalog.tableExists(target):

            delta_table = DeltaTable.forName(
                spark, target
            )

            (
                delta_table.alias("target")
                .merge(
                    df.alias("source"),
                    f"target.{merge_key} = source.{merge_key}"
                )
                .whenMatchedUpdateAll()
                .whenNotMatchedInsertAll()
                .execute()
            )

        else:

            (
                df.write
                .format("delta")
                .mode("overwrite")
                .saveAsTable(target)
            )


    else:
        raise ValueError(
            f"Unsupported loading mode: {mode}"
        )

    print(
        f"Successfully processed {record_count} records"
    )


As a result, the existing CSV pipelines continue to work.


Adding the ODCS contract

Create a new file 'contracts/exchange_rates.yaml' and insert the following code in the file.


apiVersion: v3.2.0
kind: DataContract

id: urn:datacontract:databricks:exchange-rates
name: exchange_rates
version: 1.0.0
status: active

description:
  purpose: Currency exchange rates
  usage: Used for financial reporting and analytics
  limitations: Rates are published by the Frankfurter API

team:
  name: Data Engineering

schema:
  - name: exchange_rates
    physicalName: main.demo.exchange_rates
    physicalType: table

    properties:
      - name: base_currency
        logicalType: string
        physicalType: STRING
        primaryKey: true
        required: true

      - name: target_currency
        logicalType: string
        physicalType: STRING
        primaryKey: true
        required: true

      - name: exchange_rate
        logicalType: number
        physicalType: DOUBLE

        required: true

      - name: exchange_date
        logicalType: date
        physicalType: DATE
        primaryKey: true
        required: true



Expanding dependencies

Open requirements.txt and add requests:


PyYAML==6.0.2
requests==2.32.5


Since we are using Databricks Serverless, we also need to modify resources/transfer_job.yml. Add requests to the dependencies:


dependencies:
  - PyYAML==6.0.2
  - requests==2.32.5


Running the Job

You can now use the same Databricks Job, but with a different parameter:


databricks bundle validate -t dev
databricks bundle deploy -t dev
databricks bundle run transfer_job -t dev --params entity=exchange_rates


Here is some of  debug logging :




The expected table is main.demo.exchange_rates and we can check the data using:


SELECT *
FROM main.demo.exchange_rates
ORDER BY exchange_date, target_currency;


Resulting in  :




Hennie