Prerequisites
- !Comfortable reading Python and a little SQL
- !Understanding of what a data lake and a data warehouse each store
- !Rough awareness that Apache Spark runs in clusters
What You'll Learn
- 1Describe the control plane, data plane and metastore boundaries of an Azure Databricks workspace
- 2Explain the three-level Unity Catalog namespace and where grants belong
- 3Use MERGE, time travel and OPTIMIZE correctly on Delta tables
- 4Configure a job cluster versus a shared cluster and state the cost consequence
- 5Tune Spark settings that actually move runtime, not ones that merely look sophisticated
Where the workspace actually runs
An Azure Databricks workspace has two halves that interviewers like to separate. The control plane runs in a Microsoft-managed subscription and holds notebooks, job definitions, cluster metadata and the workspace UI. The data plane runs in your subscription: the cluster VMs, the disk they shuffle on, and every byte they read or write. Encryption and networking decisions only ever apply to the data plane, which is why a workspace can be fully private while the notebook service still reaches the internet.
Clusters come in two operational flavours. A job cluster is created for one job run and terminated afterwards, so you pay for exactly the minutes the job needs. A shared or interactive cluster stays alive between sessions, which makes development fast and cost predictable in the wrong direction. The most common FinOps finding in a Databricks review is a fourteen-node shared cluster running twenty hours a day to run a fifteen-minute nightly job.
Unity Catalog changes the metastore model. Before it, each workspace kept its own Hive metastore, credentials lived as secrets in workspace scope, and governance had to be repeated everywhere. Unity Catalog centralises metadata into a single metastore per account, so a grant written once applies across every workspace that attaches to it.
The three-level namespace and where grants belong
Unity Catalog organises objects as catalog, schema, then table or volume or function. The practical consequence is that permissions inherit downward, and the level at which you grant determines how much surprise you create later.
Granting SELECT on a catalog is the right move for a shared reference dataset and the wrong move for a table containing account numbers. Granting at the table level for every table scales badly once you pass a few hundred objects. The working pattern is to define groups that mirror responsibilities, grant broad read on curated schemas to those groups, and grant write only on the specific schemas a pipeline owns.
| Object | Inherited by | Typical grant | You grant here when |
|---|---|---|---|
| Catalog | All schemas and tables inside | SELECT for analyst groups | The whole domain is public inside the company |
| Schema | Tables, views, volumes | MODIFY for the owning pipeline | A team owns a layer such as curated |
| Table | Nothing further | SELECT, MODIFY for specific users | Column-level exposure must be limited |
| Volume | Files inside | READ VOLUME, WRITE VOLUME | Raw file drops need separate control |
| Storage credential | External locations using it | CREATE EXTERNAL LOCATION | You separate who may register locations |
Row-level and column-level filters live on the table, which is the other reason to use tables as the final boundary: masking policies attached to a column travel with every view built on top of it.
-- Register the lake as a governed object, once, by the platform team
CREATE EXTERNAL LOCATION gold_location
URL 'abfss://[email protected]/'
WITH (STORAGE CREDENTIAL storage_cred);
-- Hand the curated schema to a pipeline identity, not to a person
GRANT MODIFY ON SCHEMA sales_curated TO `sp-pipeline-sales`;
GRANT SELECT ON SCHEMA sales_curated TO `grp-analysts`;
-- Mask a sensitive column for everyone outside the owner group
CREATE MASKING POLICY mask_email AS (val STRING) RETURNS STRING ->
CASE
WHEN is_member('grp-data-owners') THEN val
ELSE '***'
END;
ALTER TABLE sales_curated.customer APPLY MASKING POLICY mask_email FORCE;
Notice what is absent: no passwords in the notebook, no storage keys pasted into a job. Access flows from an Azure service principal, through a storage credential, to an external location. Revoking that credential kills access everywhere it is used, which is the auditability that a per-workspace metastore could never provide.
Delta Lake: what MERGE guarantees
Delta Lake stores data as Parquet files plus a transaction log, the _delta_log directory, which records a JSON commit for every version. Readers take a snapshot at one version, so a concurrent writer cannot tear their view. Writers use optimistic concurrency: if two transactions touch the same files, one retries.
That is what makes MERGE useful. It atomically matches rows, updates the ones that match and inserts the ones that do not, and commits as a single version. A loop of inserts and updates cannot give you that, and without it a half-finished nightly load is visible to every reader.
from pyspark.sql import SparkSession
from delta.tables import DeltaTable
spark = SparkSession.builder.getOrCreate()
target = DeltaTable.forName(spark, "sales_curated.fact_order")
updates = spark.read.format("delta").load("/mnt/lake/curated/order_delta")
target.alias("t").merge(
updates.alias("s"),
"t.order_id = s.order_id AND t.source_system = s.source_system"
).whenMatchedUpdate(
set={
"quantity": "s.quantity",
"unit_price": "s.unit_price",
"updated_at": "current_timestamp()"
}
).whenNotMatchedInsert(
values={
"order_id": "s.order_id",
"source_system": "s.source_system",
"quantity": "s.quantity",
"unit_price": "s.unit_price",
"amount": "s.quantity * s.unit_price",
"updated_at": "current_timestamp()"
}
).execute()
# Read yesterday's snapshot without rewriting anything
yesterday = (spark.read.format("delta")
.option("versionAsOf", 41)
.table("sales_curated.fact_order"))
Two details in that snippet are deliberate. The match key includes source_system, because order identifiers are rarely globally unique across systems. And time travel is a read option, not a copy: the old version stays on storage until you run VACUUM.
Compaction, Z-ORDER and the small-file problem
Every MERGE and every streaming micro-batch writes new files. Left alone, a table accumulates thousands of tiny files, and query planning and I/O both suffer. Compaction rewrites those into few large files without changing the logical contents.
Z-ORDER is the second lever. It co-locates values of the chosen columns within files so that a filter on those columns can skip whole files. It only pays for columns that are actually filtered, so pick the join key or the most common predicate, not every column you happen to index.
# Run after a bulk load or a heavy MERGE
spark.sql("""
OPTIMIZE sales_curated.fact_order
ZORDER BY (order_id, order_date)
""")
# Drop file versions older than 7 days, then check the log
spark.sql("VACUUM sales_curated.fact_order RETAIN 168 HOURS")
spark.sql("DESCRIBE HISTORY sales_curated.fact_order").show(5, truncate=False)
# Auto compaction for writes that arrive continuously
spark.conf.set("spark.databricks.delta.optimizeWrite.enabled", "true")
spark.conf.set("spark.databricks.delta.autoCompact.enabled", "true")
One caution worth memorising: VACUUM removes the files that time travel depends on. Running it with the default twenty-four-hour retention while a downstream job replays a three-day-old version produces a FileNotFound that looks like corruption and is really just retention.
The other half of the calculation is cost. Compaction rewrites files, so it consumes cluster time and produces new storage that only disappears once VACUUM reclaims the old versions. A sensible schedule runs OPTIMIZE shortly after the heaviest write window of the day and VACUUM on a weekly cadence with a retention comfortably longer than the oldest replay any consumer performs. Running both continuously on a table that is written to all day mostly generates write amplification with no measurable read benefit.
Job design, retries and timeouts
A production Databricks job is a DAG of tasks, each with its own cluster choice, timeout and retry policy. Tasks that share an existing cluster finish faster because they skip cluster startup, but they inherit that cluster's failures. Tasks that get a new cluster isolate failure at the cost of three to five minutes of provisioning.
{
"run_name": "nightly_sales",
"max_concurrent_runs": 1,
"schedule": {
"quartz_cron_expression": "0 30 2 * * ?",
"timezone_id": "UTC"
},
"tasks": [
{
"task_key": "ingest",
"new_cluster": {
"spark_version": "14.3.x-scala2.12",
"node_type_id": "Standard_D4ds_v5",
"autoscale": { "min_workers": 2, "max_workers": 8 }
},
"notebook_task": { "notebook_path": "/Repos/de/ingest_orders" },
"timeout_seconds": 3600,
"max_retries": 2
},
{
"task_key": "publish",
"depends_on": [{ "task_key": "ingest" }],
"existing_cluster_id": "0401-221456-abcdefg",
"notebook_task": { "notebook_path": "/Repos/de/publish_sales" },
"timeout_seconds": 1800
}
]
}
max_concurrent_runs set to one is a deliberate idempotency guard. Two overlapping runs of a MERGE-based load are legal but wasteful, and for anything with an append step they are a correctness bug.
Spark settings that are worth changing
Adaptive Query Execution, enabled by default on recent runtimes, already coalesces shuffle partitions and converts sort-merges into joins when statistics allow. Turning it off to "gain control" usually makes jobs slower. The settings that still matter are the ones about skew, broadcast threshold and cache.
spark.conf.set("spark.sql.adaptive.enabled", "true")
spark.conf.set("spark.sql.adaptive.skewJoin.enabled", "true")
# A dimension table you join on every step: let it broadcast
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", "100MB")
# Local SSD cache for a hot dimension repeatedly read from ADLS
spark.conf.set("spark.databricks.io.cache.enabled", "true")
# Partition count for a shuffle that AQE cannot fix afterwards
spark.conf.set("spark.sql.shuffle.partitions", "400")
Skew has two durable answers: salt the hot key so it spreads across reducers, or broadcast the small side so no shuffle happens at all. Increasing shuffle partitions to ten thousand moves the same skew into more, smaller, equally unbalanced tasks.
Common Mistakes
Leaving shared clusters running between sessions and paying for idle executors
Fix: Use job clusters for scheduled work and apply an auto-termination timeout of fifteen minutes or less to anything interactive
Granting SELECT on a whole catalog because it was quick
Fix: Grant at schema level for curated layers and at table level for anything with personal data, using groups rather than individual users
Running VACUUM immediately after a load
Fix: Retain at least the longest replay window any downstream consumer uses, then VACUUM on a schedule
Adding more shuffle partitions to fix a skewed join
Fix: Enable adaptive skew handling, salt the hot key, or broadcast the small side
Best Practices
- Keep secrets out of notebooks; authenticate with a service principal and Unity Catalog storage credentials
- Set timeouts and retries per task so one hung notebook does not burn a whole cluster
- Run OPTIMIZE on a schedule aligned with write volume rather than waiting for queries to slow
- Record cluster policies that pin node types and autoscaling bounds so cost cannot drift silently
Interview Questions
Q1: What does the Databricks control plane hold and where does it run?
Notebooks, job definitions, cluster metadata and the workspace UI, in a Microsoft-managed region. Compute and data stay in your subscription's data plane, so encryption and network controls apply only there.
Q2: Why is Unity Catalog better than a workspace-local Hive metastore?
It gives one metastore per account, a three-level namespace, centrally stored credentials, and grants and lineage that apply across every attached workspace instead of being replicated per workspace.
Q3: What does MERGE give you that an insert loop does not?
A single atomic commit that matches, updates and inserts in one version, so readers never observe a partially applied load and concurrent writers either win or retry cleanly.
Q4: Explain the difference between OPTIMIZE and VACUUM.
OPTIMIZE rewrites small files into larger ones and optionally Z-Orders data, changing the physical layout but not the logical contents. VACUUM removes old file versions that are no longer referenced, which bounds storage but also ends time travel for those versions.
Q5: How do you diagnose a data skew problem in a Spark job?
Look at the SQL plan and task metrics for a single task with far more rows than the rest, identify the key causing it, then salt the key, broadcast the small side, or repartition on a different expression.
Key Takeaways
- The control plane holds metadata; the data plane holds compute and data, and only the data plane needs your network and encryption controls
- Unity Catalog centralises metastore, credentials and grants into one three-level namespace
- Delta's transaction log is what makes MERGE atomic and time travel possible
- Compaction fixes small files, Z-ORDER fixes file skipping, and VACUUM bounds both storage and replay history
- Cost control in Databricks is mostly cluster lifecycle: job clusters, autoscaling and auto-termination