Wicked Smart Data
LearnInsightsAboutContact
Sign InLet's Build
LearnInsightsAboutContact
Sign InLet's Build
Wicked Smart Data

Intelligence, automation, and expert execution — plus an elite library of free knowledge. We turn complexity into competitive advantage.

Start a conversation

Platform

  • Learning Paths
  • Insights
  • RSS Feed

Company

  • About
  • Contact
  • Work With Us

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Wicked Smart Data. All rights reserved.

Intelligence · Automation · Advantage

All Insights
Microsoft Fabric

Implementing Cross-Lakehouse Delta Table Joins in a Fabric Spark Notebook Using Semantic Link and the Fabric REST API

Learn how to join Delta tables from multiple Fabric workspaces in a single Spark notebook — resolving OneLake paths programmatically, managing cross-workspace tokens, and writing federated results to a Gold layer with MERGE semantics. This is the architecture that powers enterprise-scale Fabric data platforms.

🔥 Expert26 min readDec 1, 2026Updated Dec 1, 2026
Implementing Cross-Lakehouse Delta Table Joins in a Fabric Spark Notebook Using Semantic Link and the Fabric REST API
On this page
  • Introduction
  • Prerequisites
  • Understanding the OneLake Path Architecture
  • Setting Up Semantic Link for Metadata Resolution
  • Understanding Workspace Tokens and Cross-Workspace Authorization
  • Resolving Paths and Reading Source Delta Tables
  • Performing the Cross-Lakehouse Join with Broadcast Awareness
  • Writing Federated Results to the Gold Layer with MERGE Semantics
  • Putting It All Together: The Complete Notebook Structure
  • Performance Considerations for Cross-Workspace Reads
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Summary & Next Steps

Implementing Cross-Lakehouse Delta Table Joins in a Fabric Spark Notebook Using Semantic Link and the Fabric REST API: Resolving OneLake Paths, Managing Workspace Tokens, and Writing Federated Results to a Gold Layer Table

Introduction

Your organization has grown. What started as a single lakehouse containing everything — raw ingestion, cleansed silver tables, and curated gold outputs — has matured into a collection of domain-specific lakehouses spread across multiple Fabric workspaces. The sales team owns their own lakehouse in the Sales-Prod workspace. Finance controls theirs in Finance-Prod. And you've been tasked with building a cross-domain Gold layer that joins customer lifetime value data from Finance with pipeline-stage data from Sales to produce a unified account health scorecard.

The obvious question is: how do you actually read Delta tables from two different lakehouses inside a single Spark notebook, resolve their OneLake paths reliably without hardcoding workspace GUIDs, authenticate across workspace boundaries, and then write the federated result back to a third "enterprise gold" lakehouse — all in a production-grade, maintainable way?

This is the kind of problem that separates practitioners who've wrestled with Fabric's internals from those who've only worked within a single lakehouse. The answer involves three moving parts working together: Semantic Link's FabricRestClient for workspace and item metadata resolution, the Fabric REST API for token-scoped access across workspace boundaries, and direct OneLake ABFS paths that let Spark read Delta tables as if they were local. By the end of this lesson, you'll have a complete, working pattern you can adapt for any multi-workspace federation scenario.

What you'll learn:

  • How OneLake paths are structured across workspaces and lakehouses, and how to resolve them programmatically without hardcoding GUIDs
  • How to use sempy.fabric.FabricRestClient to enumerate workspaces and lakehouse items via the Fabric REST API from within a notebook
  • How workspace-scoped tokens work in Fabric notebooks and how to safely pass credentials when reading cross-workspace Delta tables
  • How to perform broadcast-aware, partition-aligned joins across two remotely-read Delta DataFrames in PySpark
  • How to write federated join results to a Gold layer Delta table using merge semantics for idempotency

Prerequisites

This lesson assumes you're comfortable with the foundational layers of the Fabric stack. Specifically, you should already understand:

  • How Spark notebooks work in Fabric and basic PySpark DataFrame operations — if you need a refresher, start with Transforming Data with Spark Notebooks in Microsoft Fabric: PySpark for Lakehouse Tables
  • The structure of OneLake and how Delta tables are stored — covered in OneLake Explained: One Copy of Data, Delta Tables, and Shortcuts
  • How lakehouses are created and what the managed Tables directory contains — see Building Your First Lakehouse in Microsoft Fabric: Files, Tables, and the SQL Analytics Endpoint
  • Medallion architecture concepts, especially what "Gold layer" means in a production context — covered in Implementing the Medallion Architecture in Microsoft Fabric: Bronze, Silver, and Gold Layers

You'll also need:

  • A Fabric capacity (F2 or higher, or a trial capacity) with at least three lakehouses across two workspaces
  • The semantic-link library available in your Spark environment (it's pre-installed in Fabric runtimes 1.2+)
  • Contributor or higher role in both source workspaces, and at least Contributor in the destination Gold workspace

Understanding the OneLake Path Architecture

Before writing a single line of code, you need to understand exactly what a cross-lakehouse read means at the storage layer, because the path structure is what everything else is built on.

Every item in Microsoft Fabric that generates data ultimately stores it in OneLake. The canonical ABFS path structure for any Delta table in a managed lakehouse looks like this:

abfss://<workspace-id>@onelake.dfs.fabric.microsoft.com/<lakehouse-id>/Tables/<table-name>

The workspace ID and lakehouse ID are both GUIDs — not human-readable names. This is the first major friction point for cross-workspace work. You could go into the Fabric portal, click on each workspace and lakehouse, extract GUIDs from the URL bar, and paste them into your notebook. That works exactly once, until someone renames a lakehouse, moves it to a different workspace, or the development environment gets refreshed.

The production-grade approach is to resolve these GUIDs at runtime using the Fabric REST API. The API exposes endpoints that let you query: "given this workspace name and this lakehouse name, what is the GUID for each?" You then construct the ABFS path dynamically, so your notebook continues working even if the underlying infrastructure changes.

There's a subtlety worth understanding here: Spark doesn't read from OneLake using the lakehouse's SQL Analytics Endpoint, nor does it use the Delta Lake catalog registration that makes tables visible in the notebook's left-hand Lakehouse explorer. When you do spark.read.format("delta").load(abfss_path), Spark is making authenticated ABFS calls directly to the OneLake storage layer, bypassing any catalog entirely. This means you can read any Delta table in any location where your token has storage access, regardless of whether it's attached to your notebook's default lakehouse.

Key insight

The lakehouse explorer in a Fabric notebook only shows tables from the attached default lakehouse. Cross-workspace tables are invisible in the UI but fully accessible via ABFS paths — Spark doesn't care about the UI catalog, only about storage permissions.


Setting Up Semantic Link for Metadata Resolution

The semantic-link package (imported as sempy) ships with a FabricRestClient class that wraps the Fabric REST API with automatic token management. When you're running inside a Fabric notebook, FabricRestClient picks up your session identity and can make API calls without you handling OAuth flows manually. This is what you'll use to resolve workspace and lakehouse GUIDs.

Install confirmation first — in a notebook cell, verify the library is present:

import sempy
print(sempy.__version__)

You should see 0.7.x or higher on Fabric Runtime 1.2+. If you're on an older runtime and need to install manually, you can use %pip install semantic-link though this requires a cluster restart.

Now, let's build a reusable resolver function. The goal is a function that accepts human-readable workspace and lakehouse names and returns the fully-constructed ABFS path for any table within that lakehouse:

import sempy.fabric as fabric
from sempy.fabric import FabricRestClient

def resolve_lakehouse_abfs_path(workspace_name: str, lakehouse_name: str, table_name: str) -> str:
    """
    Resolves the ABFS path for a Delta table in any accessible Fabric workspace.
    
    Args:
        workspace_name: The display name of the target workspace
        lakehouse_name: The display name of the target lakehouse
        table_name: The Delta table name (must exist under /Tables/)
    
    Returns:
        Fully qualified abfss:// path for direct Spark reads
    """
    client = FabricRestClient()
    
    # Step 1: Enumerate all workspaces the caller has access to
    workspaces_response = client.get("/v1/workspaces")
    workspaces_response.raise_for_status()
    workspaces = workspaces_response.json().get("value", [])
    
    # Step 2: Find the target workspace by display name
    target_workspace = next(
        (ws for ws in workspaces if ws["displayName"] == workspace_name),
        None
    )
    if target_workspace is None:
        accessible_names = [ws["displayName"] for ws in workspaces]
        raise ValueError(
            f"Workspace '{workspace_name}' not found or not accessible. "
            f"Accessible workspaces: {accessible_names}"
        )
    
    workspace_id = target_workspace["id"]
    
    # Step 3: Enumerate lakehouses in that workspace
    lakehouses_response = client.get(f"/v1/workspaces/{workspace_id}/lakehouses")
    lakehouses_response.raise_for_status()
    lakehouses = lakehouses_response.json().get("value", [])
    
    # Step 4: Find the target lakehouse by display name
    target_lakehouse = next(
        (lh for lh in lakehouses if lh["displayName"] == lakehouse_name),
        None
    )
    if target_lakehouse is None:
        accessible_names = [lh["displayName"] for lh in lakehouses]
        raise ValueError(
            f"Lakehouse '{lakehouse_name}' not found in workspace '{workspace_name}'. "
            f"Available lakehouses: {accessible_names}"
        )
    
    lakehouse_id = target_lakehouse["id"]
    
    # Step 5: Construct the ABFS path
    abfs_path = (
        f"abfss://{workspace_id}@onelake.dfs.fabric.microsoft.com"
        f"/{lakehouse_id}/Tables/{table_name}"
    )
    
    return abfs_path

This function does something important beyond just constructing a string: it surfaces informative error messages. When a workspace name is wrong or the calling identity doesn't have access, the error tells you exactly what is accessible, which is invaluable when debugging cross-workspace permission issues at 2am before a Monday morning business review.

Warning

FabricRestClient resolves your token from the active Fabric session. If you run this notebook outside of a Fabric environment (e.g., in a local VS Code connected to a remote Livy endpoint), token acquisition will fail silently or throw an AttributeError. Always test cross-workspace patterns inside the Fabric notebook UI during development.


Understanding Workspace Tokens and Cross-Workspace Authorization

Here's the nuance that trips up nearly everyone doing cross-workspace work for the first time: just because your identity has access to a workspace doesn't mean your Spark session's storage credentials automatically cover that workspace's OneLake data.

In a Fabric notebook, the Spark session runs under the identity of the notebook's executing user (or, in pipeline runs, a service principal or the pipeline's system identity). OneLake enforces access control at the workspace level using the Fabric workspace role assignments — if your identity is a Contributor in Finance-Prod, your ABFS reads to that workspace's OneLake namespace will succeed. If you're only a Viewer, reads succeed but writes will fail. If you have no role at all in Finance-Prod, reads will return a 403 AuthorizationFailed error from the ABFS layer, even though the path itself is correctly constructed.

The key operational rule is: OneLake storage access in Spark follows your Fabric workspace role, not your Azure RBAC or Entra ID group memberships. This is a Fabric-native access control mechanism, separate from ADLS Gen2 ACLs. You'll see this enforced at the token level — the access token that Fabric's Spark runtime injects into ABFS calls is scoped by what your Fabric identity is permitted to do.

Note

For securing and governing access across workspaces, the safest production pattern is to use a Service Principal that has been explicitly granted the minimum required Fabric workspace roles in each source workspace. This avoids the "it works in dev because my personal account has admin everywhere, but breaks in prod under the pipeline identity" class of failures.

There's a second token consideration for the REST API calls themselves. FabricRestClient uses the Fabric API token (not the ABFS storage token). These are different token audiences. The API token lets you call api.fabric.microsoft.com endpoints to list workspaces and items. The storage token lets you call onelake.dfs.fabric.microsoft.com to read and write Delta files. In a notebook session, Fabric injects both automatically for your identity, but they can expire at different rates during a long-running notebook. A notebook that idles for more than an hour and then resumes a Spark job may hit token refresh issues — worth knowing for notebooks that run very large federated joins.

Let's add a lightweight permission verification step before attempting expensive cross-workspace reads:

def verify_workspace_access(workspace_name: str) -> dict:
    """
    Checks whether the current session identity has at least Viewer access
    to a target workspace and returns the access metadata.
    """
    client = FabricRestClient()
    
    workspaces_response = client.get("/v1/workspaces")
    workspaces_response.raise_for_status()
    workspaces = workspaces_response.json().get("value", [])
    
    target = next(
        (ws for ws in workspaces if ws["displayName"] == workspace_name),
        None
    )
    
    if target is None:
        return {
            "accessible": False,
            "workspace_name": workspace_name,
            "workspace_id": None,
            "capacity_id": None,
            "message": f"Workspace not found or no access granted."
        }
    
    return {
        "accessible": True,
        "workspace_name": workspace_name,
        "workspace_id": target["id"],
        "capacity_id": target.get("capacityId"),
        "message": "Access confirmed."
    }

# Verify before attempting expensive reads
sales_access = verify_workspace_access("Sales-Prod")
finance_access = verify_workspace_access("Finance-Prod")

print(f"Sales-Prod: {sales_access['message']} (ID: {sales_access['workspace_id']})")
print(f"Finance-Prod: {finance_access['message']} (ID: {finance_access['workspace_id']})")

if not sales_access["accessible"] or not finance_access["accessible"]:
    raise PermissionError("Required workspace access missing. Check Fabric workspace role assignments.")

Resolving Paths and Reading Source Delta Tables

With the resolver and access verification in place, let's build the actual cross-workspace read. The scenario: you're joining customer_lifetime_value from the Finance lakehouse with sales_pipeline_stages from the Sales lakehouse on a shared account_id key.

# Resolve all paths upfront — fail fast before any Spark jobs launch
sales_pipeline_path = resolve_lakehouse_abfs_path(
    workspace_name="Sales-Prod",
    lakehouse_name="SalesLakehouse",
    table_name="silver_sales_pipeline_stages"
)

finance_clv_path = resolve_lakehouse_abfs_path(
    workspace_name="Finance-Prod",
    lakehouse_name="FinanceLakehouse",
    table_name="silver_customer_lifetime_value"
)

gold_output_path = resolve_lakehouse_abfs_path(
    workspace_name="Enterprise-Gold",
    lakehouse_name="GoldLakehouse",
    table_name="gold_account_health_scorecard"
)

print("Resolved paths:")
print(f"  Sales pipeline:  {sales_pipeline_path}")
print(f"  Finance CLV:     {finance_clv_path}")
print(f"  Gold output:     {gold_output_path}")

Tip

Always resolve all paths in a single cell at the top of your notebook, before any Spark operations. If a path resolution fails due to a permissions issue or a renamed item, you want that failure to surface immediately — not after a 15-minute Spark job on the first source table has already consumed CU credits.

Now read the source tables. This is where the cross-workspace reads actually happen at the ABFS layer:

from pyspark.sql import functions as F
from pyspark.sql.types import StructType

# Read sales pipeline stages from Sales-Prod workspace
df_pipeline = (
    spark.read
    .format("delta")
    .load(sales_pipeline_path)
    .select(
        "account_id",
        "account_name",
        "pipeline_stage",
        "deal_value_usd",
        "stage_entered_date",
        "assigned_rep_id",
        "last_activity_date"
    )
    .filter(F.col("pipeline_stage") != "Closed Lost")
    .filter(F.col("last_activity_date") >= F.date_sub(F.current_date(), 90))
)

# Read customer lifetime value from Finance-Prod workspace
df_clv = (
    spark.read
    .format("delta")
    .load(finance_clv_path)
    .select(
        "account_id",
        "total_revenue_usd",
        "avg_deal_size_usd",
        "contract_renewal_date",
        "churn_risk_score",
        "customer_segment"
    )
    .filter(F.col("customer_segment").isin(["Enterprise", "Mid-Market", "Strategic"]))
)

# Cache both DataFrames — we'll use them in a join plus validation checks
df_pipeline.cache()
df_clv.cache()

print(f"Pipeline records loaded: {df_pipeline.count():,}")
print(f"CLV records loaded: {df_clv.count():,}")

The .cache() calls here are intentional and important. Without caching, Spark would re-read both source Delta tables from the remote OneLake paths every time the DataFrames are evaluated — once for the join, potentially again for quality validation, and again if you do a second action like a .count() for logging. Each re-read is an authenticated ABFS request across a workspace boundary, which costs both time and CU capacity. Caching after the first materialization pins the data in Spark memory (or on executor disk if memory pressure is high), so subsequent operations are purely local.


Performing the Cross-Lakehouse Join with Broadcast Awareness

You now have two DataFrames materialized from two different workspaces. The join itself is PySpark — there's nothing conceptually different from any other join. But the performance strategy requires thought.

The critical question is: what are the relative sizes of your two DataFrames? In this scenario, df_clv from Finance contains one record per customer account — typically tens of thousands of rows for even large enterprises. df_pipeline from Sales contains one row per active pipeline deal — potentially hundreds of thousands of rows for large sales organizations, but could also be modest in size.

When one DataFrame is significantly smaller than the other and fits comfortably in memory, a broadcast join is dramatically more efficient. Without a broadcast hint, Spark defaults to a sort-merge join, which involves a full shuffle of both DataFrames across the executor network — expensive on any cluster, doubly so when you've just read across workspace boundaries.

from pyspark.sql.functions import broadcast

# Determine broadcast candidate based on row counts
clv_count = df_clv.count()
pipeline_count = df_pipeline.count()

print(f"CLV row count: {clv_count:,} | Pipeline row count: {pipeline_count:,}")

# Apply broadcast to the smaller DataFrame
# Fabric's default autoBroadcastJoinThreshold is 10MB — 
# CLV data at ~200 bytes/row means anything under ~50K rows qualifies automatically,
# but we're explicit here for clarity and robustness
if clv_count < 500_000:
    df_joined = (
        df_pipeline
        .join(
            broadcast(df_clv),
            on="account_id",
            how="left"
        )
    )
    print("Using broadcast join (CLV is smaller dimension table)")
else:
    # Both tables are large — use repartition to co-locate join keys
    df_pipeline_repartitioned = df_pipeline.repartition(200, "account_id")
    df_clv_repartitioned = df_clv.repartition(200, "account_id")
    
    df_joined = (
        df_pipeline_repartitioned
        .join(df_clv_repartitioned, on="account_id", how="left")
    )
    print("Using sort-merge join with explicit repartitioning")

Key insight

Using a left join rather than inner is a deliberate semantic choice here. If a pipeline account doesn't appear in the CLV table (perhaps it's a new logo with no historical finance data), you still want it in your Gold scorecard — it just won't have CLV metrics populated. An inner join would silently drop new accounts from the output, which would look like a data quality problem in the Gold report.

Now build the final derived columns for the scorecard:

from pyspark.sql.functions import (
    when, col, datediff, current_date, round as spark_round,
    coalesce, lit, current_timestamp
)

df_scorecard = (
    df_joined
    .withColumn(
        "days_since_last_activity",
        datediff(current_date(), col("last_activity_date"))
    )
    .withColumn(
        "days_to_renewal",
        datediff(col("contract_renewal_date"), current_date())
    )
    .withColumn(
        "account_health_score",
        when(
            (col("churn_risk_score") < 0.3) & (col("days_since_last_activity") < 30),
            lit("Green")
        ).when(
            (col("churn_risk_score") < 0.6) | (col("days_since_last_activity") < 60),
            lit("Yellow")
        ).otherwise(lit("Red"))
    )
    .withColumn(
        "deal_to_clv_ratio",
        spark_round(
            col("deal_value_usd") / coalesce(col("avg_deal_size_usd"), lit(1)),
            3
        )
    )
    .withColumn(
        "effective_customer_segment",
        coalesce(col("customer_segment"), lit("New Logo"))
    )
    .withColumn("scorecard_refreshed_at", current_timestamp())
    .select(
        "account_id",
        "account_name",
        "pipeline_stage",
        "deal_value_usd",
        "total_revenue_usd",
        "avg_deal_size_usd",
        "deal_to_clv_ratio",
        "contract_renewal_date",
        "days_to_renewal",
        "churn_risk_score",
        "account_health_score",
        "effective_customer_segment",
        "assigned_rep_id",
        "days_since_last_activity",
        "scorecard_refreshed_at"
    )
)

# Preview the result before writing
df_scorecard.show(5, truncate=False)
print(f"Total scorecard records: {df_scorecard.count():,}")

Writing Federated Results to the Gold Layer with MERGE Semantics

Writing to the Gold layer is where idempotency matters. If this notebook is scheduled to run every four hours, a simple overwrite would work, but it's destructive — any downstream read happening at the moment of overwrite gets a half-written table. A MERGE (upsert) is safer and more professional.

The Gold table write uses the account_id as the merge key. If a record already exists in the Gold table, update it. If it's new, insert it. We'll also handle deletions — if an account was in yesterday's pipeline but dropped out today (deal closed, lost, or cancelled), we want to remove it rather than leave stale Green scores in the report.

For the merge, we'll use the Delta Lake DeltaTable API:

from delta.tables import DeltaTable
from pyspark.sql.utils import AnalysisException

def write_gold_scorecard(
    df_new: "DataFrame",
    gold_path: str,
    merge_key: str = "account_id"
) -> None:
    """
    Writes a scorecard DataFrame to the Gold Delta table using MERGE semantics.
    Creates the table if it doesn't exist yet.
    """
    
    # Check if the Gold table already exists
    try:
        gold_table = DeltaTable.forPath(spark, gold_path)
        table_exists = True
    except AnalysisException:
        table_exists = False
    
    if not table_exists:
        # First run — create the table with the full schema
        print(f"Gold table not found at {gold_path}. Creating on first write.")
        (
            df_new.write
            .format("delta")
            .mode("overwrite")
            .option("overwriteSchema", "true")
            .save(gold_path)
        )
        print(f"Gold table created with {df_new.count():,} records.")
        return
    
    # Subsequent runs — use MERGE for idempotent upserts
    print("Gold table exists. Performing MERGE operation.")
    
    (
        gold_table.alias("existing")
        .merge(
            df_new.alias("incoming"),
            f"existing.{merge_key} = incoming.{merge_key}"
        )
        .whenMatchedUpdateAll()
        .whenNotMatchedInsertAll()
        # Optionally delete records that are no longer in the source
        # Uncomment the line below if stale record removal is desired:
        # .whenNotMatchedBySourceDelete()
        .execute()
    )
    
    # Report merge statistics using Delta history
    history_df = gold_table.history(1)
    op_metrics = history_df.select("operationMetrics").collect()[0][0]
    
    print(f"MERGE complete:")
    print(f"  Rows inserted: {op_metrics.get('numTargetRowsInserted', 'N/A')}")
    print(f"  Rows updated:  {op_metrics.get('numTargetRowsUpdated', 'N/A')}")
    print(f"  Rows deleted:  {op_metrics.get('numTargetRowsDeleted', 'N/A')}")


# Execute the write
write_gold_scorecard(
    df_new=df_scorecard,
    gold_path=gold_output_path,
    merge_key="account_id"
)

One critical detail in the write function: the first-run path uses overwriteSchema: true. This handles the case where you've evolved the scorecard schema since the Gold table was last created — perhaps you added the days_to_renewal column in a hotfix. Without overwriteSchema, a schema mismatch on the first write to a new environment would throw an AnalysisException. On subsequent runs, the MERGE handles schema changes differently (Delta's whenMatchedUpdateAll will only update columns that exist in both source and target), so for schema evolution in an existing Gold table, refer to the patterns in Handling Schema Evolution in Fabric Lakehouse Delta Tables: Adding Columns, Merging Incompatible Schemas, and Enforcing Constraints Across Medallion Layers.

Warning

The .whenNotMatchedBySourceDelete() clause (commented out above) is powerful but dangerous for Gold tables that feed Power BI Direct Lake models. Deleting rows from a Gold table forces a Delta log entry that invalidates the Direct Lake framing cache, potentially causing a full table scan on the next report query. If you have high-frequency deletes, consider a soft-delete pattern using an is_active boolean flag instead, and filter that flag in your semantic model measures.


Putting It All Together: The Complete Notebook Structure

Production notebooks benefit from being structured as a series of clearly demarcated cells with explicit logging. Here's the complete orchestration layer that ties everything together and produces structured output suitable for consumption by a downstream pipeline:

# Cell 1: Imports and Configuration
import sempy.fabric as fabric
from sempy.fabric import FabricRestClient
from delta.tables import DeltaTable
from pyspark.sql import functions as F
from pyspark.sql.functions import broadcast, current_timestamp
from pyspark.sql.utils import AnalysisException
import json
from datetime import datetime

# Notebook parameters (can be overridden by pipeline)
SALES_WORKSPACE = "Sales-Prod"
SALES_LAKEHOUSE = "SalesLakehouse"
SALES_TABLE = "silver_sales_pipeline_stages"

FINANCE_WORKSPACE = "Finance-Prod"
FINANCE_LAKEHOUSE = "FinanceLakehouse"
FINANCE_TABLE = "silver_customer_lifetime_value"

GOLD_WORKSPACE = "Enterprise-Gold"
GOLD_LAKEHOUSE = "GoldLakehouse"
GOLD_TABLE = "gold_account_health_scorecard"

ACTIVITY_LOOKBACK_DAYS = 90

notebook_start = datetime.now()
print(f"Notebook started at: {notebook_start.isoformat()}")
# Cell 2: Access Verification
for ws_name in [SALES_WORKSPACE, FINANCE_WORKSPACE, GOLD_WORKSPACE]:
    result = verify_workspace_access(ws_name)
    status = "✓" if result["accessible"] else "✗"
    print(f"  {status} {ws_name}: {result['message']}")
    if not result["accessible"]:
        raise PermissionError(f"Cannot proceed: no access to {ws_name}")
# Cell 3: Path Resolution
sales_path = resolve_lakehouse_abfs_path(SALES_WORKSPACE, SALES_LAKEHOUSE, SALES_TABLE)
finance_path = resolve_lakehouse_abfs_path(FINANCE_WORKSPACE, FINANCE_LAKEHOUSE, FINANCE_TABLE)
gold_path = resolve_lakehouse_abfs_path(GOLD_WORKSPACE, GOLD_LAKEHOUSE, GOLD_TABLE)
print("All paths resolved successfully.")
# Cell 4: Data Loading
df_pipeline = spark.read.format("delta").load(sales_path).filter(...)
df_clv = spark.read.format("delta").load(finance_path).filter(...)
df_pipeline.cache()
df_clv.cache()
# Cell 5: Join and Transformation
df_scorecard = (
    df_pipeline
    .join(broadcast(df_clv), on="account_id", how="left")
    # ... transformations ...
)
# Cell 6: Write and Report
write_gold_scorecard(df_scorecard, gold_path)

notebook_end = datetime.now()
duration_seconds = (notebook_end - notebook_start).total_seconds()

# Structured output for pipeline consumption
result_summary = {
    "status": "success",
    "gold_table": f"{GOLD_WORKSPACE}/{GOLD_LAKEHOUSE}/{GOLD_TABLE}",
    "records_written": df_scorecard.count(),
    "duration_seconds": round(duration_seconds, 1),
    "completed_at": notebook_end.isoformat()
}

# mssparkutils.notebook.exit() sends this as the pipeline output variable
mssparkutils.notebook.exit(json.dumps(result_summary))

The final mssparkutils.notebook.exit() call is what allows this notebook to be chained into a larger orchestration pattern. If you're incorporating this into a multi-stage pipeline — for example, running this Gold federation after upstream Silver refreshes complete — the pipeline can read the exit value and validate that the scorecard was written successfully before proceeding. This pattern is covered in depth in Orchestrating Multi-Notebook Workflows in Microsoft Fabric: Using Pipeline Notebook Activities, Activity Dependencies, and Output Variables to Chain PySpark Transformations Across Medallion Layers.


Performance Considerations for Cross-Workspace Reads

Reading across workspace boundaries carries additional latency compared to reading from your notebook's attached lakehouse. The ABFS request traverses Fabric's internal routing layer, and while this is fast (typically milliseconds per request), it compounds over many small reads. Delta table reads issue many small metadata requests (reading _delta_log JSON files) followed by larger Parquet reads. Here's what to optimize:

Predicate pushdown: Always apply filters before .cache() and before the join. Spark can push filter predicates into the Delta log scan, meaning it only reads the Parquet files that could contain matching rows. If your pipeline table is partitioned by stage_entered_date, filtering on that column will dramatically reduce the number of files Spark needs to request from the remote workspace.

Delta log size: If your source tables have been running without OPTIMIZE and VACUUM, the Delta log can contain thousands of small JSON transaction files. Each log file is a separate ABFS request. For cross-workspace reads, this overhead is amplified. If you own the source tables, ensure they're regularly optimized — see Optimizing Delta Table Performance in a Fabric Lakehouse: V-Order, OPTIMIZE, VACUUM, and Z-Order for Faster Queries and Smaller Storage for the specifics. If you don't own the source tables, consider using a shortcut in your Gold workspace to alias the source tables — shortcuts materialize locally without copying data and can reduce remote log traversal overhead in some scenarios.

Executor count: Cross-workspace reads don't benefit from large executor counts the way local shuffle operations do. The ABFS read throughput is bounded by OneLake's per-request bandwidth, not by the number of Spark executors. For small-to-medium datasets (under a few hundred GB), a standard Fabric Spark cluster with 8–16 vCores is sufficient. Scaling up to a very large cluster won't linearly accelerate cross-workspace I/O.

Tip

If the same cross-workspace source tables are read by multiple downstream notebooks (e.g., both a scorecard notebook and a commission calculation notebook read silver_sales_pipeline_stages), consider whether a single "federation hub" notebook that materializes both sources as local Delta tables in the Gold workspace makes more sense. Each downstream notebook then reads locally, and the cross-workspace reads happen exactly once per refresh cycle.


Hands-On Exercise

Apply what you've learned by building a cross-workspace customer support health dashboard:

Setup: Create three workspaces in your Fabric capacity:

  • Support-Silver with a lakehouse containing a silver_support_tickets table (columns: customer_id, ticket_id, severity, opened_date, resolved_date, satisfaction_score)
  • Product-Silver with a lakehouse containing a silver_product_usage table (columns: customer_id, feature_name, usage_events_30d, last_used_date)
  • CX-Gold with an empty lakehouse called CXGoldLakehouse

You can generate synthetic data for both silver tables using spark.createDataFrame() with a list of Python dicts, or use Fabric's sample data generation in a Dataflow Gen2.

Your task:

  1. Write a resolve_lakehouse_abfs_path() function and verify access to all three workspaces before reading any data

  2. Load silver_support_tickets and silver_product_usage, filtering to customers with at least one ticket opened in the last 60 days

  3. Join the two DataFrames on customer_id using an appropriate broadcast strategy based on relative DataFrame sizes

  4. Compute three derived columns:

    • avg_resolution_days: average days from opened_date to resolved_date
    • engagement_tier: "High" if usage_events_30d > 100, "Medium" if > 20, else "Low"
    • cx_risk_flag: True if avg_resolution_days > 5 AND satisfaction_score < 3.5
  5. Write the result to gold_cx_support_health in CXGoldLakehouse using MERGE semantics with customer_id as the merge key

  6. Run the notebook twice. On the second run, modify a filter to include slightly different records. Verify via DeltaTable.history() that the second run shows MERGE operation metrics with both inserts and updates

Stretch goal: Wrap the notebook in a Fabric Data Pipeline with a Notebook Activity, and configure the pipeline to send an email alert if mssparkutils.notebook.exit() returns a payload where records_written is less than 100 (use an If Condition activity with the pipeline expression @less(int(activity('RunScorecardNotebook').output.exitValue.records_written), 100)).


Common Mistakes & Troubleshooting

"Workspace not found" despite having access

The FabricRestClient.get("/v1/workspaces") endpoint only returns workspaces where your identity has an explicit Fabric role assignment. If you were granted access via an Entra ID group and that group wasn't directly added as a workspace role (only you individually were added to the group, and the group was added to something else), the workspace may not appear. Solution: verify the workspace role assignment directly in the Fabric workspace settings — your user or service principal should appear explicitly in the Members list.

403 AuthorizationFailed on ABFS read despite visible workspace

Being able to list a workspace via the REST API doesn't guarantee storage read access. The minimum Fabric workspace role for ABFS reads is Viewer. Having the workspace appear in /v1/workspaces only means your identity has at least some API-level visibility. Check the workspace's Members section and confirm your identity (or the pipeline service principal) has Viewer or higher. For pipeline runs, also check that the workspace role is assigned to the service principal's object ID, not just its application ID.

Delta log AnalysisException: Path does not exist

This almost always means the table_name argument you passed to resolve_lakehouse_abfs_path() doesn't match an actual managed table name. Delta tables in a lakehouse's managed /Tables/ directory are case-sensitive at the ABFS path level, even though the SQL Analytics Endpoint normalizes casing. silver_Sales_Pipeline_Stages and silver_sales_pipeline_stages are different paths. Query the lakehouse's table list via the REST API to get the exact name: client.get(f"/v1/workspaces/{workspace_id}/lakehouses/{lakehouse_id}/tables").

Token expiry during long-running joins

If your cross-workspace join involves very large DataFrames and runs for more than 45–60 minutes, you may hit ABFS token expiry. The symptom is an error like AuthenticationFailed: Server failed to authenticate the request mid-job. The mitigation: .cache() both source DataFrames with an explicit .count() action immediately after loading, before the join. This forces full materialization while tokens are fresh. All subsequent Spark actions work from the in-memory cache, not from the remote ABFS paths.

MERGE fails with AnalysisException: DELTA_MERGE_MISSING_WHEN

Delta Lake requires at least one whenMatched or whenNotMatched clause. If you accidentally call .execute() on a .merge() builder without chaining at least one action clause, you'll see this error. Always include at minimum .whenMatchedUpdateAll().whenNotMatchedInsertAll().

Gold table write succeeds but table is invisible in Fabric's lakehouse explorer

When you write a Delta table to a Gold lakehouse via an ABFS path in a different notebook's session (i.e., the notebook is attached to a different default lakehouse), the table won't automatically register in the Gold lakehouse's catalog. You can manually trigger catalog synchronization via the REST API: client.post(f"/v1/workspaces/{gold_workspace_id}/lakehouses/{gold_lakehouse_id}/tables/loadTable", json={"relativePath": "Tables/gold_account_health_scorecard", "pathType": "File", "mode": "Overwrite"}). Alternatively, switch the notebook's default lakehouse to the Gold lakehouse and use spark.catalog.refreshTable().

Note

When this Gold table is used as the source for a Direct Lake semantic model, the Power BI dataset framing will pick up the new Delta log state automatically on the next report query or scheduled refresh. You don't need to manually refresh the semantic model just because the underlying Delta table changed — that's the core value of Direct Lake Mode.


Summary & Next Steps

You've now implemented a complete cross-lakehouse federation pattern that handles the full lifecycle: programmatic OneLake path resolution via the Fabric REST API and Semantic Link, permission verification before expensive Spark operations, optimized broadcast joins across workspace-boundary DataFrames, and idempotent MERGE writes to a Gold layer Delta table with operational metrics.

The architectural pattern you've built here is genuinely reusable. The resolve_lakehouse_abfs_path() and verify_workspace_access() functions are utility code that belongs in a shared notebook or a Fabric custom library package — not duplicated across every Gold layer notebook. As your Fabric estate grows and more domain teams own their own Silver lakehouses, this pattern scales: add a new source workspace to the resolver calls, and your federation logic handles the rest without structural changes.

To deepen your production readiness from here, the natural next steps are:

  • Incremental loading: Rather than re-reading all active pipeline records every run, implement a watermark pattern against last_activity_date to only process records changed since the last run. See Incrementally Loading Data into a Fabric Lakehouse with Watermarks and Pipeline Lookup Activities for the pipeline-side of that pattern.

  • Write patterns: The MERGE pattern here covers upserts, but as your Gold table's requirements grow, you'll want the full taxonomy of append, overwrite, and MERGE behaviors — covered in Writing Data from a Spark Notebook to a Fabric Lakehouse Delta Table: Append, Overwrite, and Merge Patterns with PySpark.

  • Star schema design: Once your Gold tables are reliable, structuring them as proper dimension and fact tables unlocks the full performance potential of Direct Lake reporting. See Building a Star Schema in a Fabric Lakehouse Gold Layer: Creating Dimension and Fact Delta Tables with PySpark for Direct Lake Reporting for the design and implementation details.

The pattern you've built today is the connective tissue of a mature Fabric data platform — the layer that takes domain-owned data and assembles it into enterprise-grade analytical products without duplicating data or sacrificing governance.

Work With Us

From insight to implementation

Reading is the start. When you're ready to build the data, automation, or AI systems behind it, our team turns strategy into shipped results.

Let's Build

Microsoft Fabric Fundamentals

Previous

Implementing Fabric Lakehouse Table Maintenance Automation: Scheduling OPTIMIZE, VACUUM, and V-Order Enforcement Across Multiple Delta Tables Using a PySpark Notebook and Pipeline

Related Insights

Microsoft FabricPractitioner

Implementing Fabric Lakehouse Table Maintenance Automation: Scheduling OPTIMIZE, VACUUM, and V-Order Enforcement Across Multiple Delta Tables Using a PySpark Notebook and Pipeline

24 min
Microsoft FabricFoundation

Creating and Sharing Fabric Reports in Power BI Service: Publishing a Direct Lake Semantic Model, Building a Report, and Distributing It to Workspace Colleagues

18 min
Microsoft FabricExpert

Implementing Change Data Capture in a Fabric Data Pipeline: Using Lookup, GetMetadata, and Delta Lake MERGE to Detect and Apply Source Changes Without Full Reloads

28 min

On this page

  • Introduction
  • Prerequisites
  • Understanding the OneLake Path Architecture
  • Setting Up Semantic Link for Metadata Resolution
  • Understanding Workspace Tokens and Cross-Workspace Authorization
  • Resolving Paths and Reading Source Delta Tables
  • Performing the Cross-Lakehouse Join with Broadcast Awareness
  • Writing Federated Results to the Gold Layer with MERGE Semantics
  • Putting It All Together: The Complete Notebook Structure
  • Performance Considerations for Cross-Workspace Reads
  • Hands-On Exercise
  • Common Mistakes & Troubleshooting
  • Summary & Next Steps