everprep

43m read · 8509 words

Delta lake

Explain schema evolution using MergeSchema

To perform schema evolution:

ALTER TABLE catalog.schema.my_table
SET TBLPROPERTIES (
    'delta.enableTypeWidening' = 'true'
);

Schema evolution will either add a new column, or optionally widen the type of an existing column.


There can be 3 scenarios:


Type widening datatypes: link

Source type Supported wider types
BYTE SHORT, INT, BIGINT, DECIMAL, DOUBLE
SHORT INT, BIGINT, DECIMAL, DOUBLE
INT BIGINT, DECIMAL, DOUBLE
BIGINT DECIMAL
FLOAT DOUBLE
DECIMAL DECIMAL with greater precision and scale
DATE TIMESTAMP_NTZ
VOID Any type

Explain delta lake's history table

It contains the table level commit log of a delta table. One row per version (transaction).

Every write (insert, update, delete, merge, optimize, schema change, and so on) creates a new numbered version.

Delta records each one as a JSON commit file in the table’s _delta_log/ folder, and DESCRIBE HISTORY reads that log and shows it as a table.

-- SQL
DESCRIBE HISTORY sales;                    -- all versions, newest first
DESCRIBE HISTORY sales LIMIT 5;            -- last 5 commits
DESCRIBE HISTORY delta.`/mnt/data/sales`;  -- by path
Column What it tells you
version Commit number, starting at 0 and increasing by one per commit
timestamp When the commit happened
userId / userName Who made the change
operation What happened: WRITE, MERGE, UPDATE, DELETE, OPTIMIZE, RESTORE, STREAMING UPDATE, ADD COLUMNS, …
operationParameters Details of that operation, such as write mode, the predicate of a delete or merge, or partitionBy
operationMetrics Numbers about the change: numOutputRows, numFiles, numTargetRowsUpdated, numTargetRowsDeleted, and so on
readVersion The version the transaction read before writing
isolationLevel Serializable or WriteSerializable
isBlindAppend True if the write only appended without reading existing data
job, notebook, clusterId Where the write came from (on Databricks)
userMetadata A custom note you attached to the commit
engineInfo The Spark/Delta version that wrote the commit

When is liquid clustering triggered?

3 triggers

TRIGGER ON WRITE

Liquid clustering happens at write-time. Every time delta writes writes to a table, liquid clustering is performed on it (INSERT, MERGE, COPY INTO etc). So, all liquid clustering work happens inside the spark jobs that are touching the table. There is no separate background service that continuously optimizes the tables.

MANUAL/EXPLICIT TRIGGER

Liquid clustering can be manually triggered via the optimize command

from delta.tables import *
    deltaTable = DeltaTable.forPath(spark, "path/to/table")
    deltaTable.optimize().executeCompaction()
OPTIMIZE table_name;

AUTOMATED TRIGGER (databricks only)

When predictive optimization is enabled (requires databricks premium plan), databricks will automatically run ANALYZE, OPTIMIZE, VACUUM operations - by queueing them as job to be run on serverless compute instances.

Since OPTIMIZE is being run, it will also end up triggering liquid clustering.

What happens during liquid-clustering?

  1. Delta reads clustering metadata - looks at existing files, their min/max ranges on clustering keys, clustering quality scores
  2. Incoming rows are sorted and grouped by the clustering keys.
  3. Delta will append rows into files whose key ranges are a good match for that particular row. If there is no existing file with a good match, it will create new file with tight range.

The computational cost is proportional only to the new data. There is no global-sort. No full table scan (only file statistics are read).

If liquid clustering finds that the existing data is horribly clustered, it won't re-organize and re-write the whole table. Instead, it will only rewrite a few of the worst files. If it sees diminishing returns, it will stop early.

Why? because it doesn't want to break streaming SLAs. Re-organizing the entire table may take a long time, breaking the SLA. So instead, it will fix only a few existing files on every run. Over time, as more and more writes trigger liquid clustering, the table will eventually become well-clustered.

So, in short, liquid clustering will touch a few files on every run, keeping the rewrite size small.

What is automated liquid clustering?

(Databricks only feature)

When automated liquid clustering is enabled, the runtime will analyze the historical query workload, and automatically identify the best columns for clustering. It will figure out the keys which will lead to cost savings from data skipping.
In this case, the liquid clustering columns won't need to be manually declared.

-- Enable automatic liquid clustering on an existing table,
-- including tables that previously had manually specified keys.
ALTER TABLE table1 CLUSTER BY AUTO;

-- Disable automatic liquid clustering on an existing table.
ALTER TABLE table1 CLUSTER BY NONE;

-- Disable automatic liquid clustering by setting the clustering keys
-- to chosen clustering columns or new columns.
ALTER TABLE table1 CLUSTER BY (column01, column02);

Source: Databricks: Delta Clustering: Enable/disable automatic liquid clustering

What triggers reclustering?

A re-clustering is triggered when:

What is auto compaction? How does it work?

Auto compaction kicks in when the number of file sizes is above a threshold (the spark configuration variable is spark.databricks.delta.autoCompact.minNumFiles). The output file size is controlled using spark.databricks.delta.autoCompact.maxFileSize.

Like liquid clustering, auto compaction comes in 2 flavours:

Auto compaction executes an OPTIMIZE command at the end of a transaction. Keep in mind that since OPTIMIZE is being run - if liquid clustering was enabled, then liquid clustering will also be performed on the table.

To enable auto compaction, following variables can be set:

The values these 2 settings take are:

Options Behavior
auto (recommended) Tunes target file size while respecting other autotuning functionality. Requires Databricks Runtime 10.4 LTS or above.
legacy Alias for true. Requires Databricks Runtime 10.4 LTS or above.
true Use 128 MB as the target file size. No dynamic sizing.
false Turns off auto compaction. Can be set at the session level to override auto compaction for all Delta tables modified in the workload.

Source: Databricks: Auto compaction for Delta Lake on Databricks

What file sizes does auto compaction target?

Databricks aims for smaller file sizes for smaller tables, and larger file sizes for larger tables. The aim it to make sure that the number of files doesn't increase too much.

However, it won't set the file size dynamically if you've explicitly set target file size (set via delta table property delta.targetFileSize. Its default value is None).

Table size Target file size Approximate number of files in table
10 GB 256 MB 40
1 TB 256 MB 4096
2.56 TB 256 MB 10240
3 TB 307 MB 12108
5 TB 512 MB 17339
7 TB 716 MB 20784
10 TB 1 GB 24437
20 TB 1 GB 34437
50 TB 1 GB 64437
100 TB 1 GB 114437

What is predictive optimization?

This is a feature available for Unity Catalog managed tables. It requires databricks premium plan.

When predictive optimization is enabled, databricks will automatically run ANALYZE, OPTIMIZE, VACUUM operations - by queueing them as job to be run on serverless compute (you will be billed for this compute).

Since OPTMIZE is being run, it will end up triggering both liquid clustering and auto-compaction on tables.

Observability statistics for predictive optimization executions are stored in the table system.storage.predictive_optimization_operations_history.

To explicitly enable/disable predictive optimization on a table:

ALTER CATALOG [catalog_name] { ENABLE | DISABLE | INHERIT } PREDICTIVE OPTIMIZATION;
ALTER { SCHEMA | DATABASE } schema_name { ENABLE | DISABLE | INHERIT } PREDICTIVE OPTIMIZATION;

How does z-order work?

NOTE: As of now (2025), liquid clustering is recommended over Z-ORDERING.

WARNING:

Very costly operation to perform. Z-order will lead to re-write amplification. Every OPTIMIZE ZORDER will rewrite large chunks of data.

Now, spark can skip entire files by looking at the min/max stats. Very effective for range and equality filters

Z-ORDER has to be triggered manually (in pipelines or scheduled jobs).
So, use Z-ORDER only for legacy tables, and one-off historical backfills.

By default, simply prefer liquid clustering.

To run z-order:

OPTIMIZE orders
ZORDER BY (customer_id, order_date)

Explain z-order vs bucketing

Bucketing is not supported for delta tables.

Similar to partitioning+bucketing for normalparquet tables, partitioning+z-ordering is the way to go for delta tables.

However, it is still recommended to simply use liquid clustering instead of partitioning+z-ordering.

Zorder and bucketing solve completely different problems.
Zorder will help speed up writes through data-skipping. Bucketing will help speed up execution by preventing shuffles during joins and aggregations.

Z-order doesn't prevent the data-shuffle problem that bucketing does.

What is VACUUM?

Removing stale files by trimming history

VACUUM will:

It is never run automatically. It will always have to be manually executed by a job or a user.

Delete old data files (loses history)

VACUUM events RETAIN 168 HOURS

Spark theory

Explain spark architecture

Apache Spark follows a distributed master-worker architecture with three main components:

Cluster Manager

Driver

Executors

In short: The Driver coordinates, the Cluster Manager allocates resources, and Executors perform the computation.

Explain transformations vs actions

In Spark, operations are classified into Transformations and Actions.

Transformations

Actions

Explain lazy evaluation in spark

In Spark, lazy evaluation means transformations are not executed immediately. Instead, Spark builds an execution plan (DAG) and executes it only when an action is triggered.

It allows Spark to optimize the entire computation pipeline before executing it.

Why is lazy evaluation useful?

How does spark do fault tolerance?

Spark provides fault tolerance primarily through RDD lineage, task retries, and data replication.

Spark achieves fault tolerance through recomputation rather than relying entirely on replication of intermediate data.

  1. RDD Lineage: Spark maintains the sequence of transformations used to create an RDD. If a partition is lost, Spark can recompute it from the original data using its lineage.
  2. Task Retry: If an executor fails while processing a task, Spark can reschedule that task on another executor.
  3. Data Replication: Cached data can be replicated across executors using persistence options such as MEMORYONLY2.
  4. Checkpointing: Spark can save intermediate data to reliable storage like ADLS or HDFS, reducing the need to recompute long transformation chains.

Example: If an executor crashes while processing a partition, Spark identifies the lost partition and recomputes it on another executor using lineage.

how to resolve data skewness?

Data skewness occurs when data is unevenly distributed across partitions, causing some Spark tasks to process significantly more data than others. This leads to stragglers and poor job performance.

I handle data skew using these techniques:

  1. Salting: Add a random key to skewed records to distribute them across multiple partitions, then aggregate again.
  2. Broadcast Join: If one table is small, broadcast it instead of performing a shuffle join.
  3. AQE (Adaptive Query Execution): Enable Spark's AQE to detect and optimize skewed joins automatically.
  4. Repartitioning: Redistribute data using appropriate partitioning keys.
  5. Skew-aware joins: Split heavily skewed keys and process them separately.

How to optimize data shuffling?

Data shuffling happens when Spark redistributes data across partitions, typically during joins, groupBy, distinct, and repartition operations. It involves network I/O and disk I/O, making it expensive.

I optimize shuffling using these techniques:

  1. Broadcast Joins: Broadcast smaller tables to avoid shuffling both datasets.
  2. Reduce Data Early: Apply filters and column pruning before joins and aggregations.
  3. Avoid Unnecessary Shuffles: Minimize repartition, distinct, and groupBy operations.
  4. Use AQE: Enable Adaptive Query Execution to optimize partition sizes and skewed joins.
  5. Optimize Partitioning: Choose appropriate partition counts and partitioning keys.
  6. Use Efficient Formats: Prefer Parquet or Delta to reduce data scanned and transferred.

Interview takeaway: I use Spark UI to identify shuffle read/write volume, spill to disk, and task duration, then optimize the operations responsible for excessive shuffling.

Explain MergeSchema vs OverwriteSchema

Overwriteschema - will delete existing schema, and use the new incoming schema only. May corrupt existing table. Older data remains recoverable through time travel.

MergeSchema - leads to schema evolution. Used when appending data to an existing location. Combines existing data with new data.

Type widening formats: link

Source type Supported wider types
BYTE SHORT, INT, BIGINT, DECIMAL, DOUBLE
SHORT INT, BIGINT, DECIMAL, DOUBLE
INT BIGINT, DECIMAL, DOUBLE
BIGINT DECIMAL
FLOAT DOUBLE
DECIMAL DECIMAL with greater precision and scale
DATE TIMESTAMP_NTZ
VOID Any type

Explain checkpointing - what does it do?

Checkpoint materializes the data and cuts off the lineage.
Persist caches the computed data but keeps the lineage.

Checkpoint is primarily about lineage truncation.

Explain Jobs, Stages, Tasks

Spark breaks your work into a three-level hierarchy: job → stages → tasks. Each level is defined by a different trigger.

Interview one-liner:

Job — created every time you call an action (count(), collect(), show(), write). Transformations like filter or select are lazy and create nothing until an action fires. One action usually means one job, though some actions spawn extra ones (e.g. schema inference on read.csv, or the sampling job behind sortBy).

Stage — Spark's DAG scheduler cuts each job into stages at shuffle boundaries. Narrow transformations (map, filter, withColumn) need no data movement, so they're pipelined together in one stage. Wide transformations (groupBy, join, repartition, distinct) need data redistributed across executors, which forces a new stage. So: number of stages ≈ number of shuffles + 1. Intermediate stages are ShuffleMapStages; the last one is the ResultStage.

Task — the actual unit of work sent to an executor core. Each stage runs one task per partition, all executing the same code on different slices of data. Stage 0's task count comes from your input partitions (e.g. file splits); after a shuffle it's spark.sql.shuffle.partitions (default 200, often coalesced by AQE).

Tasks in a stage run in parallel, but a stage after a shuffle waits for the previous stage to finish — which is why too few partitions underuse your cluster and skewed partitions create straggler tasks.

Explain parallelism when reading Parquet files

Read granularity is at row group level.

Consequences:

Why are UDFs slow?

Because of the serialization bottleneck

Moving data between jvm (spark) and python is very expensive

To run python code on data:

SOLUTION

Use arrow. Arrow memory format is readable by both jvm and python. So no serde is required.

Arrow is faster because arrow is column based, while pickling is row based. So arrow takes advantage of SIMD etc and gives a tremendous performance improvement.

spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")

Explain read modes in spark

There are 3 read modes

Mode Behavior
PERMISSIVE Reads valid records and handles malformed records by setting corrupt fields to null. Default mode.
DROPMALFORMED Drops malformed records entirely.
FAILFAST Throws an exception immediately when malformed data is encountered.

Explain write modes in spark

There are 4 write modes

Mode Behavior
error / errorifexists Default mode. Throws an exception if the destination already exists.
append Adds new records without modifying existing data.
overwrite Replaces existing data with new data.
ignore Skips writing if the destination already exists.

Explain reduceByKey vs groupByKey

groupByKey shuffles all values belonging to a key, whereas reduceByKey performs local aggregation before the shuffle, reducing network traffic and memory usage. Therefore, use reduceByKey when you can express the operation as an associative and commutative reduction.

reduceByKey performs a Map-side Combine.

groupByKey is a "brute force" operation.

- reduceByKey groupByKey
Shuffle data Less More
Map-side combine ✅ ❌
Memory usage Lower Higher
Requires aggregation function ✅ ❌
Typical use Aggregations Need all values

Pro Tip: In the DataFrame API, when you use df.groupBy("key").sum(), Spark is smart enough to use the reduceByKey logic under the hood. You don't have to worry about this choice unless you are working with the low-level RDD API.

Explain map vs flatmap

In PySpark, both map() and flatMap() are transformations used to process RDD elements.

Map

FlatMap

Spark optimization

How do you do performance optimization?

Overall strategy is:

  1. Enable AQE
  2. Optimize joins
  3. Reduce the amount of data being processed
  4. Use caching and buffering to re-use lineages
  5. Use better data serialization formats

Key optimization techniques:

  1. Reduce the amount of data being processed
    1. Predicate Pushdown: Filter data as early as possible to reduce the amount of data scanned.
    2. Column Pruning: Select only required columns instead of reading entire datasets.
  2. Optimize joins
    1. Broadcast Join: Broadcast smaller datasets to avoid expensive shuffle joins.
  3. Data Skew Handling: Use salting, AQE, or skew join optimization to distribute data evenly.
  4. Partitioning: Choose appropriate partition sizes and avoid excessive small partitions.
  5. Caching: Cache frequently reused DataFrames to avoid recomputation.
  6. AQE (Adaptive Query Execution): Dynamically optimize query execution based on runtime statistics.
  7. File Compaction: Use Delta OPTIMIZE to combine small files and reduce file-reading overhead.
  8. Avoid UDFs: Prefer built-in Spark SQL functions because they benefit from Catalyst optimization.
  9. Join Optimization: Filter datasets before joining and select appropriate join strategies.

Explain projection pruning, predicate pushdown

Cut down the data as much as possible before processing it.

The words come from relational algebra

Projection pruning

Reduce the number of columns read.
Spark does this automatically via catalyst optimizer. If a column isn't used in any calculation, then it is simply not even read.

Predicate pushdown

Reduce the number of rows read, by pushing filters as close to data source as possible. Also done automatically by catalyst.

Shows up in df.explain(True) as:

PushedFilters: [GreaterThan(salary,100000)]

Pushdown depends on the data source. It won't work when filters use:

How will you do join optimization

USE BUCKETING

Bucketing improves joins by pre-organizing data into buckets based on a join key, reducing or eliminating the need for a full shuffle during the join.

If the bucketed column is also the basis of the join, then the related rows are already within the same executor. This eliminates the need of a data shuffle.

FORCE BROADCAST JOIN

Using hint when the df is larger than autobroadcast threshold, but will still fit in memory.

from pyspark.sql.functions import broadcast

result = large_df.join(
    broadcast(small_df),
    "customer_id"
)

Cache and persist

Caching will cause AQE to fail.
Use it anyways when

AQE looks at statistics of data as it is written to shuffle files.

So it doesn't work well if data is cached, because the current state of the df is frozen. So AQE cannot optimize it.

Once data is cached, its execution plan in considered to be fixed. So AQE cannot modify it further.

AQE's effectiveness changes based on where data is stored. The shuffle data write has varying levels of AQE awareness:

WHAT TO DO?

Explain AQE - what does it do?

Is a runtime optmizer for batch optimization tool where data is large. Won't work for streaming pipelines.

Does 3 things:

AQE looks at statistics of data as it is written to shuffle files. It is a runtime shuffle-stage-boundary optimizer.

What it does

COALESCE SHUFFLE PARTITIONS

After a shuffle stage is completed, AQE looks at the partition sizes, and coalesces the partitions smaller than minPartitionNum to achieve target size specified in advisoryPartitionSizeInBytes

Variables are set in:

CHANGE JOIN STRATEGY

Looks at the sizes of data.

Uses variables in the scope spark.sql.adaptive

Note: AQE will ignore the preferSortMergeJoin setting, and go ahead with shuffle hash join when:

HANDLE SKEWED JOINS

AQE detects oversized shuffle partitions, splits them into smaller pieces, and replicates the matching data from the other side so the join work can run in parallel.
It doesn't use salting. It simply breaks down dataframes using split points directly on the dataframes.

Detects skew using variables in scope spark.sql.adaptive.skewJoin

A partition considered to be skewed when:

partition_size > median_partition_size × skewedPartitionFactor
AND
partition_size > skewedPartitionThresholdInBytes

Why is AQE better than static optimization?

AQE does runtime level-optimization. So it can deal with performance issues DURING the execution itself. So it handles problems as they occur, and we don't have to know them beforehand.

When does AQE not work?

So it doesn't work well if data is cached, because the current state of the df is frozen. So AQE cannot optimize it.

Once data is cached, its execution plan in considered to be fixed. So AQE cannot modify it further.

AQE's effectiveness changes based on where data is stored. The shuffle data write has varying levels of AQE awareness:

Doesn't work for:

How to find driver oom vs executor oom

Driver OOM symptoms:

Executor OOM:

How to do optimization in databricks?

How to detect data skews, and how to handle them

To detect skew

Solutions

Spark code

Implement SCD2 using merge

  1. If a customer is new, insert a new record.
  2. If an existing customer's attributes change, expire the old record.
  3. Insert the updated customer as a new current record.
  4. If nothing changes, do nothing.
from delta.tables import DeltaTable
from pyspark.sql.functions import current_timestamp, lit

target = DeltaTable.forName(spark, "gold.dim_customer")

source = source_df.withColumn(
    "effective_start_date", current_timestamp()
).withColumn(
    "effective_end_date", lit(None).cast("timestamp")
).withColumn(
    "is_current", lit(True)
)

# Step 1: Expire existing records when attributes change
target.alias("t").merge(
    source.alias("s"),
    "t.customer_id = s.customer_id AND t.is_current = true"
).whenMatchedUpdate(
    condition="t.customer_name <> s.customer_name OR t.city <> s.city",
    set={
        "is_current": "false",
        "effective_end_date": "s.effective_start_date"
    }
).execute()

# Step 2: Insert new records
target.alias("t").merge(
    source.alias("s"),
    "t.customer_id = s.customer_id AND t.is_current = true"
).whenNotMatchedInsert(
    values={
        "customer_id": "s.customer_id",
        "customer_name": "s.customer_name",
        "city": "s.city",
        "effective_start_date": "s.effective_start_date",
        "effective_end_date": "s.effective_end_date",
        "is_current": "s.is_current"
    }
).execute()

Read json with schema, flatten, explode, write to delta

{
  "customer_id": 101,
  "name": "John",
  "address": {
    "city": "Pune",
    "country": "India"
  },
  "orders": [
    {"order_id": 1, "amount": 500},
    {"order_id": 2, "amount": 1000}
  ]
}
from pyspark.sql.types import *
from pyspark.sql.functions import col, explode

# 1. Define schema
schema = StructType([
    StructField("customer_id", IntegerType()),
    StructField("name", StringType()),
    StructField("address", StructType([
        StructField("city", StringType()),
        StructField("country", StringType())
    ])),
    StructField("orders", ArrayType(
        StructType([
            StructField("order_id", IntegerType()),
            StructField("amount", DoubleType())
        ])
    ))
])

# 2. Read JSON
df = (
    spark.read
    .schema(schema)
    .json("/data/customers/")
)

# 3. Flatten nested structures and explode array
result_df = df.select(
    col("customer_id"),
    col("name"),
    col("address.city").alias("city"),
    col("address.country").alias("country"),
    explode(col("orders")).alias("order")
).select(
    "customer_id",
    "name",
    "city",
    "country",
    col("order.order_id").alias("order_id"),
    col("order.amount").alias("amount")
)

# 4. Write to Delta table
(
    result_df.write
    .format("delta")
    .mode("overwrite")
    .saveAsTable("gold.customer_orders")
)

How will you deduplicate rows?

# all cols
fully_unique_rows_df = df.distinct()
# specific cols
unique_names_df = df.dropDuplicates(subset=["name", "surname"])

How will you handle nulls?

. Check for nulls

df.filter(col("age").isNull())df.filter(col("age").isNotNull())

2. Replace nulls

df.fillna({"age": 0, "name": "Unknown"})

3. Drop null records

df.dropna(subset=["customer_id"])

4. Use the first non-null value

df.withColumn(    "phone",    coalesce(col("mobile"), col("home_phone")))

5. Conditional handling

df.withColumn(    "status",    when(col("status").isNull(), "UNKNOWN")    .otherwise(col("status")))

6. Null-safe joins

df1.join(df2, df1.id.eqNullSafe(df2.id))

Data engineering - general

How'll you do incremental load?

I implement incremental loading by processing only new or modified records instead of reprocessing the entire dataset.

My approach:

  1. Identify changes: Use a watermark column such as updated_at, CDC, or Delta Change Data Feed.
  2. Store the watermark: Maintain the last successful processing timestamp in a control table.
  3. Extract incrementally: Read records where updated_at is greater than the previous watermark.
  4. Process changes: Apply transformations, deduplication, and data quality checks.
  5. Upsert: Use Delta Lake MERGE to insert new records and update existing ones.
  6. Update watermark: Advance it only after successful processing.

Then use Delta MERGE to upsert the records.

Production considerations: Handle late-arriving data using a lookback window, make processing idempotent, and update watermarks only after successful commits.

last_watermark = get_watermark("customers")

incremental_df = (
    spark.read.format("jdbc")
    .option("query", f"""
        SELECT * FROM customers
        WHERE updated_at > '{last_watermark}'
    """)
    .load()
)

How to debug long running spark jobs?

I debug long-running Spark jobs primarily using Spark UI and execution metrics.

I first identify the slowest stage, investigate task-level metrics, determine the bottleneck, and then optimize the underlying operation rather than blindly increasing cluster resources.

My approach:

  1. Spark UI – Jobs & Stages: Identify which stage is taking the most time and whether tasks are stuck.
  2. Task Analysis: Compare task execution times, input sizes, and shuffle read/write to identify data skew.
  3. Shuffle & Spill: Check whether excessive shuffling or memory spills are causing performance issues.
  4. Executor Metrics: Monitor CPU utilization, memory usage, GC time, and executor failures.
  5. Query Plan: Use explain("formatted") to inspect the physical execution plan.
  6. Data Skew: Look for a few tasks taking significantly longer than others.
  7. Optimization: Apply broadcast joins, repartitioning, AQE, predicate pushdown, and caching where appropriate.

Explain SCD 1 2 3 4 6

SCD (Slowly Changing Dimensions) techniques are used in data warehousing to manage changes in dimension attributes over time.

Type Description Historical data
SCD 1 Overwrite existing record with new values. Not maintained
SCD 2 Insert a new row for every change, maintaining effective dates and current flag. Full history
SCD 3 Maintain current and previous values in separate columns. Limited history
SCD 4 Keep current data in one table and historical records in a separate history table. Full history
SCD 6 Hybrid of SCD 1, 2, and 3. Maintains full history plus current and previous values. Full history

Example: Customer changes city from Pune to Mumbai

SCD 1 – Overwrite

Customer City
101 Mumbai

SCD 2 – New row

Customer City Start Date End Date Current
101 Pune Jan 2024 Mar 2025 No
101 Mumbai Mar 2025 NULL Yes

SCD 3 – Previous value column

Customer Current City Previous City
101 Mumbai Pune

SCD 4 – Separate history table

SCD 6 – Hybrid

Combines:

When would I use each?

Interview takeaway: SCD Type 2 is the most commonly used approach in enterprise data warehouses because it preserves complete historical changes and supports point-in-time reporting.

Explain file formats and their advantages - parquet, orc, avro

Parquet

Parquet is a columnar storage format, optimized for analytical workloads (OLAP).

Advantages:

ORC (Optimized Row Columnar)

ORC is also a columnar storage format, designed primarily for efficient analytical processing in the Hadoop ecosystem.

Advantages:

Avro
Avro is a row-based storage format, designed for serialization and data exchange.

Advantages:

Databricks - data quality

How will you ensure data quality in databricks?

I ensure data quality in Databricks through multiple layers of validation across the data pipeline, following a Bronze, Silver, and Gold architecture.

  1. Schema Validation: Define explicit schemas and enforce schema evolution rules using Delta Lake.
  2. Data Completeness: Check for null values, missing records, and mandatory columns.
  3. Uniqueness: Identify duplicate records using business keys.
  4. Referential Integrity: Validate foreign keys against dimension or master tables.
  5. Business Rules: Implement domain-specific validations using PySpark or SQL.
  6. Delta Live Tables Expectations: Define constraints to retain, drop, or fail on invalid records.
  7. Data Reconciliation: Compare source and target record counts and aggregate values.
  8. Monitoring: Track quality metrics, failed records, and anomalies using Databricks Workflows and alerts.
from pyspark.sql.functions import col

valid_df = df.filter(
    col("customer_id").isNotNull() &
    col("amount").isNotNull() &
    (col("amount") >= 0)
)

invalid_df = df.subtract(valid_df)

Bronze layer – Validate ingestion

At this stage, I focus on ensuring that the data has been ingested correctly.

Silver layer – Enforce data quality rules

This is where I implement most of my data quality checks.

I validate different dimensions of data quality:

Dimension Example
Completeness Customer ID should not be NULL
Uniqueness Transaction ID should be unique
Validity Transaction amount must be positive
Consistency Start date must be before end date
Referential integrity Every transaction must reference an existing customer
Accuracy Reconcile totals against the source system
Timeliness Data should arrive within the expected SLA

Implemented using:

Gold layer – Validate business-level correctness

At this stage, I focus on ensuring that the data is correct from a business perspective.

For example:

How would you monitor data quality in production?

I would establish a centralized data quality monitoring mechanism.

For every validation rule, I would capture:

I would store these metrics in a Delta table and expose them through Databricks SQL dashboards.

Requirement Databricks solution
Schema enforcement Delta Lake
Table-level constraints Delta constraints
Pipeline validation Lakeflow expectations
Complex business rules PySpark
Invalid record handling Quarantine Delta tables
Data profiling Unity Catalog Data Quality Monitoring
Freshness/completeness anomalies Unity Catalog monitoring
Lineage and traceability Unity Catalog
Reporting and alerting Databricks SQL dashboards and alerts

I would also consider DQX or Great Expectations if the organization needs a reusable data quality framework across multiple pipelines.

How would you implement referential integrity checks efficiently on large Delta tables?

I would implement referential integrity checks using anti-joins, but I would pay particular attention to the volume of data being scanned, join strategy, and whether the validation is incremental or full-table.

For optimization, validate only incremental records. If 100k records were inserted today, will check up those records only.

How would you implement a reusable data quality framework across 100 Databricks tables?

I would build a metadata-driven framework with a registry of reusable validators, centralized rule configuration, standardized validation results, and Databricks Workflows for orchestration.

This would allow us to manage data quality across hundreds of tables without duplicating validation logic in individual pipelines.

I'll define a metadata driven rule configuration

I would maintain a configuration table containing the rules for each dataset.

This allows us to add or modify validation rules without changing the execution engine.

Eg - main.metadata.data_quality_rules

table_name rule_name rule_type column_name severity
customers customeridnot_null NOT_NULL customer_id CRITICAL
customers emailnotnull NOT_NULL email HIGH
customers valid_age RANGE age MEDIUM
transactions amount_positive EXPRESSION amount CRITICAL
transactions transaction_unique UNIQUE transaction_id CRITICAL

I would implement individual validators and register them with a common execution engine.

from pyspark.sql import functions as F

class DataQualityValidator:

    @staticmethod
    def not_null(df, column):
        return F.col(column).isNotNull()

    @staticmethod
    def positive(df, column):
        return F.col(column) > 0

    @staticmethod
    def valid_range(df, column, minimum, maximum):
        return F.col(column).between(
            minimum, maximum
        )


VALIDATORS = {
    "NOT_NULL": DataQualityValidator.not_null,
    "POSITIVE": DataQualityValidator.positive,
}


def execute_rule(df, rule):
    validator = VALIDATORS[rule["rule_type"]]

    condition = validator(
        df,
        rule["column_name"]
    )
    return df.filter(~condition)

I would standardize the output of every validator.

main.monitoring.data_quality_results

Eg:

Field Description
run_id Unique execution identifier
table_name Validated table
rule_id Validation rule
total_records Records evaluated
failed_records Records violating the rule
passed_records Records passing
failure_percentage Percentage failed
executiontimems Execution duration
status PASS / FAIL
executed_at Execution timestamp

For production, I would not necessarily execute all 100 tables sequentially in one Spark driver process.

I would use Databricks Workflows to orchestrate independent table validations, with controlled concurrency and separate tasks for high-volume datasets.

I would also group rules that can be evaluated in the same Spark aggregation to avoid repeatedly scanning the same table.

Why this architecture?
It provides several advantages:

  1. Reusability: Common validation logic is implemented once.
  2. Consistency: All tables follow the same validation conventions.
  3. Extensibility: New rules can be added through configuration.
  4. Observability: All validation results are stored centrally.
  5. Maintainability: Business logic and validation infrastructure remain separate.
  6. Scalability: Different tables can be validated independently.

How would you ensure data quality checks don't significantly increase Spark job execution time?

My approach would be to treat data quality validation as part of the performance engineering of the pipeline.

I would focus on minimizing additional data scans and making validation incremental wherever possible.

Separate lightweight and expensive checks

Check Frequency
NOT NULL Every batch
Data type / schema Every batch
Basic range validation Every batch
Duplicate detection Every batch or incremental state-aware check
Referential integrity Every batch against an appropriate reference snapshot
Statistical profiling Periodically
Full historical reconciliation Daily / weekly
Deep distribution drift analysis Periodically or on anomaly

What interviewers are really evaluating

Across these three questions, I would make sure to communicate these engineering principles:

Area Senior-level consideration
Referential integrity Incremental validation, anti-joins, late-arriving dimensions
Reusable framework Metadata-driven rules, extensibility, centralized metrics
Performance Minimize scans, shuffles, and repeated Spark actions
Reliability Idempotency, quarantine, retries, auditability
Operations Monitoring, alerting, ownership, SLAs

Databricks - cicd

Explain how to package and deploy pipelines

Use declarative automation bundles. Deployed via ci-cd

(Previously was called databricks asset bundles)

File organization looks like:


my-databricks-project/
│
├── databricks.yml                 # Main bundle configuration
├── pyproject.toml                 # Python dependencies and packaging
├── README.md
├── .gitignore
│
├── resources/                     # Databricks resource definitions
│   ├── jobs/
│   │   ├── ingestion.job.yml
│   │   ├── transformation.job.yml
│   │   └── data_quality.job.yml
│   │
│   ├── pipelines/
│   │   ├── bronze.pipeline.yml
│   │   └── silver.pipeline.yml
│   │
│   └── permissions.yml            # Optional shared configuration
│
├── src/                           # Actual application code
│   ├── ingestion/
│   │   ├── __init__.py
│   │   └── main.py
│   │
│   ├── transformations/
│   │   ├── __init__.py
│   │   ├── customers.py
│   │   └── orders.py
│   │
│   ├── data_quality/
│   │   ├── __init__.py
│   │   ├── expectations.py
│   │   └── validators.py
│   │
│   └── common/
│       ├── __init__.py
│       ├── config.py
│       └── logging.py
│
├── tests/
│   ├── unit/
│   │   ├── test_customers.py
│   │   └── test_validators.py
│   │
│   └── integration/
│       └── test_pipeline.py
│
└── notebooks/                     # Optional development notebooks
    └── exploration.ipynb

Sql theory

What are the key types

What is SQL's clause execution order

  1. FROM, JOIN, ON - Take in all source tables. Join them to create a single large table.
  2. WHERE - Filter the large combined table to remove unnecessary rows.
  3. GROUP BY
  4. HAVING
  5. Window functions, SELECT, distinct() - Select required columns from the table. Apply window functions if required.
  6. ORDER BY
  7. LIMIT
  8. Return the data as result.

Explain the various null interactions with joins, sort, group by, aggregates

Explain normal vs materialized views

Normal View (Virtual View)

Materialized View

Data Modelling

How to approach?

List:

Then model using snowflake to star

Python

Explain lists vs sets vs tuple

Explain deep vs shallow copy

In Python, shallow copy and deep copy differ in how they handle nested objects.

Shallow vs deep copy matters primarily for mutable objects containing other objects, such as lists, dictionaries, and sets containing mutable elements.

Shallow Copy

Deep Copy

Explain decorators in python

A decorator in Python is a function that modifies or extends the behavior of another function without changing its original implementation.

The decorator wraps the original function and adds additional behavior.

Common use cases:

Decorators use Python's first-class functions and closures.

def my_decorator(func):
    def wrapper():
        print("Before function execution")
        func()
        print("After function execution")
    return wrapper

@my_decorator
def hello():
    print("Hello!")

hello()

# Before function execution
# Hello!
# After function execution

Decorator is a syntatic sugar for:

hello = my_decorator(hello)

Explain iterators in python

Iterators enable lazy, sequential data processing without loading the entire collection into memory.

An iterator implements two methods:

Iterator vs Iterable:

Why are iterators useful?

Explain return vs yeild

In Python, return and yield both produce values from a function, but they behave differently.

Return

def get_numbers():
    return [1, 2, 3]

result = get_numbers()

Yield

def get_numbers():
    yield 1
    yield 2
    yield 3

for num in get_numbers():
    print(num)
Colophon 8509 words · 43m read
Written as a markdown note in Obsidian. Built into this page by a Python script on 2026-11-15.

Pages