Delta table maintenance isn't a one-time task — it's an ongoing operational concern. This lesson walks you through building a self-discovering PySpark notebook that runs OPTIMIZE, VACUUM, and V-Order enforcement across all Delta tables in a Fabric lakehouse, wired to a scheduled pipeline with failure alerting and a queryable audit log.

Here's a scenario that plays out in real production Fabric environments with uncomfortable regularity: your lakehouse was fast when you built it. Queries against your gold-layer fact tables returned in seconds, Direct Lake reports loaded instantly, and everyone was happy. Three months later, the same tables have absorbed thousands of incremental loads, schema evolution events, and the occasional bad-merge-followed-by-rollback. Now your OPTIMIZE runs take twice as long as they used to, your storage bill quietly crept up 40%, and that Direct Lake report that used to snap open is now taking long enough for people to notice.
The root cause is almost always the same: Delta table maintenance was treated as a one-time setup task instead of an ongoing operational concern. OPTIMIZE compacts small files into large, efficiently-scanned ones. VACUUM removes the stale Parquet files that Delta's time-travel capability accumulates over time. V-Order encoding rewrites data in a way that Microsoft's Verti-Scan engine can read dramatically faster — and it must be explicitly enforced after certain write patterns. Left unattended, any one of these degrades. Left unattended together, they compound.
By the end of this lesson, you'll have a production-ready maintenance system: a single parameterized PySpark notebook that discovers and maintains all Delta tables in a lakehouse, combined with a Fabric Data Pipeline that schedules it on a cadence, passes runtime configuration, and handles failures gracefully. You'll understand not just the mechanics, but why each maintenance operation matters and how to tune it for your specific workload patterns.
What you'll learn:
Before working through this lesson, you should be comfortable with:
You'll need a Fabric workspace with Contributor access and at least one lakehouse containing multiple Delta tables to maintain. A multi-layer medallion lakehouse works best for demonstrating the value of this approach.
Before writing a single line of code, it's worth being precise about what each operation does and what happens when you skip it — because that understanding drives the scheduling decisions you'll make.
When Spark writes data to a Delta table, it creates Parquet files sized according to the number of partitions in the DataFrame and the volume of data being written. A single incremental load that appends 50,000 rows might create 8 small files instead of one well-sized one. Multiply that by hundreds of daily loads across a medallion architecture and you end up with tens of thousands of files where a few hundred would do. The query engine has to open, read metadata from, and filter each file individually — small-file problems are I/O problems.
OPTIMIZE compacts those files, targeting 128MB per output file by default in Delta Lake. Crucially, OPTIMIZE in Fabric also re-applies V-Order encoding during the compaction process (when V-Order is enabled), so the two operations are closely linked.
Delta's time travel capability works by retaining old Parquet files that have been logically deleted or replaced. VACUUM removes files older than a configurable retention threshold (default 7 days). Without regular VACUUM runs, your OneLake storage grows indefinitely even when the logical table size is stable. For high-velocity tables that receive frequent MERGE operations — like a slowly changing dimension being updated daily — un-vacuumed storage can easily become 5-10x the actual logical table size.
Warning
Never set your VACUUM retention period below 7 days (168 hours) unless you have explicitly disabled the retention duration check and have a very specific reason. Delta Lake's default safety check prevents this, and for good reason: if any active query or Direct Lake framing is reading old table versions, VACUUM can delete files that are still in use.
V-Order is a Fabric-specific write-time optimization that sorts, encodes, and compresses Parquet data in a way that Microsoft's Verti-Scan engine reads significantly faster — sometimes 10-15x faster for Direct Lake scenarios. The critical thing to understand is that V-Order is applied at write time. If a table was written without V-Order (for example, by an external process, an older notebook, or a Delta Lake client that doesn't support V-Order), those files don't have V-Order encoding.
Running OPTIMIZE with V-Order enabled rewrites the files and applies the encoding. This is why you can't just "turn on V-Order" for an existing table and walk away — you need to trigger a compaction to actually re-encode the data.
Key insight
V-Order is not a table property you configure once and forget. It's an encoding applied to individual Parquet files at write time. Tables that receive writes from multiple sources — a Fabric notebook plus a mirrored database plus a Dataflow — may have files with inconsistent V-Order encoding. Regular OPTIMIZE runs with V-Order enabled are your enforcement mechanism.
The core design principle of your maintenance notebook will be a configuration-driven approach where different tables can have different maintenance profiles:
| Profile | OPTIMIZE Frequency | VACUUM Frequency | Z-Order Columns | Typical Table Type |
|---|---|---|---|---|
hot |
Daily | Weekly | Yes | High-velocity fact tables |
warm |
Weekly | Weekly | Optional | Silver-layer staging tables |
cold |
Monthly | Monthly | No | Slowly changing reference data |
critical |
Daily | Daily | Yes | Gold-layer aggregates serving Direct Lake |
You'll store this configuration as a JSON structure passed in as a pipeline parameter, which lets you change maintenance schedules without touching notebook code.
The notebook will follow a clear flow with four distinct phases:
This design is intentional. The alternative — hardcoding a list of tables — requires updating the notebook every time you add a new table to the lakehouse. A self-discovering approach means your maintenance coverage automatically expands as your data platform grows.
In Fabric notebooks, parameter cells use a special toggle that makes them overridable by pipeline activities. Create a new cell, write your defaults, and then toggle it as a parameter cell using the "..." menu on the cell and selecting "Toggle parameter cell."
# Parameters cell - toggle this as a parameter cell in the Fabric UI
# These defaults are used for interactive testing; the pipeline overrides them at runtime.
LAKEHOUSE_NAME = "sales_analytics_lakehouse"
WORKSPACE_ID = "" # Leave blank to use the current workspace
MAINTENANCE_MODE = "daily" # Options: daily, weekly, monthly, full
VACUUM_RETAIN_HOURS = 168 # 7 days - never go below this without careful thought
ENABLE_VORDER = True
DRY_RUN = False # Set True to log what would happen without actually running maintenance
ZORDER_CONFIG = '{"sales_fact": "order_date,customer_id", "product_dim": "product_category"}'
Tip
Setting DRY_RUN = True during development is invaluable. It lets you run the full notebook against production tables, see exactly which OPTIMIZE and VACUUM commands would fire, and verify your table discovery logic — without touching any data.
import json
import datetime
from pyspark.sql import functions as F
from pyspark.sql.types import StructType, StructField, StringType, TimestampType, BooleanType, LongType
from delta.tables import DeltaTable
# Parse Z-Order configuration from JSON string
# Format: {"table_name": "col1,col2", "another_table": "col1"}
try:
zorder_map = json.loads(ZORDER_CONFIG)
except (json.JSONDecodeError, TypeError):
print("Warning: ZORDER_CONFIG could not be parsed. Z-Order will be skipped for all tables.")
zorder_map = {}
# Map maintenance modes to which operations to perform
# This lets a single notebook serve daily, weekly, and monthly schedules
# by just changing the MAINTENANCE_MODE parameter
mode_config = {
"daily": {
"run_optimize": True,
"run_vacuum": False, # Vacuum is expensive; run it less often
"enforce_vorder": True,
},
"weekly": {
"run_optimize": True,
"run_vacuum": True,
"enforce_vorder": True,
},
"monthly": {
"run_optimize": True,
"run_vacuum": True,
"enforce_vorder": True,
},
"full": {
"run_optimize": True,
"run_vacuum": True,
"enforce_vorder": True,
},
}
current_mode = mode_config.get(MAINTENANCE_MODE, mode_config["weekly"])
run_timestamp = datetime.datetime.utcnow()
print(f"Maintenance run starting at: {run_timestamp.isoformat()}")
print(f"Mode: {MAINTENANCE_MODE}")
print(f"Config: {json.dumps(current_mode, indent=2)}")
print(f"Dry run: {DRY_RUN}")
This is the self-discovering piece that makes the notebook maintenance-free as your lakehouse grows. We use spark.catalog.listTables() to enumerate registered tables, then verify each one is actually a Delta table before processing it.
def get_delta_tables(lakehouse_name: str) -> list[dict]:
"""
Discover all Delta tables in the target lakehouse.
Returns a list of dicts with table metadata.
"""
discovered_tables = []
# List all tables registered in the lakehouse
# In Fabric, the lakehouse name maps to a database/catalog namespace
try:
tables_df = spark.sql(f"SHOW TABLES IN {lakehouse_name}")
raw_tables = [(row.tableName, row.database) for row in tables_df.collect()]
except Exception as e:
# Fallback: list tables in the currently attached lakehouse
print(f"Could not list tables for {lakehouse_name}, using default attached lakehouse: {e}")
tables_df = spark.sql("SHOW TABLES")
raw_tables = [(row.tableName, row.database) for row in tables_df.collect()]
for table_name, database in raw_tables:
full_table_name = f"{database}.{table_name}" if database else table_name
# Verify it's a Delta table before attempting Delta operations
try:
detail = spark.sql(f"DESCRIBE DETAIL {full_table_name}").collect()[0]
if detail.format.lower() == "delta":
table_location = detail.location
num_files = detail.numFiles
size_bytes = detail.sizeInBytes
discovered_tables.append({
"table_name": table_name,
"full_table_name": full_table_name,
"location": table_location,
"num_files": num_files,
"size_bytes": size_bytes,
"size_gb": round(size_bytes / (1024**3), 3) if size_bytes else 0,
"zorder_columns": zorder_map.get(table_name, None),
})
print(f" ✓ {full_table_name} — {num_files} files, {round(size_bytes/(1024**3), 3)} GB")
else:
print(f" ✗ Skipping {full_table_name} — format is {detail.format}, not Delta")
except Exception as e:
print(f" ✗ Could not inspect {full_table_name}: {e}")
print(f"\nDiscovered {len(discovered_tables)} Delta tables for maintenance.")
return discovered_tables
delta_tables = get_delta_tables(LAKEHOUSE_NAME)
This function handles OPTIMIZE, V-Order enforcement, and VACUUM for a single table. By encapsulating it in a function, you can call it in a loop, catch per-table errors without killing the entire run, and test it against one table interactively.
def maintain_table(table_info: dict, mode_cfg: dict, dry_run: bool = False) -> dict:
"""
Run maintenance operations against a single Delta table.
Returns a dict describing what was done (or would be done in dry_run mode).
"""
table_name = table_info["full_table_name"]
short_name = table_info["table_name"]
zorder_cols = table_info.get("zorder_columns")
result = {
"table_name": short_name,
"full_table_name": table_name,
"run_timestamp": run_timestamp,
"maintenance_mode": MAINTENANCE_MODE,
"dry_run": dry_run,
"optimize_ran": False,
"optimize_files_added": 0,
"optimize_files_removed": 0,
"vacuum_ran": False,
"vacuum_files_deleted": 0,
"vorder_enforced": False,
"zorder_applied": False,
"zorder_columns": zorder_cols or "",
"error_message": "",
"success": True,
}
print(f"\n{'='*60}")
print(f"Processing: {table_name}")
print(f" Files: {table_info['num_files']} | Size: {table_info['size_gb']} GB")
if zorder_cols:
print(f" Z-Order columns: {zorder_cols}")
# --- OPTIMIZE + V-Order ---
if mode_cfg["run_optimize"]:
try:
# Build the OPTIMIZE statement
# V-Order is controlled by a Spark session config, not SQL syntax
# Setting it here ensures it applies to the OPTIMIZE rewrite
if mode_cfg["enforce_vorder"] and ENABLE_VORDER:
spark.conf.set("spark.sql.parquet.vorder.enabled", "true")
result["vorder_enforced"] = True
print(f" V-Order: enabled for OPTIMIZE rewrite")
else:
spark.conf.set("spark.sql.parquet.vorder.enabled", "false")
print(f" V-Order: disabled")
# Construct OPTIMIZE with optional Z-Order
if zorder_cols:
optimize_sql = f"OPTIMIZE {table_name} ZORDER BY ({zorder_cols})"
result["zorder_applied"] = True
else:
optimize_sql = f"OPTIMIZE {table_name}"
print(f" SQL: {optimize_sql}")
if not dry_run:
opt_result = spark.sql(optimize_sql)
opt_metrics = opt_result.collect()[0]
# Extract metrics from the OPTIMIZE result
# The result schema includes metrics.numFilesAdded and numFilesRemoved
try:
result["optimize_files_added"] = opt_metrics["metrics"]["numFilesAdded"]
result["optimize_files_removed"] = opt_metrics["metrics"]["numFilesRemoved"]
print(f" OPTIMIZE complete: +{result['optimize_files_added']} files, -{result['optimize_files_removed']} files removed")
except (KeyError, TypeError):
# Metrics structure may vary; log what we can
print(f" OPTIMIZE complete (metrics unavailable)")
else:
print(f" [DRY RUN] OPTIMIZE would run: {optimize_sql}")
result["optimize_ran"] = True
except Exception as e:
result["error_message"] = f"OPTIMIZE failed: {str(e)}"
result["success"] = False
print(f" ERROR in OPTIMIZE: {e}")
# --- VACUUM ---
if mode_cfg["run_vacuum"] and result["success"]:
try:
vacuum_sql = f"VACUUM {table_name} RETAIN {VACUUM_RETAIN_HOURS} HOURS"
print(f" SQL: {vacuum_sql}")
if not dry_run:
# DeltaTable API gives us better control and metrics for VACUUM
delta_table = DeltaTable.forName(spark, table_name)
delta_table.vacuum(retentionHours=VACUUM_RETAIN_HOURS)
result["vacuum_ran"] = True
print(f" VACUUM complete (retained {VACUUM_RETAIN_HOURS}h / {VACUUM_RETAIN_HOURS//24} days)")
else:
print(f" [DRY RUN] VACUUM would run with {VACUUM_RETAIN_HOURS}h retention")
result["vacuum_ran"] = True
except Exception as e:
result["error_message"] += f" VACUUM failed: {str(e)}"
result["success"] = False
print(f" ERROR in VACUUM: {e}")
return result
Note
You'll notice VACUUM uses the DeltaTable.forName() API rather than raw SQL. Both approaches work, but the Python API gives you a slightly cleaner interface for programmatic use and doesn't require manually suppressing Delta's "Are you sure?" safety prompt that you'd need to handle in SQL (SET spark.databricks.delta.retentionDurationCheck.enabled = false).
maintenance_results = []
failed_tables = []
for table_info in delta_tables:
try:
result = maintain_table(
table_info=table_info,
mode_cfg=current_mode,
dry_run=DRY_RUN
)
maintenance_results.append(result)
if not result["success"]:
failed_tables.append(result["table_name"])
except Exception as e:
# Catch truly unexpected errors that escaped the function's own error handling
error_result = {
"table_name": table_info["table_name"],
"full_table_name": table_info["full_table_name"],
"run_timestamp": run_timestamp,
"maintenance_mode": MAINTENANCE_MODE,
"dry_run": DRY_RUN,
"optimize_ran": False,
"optimize_files_added": 0,
"optimize_files_removed": 0,
"vacuum_ran": False,
"vacuum_files_deleted": 0,
"vorder_enforced": False,
"zorder_applied": False,
"zorder_columns": "",
"error_message": f"Unhandled exception: {str(e)}",
"success": False,
}
maintenance_results.append(error_result)
failed_tables.append(table_info["table_name"])
print(f"\nUnhandled error for {table_info['table_name']}: {e}")
print(f"\n{'='*60}")
print(f"Maintenance run complete.")
print(f" Total tables processed: {len(maintenance_results)}")
print(f" Successful: {len(maintenance_results) - len(failed_tables)}")
print(f" Failed: {len(failed_tables)}")
if failed_tables:
print(f" Failed tables: {', '.join(failed_tables)}")
The audit log is itself a Delta table in your lakehouse. This gives you a queryable history of every maintenance run — which tables were processed, how many files were compacted or removed, and whether anything failed. It's also the data source for a simple Power BI report if you want visibility into your maintenance health over time.
def write_maintenance_log(results: list[dict], lakehouse_name: str):
"""
Write maintenance run results to the audit log Delta table.
Appends to existing history; creates the table on first run.
"""
if not results:
print("No results to log.")
return
# Convert results to Spark DataFrame
# Using explicit schema to ensure consistent types on first run
schema = StructType([
StructField("table_name", StringType(), True),
StructField("full_table_name", StringType(), True),
StructField("run_timestamp", TimestampType(), True),
StructField("maintenance_mode", StringType(), True),
StructField("dry_run", BooleanType(), True),
StructField("optimize_ran", BooleanType(), True),
StructField("optimize_files_added", LongType(), True),
StructField("optimize_files_removed", LongType(), True),
StructField("vacuum_ran", BooleanType(), True),
StructField("vacuum_files_deleted", LongType(), True),
StructField("vorder_enforced", BooleanType(), True),
StructField("zorder_applied", BooleanType(), True),
StructField("zorder_columns", StringType(), True),
StructField("error_message", StringType(), True),
StructField("success", BooleanType(), True),
])
# Cast run_timestamp to proper timestamp type
for r in results:
if isinstance(r["run_timestamp"], datetime.datetime):
r["run_timestamp"] = r["run_timestamp"]
results_df = spark.createDataFrame(results, schema=schema)
log_table = f"{lakehouse_name}.maintenance_log"
results_df.write \
.format("delta") \
.mode("append") \
.option("mergeSchema", "true") \
.saveAsTable(log_table)
print(f"Maintenance log written to: {log_table}")
print(f" Rows written: {results_df.count()}")
if not DRY_RUN:
write_maintenance_log(maintenance_results, LAKEHOUSE_NAME)
else:
print("[DRY RUN] Maintenance log write skipped.")
This final cell is crucial for pipeline integration. By using mssparkutils.notebook.exit(), you signal back to the calling pipeline whether the run succeeded or had failures. The pipeline can then route to a failure notification activity if success is false.
import json
exit_payload = {
"success": len(failed_tables) == 0,
"tables_processed": len(maintenance_results),
"tables_failed": len(failed_tables),
"failed_table_names": failed_tables,
"run_timestamp": run_timestamp.isoformat(),
"maintenance_mode": MAINTENANCE_MODE,
"dry_run": DRY_RUN,
}
exit_message = json.dumps(exit_payload)
print(f"\nNotebook exit payload: {exit_message}")
# This signals the result back to the calling pipeline
mssparkutils.notebook.exit(exit_message)
With the notebook built, you need a Fabric Data Pipeline that schedules it, passes the right parameters for each maintenance mode, and handles failures. The pipeline will have four activities: a Notebook activity, a conditional check on the notebook's output, an email notification on failure, and a final log activity.
In your Fabric workspace, create a new Data Pipeline. Name it something clear like pl_lakehouse_maintenance. You'll add the following activities:
Activity 1: Run Maintenance Notebook
Add a Notebook activity. In the Settings tab, select your maintenance notebook. In the Base Parameters section, add these parameters:
| Parameter Name | Type | Value |
|---|---|---|
LAKEHOUSE_NAME |
String | sales_analytics_lakehouse |
MAINTENANCE_MODE |
String | @pipeline().parameters.MaintenanceMode |
VACUUM_RETAIN_HOURS |
Int | 168 |
ENABLE_VORDER |
Bool | true |
DRY_RUN |
Bool | false |
ZORDER_CONFIG |
String | @pipeline().parameters.ZOrderConfig |
Notice that MAINTENANCE_MODE and ZORDER_CONFIG reference pipeline-level parameters. This is what allows you to call the same pipeline from multiple triggers with different configurations — a daily trigger passes "daily", a weekly trigger passes "weekly". You set up the pipeline parameters by clicking the canvas background and going to Parameters in the properties panel.
Tip
Store your Z-Order configuration JSON in a pipeline parameter with a default value. This way you can override it for a specific run from the UI without touching either the notebook or the pipeline definition. It's a simple but effective way to give yourself operational flexibility.
Activity 2: Evaluate Notebook Output
Add an If Condition activity connected to the Notebook activity's Success output. In the Expression field, use:
@equals(json(activity('Run Maintenance Notebook').output.result.exitValue).success, true)
This parses the JSON payload your notebook wrote via mssparkutils.notebook.exit() and checks whether the success key is true.
In the False branch of the If Condition, add an Office 365 Outlook (or Teams) activity that sends a notification with failure details. The message body can include dynamic content like:
Lakehouse maintenance run FAILED at @{utcNow()}.
Failed tables: @{json(activity('Run Maintenance Notebook').output.result.exitValue).failed_table_names}
Mode: @{pipeline().parameters.MaintenanceMode}
Please check the maintenance_log table in the lakehouse for details.
For a deeper look at this error handling pattern, Implementing End-to-End Pipeline Error Handling in Microsoft Fabric covers it thoroughly.
The power of the parametric approach is that you create multiple triggers for the same pipeline:
Daily trigger (runs every morning at 02:00):
MaintenanceMode: dailyZOrderConfig: your JSON configWeekly trigger (runs every Sunday at 01:00):
MaintenanceMode: weeklyZOrderConfig: your JSON configYou can set these up in the Manage tab of the pipeline by clicking "New schedule trigger." For production environments where you want to track trigger history and get alerts, Scheduling and Automating Fabric Data Pipeline Runs with Activity-Level Retries, Alerts, and Email Notifications covers the full scheduling and alerting setup.
Note
Schedule maintenance runs during low-usage windows. OPTIMIZE is a resource-intensive operation — it reads every file in a table and writes new compacted files. On a large fact table, it can consume significant Fabric capacity units. Running at 02:00 AM when reporting workloads are idle avoids contention and keeps your capacity utilization predictable. You can monitor this in the Fabric Monitoring Hub.
Not every table in a production lakehouse is a simple append target. Some tables need nuanced treatment.
If your fact tables are partitioned by date (a common pattern when building a star schema gold layer), OPTIMIZE can be scoped to specific partitions to reduce runtime:
# For partitioned tables, run OPTIMIZE only on recently modified partitions
# This is significantly faster than optimizing the entire table daily
def get_recently_modified_partitions(table_name: str, lookback_days: int = 7) -> list[str]:
"""
Return partition values for partitions written to in the last N days.
Assumes a date partition column named 'event_date' or similar.
"""
cutoff = (datetime.datetime.utcnow() - datetime.timedelta(days=lookback_days)).date()
history_df = spark.sql(f"""
DESCRIBE HISTORY {table_name}
""").filter(
F.col("timestamp") >= F.lit(str(cutoff))
).filter(
F.col("operation").isin(["WRITE", "MERGE", "STREAMING UPDATE"])
)
# Extract partition info from operationParameters if available
# This is a simplified approach; production code may need to parse the JSON
recent_operations = history_df.count()
return recent_operations > 0
# Modified OPTIMIZE for partitioned large tables
def optimize_partitioned_table(table_name: str, partition_col: str, lookback_days: int = 3):
"""
Run OPTIMIZE only on date partitions written in the last N days.
Much faster than whole-table OPTIMIZE for large fact tables.
"""
cutoff_date = (datetime.datetime.utcnow() - datetime.timedelta(days=lookback_days)).strftime('%Y-%m-%d')
optimize_sql = f"""
OPTIMIZE {table_name}
WHERE {partition_col} >= '{cutoff_date}'
"""
print(f" Partition-scoped OPTIMIZE: {partition_col} >= {cutoff_date}")
result = spark.sql(optimize_sql)
return result
If you have workloads that use Delta Lake time travel to query historical snapshots — auditing workflows, for instance — you need to coordinate your VACUUM retention window with those workloads. Never set retention below the furthest back any active query needs to look.
# Tables with active time travel needs should have extended retention
# Configure this in your Z-order/profile config and read it here
TIME_TRAVEL_TABLES = {
"sales_fact_audit": 720, # 30 days retention for audit queries
"customer_dim_history": 2160, # 90 days for compliance
}
def get_vacuum_retention(table_name: str, default_hours: int) -> int:
return TIME_TRAVEL_TABLES.get(table_name, default_hours)
Build a complete maintenance system for a three-table medallion lakehouse.
Setup: If you don't have an existing lakehouse with multiple tables, create one using the patterns from Implementing the Medallion Architecture in Microsoft Fabric. You need at least three Delta tables: a bronze ingestion table, a silver cleansed table, and a gold aggregation table.
Step 1: Simulate the small-file problem by running this cell to append small batches to a table 20 times:
# Generate artificial small-file fragmentation for testing
import random
for i in range(20):
batch_data = [(j, f"product_{random.randint(1, 100)}", random.uniform(10.0, 999.99),
f"2024-{random.randint(1,12):02d}-{random.randint(1,28):02d}")
for j in range(100)]
batch_df = spark.createDataFrame(batch_data, ["order_id", "product_name", "amount", "order_date"])
batch_df.write \
.format("delta") \
.mode("append") \
.saveAsTable("sales_analytics_lakehouse.orders_bronze")
print(f"Batch {i+1}/20 written")
# Check the file count before maintenance
print("\nBefore OPTIMIZE:")
spark.sql("DESCRIBE DETAIL sales_analytics_lakehouse.orders_bronze").select("numFiles", "sizeInBytes").show()
Step 2: Run the full maintenance notebook in DRY_RUN = True mode against your lakehouse. Verify the output shows all three tables discovered and shows the SQL that would run.
Step 3: Set DRY_RUN = False and run again. After completion, check the file count on your orders table:
print("After OPTIMIZE:")
spark.sql("DESCRIBE DETAIL sales_analytics_lakehouse.orders_bronze").select("numFiles", "sizeInBytes").show()
# Verify the maintenance log was written
print("\nMaintenance log entries:")
spark.sql("SELECT table_name, optimize_files_removed, vorder_enforced, success FROM sales_analytics_lakehouse.maintenance_log ORDER BY run_timestamp DESC LIMIT 10").show()
Step 4: Create the pipeline with both a daily and weekly schedule trigger. Run the pipeline manually with MaintenanceMode = "full" and verify the email notification activity does not fire (because there are no failures).
Step 5: Intentionally break one table name in your Z-Order config (use a column name that doesn't exist) and re-run. Verify that:
maintenance_log table shows success = false for the broken table with a meaningful error message"The notebook can't find any tables."
The most common cause is that the LAKEHOUSE_NAME parameter doesn't match the actual name of the attached lakehouse (names are case-sensitive in Spark catalog). Open a test cell and run spark.sql("SHOW DATABASES").show() to see what namespaces are available. If your lakehouse isn't appearing, verify it's attached to the notebook via the Data pane on the left sidebar.
"OPTIMIZE runs for 45 minutes on a 2GB table."
This usually means you're trying to Z-Order by too many columns, or by a column with extremely high cardinality (like a UUID primary key). Z-Order works best on columns you actually filter by in queries — 2-3 columns maximum. Remove the Z-Order specification and run plain OPTIMIZE first to establish a baseline.
"VACUUM isn't freeing up any storage."
Check when the files you're expecting to remove were written. If they're less than VACUUM_RETAIN_HOURS old, VACUUM correctly leaves them alone. Also check whether the Delta log shows recent OPTIMIZE runs — if OPTIMIZE hasn't run yet, there are no "superseded" files for VACUUM to clean up. OPTIMIZE first, VACUUM second.
"V-Order doesn't seem to be applying."
Verify with spark.conf.get("spark.sql.parquet.vorder.enabled") that the config is actually being set in your session. Also check that the OPTIMIZE command is actually rewriting files — if all files are already at the target size, OPTIMIZE may be a no-op and won't re-encode anything. This is the "files already optimal" scenario; you can force a rewrite by temporarily reducing the target file size, running OPTIMIZE, restoring it, and running again (though this is rarely necessary in practice).
"The pipeline's If Condition always evaluates the wrong branch."
The expression @json(activity('Run Maintenance Notebook').output.result.exitValue) requires that your notebook used mssparkutils.notebook.exit() with a JSON string. If the notebook errored before reaching the exit cell, there's no exit value and the expression fails. Add a Failed dependency on the If Condition activity that connects directly to your notification activity, so pipeline-level failures (not just notebook-reported failures) also trigger alerts.
Warning
Be careful about running multiple maintenance pipelines against the same lakehouse simultaneously. Delta Lake uses optimistic concurrency control, but simultaneous OPTIMIZE operations on the same table will conflict and one will fail. If you have multiple teams running their own maintenance jobs, coordinate schedules or implement a mutex pattern using a Delta table as a lock registry.
You've built a production-grade maintenance automation system that covers the three pillars of Delta table health: file compaction via OPTIMIZE, storage reclamation via VACUUM, and read-time performance via V-Order encoding. The design is intentionally configuration-driven and self-discovering — it handles new tables automatically, respects per-table scheduling profiles, and reports its own health back to a queryable audit log.
The key architectural decisions to remember:
From here, consider extending this system in a few directions. You could add a pre-maintenance stats collection step that records file counts and sizes before operations and then recalculates after, giving you a precise "bytes reclaimed" and "files compacted" metric per run. You could integrate the maintenance log table into a Direct Lake Power BI report that surfaces tables approaching critical file fragmentation before they become a problem. You could also extend the table discovery logic to read a configuration table from the lakehouse itself, enabling non-engineers to manage table profiles without touching the notebook code.
This maintenance layer is also a natural complement to the ingestion patterns you're running. If you're using incremental loading with watermarks and pipeline lookup activities to append data daily, your maintenance pipeline is what ensures those daily appends don't slowly erode the query performance you achieved on day one. Build it once, schedule it properly, and your lakehouse stays fast automatically.
Microsoft Fabric Fundamentals