1. Lakehouse Architecture & Unity Catalog
01. What is the Databricks Lakehouse architecture and how does it differ from a two-tier Data Lake + Warehouse?
A Lakehouse combines the low-cost, open object storage of a data lake (S3, ADLS, GCS) with ACID transactions, schema governance, indexing, and BI performance of a data warehouse on a single platform. Unlike a two-tier architecture, it eliminates duplicate copies, stale ETL syncs, and separate governance layers for BI and ML.
02. Explain the Medallion Architecture (Bronze, Silver, Gold) in Databricks.
Bronze stores raw, immutable ingested data with metadata (audit columns, ingestion timestamp) for full replayability. Silver contains cleansed, deduplicated, conformed, and enriched datasets with enforced schemas. Gold holds business-level aggregates, star schemas, and feature tables optimized for BI dashboards and ML consumption.
03. What is Unity Catalog and how does its three-level namespace work?
Unity Catalog is Databricks' centralized governance layer across workspaces for data, files, and AI models. It uses a three-level namespace: catalog.schema.table (or volume/function/model), allowing clean separation by environment or domain (e.g., prod.finance.invoices).
04. How does Unity Catalog differ from the legacy Hive Metastore?
The Hive Metastore is workspace-scoped, uses two-level naming, lacks unified file/model governance, and has limited row/column security. Unity Catalog is account-level across multiple workspaces, provides ANSI SQL RBAC, automatic column-level lineage, system tables for audit/billing, and governs Volumes and ML models alongside tables.
05. What is the difference between Managed and External tables in Unity Catalog?
For a Managed table, Unity Catalog manages both metadata and underlying storage files inside the catalog/schema managed location, and dropping the table deletes the data after the retention period. For an External table, data lives at a user-specified External Location; dropping the table removes only the metadata while preserving the cloud storage files.
06. What are Storage Credentials and External Locations in Unity Catalog?
A Storage Credential wraps cloud IAM authentication (e.g., AWS IAM Role, Azure Managed Identity, GCP Service Account). An External Location pairs a cloud storage path (like s3://bucket/raw/) with a Storage Credential so Unity Catalog can authorize fine-grained reads/writes without embedding keys in notebooks.
07. What are Unity Catalog Volumes and when should you use them?
Volumes are Unity Catalog objects that govern non-tabular files (images, PDFs, JSON dumps, CSVs, wheel packages) in cloud storage. Use Volumes instead of legacy DBFS mounts so unstructured landing files inherit centralized RBAC, lineage, and audit logging.
08. Why are DBFS root and DBFS mounts discouraged in modern Databricks?
DBFS mounts attach workspace-wide credentials that bypass user-level governance and can expose sensitive data to any workspace user. Unity Catalog External Locations and Volumes replace mounts with per-user/group permissions and no shared workspace storage keys.
09. How do you implement Row-Level Security (RLS) and Column Masking in Unity Catalog?
You define SQL UDFs (e.g., checking is_account_group_member('eu_analysts')) and attach them to tables via ALTER TABLE ... SET ROW FILTER for row filtering or ALTER COLUMN ... SET MASK to redact PII like emails/SSNs dynamically at query time.
10. What is Delta Sharing and how does Databricks-to-Databricks vs Open Sharing work?
Delta Sharing is an open protocol for securely sharing live Delta tables, views, notebooks, and models across clouds and organizations without copying data. Recipients with Databricks use Unity Catalog-to-UC sharing natively, while non-Databricks recipients authenticate via a bearer token or OIDC to read Parquet slices directly via pre-signed URLs.
11. Explain the Control Plane vs Compute (Data) Plane in Databricks architecture.
The Control Plane is hosted by Databricks and manages the UI, notebooks, job scheduler, APIs, and cluster configuration. The Compute Plane runs Spark/Photon workers (either in your cloud VPC/VNet for Classic Compute or in Databricks-managed isolated containers for Serverless Compute) where actual customer data is processed.
12. What are Databricks System Tables and what insights do they provide?
System Tables (under the system catalog) expose account-wide operational metadata such as system.billing.usage for DBU cost attribution, system.access.audit for security compliance, system.access.table_lineage / column_lineage, and query history.
13. What is Lakehouse Federation?
Lakehouse Federation lets Unity Catalog query external databases (Snowflake, BigQuery, PostgreSQL, MySQL, Redshift, SQL Server) using foreign catalogs without migrating the data first, pushing down predicates where supported and applying unified governance.
14. How does Databricks Connect work?
Databricks Connect is a client library built on Spark Connect that lets developers write and debug PySpark code locally in IDEs like VS Code or PyCharm while executing the DataFrame plan remotely on a Databricks cluster or Serverless compute.
15. What are Service Principals in Databricks and why use them in production?
Service Principals are non-human API identities used to run production Workflows, CI/CD pipelines, and dashboards. Using them prevents jobs from breaking if an employee leaves and allows least-privilege permission scoping separate from personal accounts.
2. Delta Lake & Storage Internals
16. How does the Delta Lake transaction log (_delta_log) guarantee ACID transactions?
Every commit writes an ordered JSON file (e.g., 00000000000000000001.json) listing added/removed Parquet files and metadata. Using optimistic concurrency control and atomic put-if-absent cloud primitives, readers always see a consistent snapshot while concurrent writers serialize safely or retry non-conflicting commits.
17. What are Delta Checkpoints and why are they created every 10 commits (or via V2 checkpoints)?
Replaying thousands of small JSON commit files slows down table state reconstruction. Periodically (by default every 10 commits), Delta writes a Parquet checkpoint file summarizing all active files up to that version so readers only scan the latest checkpoint plus subsequent JSON logs.
18. How does Delta Time Travel work and what are its limits?
You can query historical snapshots using VERSION AS OF N or TIMESTAMP AS OF '2026-...' because Delta keeps older Parquet files referenced in prior log entries. However, once VACUUM removes obsolete files past the retention window (default 7 days), time travel to those older versions fails.
19. What is the difference between RESTORE TABLE and CLONE (Shallow vs Deep)?
RESTORE TABLE rolls a table back in place to a previous version. DEEP CLONE copies both metadata and data files to a new independent table (great for disaster recovery/migration), whereas SHALLOW CLONE creates a new metadata log pointing to the source's existing Parquet files—fast and zero-copy for dev/test branching.
20. Explain Liquid Clustering vs Hive-style Partitioning + Z-Ordering.
Hive partitioning creates rigid physical folders that cause skew or over-partitioning, and Z-Ordering requires full rewrite passes. Liquid Clustering (CLUSTER BY) dynamically organizes data into balanced clusters using Hilbert curves without physical directory splits, supports incremental clustering on OPTIMIZE, and lets you change clustering keys without rewriting historical data.
21. What does the OPTIMIZE command do in Delta Lake?
OPTIMIZE compacts many small Parquet files into larger, analytics-friendly files (commonly around 1 GB depending on adaptive target file sizing) and applies Z-Ordering or Liquid Clustering, dramatically reducing file-listing and I/O overhead.
22. Explain VACUUM, retention thresholds, and why setting retention to 0 hours is risky.
VACUUM permanently deletes data files no longer referenced by the current transaction log older than the retention threshold (default 168 hours / 7 days). Lowering it near 0 hours can corrupt active concurrent readers or break time travel, which is why Databricks guards it behind spark.databricks.delta.retentionDurationCheck.enabled.
23. What are Deletion Vectors in Delta Lake and how do they speed up DELETE/UPDATE/MERGE?
Without Deletion Vectors (Copy-on-Write), deleting or updating one row forces Spark to rewrite the entire Parquet file containing it. Deletion Vectors (Merge-on-Read) record deleted row positions in a lightweight sidecar bitmap file, making DML writes much faster until background/explicit compaction reconciles them.
24. What is Change Data Feed (CDF) in Delta Lake?
When delta.enableChangeDataFeed = true is set, Delta records row-level changes (insert, update_preimage, update_postimage, delete) across versions. Downstream Silver/Gold pipelines can read only incremental changes via table_changes() instead of rescanning full tables.
25. What is Auto Loader (cloudFiles) and why is it superior to standard Spark file streaming?
Auto Loader incrementally ingests new files from cloud storage using RocksDB state tracking and either directory listing or cloud file-notification queues (SQS/Event Grid/PubSub). Unlike standard Spark streaming, it scales to millions of files without repeated directory scans and supports schema inference, evolution, and rescued data columns.
26. How does Auto Loader handle unexpected or corrupt fields using _rescued_data?
When cloudFiles.schemaEvolutionMode is configured (e.g., addNewColumns or rescue), mismatched types or unexpected columns are captured as a JSON string in the _rescued_data column rather than silently dropping records or failing the stream.
27. Explain Schema Enforcement vs Schema Evolution in Delta Lake.
Schema Enforcement blocks writes whose columns or data types don't match the target table, preventing silent data corruption. Schema Evolution (via .option("mergeSchema", "true") or WITH SCHEMA EVOLUTION in SQL MERGE) explicitly allows adding new compatible columns during a write.
28. What are Data Skipping and Min/Max Statistics in Delta Lake?
Delta automatically stores per-file column statistics (min, max, null count) for the first 32 columns (configurable) in the transaction log. During queries with WHERE filters, Spark skips reading entire Parquet files whose min/max range cannot match the predicate.
29. What is Predictive Optimization in Databricks Unity Catalog?
Predictive Optimization uses Databricks AI/telemetry on Unity Catalog Managed tables to automatically schedule and run OPTIMIZE, VACUUM, and ANALYZE TABLE statistics collection when needed—eliminating manual maintenance notebooks.
30. What is Delta UniForm (Universal Format)?
Delta UniForm lets a single Delta table automatically generate lightweight Iceberg and Hudi metadata alongside _delta_log without duplicating Parquet data files, allowing Iceberg/Hudi engines like Snowflake, Trino, or BigQuery to read the same table directly.
3. Spark & PySpark Performance on Databricks
31. What is the Photon Engine and when does it accelerate workloads?
Photon is Databricks' native C++ vectorized query engine that executes Spark SQL and DataFrame operations on CPU SIMD instructions instead of the JVM. It dramatically speeds up scans, joins, aggregations, window functions, and Delta writes while reducing garbage-collection overhead; Python UDFs still fall back to Python workers.
32. How does Adaptive Query Execution (AQE) optimize Spark jobs at runtime?
AQE re-optimizes the physical execution plan mid-query using actual shuffle stage statistics: it dynamically coalesces small post-shuffle partitions, converts Sort-Merge Joins into Broadcast Hash Joins when a table turns out small after filtering, and splits skewed partitions automatically.
33. Compare Broadcast Hash Join vs Shuffle Sort-Merge Join vs Shuffle Hash Join.
Broadcast Hash Join sends a small table (<10 MB default, tunable) to every executor, avoiding a shuffle of the large table. Sort-Merge Join shuffles and sorts both large tables on the join key and is memory-safe for huge joins. Shuffle Hash Join shuffles both sides and hashes the smaller partition without sorting when it fits in executor memory.
34. How do you diagnose and resolve Data Skew in PySpark on Databricks?
In the Spark UI Stages tab, check if 199 tasks finish in seconds while 1 task runs for minutes with huge shuffle read/spill. Fix it by enabling AQE skew join optimization (spark.sql.adaptive.skewJoin.enabled), filtering NULL/default keys before joins, broadcasting the smaller side, or salting hot keys.
35. What is the difference between Spark cache()/persist() and Databricks Disk Cache (formerly Delta Cache)?
Spark cache() stores deserialized/serialized DataFrame blocks in executor JVM memory (or spill disk) and must be explicitly managed. Disk Cache automatically caches remote Parquet data files on fast local NVMe SSDs on worker nodes in compressed form, accelerating repeated reads with zero code changes.
36. Explain Catalyst Optimizer and Project Tungsten in Spark.
Catalyst is Spark's extensible query optimizer that applies logical rules (predicate pushdown, column pruning, constant folding) and cost-based physical planning. Tungsten manages off-heap binary memory, cache-aware layouts, and whole-stage code generation to maximize CPU/memory efficiency.
37. Why should you prefer built-in Spark SQL functions or Pandas (Arrow) UDFs over standard Python UDFs?
Standard Python UDFs serialize every row between the JVM/Photon and a Python process one by one, bypassing Catalyst/Photon optimizations. Built-in Spark functions execute natively inside Photon/JVM, and Vectorized Pandas UDFs batch columnar data via Apache Arrow for much higher throughput.
38. What is the difference between repartition() and coalesce()?
repartition(n) performs a full network shuffle to evenly distribute data across n partitions (can increase or decrease count). coalesce(n) reduces partitions by merging existing partitions locally without a full shuffle, making it faster before writes unless data is heavily skewed.
39. What causes Disk Spill and Memory Spill in Spark, and how do you fix it?
Spill happens when shuffle buffers or aggregation hash maps exceed an executor's execution memory, forcing Spark to serialize data to local disk. Fix it by increasing shuffle partitions (or letting AQE auto-tune), eliminating skew, avoiding collect()/wide explosions, or selecting memory-optimized worker nodes.
40. How do you fix Driver OutOfMemory (OOM) errors in Databricks?
Driver OOM usually comes from calling df.collect(), toPandas() on huge DataFrames, broadcasting too-large tables, or accumulating massive Spark listener/metadata state. Avoid collecting large results to the driver, write directly to Delta, or raise driver memory / use Spark-native aggregations.
41. Explain Narrow vs Wide Transformations in Spark.
Narrow transformations (filter, map, withColumn) compute each output partition from a single input partition with no network movement. Wide transformations (groupBy, join, distinct, repartition) require shuffling data across partitions over the network and create stage boundaries.
42. What is Dynamic File Pruning (DFP) in Databricks?
When joining a large partitioned/clustered Delta fact table with a filtered dimension table, DFP uses runtime filter values from the dimension side to prune non-matching files in the fact table scan, even when the filter isn't directly on the fact table.
43. Why should you avoid count() or display() inside production ETL notebooks?
Both are Spark actions that force immediate full evaluation of the DAG. Leaving debugging df.count() or display(df) calls in production pipelines re-executes expensive scans and shuffles unnecessarily, wasting DBUs and runtime.
44. What is Range Partitioning vs Hash Partitioning in Spark?
Hash partitioning routes keys by hash(key) % numPartitions—fast for joins and equality groupings. Range partitioning samples data to split ordered key ranges evenly across partitions, ideal for global sorting or writing well-balanced time/ordered ranges.
45. How does spark.sql.shuffle.partitions = auto work in Databricks?
In Databricks Runtime, setting shuffle partitions to auto lets AQE choose the optimal initial/coalesced shuffle partition count based on cluster size and actual input data volume rather than relying on the outdated default of 200.
4. Workflows, DLT & Streaming
46. What are Delta Live Tables (DLT / Lakeflow Declarative Pipelines) and what problems do they solve?
DLT is a declarative ETL framework where you define tables and transformations (SQL/Python) rather than imperative job orchestration. Databricks automatically builds the dependency DAG, manages checkpoints, handles retries/autoscaling, enforces data quality Expectations, and tracks lineage.
47. Explain Streaming Tables vs Materialized Views in DLT / Databricks SQL.
Streaming Tables process append-only incoming data incrementally once-only (ideal for Bronze/Silver ingestion). Materialized Views precompute query results (joins, aggregations) and incrementally refresh when upstream sources change—ideal for Gold serving layers.
48. How do DLT Expectations work (WARN, DROP ROW, FAIL UPDATE)?
Expectations are declarative data quality assertions on rows: EXPECT logs violations while keeping rows, EXPECT ... ON VIOLATION DROP ROW quarantines/discards invalid rows, and EXPECT ... ON VIOLATION FAIL UPDATE halts the pipeline immediately on critical violations.
49. How does APPLY CHANGES INTO / Auto CDC work in DLT?
APPLY CHANGES INTO simplifies CDC ingestion by handling out-of-order events via a sequence column, deletes, deduplication, and automatic SCD Type 1 (overwrite) or SCD Type 2 (historical effective start/end columns) without writing complex manual MERGE boilerplate.
50. What is trigger(availableNow=True) in Structured Streaming and why is it widely used?
availableNow=True processes all currently available unconsumed data in bounded micro-batches (respecting maxFilesPerTrigger) and then cleanly shuts down the cluster. It gives streaming's incremental state/checkpointing benefits at batch-job cost.
51. Explain Watermarking and Stateful Checkpointing in Spark Structured Streaming.
Checkpointing persists Kafka offsets / file logs and RocksDB operator state to cloud storage for exactly-once recovery. Watermarking (withWatermark("event_time", "10 minutes")) tells Spark how late events can arrive before closing and purging old window aggregation state so memory does not grow unboundedly.
52. Compare Job Compute vs All-Purpose Compute vs Serverless Compute in Databricks.
All-Purpose clusters are interactive, stay running for ad-hoc exploration, and carry a higher DBU rate. Job Compute spins up per workflow run, terminates automatically, and costs significantly less per DBU. Serverless Compute starts in seconds with zero infrastructure tuning and auto-scales per query or task.
53. How do Databricks Workflows support orchestration beyond single notebooks?
Workflows support multi-task DAGs mixing notebooks, Python wheels, SQL tasks, dbt, DLT pipelines, conditional If/else branching, For each loops, task values for passing parameters, file-arrival triggers, and automated repair/rerun from failed tasks.
54. How do you pass parameters and outputs between tasks in a Databricks Workflow?
Use job/task parameters (widget values via dbutils.widgets.get()) for inputs, and dbutils.jobs.taskValues.set(key, value) / .get() to pass lightweight dynamic metadata (like batch dates or row counts) between dependent tasks.
55. What is RocksDB State Store in Databricks Structured Streaming?
Default JVM HDFS-backed state stores suffer GC pauses on millions of streaming keys (like deduplication or stream-stream joins). Enabling RocksDB offloads state management to native off-heap storage with incremental checkpointing, scaling smoothly to tens of millions of keys.
5. Databricks SQL, MLflow & GenAI
56. What is a Databricks SQL Warehouse (Classic, Pro, Serverless) and how does it scale?
SQL Warehouses are Photon-powered compute endpoints tuned for BI, SQL analytics, and JDBC/ODBC concurrency. Serverless SQL Warehouses launch in seconds, handle burst concurrency with multi-cluster autoscaling, and scale down aggressively during idle periods.
57. How does Predictive I/O work in Databricks SQL?
Predictive I/O combines learned index lookups, smart prefetching, and accelerated selective scans on Photon/Delta tables so point lookups and selective BI filters run orders of magnitude faster without manual secondary indexes.
58. How does Query Result Caching work in Databricks SQL?
Databricks SQL caches final query results locally and remotely; if an identical query hits unchanged underlying Delta table versions, the cached result is returned instantly without spinning up compute or re-scanning data.
59. Explain MLflow Tracking and Model Registry inside Unity Catalog.
MLflow Tracking logs parameters, metrics, artifacts, and code versions per experiment run. Registering models in Unity Catalog (catalog.schema.model_name) gives models cross-workspace RBAC, lineage back to training Delta tables, and aliases (like @champion / @challenger) instead of legacy stage names.
60. What is Feature Engineering in Unity Catalog (Feature Store) and why does it prevent training-serving skew?
Any Delta table with a primary key in Unity Catalog can act as a feature table. Feature lookup joins automatically point-in-time match training features and sync the exact same feature definitions to low-latency online tables for real-time inference, eliminating training-serving skew.
61. What is Mosaic AI Vector Search in Databricks?
Mosaic AI Vector Search is a serverless vector index tightly synced with a source Delta table via Delta Sync. When rows in the source Delta table insert or update, Databricks automatically computes/syncs embeddings so RAG applications always query fresh governed data.
62. How does Mosaic AI Model Serving deploy LLMs and custom ML models?
Model Serving packages MLflow models or Foundation Models behind autoscaling, scale-to-zero REST endpoints with GPU support, traffic splitting for A/B testing, AI Gateway rate-limiting/guardrails, and Inference Tables that log requests/responses back to Delta for monitoring.
63. What is Lakehouse Monitoring in Databricks?
Lakehouse Monitoring automatically computes data quality statistics, distribution drift, null spikes, and model accuracy metrics over time on any Unity Catalog Delta table (including Inference Tables) and stores profiles/alerts in dashboard-ready Delta tables.
64. How does Databricks AI/BI Genie help business users?
AI/BI Genie is a conversational analytics workspace grounded in your Unity Catalog metadata, table comments, certified SQL expressions, and sample queries so non-technical stakeholders can ask natural-language questions and receive verified SQL and charts.
65. How do you manage API keys and secrets securely in Databricks notebooks?
Store secrets in Databricks Secret Scopes (backed by Databricks or Azure Key Vault / AWS Secrets Manager) and retrieve them via dbutils.secrets.get(scope, key). Databricks automatically redacts secret values if accidentally printed to notebook output or logs.
6. Production Scenarios & Cost Optimization
66. How do you write an idempotent, high-performance MERGE INTO (CDC Upsert) in Databricks?
Deduplicate incoming source batches on the primary key first (keeping latest timestamp), add partition/cluster-key predicates in the ON clause so Delta prunes untouched target files, enable Deletion Vectors, and only update rows where values actually changed (WHEN MATCHED AND source.hash != target.hash).
67. How do you diagnose and solve the "Small File Problem" in a streaming Delta pipeline?
Frequent micro-batches create thousands of tiny Parquet files, degrading read speed. Enable Optimized Writes (delta.autoOptimize.optimizeWrite = true) and Auto Compaction (delta.autoOptimize.autoCompact = true), or use Liquid Clustering + scheduled/Predictive OPTIMIZE.
68. What are Databricks Asset Bundles (DABs) and how do you use them for CI/CD?
DABs let you define Databricks jobs, DLT pipelines, dashboards, and permissions in version-controlled YAML (databricks.yml). Using databricks bundle validate and deploy in GitHub Actions or Azure DevOps promotes identical configurations cleanly across dev, staging, and prod.
69. How do you reduce Databricks DBU and cloud infrastructure costs without slowing SLAs?
Move scheduled pipelines from All-Purpose to Job/Serverless Compute, use Spot instances with on-demand fallback for workers (never for the driver), enable Autoscaling, set tight auto-termination on interactive clusters, leverage Photon selectively where it cuts total runtime-cost, and audit outliers via system.billing.usage.
70. How do you handle concurrent writes causing ConcurrentAppendException in Delta Lake?
ConcurrentAppendException occurs when two jobs modify overlapping files/partitions simultaneously (e.g., an UPDATE colliding with an unconditional write). Isolate writes using disjoint partition/cluster predicates (e.g., replaceWhere), serialize conflicting jobs in Workflows, or enable Row-Level Concurrency with Deletion Vectors.
71. How do you safely backfill historical data in a Silver/Gold table without disrupting live dashboards?
Use Delta's atomic replaceWhere option for targeted date ranges, or run backfills into a SHALLOW CLONE / staging table, validate row counts and expectations, and atomically swap or merge into production while readers continue reading consistent snapshots.
72. When should you choose CLUSTER BY (Liquid Clustering) over traditional PARTITIONED BY?
Always prefer Liquid Clustering for new Delta tables unless you have a strict physical-isolation requirement (such as external consumers needing partition folders). Traditional partitioning hurts performance when partitions are smaller than ~1 GB or when filter patterns change over time.
73. How do you handle Schema Evolution safely when an upstream vendor changes JSON payloads?
Ingest raw JSON into Bronze using Auto Loader with rescuedDataColumn so ingestion never fails on unexpected fields. Validate/parse the schema explicitly in Silver with DLT Expectations or schema contracts, alerting data owners before promoting new columns to Gold.
74. How do Cluster Policies help enterprise platform teams govern Databricks workspaces?
Cluster Policies enforce guardrails on cluster creation—restricting allowed VM families, max DBUs/workers, mandatory auto-termination minutes, Spark configs, and tagging for chargeback—so teams cannot accidentally spin up oversized GPU or All-Purpose clusters.
75. Walk through how you would migrate a legacy on-prem Hadoop/Hive or SQL Server warehouse to Databricks.
First, inventory tables, SLAs, and dependencies; set up Unity Catalog governance, External Locations, and DABs CI/CD. Land historical data and incremental CDC streams into Bronze via Auto Loader/Lakehouse Federation, convert HiveQL/SQL logic into modular DLT or Spark SQL Medallion pipelines, validate parity with automated reconciliation checks, and cut over BI dashboards to Serverless SQL Warehouses.