/

/

Diagnosing and optimizing batch ETL workloads in Azure Databricks

Diagnosing and optimizing batch ETL workloads in Azure Databricks

Author

Executive summary

As data volumes, users, and AI workloads grow, Azure Databricks pipelines must deliver predictable performance without allowing compute costs to rise unchecked. When a workload slows, however, the visible delay rarely identifies the cause. Excessive scans, shuffle, skew, CPU pressure, inefficient MERGE operations, application logic, and capacity waits can produce similar symptoms while requiring different fixes.

This white paper presents a method grounded in execution evidence for diagnosing and optimizing batch ETL workloads in Azure Databricks. Its goal is to help data engineers replace trial-and-error tuning with a repeatable workflow that connects execution evidence to a specific bottleneck, tests one focused change, and validates the result across runtime, resource use, downstream impact, and cost.

The paper moves from baseline measurement and execution triage to targeted remedies for scan, shuffle, skew, CPU, write, and application bottlenecks. It then shows how to demonstrate improvements in performance relative to cost through a worked investigation, a decision matrix, review checklists, and reusable SQL templates.

By the end of the white paper, readers will be able to achieve five practical outcomes.

  1. Build a comparable baseline that captures runtime, waiting, input, data movement, resource pressure, and cost.

  2. Use Query Profile, Spark UI, query history, and Delta table metadata to identify the dominant bottleneck.

  3. Select a focused optimization that addresses the measured cause rather than the visible symptom.

  4. Run a controlled test that compares performance before and after a change and verify that the predicted metric moved.

  5. Decide whether to keep, revert, or extend the change based on correctness, downstream effects, and performance relative to cost.

The result is a practical engineering discipline for explaining why a workload is slow, applying the right intervention, and demonstrating that the improvement is real and repeatable.

Diagnose the cause before choosing the fix

Consider a daily pipeline that has slowed over time. Teams often respond by adding workers, choosing a larger instance, or increasing the SQL warehouse size. The next run finishes sooner, so the team declares success and moves on.

But the team still does not know why the workload slowed down. The following examples show why the same visible delay can point to different underlying constraints.

  • If the workload reads far more data than the business request needed, more compute may have reduced runtime without fixing the data access problem.

  • If one join key was heavily skewed, extra workers may have left the slowest partition almost untouched.

  • If the query was waiting for capacity, a resize may have been the right answer.

  • If the Python UDF logic is unsupported by Photon logic and kept the job CPU-bound, the resize may have been an expensive workaround.

In each case, the run got faster, but the workload is still not understood. The practical goal is to explain why the workload is slow, choose a change that addresses that cause, and prove that the change improved the right parts of performance.

Use the following loop for every meaningful optimization:

  • Establish a baseline by measuring the current workload and capturing its performance.

  • Diagnose the bottleneck by identifying the operator or system symptom with the greatest impact. Then classify the issue as scan, shuffle, skew, CPU, spill, write, code, waiting, or cost.

  • Test a hypothesis by stating it in one sentence and changing one meaningful variable.

  • Validate the results by rerunning the same or a representative workload under comparable conditions. Compare runtime, data movement, resource pressure, and cost.

  • Decide the next step based on the evidence. Keep or revert the change, or continue investigating.

Figure 1: A simplified workflow for diagnosing and validating performance improvements
Figure 1: A simplified workflow for diagnosing and validating performance improvements

2. What to measure before changing anything

That loop starts with a useful baseline. Keep it small enough to collect every time, but broad enough to prevent tunnel vision. Runtime alone is not enough, so begin with the following measures that explain where time and money are spent.

  • Capture execution time and waiting time.

  • Capture input bytes and the number of files that were read or pruned.

  • Capture shuffle, spill, and the spread of task durations.

  • Capture a cost measure such as DBUs.

The table below connects each baseline metric to the question it answers and the Azure Databricks interface or system table where engineers can inspect it.


Metric

Why it matters

Where to inspect

Elapsed runtime

Shows how quickly users receive results and whether the workload meets its service level agreement.

Job run, Query Profile, notebook or query history

Execution vs waiting duration

Separates execution work from capacity or scheduling delays.

system.query.history

Read bytes

Shows how much data entered the plan.

Query Profile, query history

Files read or pruned

Shows whether file pruning and layout are effective.

Query Profile, query history, table metadata

Shuffle reads and writes

Identifies joins, aggregations, repartitions and exchanges.

Spark UI, Query Profile, query history

Spill bytes

Signals memory pressure during execution.

Spark UI, query history where available

Variation in task duration

Reveals skew and partitions that take much longer to finish.

Spark UI

CPU and task time

Distinguishes logic that uses substantial CPU resources from work that involves substantial input and output.

Spark UI, Query Profile

DBUs or another cost measure

Measures performance relative to cost rather than speed alone.

system.billing.usage

2.1 Establish a comparable baseline

Once you know what to capture, make sure the comparison is fair. Record the information that can change the result.

  • Use comparable data and record the input data range and the relevant table versions. Compare the same business period or a representative data slice. A small recent input and a much larger historical input cannot show whether an optimization worked.

  • Record the compute configuration by noting the cluster or warehouse configuration and the runtime version. Keep compute configuration unchanged while testing a query or code change unless compute sizing is the hypothesis.

  • Record the query parameters and cache use by noting the parameters and whether the result came from cache. Avoid comparing a cached result with a cold run.

  • Record capacity conditions by noting concurrency and queueing conditions when capacity is part of the investigation.

  • Control changes by changing one major variable at a time.

Use the template below to record your baseline and compare the results after a change. Copy it into an engineering repository, notebook, pull request, or optimization review.

Complete the workload and configuration fields before testing a change, then record the baseline metrics and their sources in the Before column. After the rerun, fill in the After and Delta columns and document the hypothesis, the single change, the result, and the decision to keep, revert, or continue.

## Workload Optimization Baseline
 
Workload name:
Business SLA:
Run ID / Statement ID:
Date/time:
Compute type:
Runtime / warehouse size:
Input tables:
 
| Metric | Before | After | Delta | Source |
| --- | ---: | ---: | ---: | --- |
| Wall-clock runtime | | | | |
| Execution duration | | | | |
| Waiting duration | | | | |
| Read bytes | | | | |
| Read files | | | | |
| Pruned files | | | | |
| Shuffle read bytes | | | | |
| Spill bytes | | | | |
| Peak memory | | | | |
| DBUs / cost proxy | | | | |
 
Hypothesis:
One change made:
Result:
Keep / revert / continue:

2.2 Use query history as the longitudinal view

A single run gives you only part of the story. Query Profile and Spark UI are excellent for understanding one execution, while query history helps you compare repeated runs, spot regressions, and separate execution time from time spent waiting for compute. System tables can then connect that workload behavior to cost.

Use the query below to populate the execution metrics in your baseline record. It returns the 50 completed statements with the longest total duration over the past seven days. Adjust the time filter and result limit, then select the statements relevant to your workload before comparing runs.

SELECT
workspace_id,
statement_id,
start_time,
executed_by,
client_application,
compute.type AS compute_type,
compute.warehouse_id,
total_duration_ms,
waiting_for_compute_duration_ms,
waiting_at_capacity_duration_ms,
execution_duration_ms,
compilation_duration_ms,
read_bytes,
read_files,
pruned_files,
shuffle_read_bytes,
spilled_local_bytes,
produced_rows,
from_result_cache
FROM system.query.history
WHERE start_time >= current_timestamp() - INTERVAL 7 DAYS
AND execution_status = 'FINISHED'
ORDER BY total_duration_ms DESC
LIMIT 50;


Use the columns available in your workspace and runtime because system table schemas can change. Compare execution time, waiting time, input and output, shuffle, spill and cache behavior together. Do not use one field as the final verdict. Once you have a fair baseline and enough history, open the execution evidence and find where the workload spends its time. On serverless compute, DataFrame (df) cache is not currently supported. Also, the driver itself can sometimes fall behind, and driver cluster sizing can cause slowness in the job.

Note: On classic compute, use Spark UI, task run details, and available logs. On serverless notebooks and jobs, use Query Profile and run details: Spark UI is unavailable, and DataFrame cache/persist and SQL cache APIs are unsupported. If system.query.history is inaccessible or does not cover the workload, collect the baseline from the applicable UI and run metadata.

3. Read Query Profile and Spark UI as a triage board

Use Query Profile and Spark UI to locate the main constraint on execution’s main time or resource constraint, then review the relevant SQL to investigate its cause. Fig 2.1 and Fig 2.2 show this analysis on traditional compute, while Fig 3.1 and Fig 3.2 show it on serverless compute.

Follow this diagnostic sequence to narrow the investigation.

  • Data access and movement: Start with the scan. Then inspect shuffle and skew.

  • CPU and execution path: Next, check CPU use and the execution path.

  • Waiting versus execution: Finally, separate waiting time from execution time.

Option1: Analyzing from traditional compute - Spark UI


Figure 2.1 and 2.2: Identifying the long running job group and understanding the DAG which explains there is shuffling during joining.
Figure 2.1 and 2.2: Identifying the long running job group and understanding the DAG which explains there is shuffling during joining.


Option 2: Using Serverless compute and viewing performance


Figure 3.1 and 3.2: Same metrics in spark UI, indicating high shuffle on join.
Figure 3.1 and 3.2: Same metrics in spark UI, indicating high shuffle on join.

Follow these five diagnostic areas in order, stopping when evidence identifies the strongest constraint.

  1. Scan operators and excessive data access: A scan deserves immediate attention when it reads a large amount of data for a small business request. Check read bytes, files read, files pruned and filter predicates. A selective SQL filter does not guarantee a selective physical read. The table layout must let the engine skip irrelevant files.

  2. Exchange operators and shuffle: Shuffle moves data between tasks. Joins, aggregations, window functions, distinct operations and explicit repartitioning can create that movement. A large shuffle is not always a problem. Investigate it when it dominates execution time, causes spill or moves far more data than the business logic needs.

  3. Task distribution and partition skew: Average task time can hide skew. Use the Spark UI to compare task duration and input and output size. If most tasks finish quickly while a few run much longer, a skewed key or partition may be holding up the stage. The stage cannot finish until the slowest task completes.

  4. CPU utilization and Photon execution: High task time with normal input and shuffle can point to expensive expressions or an execution path that cannot use the native vectorized engine. Photon can speed up eligible SQL and DataFrame work, including scans, joins, aggregations and writes. It does not support every Spark API or UDF path. Do not expect Photon to fix application logic that blocks efficient native execution.

  5. Waiting time versus execution time: A healthy execution plan can still feel slow when the workload waits for capacity. This often matters on shared SQL warehouses and busy job compute. If waiting takes up a significant share of the total time, changing the SQL may not reduce the delay users see. (refer Fig 3.5.1)





Figure 4: Image showing total run time for a job run, but the job was waiting for resources to be executed.

4. Investigate the five primary execution bottlenecks

The baseline tells you what changed, and the profile tells you where to look. Use the workflow in Section 1 to test the remedy that matches the dominant symptom.

The rest of the diagnosis focuses on five primary execution bottlenecks. These cover excessive scans, shuffle and skew, CPU-intensive work, inefficient MERGE behavior, and unnecessary application work. Waiting time and price-performance are assessed separately because they can affect the result even when the execution plan itself is healthy.

Figure 5: Five primary execution bottlenecks that can slow an Azure Databricks workload
Figure 5: Five primary execution bottlenecks that can slow an Azure Databricks workload

4.1 Bottleneck 1: The workload scans too much data

If the scan is the dominant bottleneck, reduce the data entering the plan before tuning downstream operators. The application may ask for a narrow slice, but the physical table can still force the engine to inspect a large share of the data.

You will usually see the following signs:

  • Scan volume and impact: Read bytes are much larger than the expected business slice. A scan operator dominates the profile.

  • File pruning: A large number of files are read with relatively weak pruning.

  • Downstream row volume: Downstream operators receive far more rows than they need.

These signs point to excessive scanning but do not explain its cause. To investigate why the workload reads more data than it needs, check the following areas in order.

  • Filter selectivity and statistics: Start by assessing how selective the filter predicates are and reviewing the availability of useful table statistics.

  • Physical layout: Compare the physical layout with the filters the workload uses most often.

  • Small files: Look for an accumulation of small files in the table.

  • Partitioning: Examine whether partitioning creates too many directories or prevents effective pruning.

  • Liquid clustering: Consider whether liquid clustering would better support high cardinality or changing access patterns.

4.1.1 Statistics and data skipping

Statistics help the engine understand the data and make better planning and file-level decisions. Missing or outdated statistics leave the optimizer with less useful information. Before you change the application, check the table statistics and metadata.

Use the commands below to compute Delta statistics for the table you are investigating.

COMPUTE DELTA STATISTICS refreshes per-file statistics in the Delta log for configured columns. It does not collect normal optimizer statistics. State Databricks Runtime 14.3 LTS or later for this command. Use COMPUTE STATISTICS for optimizer statistics, adding FOR COLUMNS when column estimates are needed.

-- Refresh file-skipping statistics for configured columns
ANALYZE TABLE catalog.schema.table_name
COMPUTE DELTA STATISTICS;
-- Refresh optimizer table and relevant column statistics
ANALYZE TABLE catalog.schema.table_name
COMPUTE STATISTICS FOR COLUMNS customer_id, event_date;


Use statistics as part of a broader layout strategy, not as a substitute for one. Statistics cannot make an inherently poorly organized table behave like a well-clustered one.

4.1.2 Liquid clustering

Liquid clustering can help when filter columns have high cardinality, query patterns change, data is skewed, the table grows quickly or traditional partitioning lacks a stable key. For new tables, automatic clustering can reduce the need to predict one permanent partitioning strategy.

Choose the creation statement below for a new table or one of the alteration statements for an existing table rather than running all three in sequence. Replace the table and column names, and choose automatic clustering or explicit columns based on the workload’s access patterns. The creation statement can replace an existing table, so confirm the target name before running it. The final commands optimize the table and let you inspect its details and properties.

-- New Unity Catalog managed Delta table; DBR 15.4 LTS+
-- Requires predictive optimization for automatic key selection
CREATE TABLE catalog.schema.new_table
USING DELTA CLUSTER BY AUTO
AS SELECT * FROM catalog.schema.source_table;
-- Alternative: existing unpartitioned eligible managed table
ALTER TABLE catalog.schema.table_name CLUSTER BY AUTO;
-- Alternative: explicit keys on an unpartitioned Delta table
ALTER TABLE catalog.schema.table_name
CLUSTER BY (customer_id, event_date);
-- Routine incremental layout maintenance when needed
OPTIMIZE catalog.schema.table_name;
-- Optional full reclustering; DBR 16.0+, after assessing cost
-- OPTIMIZE catalog.schema.table_name FULL;


Do not choose clustering columns simply because they appear often. Choose them because workload evidence shows that they support real access patterns. Use Query Profile and workload history to find the predicates that repeatedly determine which data the engine needs.

4.1.3 Small-file fragmentation

Small files create work before the engine can do useful computation. They increase file metadata work, create more task scheduling and file opens, and weaken scan efficiency. They often build up slowly when frequent incremental writes fragment the table. Unity Catalog managed tables can receive automatic file-size tuning, and predictive optimization can automate table maintenance for eligible managed tables. Section 8 illustrates how to test a table layout change and compare its effects on scanning, runtime, and a DBU-based cost proxy.

Inspect table details and history before deciding whether compaction is necessary. Section 6 provides the inspection commands and explains how to interpret this evidence.

4.2 Bottleneck 2: The workload shuffles too much data or suffers from skew

If scan volume looks reasonable, the next place to look is data movement. Shuffle is where a logically simple ETL pipeline can become physically expensive because rows with the same join or aggregation key must reach the same task. That movement consumes network, CPU, memory, and disk when spilling occurs.

You will usually see the following signs:

  • Shuffle read/write is large compared with the useful input.

  • Join, aggregate, window, or exchange stages dominate the profile.

  • The workload spills heavily.

  • One or a few tasks are dramatically slower than the rest.

4.2.1 Reduce data before the join

The simplest way to reduce shuffle is often to reduce the data that enters it. Filter as early as the logic allows and select only the columns the pipeline needs. Wide rows make every later movement more expensive.

The example below applies a date filter to the fact table and selects only the required columns from both tables before joining them on business_key. Replace the table and column names and adjust the date filter to match your workload.

SELECT
f.business_key,
f.event_date,
f.metric_value,
d.category
FROM (
SELECT business_key, event_date, metric_value
FROM catalog.schema.fact_table
WHERE event_date >= DATE '2026-08-01'
) f
JOIN (
SELECT business_key, category
FROM catalog.schema.dimension_table
) d
ON f.business_key = d.business_key;
 


If AQE does not choose a broadcast join because the estimated input size exceeds the configured threshold, you can consider increasing spark.sql.adaptive.autoBroadcastJoinThreshold. Set it only after confirming that the table can safely fit in memory on each executor. AQE can then use a broadcast join when runtime statistics show that the input is within the threshold. Check the resulting plan and executor memory pressure to validate the change.

The exact rewrite depends on the query plan and optimizer behavior. The principle is simple: do not move rows or columns that the rest of the pipeline does not need.

4.2.2 Broadcast joins for eligible small inputs

If one side of a join is small enough and the workload supports it, broadcasting can avoid a large shuffle. Use a broadcast hint only when you have evidence that the smaller table is stable and fits in memory.

The example below applies a broadcast hint to the dimension table, aliased as d, when joining it to filtered_fact on business_key. Replace the table and column names to match your workload, and use the hint only when the smaller table is stable and fits in memory.

SELECT /*+ BROADCAST(d) */
f.business_key,
f.event_date,
d.category
FROM filtered_fact f
JOIN dimension d
ON f.business_key = d.business_key;


The validation question is simple: did shuffle volume and join time decrease without creating memory pressure? A broadcast that causes executor memory problems is not an optimization.

4.2.3 Adaptive Query Execution

Adaptive Query Execution uses runtime information to improve the plan. It can change join strategies and address some skew patterns. Before you force partitioning or join behavior, check whether adaptive execution is available and whether it already addresses the problem.

4.2.4 Skew and long-tail tasks

A reasonable average task time can hide skew in a join. When one partition holds far more rows than the others, it creates a long tail that the average does not reveal. To identify this imbalance, examine the longest task, task input sizes, and the full distribution of task durations rather than relying on stage averages.

If these comparisons reveal skew, investigate its cause before choosing a remedy. A default value, a popular customer or a field with few distinct values can create uneven partitions. Adaptive Query Execution may help address the imbalance. Use salting only after the evidence proves that skew is the main bottleneck, because salting adds complexity.

4.2.5 Avoid unnecessary shuffle

Review explicit repartitioning, unnecessary distinct operations, repeated aggregations, and window functions. Developers sometimes add repartition calls to create more parallel work without checking whether the new exchange costs more than it saves.

If the Spark UI shows a large exchange immediately before a stage, ask what business requirement forced the data to move. If there is no good answer, test the plan without that exchange.

4.3 Bottleneck 3: CPU-intensive work slows execution

When reads and shuffle both look reasonable, move to computation. A workload can still be slow because expensive expressions, parsing, serialization, or UDF execution keep task time high.

You will usually see the following signs:

  • High task time despite moderate input and shuffle.

  • Expensive JSON, string, regex, or parsing operations.

  • Python or other UDFs in hot parts of the plan.

  • Repeated transformations that could be expressed with native SQL/DataFrame functions.

The following sections explain how to reduce this CPU work.

4.3.1 Prefer built-in functions

Built-in SQL and DataFrame functions give the engine more room to optimize and run work natively. Higher-order functions can often replace custom UDF logic for arrays, maps, and nested structures. The example below uses transform and upper to convert each string in the attributes array to uppercase without a custom UDF. Replace the table and column names to match your data.

-- Prefer native expressions where possible
SELECT
business_key,
transform(attributes, x -> upper(x)) AS normalized_attributes
FROM source_table;


Choose the function that matches the transformation. The principle is simple: express the work in a form the engine can understand and optimize instead of forcing custom row-by-row execution.

4.3.2 Photon eligibility and native execution

Photon can speed up eligible SQL and DataFrame workloads through native vectorized execution. It can help with scans, joins, aggregations, writes, and high concurrency analytics. Unsupported APIs, UDFs, and RDD-based code can limit that benefit.

Ask whether the workload can use efficient native execution and whether that execution is actually happening. Do not stop at asking whether Photon is enabled.

4.3.3 Precompute reused expensive expressions

If the same expensive parsing or normalization logic is repeated across many downstream queries, consider materializing the derived value at an appropriate stage. This trades additional storage and write work for less repeated CPU computation.

Measure the total pipeline, not just the query that becomes faster. That whole-pipeline view matters even more when the workload writes results, because the next bottleneck may appear in MERGE rather than in the transformation itself.

4.4 Bottleneck 4: MERGE scans or rewrites too much data

The bottleneck can also move from reading and computation to writing. Incremental pipelines often process a small source dataset but still force a MERGE to inspect or rewrite a large part of the target table.

You will usually see the following signs:

  • MERGE duration grows faster than source volume.

  • Target read bytes are much larger than expected.

  • Many files are rewritten.

  • Frequent updates produce small files.

  • Downstream reads become slower after repeated incremental writes.

The following sections explain how to reduce MERGE work and validate its impact on the whole pipeline.

4.4.1 Constrain the target search space

The MERGE match condition defines the business logic and determines which target rows can match source rows. Valid constraints can reduce the target data scanned, but a row-dependent condition such as t.event_date >= s.min_event_date does not by itself guarantee target-file pruning.

When the business rules support it, a proven batch-wide date bound can help limit the target search. Dynamic file pruning for MERGE requires Photon-enabled compute; verify the actual scan metrics to confirm whether the expected pruning occurs.

-- Assumes every existing match is dated on or after this bound.
-- Prepare the source so each target row matches at most one source row.
 
MERGE INTO catalog.schema.target AS t
USING catalog.schema.source_changes AS s
ON t.business_key = s.business_key
AND t.event_date >= DATE '2026-08-01'
 
WHEN MATCHED THEN UPDATE SET
t.event_date = s.event_date,
t.metric_value = s.metric_value
 
WHEN NOT MATCHED THEN
INSERT (business_key, event_date, metric_value)
VALUES (s.business_key, s.event_date, s.metric_value);


Use explicit column assignments so source helper fields, such as min_event_date, are not unintentionally included in updates or schema-evolution paths.

Only add constraints that are logically correct. An overly aggressive predicate can make a correct MERGE incorrect. Performance optimization never overrides data correctness.

4.4.2 Low-shuffle MERGE and runtime behavior

Databricks runtimes include MERGE optimizations, including low-shuffle behavior in supported configurations. Check the runtime and current defaults before you add custom repartitioning or complex write workarounds.

4.4.3 Optimized writes, compaction, and table maintenance

A better write can make later reads faster. Poorly sized files increase metadata and scheduling work and can weaken scan performance. Databricks table management features can improve file sizing for eligible managed tables. OPTIMIZE and predictive optimization can also reduce maintenance work.

After a period of frequent MERGE operations, use the inspection commands in Section 6 with your target table’s full name to review its details and history. That section also explains which storage and maintenance signals to examine.

Do not automatically add manual coalesce or repartition calls before every write. Such controls can be useful in specific workloads, but they can also reduce parallelism or create a new bottleneck.

4.4.4 Whole-pipeline MERGE validation

A faster MERGE can still be a poor trade if it leaves the table badly fragmented. Include downstream query performance in the validation window when other workloads use the target table. Record the following measures to assess the change across the whole pipeline.

  • Measure the MERGE runtime.

  • Measure the target read bytes.

  • Measure the files that were read and written.

  • Measure shuffle bytes and spill bytes.

  • Measure downstream query runtime after the MERGE completes.

Then check whether the application creates avoidable work through repeated scans, wide rows, unnecessary actions or repeated computation.

4.5 Bottleneck 5: Application code performs unnecessary work

Not every problem starts in the table or the engine. Some problems begin in the application itself. Look for the following patterns:

  • The application can scan the same data more than once.

  • Wide rows with unneeded columns can pass through the pipeline.

  • Actions may run even when the business result does not need them.

  • The application may recompute the same result across multiple actions.

  • Data may be cached without evidence that the cache will help.

The following sections explain how to address these patterns.

4.5.1 Explicit column projection

SELECT * is convenient during exploration, but it can make production pipelines more expensive. Unneeded columns increase input and output, memory use, serialization, shuffle and sometimes write volume.

The example below selects three columns instead of using SELECT * and applies a date filter. Replace the table and column names and adjust the date filter to match your workload.

-- Prefer an explicit projection in production
SELECT business_key, event_date, metric_value
FROM catalog.schema.fact_table
WHERE event_date >= DATE '2026-08-01';

4.5.2 Repeated Spark actions and recomputation

During development, notebooks often include count, display, collect, and write actions. Each Spark action can start execution. When production code repeats actions against the same lineage, the workload may run the same expensive stages several times.

Use the Spark UI to confirm whether the same stages run more than once. Then decide whether to combine the work, materialize the result or cache it for a clear reason.

4.5.3 Evidence-based caching

Caching is not a universal acceleration switch. It consumes memory and can change the normal storage and data skipping path. For Delta workloads, first ask whether better table layout and pruning can remove the repeated scan. Cache an expensive intermediate result only when the pipeline reuses it often enough to justify the storage cost. Once the technical work is complete, judge the result against the business objective. Decide whether the workload needs to be faster, cheaper, or both.

5. Check factors outside the execution plan

After a change improves the main bottleneck, check whether the workload became more efficient or simply used more compute. A job that runs twice as fast while using three times the resources may still meet a strict service level agreement, but it is not automatically a price-performance win.

To evaluate this tradeoff, measure cost alongside performance. System billing data can help attribute DBU usage to products, warehouses, clusters, jobs, and runs, depending on the available metadata.

The query below summarizes net recorded DBU usage over the past 30 days, including corrections received so far. It aggregates signed usage quantities across original records, retractions, and restatements, and keeps workspace and SKU details to help distinguish resources and pricing contexts. Adjust the date filter and use the available identifiers to focus on the workload you are investigating.

SELECT
usage_date,
billing_origin_product,
usage_metadata.warehouse_id,
usage_metadata.cluster_id,
usage_metadata.job_id,
usage_metadata.job_run_id,
product_features.is_serverless,
product_features.is_photon,
SUM(usage_quantity) AS dbus
FROM system.billing.usage
WHERE usage_date >= current_date() - INTERVAL 30 DAYS
AND record_type = 'ORIGINAL'
GROUP BY ALL
ORDER BY usage_date DESC, dbus DESC;

Compare the cost of similar successful runs. Daily totals can include several workloads, retries, idle time and unrelated compute. Connect the cost signal to the workload you are investigating.

5.1 Evaluate cost and price-performance

The table below summarizes the four common runtime and cost outcomes. Use it to judge whether a faster run represents a genuine price-performance improvement or an intentional service-level tradeoff.

Runtime

Cost

Interpretation

Lower

Lower

The optimization is strong because the workload is faster and cheaper.

Lower

Same

Good speed improvement with neutral cost.

Lower

Higher

Faster but potentially a poor price-performance tradeoff.

Same

Lower

Useful cost optimization even without an SLA gain.

State the optimization target before judging the result. A strict SLA workload may accept higher cost for a required latency reduction, while a nightly batch with a generous SLA may prioritize DBU reduction. Once the tradeoff is clear, verify any remaining storage signal against the Delta table’s current layout, file behavior, statistics, and maintenance history.

6. Verify the table when storage signals remain

Cost tells you whether the optimization was worthwhile, but the profile tells you whether more investigation is needed. If the evidence still points to file count, layout, clustering, statistics, or maintenance history, inspect the Delta table directly before changing more query code. This inspection applies the earlier scan guidance to the table’s current physical state.

The commands below return the table’s current details, operation history, and extended metadata. Replace catalog.schema.table_name with the full name of the table you are investigating.

DESCRIBE DETAIL catalog.schema.table_name;
DESCRIBE HISTORY catalog.schema.table_name;
DESCRIBE TABLE EXTENDED catalog.schema.table_name;


Use the results to inspect sizeInBytes, numFiles, clustering configuration, table properties, maintenance operations, and recent MERGE, OPTIMIZE, and ANALYZE activity. The following checks help interpret this evidence. If they point to a layout problem, assess whether the liquid clustering guidance and examples in Section 4.1.2 fit the workload.

  • Review the table size, number of files, and partitioning or clustering configuration.

  • Examine the frequency of MERGE, UPDATE, DELETE, and INSERT operations and look for evidence of repeated small writes.

  • Review recent OPTIMIZE operations and the predictive optimization configuration where applicable.

  • Check statistics availability and recent ANALYZE activity.

  • Compare the maintenance history with the period when performance degraded.

A table is part of the execution plan even when it is not visible in the SQL text. Data layout, file sizes, clustering, and statistics determine how much physical work the query must do. The decision matrix brings these signals together so you can move from an observed symptom to the next investigation, the likely cause, and the metric that should prove the fix.

7. Use the decision matrix to choose the next step

Use this matrix when you need to move quickly from an observed symptom to the next investigation, likely cause, first change, and proof metric. It is a compact synthesis of the method, not a replacement for Query Profile or Spark UI.

What you observe

Investigate

Likely cause

Try first

Prove with

High read bytes

Scan operator, pruning

Poor layout/stats

Clustering, statistics, predictive optimization

Lower read bytes and higher pruning

Many small files

Table detail/ history

Fragmented writes

OPTIMIZE / automatic maintenance

Lower file count and scan overhead

Large shuffle

Exchange/ join stages

Join, aggregation, repartition

Reduce input, AQE, broadcast where eligible

Lower shuffle bytes/time

One task much slower

Task distribution

Skewed partition/key

AQE skew handling, targeted strategy

Lower max task time

High spill

Spark UI

Memory pressure

Reduce shuffle, redesign join, right-size compute

Lower spill bytes

High CPU

Task time, execution path

UDFs/ expensive expressions

Built-ins, Photon, precompute

Lower CPU/task time

Slow MERGE

Target scan/ rewrite

Broad match or layout

Constrain match, modern MERGE behavior, layout

Lower MERGE duration and file work

Faster but costlier

Billing + runtime

Oversized compute

Right-size compute

Lower DBU per successful run

High waiting time

Query history

Capacity/ queueing

Capacity or sizing investigation

Lower waiting duration

8. See the full method in one end-to-end example

The decision matrix helps select the next investigation. This example shows how to apply that choice through the full process, from baseline and diagnosis to change, validation, and the decision to stop.

The scenario and figures below are illustrative rather than benchmarks, and actual results will vary by workload, data, and configuration. In this example, a daily incremental pipeline reads a large event table, filters the current processing window, joins reference data and merges the result into a curated Delta table.

The initial baseline shows the following results:

Metric

Observed

Wall-clock runtime

18 minutes

Execution duration

16 minutes

Waiting duration

2 minutes

Read bytes

4.8 TB

Files read

1.9 million

Shuffle

640 GB

Spill

85 GB

Longest task

9.4 minutes

DBU proxy

42

Do not label the problem from one metric. A long-running task may suggest skew, and a large shuffle may suggest an expensive join. Start with the profile and find the signal that feeds the rest of the plan. In this example, the scan is the strongest signal.

The team forms a hypothesis: the source event table is poorly organized for the pipeline’s selective filters, causing the scan to read more data than necessary.

They make one combined intervention on that source table: apply an appropriate clustering strategy and refresh its Delta statistics. They do not resize compute or change the join in the same experiment.

The team reruns the same processing window and sees the following results:

Metric

Before

After

Result

Runtime

18 min

7 min

Improved

Read bytes

4.8 TB

620 GB

Strong improvement

Files read

1.9M

240K

Strong improvement

Shuffle

640 GB

625 GB

Mostly unchanged

Spill

85 GB

12 GB

Improved

Longest task

9.4 min

3.1 min

Improved

DBU proxy

42

17

Improved

The rerun supports the scan-reduction hypothesis: read bytes fell from 4.8 TB to 620 GB, and runtime fell from 18 to 7 minutes. Shuffle volume remained broadly similar, so this experiment does not establish that the join was free of bottlenecks. Spill also declined, but operator-level row counts, partition metrics, and task details are needed to explain that change.

In this illustrative example, runtime decreased by about 61%, read bytes by 87%, and the DBU proxy by 60%. These figures describe the example, not a measured benchmark. The DBU proxy is not a monetary cost calculation; include maintenance cost and applicable SKU prices before claiming net savings.

After documenting the result, the team decides whether further optimization is worthwhile. If the new runtime meets the service level agreement, investigating the remaining shuffle may add little business value.

The investigation is complete when the team can explain the evidence for the bottleneck, show how the expected metrics changed, and decide whether to keep the intervention. The remaining sections turn the method into a reusable operating model with guardrails and a review checklist.

9. Avoid shortcuts that hide the real cause

The evidence-first method also depends on avoiding changes that obscure causality or move the bottleneck elsewhere. Keep the following guardrails in place throughout the investigation:

  • Do not resize compute before checking whether the workload is actually compute-bound.

  • Do not run OPTIMIZE as a reflex without checking table health and workload behavior.

  • Do not add partition columns because they are popular filters without considering cardinality and write behavior.

  • Do not add broadcast hints without verifying the broadcast side is appropriately small and stable.

  • Do not salt keys before proving that skew is the bottleneck.

  • Do not add repartition calls simply because the job has many workers.

  • Do not cache every DataFrame in a notebook and assume it will improve production performance.

  • Do not combine a query rewrite, table rewrite, cluster resize, and runtime upgrade into one test if you need to understand causality.

  • Do not declare success from runtime alone.

  • Do not optimize a workload beyond its actual SLA or cost objective without a reason.

10. Use the review checklist on every investigation

The guardrails above help keep an investigation focused on the cause of the problem. This checklist turns those guardrails and the worked example into a repeatable review. Before making a change, confirm that you have captured the baseline, identified the bottleneck, and selected an optimization that addresses it.

  • I captured runtime, execution and waiting times, read bytes, files read and pruned, shuffle, spill, task skew, and a cost proxy, and recorded the workload inputs and compute configuration.

  • I inspected Query Profile and Spark UI.

  • I wrote the bottleneck hypothesis in one sentence and selected one optimization mapped directly to it.

With the baseline and hypothesis in place, use the following checks to keep the experiment focused while making the change.

  • I changed one meaningful variable without mixing unrelated optimizations into the experiment.

  • I kept input data and execution conditions comparable and preserved correctness constraints.

After making the change, rerun the workload and use the following checks to assess the result and decide what to do next.

  • I reran the same or a representative workload, compared the same metrics before and after, and confirmed that the predicted metric moved.

  • I measured performance relative to cost, not just runtime, and checked for downstream effects such as table fragmentation or slower subsequent queries.

  • I documented whether to keep, revert, or continue.

Conclusion

As data volumes and workload demands grow, businesses need predictable performance while keeping compute costs under control. Adding compute may reduce delays, but it can leave the underlying cause unresolved and does not, on its own, demonstrate better performance relative to cost.

Use the diagnostic workflow and decision matrix in this white paper to identify what is holding your workload back and prioritize changes that address the cause. Focus your effort on improvements that support your performance targets and cost objectives rather than speed alone.

Bring the baseline template, SQL examples, and review checklists into your engineering workflow to compare results consistently and validate each change. Use that evidence to retain improvements without compromising correctness or shifting problems elsewhere in the pipeline.

Judge success by your ability to meet service commitments at an appropriate cost and stop tuning when further work no longer serves a clear business need. Applied consistently, this approach gives your team a repeatable basis for delivering reliable Azure Databricks performance.

Executive summary

As data volumes, users, and AI workloads grow, Azure Databricks pipelines must deliver predictable performance without allowing compute costs to rise unchecked. When a workload slows, however, the visible delay rarely identifies the cause. Excessive scans, shuffle, skew, CPU pressure, inefficient MERGE operations, application logic, and capacity waits can produce similar symptoms while requiring different fixes.

This white paper presents a method grounded in execution evidence for diagnosing and optimizing batch ETL workloads in Azure Databricks. Its goal is to help data engineers replace trial-and-error tuning with a repeatable workflow that connects execution evidence to a specific bottleneck, tests one focused change, and validates the result across runtime, resource use, downstream impact, and cost.

The paper moves from baseline measurement and execution triage to targeted remedies for scan, shuffle, skew, CPU, write, and application bottlenecks. It then shows how to demonstrate improvements in performance relative to cost through a worked investigation, a decision matrix, review checklists, and reusable SQL templates.

By the end of the white paper, readers will be able to achieve five practical outcomes.

  1. Build a comparable baseline that captures runtime, waiting, input, data movement, resource pressure, and cost.

  2. Use Query Profile, Spark UI, query history, and Delta table metadata to identify the dominant bottleneck.

  3. Select a focused optimization that addresses the measured cause rather than the visible symptom.

  4. Run a controlled test that compares performance before and after a change and verify that the predicted metric moved.

  5. Decide whether to keep, revert, or extend the change based on correctness, downstream effects, and performance relative to cost.

The result is a practical engineering discipline for explaining why a workload is slow, applying the right intervention, and demonstrating that the improvement is real and repeatable.

Diagnose the cause before choosing the fix

Consider a daily pipeline that has slowed over time. Teams often respond by adding workers, choosing a larger instance, or increasing the SQL warehouse size. The next run finishes sooner, so the team declares success and moves on.

But the team still does not know why the workload slowed down. The following examples show why the same visible delay can point to different underlying constraints.

  • If the workload reads far more data than the business request needed, more compute may have reduced runtime without fixing the data access problem.

  • If one join key was heavily skewed, extra workers may have left the slowest partition almost untouched.

  • If the query was waiting for capacity, a resize may have been the right answer.

  • If the Python UDF logic is unsupported by Photon logic and kept the job CPU-bound, the resize may have been an expensive workaround.

In each case, the run got faster, but the workload is still not understood. The practical goal is to explain why the workload is slow, choose a change that addresses that cause, and prove that the change improved the right parts of performance.

Use the following loop for every meaningful optimization:

  • Establish a baseline by measuring the current workload and capturing its performance.

  • Diagnose the bottleneck by identifying the operator or system symptom with the greatest impact. Then classify the issue as scan, shuffle, skew, CPU, spill, write, code, waiting, or cost.

  • Test a hypothesis by stating it in one sentence and changing one meaningful variable.

  • Validate the results by rerunning the same or a representative workload under comparable conditions. Compare runtime, data movement, resource pressure, and cost.

  • Decide the next step based on the evidence. Keep or revert the change, or continue investigating.

Figure 1: A simplified workflow for diagnosing and validating performance improvements

2. What to measure before changing anything

That loop starts with a useful baseline. Keep it small enough to collect every time, but broad enough to prevent tunnel vision. Runtime alone is not enough, so begin with the following measures that explain where time and money are spent.

  • Capture execution time and waiting time.

  • Capture input bytes and the number of files that were read or pruned.

  • Capture shuffle, spill, and the spread of task durations.

  • Capture a cost measure such as DBUs.

The table below connects each baseline metric to the question it answers and the Azure Databricks interface or system table where engineers can inspect it.


Metric

Why it matters

Where to inspect

Elapsed runtime

Shows how quickly users receive results and whether the workload meets its service level agreement.

Job run, Query Profile, notebook or query history

Execution vs waiting duration

Separates execution work from capacity or scheduling delays.

system.query.history

Read bytes

Shows how much data entered the plan.

Query Profile, query history

Files read or pruned

Shows whether file pruning and layout are effective.

Query Profile, query history, table metadata

Shuffle reads and writes

Identifies joins, aggregations, repartitions and exchanges.

Spark UI, Query Profile, query history

Spill bytes

Signals memory pressure during execution.

Spark UI, query history where available

Variation in task duration

Reveals skew and partitions that take much longer to finish.

Spark UI

CPU and task time

Distinguishes logic that uses substantial CPU resources from work that involves substantial input and output.

Spark UI, Query Profile

DBUs or another cost measure

Measures performance relative to cost rather than speed alone.

system.billing.usage

2.1 Establish a comparable baseline

Once you know what to capture, make sure the comparison is fair. Record the information that can change the result.

  • Use comparable data and record the input data range and the relevant table versions. Compare the same business period or a representative data slice. A small recent input and a much larger historical input cannot show whether an optimization worked.

  • Record the compute configuration by noting the cluster or warehouse configuration and the runtime version. Keep compute configuration unchanged while testing a query or code change unless compute sizing is the hypothesis.

  • Record the query parameters and cache use by noting the parameters and whether the result came from cache. Avoid comparing a cached result with a cold run.

  • Record capacity conditions by noting concurrency and queueing conditions when capacity is part of the investigation.

  • Control changes by changing one major variable at a time.

Use the template below to record your baseline and compare the results after a change. Copy it into an engineering repository, notebook, pull request, or optimization review.

Complete the workload and configuration fields before testing a change, then record the baseline metrics and their sources in the Before column. After the rerun, fill in the After and Delta columns and document the hypothesis, the single change, the result, and the decision to keep, revert, or continue.

## Workload Optimization Baseline
 
Workload name:
Business SLA:
Run ID / Statement ID:
Date/time:
Compute type:
Runtime / warehouse size:
Input tables:
 
| Metric | Before | After | Delta | Source |
| --- | ---: | ---: | ---: | --- |
| Wall-clock runtime | | | | |
| Execution duration | | | | |
| Waiting duration | | | | |
| Read bytes | | | | |
| Read files | | | | |
| Pruned files | | | | |
| Shuffle read bytes | | | | |
| Spill bytes | | | | |
| Peak memory | | | | |
| DBUs / cost proxy | | | | |
 
Hypothesis:
One change made:
Result:
Keep / revert / continue:

2.2 Use query history as the longitudinal view

A single run gives you only part of the story. Query Profile and Spark UI are excellent for understanding one execution, while query history helps you compare repeated runs, spot regressions, and separate execution time from time spent waiting for compute. System tables can then connect that workload behavior to cost.

Use the query below to populate the execution metrics in your baseline record. It returns the 50 completed statements with the longest total duration over the past seven days. Adjust the time filter and result limit, then select the statements relevant to your workload before comparing runs.

SELECT
workspace_id,
statement_id,
start_time,
executed_by,
client_application,
compute.type AS compute_type,
compute.warehouse_id,
total_duration_ms,
waiting_for_compute_duration_ms,
waiting_at_capacity_duration_ms,
execution_duration_ms,
compilation_duration_ms,
read_bytes,
read_files,
pruned_files,
shuffle_read_bytes,
spilled_local_bytes,
produced_rows,
from_result_cache
FROM system.query.history
WHERE start_time >= current_timestamp() - INTERVAL 7 DAYS
AND execution_status = 'FINISHED'
ORDER BY total_duration_ms DESC
LIMIT 50;


Use the columns available in your workspace and runtime because system table schemas can change. Compare execution time, waiting time, input and output, shuffle, spill and cache behavior together. Do not use one field as the final verdict. Once you have a fair baseline and enough history, open the execution evidence and find where the workload spends its time. On serverless compute, DataFrame (df) cache is not currently supported. Also, the driver itself can sometimes fall behind, and driver cluster sizing can cause slowness in the job.

Note: On classic compute, use Spark UI, task run details, and available logs. On serverless notebooks and jobs, use Query Profile and run details: Spark UI is unavailable, and DataFrame cache/persist and SQL cache APIs are unsupported. If system.query.history is inaccessible or does not cover the workload, collect the baseline from the applicable UI and run metadata.

3. Read Query Profile and Spark UI as a triage board

Use Query Profile and Spark UI to locate the main constraint on execution’s main time or resource constraint, then review the relevant SQL to investigate its cause. Fig 2.1 and Fig 2.2 show this analysis on traditional compute, while Fig 3.1 and Fig 3.2 show it on serverless compute.

Follow this diagnostic sequence to narrow the investigation.

  • Data access and movement: Start with the scan. Then inspect shuffle and skew.

  • CPU and execution path: Next, check CPU use and the execution path.

  • Waiting versus execution: Finally, separate waiting time from execution time.

Option1: Analyzing from traditional compute - Spark UI


Figure 2.1 and 2.2: Identifying the long running job group and understanding the DAG which explains there is shuffling during joining.


Option 2: Using Serverless compute and viewing performance


Figure 3.1 and 3.2: Same metrics in spark UI, indicating high shuffle on join.

Follow these five diagnostic areas in order, stopping when evidence identifies the strongest constraint.

  1. Scan operators and excessive data access: A scan deserves immediate attention when it reads a large amount of data for a small business request. Check read bytes, files read, files pruned and filter predicates. A selective SQL filter does not guarantee a selective physical read. The table layout must let the engine skip irrelevant files.

  2. Exchange operators and shuffle: Shuffle moves data between tasks. Joins, aggregations, window functions, distinct operations and explicit repartitioning can create that movement. A large shuffle is not always a problem. Investigate it when it dominates execution time, causes spill or moves far more data than the business logic needs.

  3. Task distribution and partition skew: Average task time can hide skew. Use the Spark UI to compare task duration and input and output size. If most tasks finish quickly while a few run much longer, a skewed key or partition may be holding up the stage. The stage cannot finish until the slowest task completes.

  4. CPU utilization and Photon execution: High task time with normal input and shuffle can point to expensive expressions or an execution path that cannot use the native vectorized engine. Photon can speed up eligible SQL and DataFrame work, including scans, joins, aggregations and writes. It does not support every Spark API or UDF path. Do not expect Photon to fix application logic that blocks efficient native execution.

  5. Waiting time versus execution time: A healthy execution plan can still feel slow when the workload waits for capacity. This often matters on shared SQL warehouses and busy job compute. If waiting takes up a significant share of the total time, changing the SQL may not reduce the delay users see. (refer Fig 3.5.1)





Figure 4: Image showing total run time for a job run, but the job was waiting for resources to be executed.

4. Investigate the five primary execution bottlenecks

The baseline tells you what changed, and the profile tells you where to look. Use the workflow in Section 1 to test the remedy that matches the dominant symptom.

The rest of the diagnosis focuses on five primary execution bottlenecks. These cover excessive scans, shuffle and skew, CPU-intensive work, inefficient MERGE behavior, and unnecessary application work. Waiting time and price-performance are assessed separately because they can affect the result even when the execution plan itself is healthy.

Figure 5: Five primary execution bottlenecks that can slow an Azure Databricks workload

4.1 Bottleneck 1: The workload scans too much data

If the scan is the dominant bottleneck, reduce the data entering the plan before tuning downstream operators. The application may ask for a narrow slice, but the physical table can still force the engine to inspect a large share of the data.

You will usually see the following signs:

  • Scan volume and impact: Read bytes are much larger than the expected business slice. A scan operator dominates the profile.

  • File pruning: A large number of files are read with relatively weak pruning.

  • Downstream row volume: Downstream operators receive far more rows than they need.

These signs point to excessive scanning but do not explain its cause. To investigate why the workload reads more data than it needs, check the following areas in order.

  • Filter selectivity and statistics: Start by assessing how selective the filter predicates are and reviewing the availability of useful table statistics.

  • Physical layout: Compare the physical layout with the filters the workload uses most often.

  • Small files: Look for an accumulation of small files in the table.

  • Partitioning: Examine whether partitioning creates too many directories or prevents effective pruning.

  • Liquid clustering: Consider whether liquid clustering would better support high cardinality or changing access patterns.

4.1.1 Statistics and data skipping

Statistics help the engine understand the data and make better planning and file-level decisions. Missing or outdated statistics leave the optimizer with less useful information. Before you change the application, check the table statistics and metadata.

Use the commands below to compute Delta statistics for the table you are investigating.

COMPUTE DELTA STATISTICS refreshes per-file statistics in the Delta log for configured columns. It does not collect normal optimizer statistics. State Databricks Runtime 14.3 LTS or later for this command. Use COMPUTE STATISTICS for optimizer statistics, adding FOR COLUMNS when column estimates are needed.

-- Refresh file-skipping statistics for configured columns
ANALYZE TABLE catalog.schema.table_name
COMPUTE DELTA STATISTICS;
-- Refresh optimizer table and relevant column statistics
ANALYZE TABLE catalog.schema.table_name
COMPUTE STATISTICS FOR COLUMNS customer_id, event_date;


Use statistics as part of a broader layout strategy, not as a substitute for one. Statistics cannot make an inherently poorly organized table behave like a well-clustered one.

4.1.2 Liquid clustering

Liquid clustering can help when filter columns have high cardinality, query patterns change, data is skewed, the table grows quickly or traditional partitioning lacks a stable key. For new tables, automatic clustering can reduce the need to predict one permanent partitioning strategy.

Choose the creation statement below for a new table or one of the alteration statements for an existing table rather than running all three in sequence. Replace the table and column names, and choose automatic clustering or explicit columns based on the workload’s access patterns. The creation statement can replace an existing table, so confirm the target name before running it. The final commands optimize the table and let you inspect its details and properties.

-- New Unity Catalog managed Delta table; DBR 15.4 LTS+
-- Requires predictive optimization for automatic key selection
CREATE TABLE catalog.schema.new_table
USING DELTA CLUSTER BY AUTO
AS SELECT * FROM catalog.schema.source_table;
-- Alternative: existing unpartitioned eligible managed table
ALTER TABLE catalog.schema.table_name CLUSTER BY AUTO;
-- Alternative: explicit keys on an unpartitioned Delta table
ALTER TABLE catalog.schema.table_name
CLUSTER BY (customer_id, event_date);
-- Routine incremental layout maintenance when needed
OPTIMIZE catalog.schema.table_name;
-- Optional full reclustering; DBR 16.0+, after assessing cost
-- OPTIMIZE catalog.schema.table_name FULL;


Do not choose clustering columns simply because they appear often. Choose them because workload evidence shows that they support real access patterns. Use Query Profile and workload history to find the predicates that repeatedly determine which data the engine needs.

4.1.3 Small-file fragmentation

Small files create work before the engine can do useful computation. They increase file metadata work, create more task scheduling and file opens, and weaken scan efficiency. They often build up slowly when frequent incremental writes fragment the table. Unity Catalog managed tables can receive automatic file-size tuning, and predictive optimization can automate table maintenance for eligible managed tables. Section 8 illustrates how to test a table layout change and compare its effects on scanning, runtime, and a DBU-based cost proxy.

Inspect table details and history before deciding whether compaction is necessary. Section 6 provides the inspection commands and explains how to interpret this evidence.

4.2 Bottleneck 2: The workload shuffles too much data or suffers from skew

If scan volume looks reasonable, the next place to look is data movement. Shuffle is where a logically simple ETL pipeline can become physically expensive because rows with the same join or aggregation key must reach the same task. That movement consumes network, CPU, memory, and disk when spilling occurs.

You will usually see the following signs:

  • Shuffle read/write is large compared with the useful input.

  • Join, aggregate, window, or exchange stages dominate the profile.

  • The workload spills heavily.

  • One or a few tasks are dramatically slower than the rest.

4.2.1 Reduce data before the join

The simplest way to reduce shuffle is often to reduce the data that enters it. Filter as early as the logic allows and select only the columns the pipeline needs. Wide rows make every later movement more expensive.

The example below applies a date filter to the fact table and selects only the required columns from both tables before joining them on business_key. Replace the table and column names and adjust the date filter to match your workload.

SELECT
f.business_key,
f.event_date,
f.metric_value,
d.category
FROM (
SELECT business_key, event_date, metric_value
FROM catalog.schema.fact_table
WHERE event_date >= DATE '2026-08-01'
) f
JOIN (
SELECT business_key, category
FROM catalog.schema.dimension_table
) d
ON f.business_key = d.business_key;
 


If AQE does not choose a broadcast join because the estimated input size exceeds the configured threshold, you can consider increasing spark.sql.adaptive.autoBroadcastJoinThreshold. Set it only after confirming that the table can safely fit in memory on each executor. AQE can then use a broadcast join when runtime statistics show that the input is within the threshold. Check the resulting plan and executor memory pressure to validate the change.

The exact rewrite depends on the query plan and optimizer behavior. The principle is simple: do not move rows or columns that the rest of the pipeline does not need.

4.2.2 Broadcast joins for eligible small inputs

If one side of a join is small enough and the workload supports it, broadcasting can avoid a large shuffle. Use a broadcast hint only when you have evidence that the smaller table is stable and fits in memory.

The example below applies a broadcast hint to the dimension table, aliased as d, when joining it to filtered_fact on business_key. Replace the table and column names to match your workload, and use the hint only when the smaller table is stable and fits in memory.

SELECT /*+ BROADCAST(d) */
f.business_key,
f.event_date,
d.category
FROM filtered_fact f
JOIN dimension d
ON f.business_key = d.business_key;


The validation question is simple: did shuffle volume and join time decrease without creating memory pressure? A broadcast that causes executor memory problems is not an optimization.

4.2.3 Adaptive Query Execution

Adaptive Query Execution uses runtime information to improve the plan. It can change join strategies and address some skew patterns. Before you force partitioning or join behavior, check whether adaptive execution is available and whether it already addresses the problem.

4.2.4 Skew and long-tail tasks

A reasonable average task time can hide skew in a join. When one partition holds far more rows than the others, it creates a long tail that the average does not reveal. To identify this imbalance, examine the longest task, task input sizes, and the full distribution of task durations rather than relying on stage averages.

If these comparisons reveal skew, investigate its cause before choosing a remedy. A default value, a popular customer or a field with few distinct values can create uneven partitions. Adaptive Query Execution may help address the imbalance. Use salting only after the evidence proves that skew is the main bottleneck, because salting adds complexity.

4.2.5 Avoid unnecessary shuffle

Review explicit repartitioning, unnecessary distinct operations, repeated aggregations, and window functions. Developers sometimes add repartition calls to create more parallel work without checking whether the new exchange costs more than it saves.

If the Spark UI shows a large exchange immediately before a stage, ask what business requirement forced the data to move. If there is no good answer, test the plan without that exchange.

4.3 Bottleneck 3: CPU-intensive work slows execution

When reads and shuffle both look reasonable, move to computation. A workload can still be slow because expensive expressions, parsing, serialization, or UDF execution keep task time high.

You will usually see the following signs:

  • High task time despite moderate input and shuffle.

  • Expensive JSON, string, regex, or parsing operations.

  • Python or other UDFs in hot parts of the plan.

  • Repeated transformations that could be expressed with native SQL/DataFrame functions.

The following sections explain how to reduce this CPU work.

4.3.1 Prefer built-in functions

Built-in SQL and DataFrame functions give the engine more room to optimize and run work natively. Higher-order functions can often replace custom UDF logic for arrays, maps, and nested structures. The example below uses transform and upper to convert each string in the attributes array to uppercase without a custom UDF. Replace the table and column names to match your data.

-- Prefer native expressions where possible
SELECT
business_key,
transform(attributes, x -> upper(x)) AS normalized_attributes
FROM source_table;


Choose the function that matches the transformation. The principle is simple: express the work in a form the engine can understand and optimize instead of forcing custom row-by-row execution.

4.3.2 Photon eligibility and native execution

Photon can speed up eligible SQL and DataFrame workloads through native vectorized execution. It can help with scans, joins, aggregations, writes, and high concurrency analytics. Unsupported APIs, UDFs, and RDD-based code can limit that benefit.

Ask whether the workload can use efficient native execution and whether that execution is actually happening. Do not stop at asking whether Photon is enabled.

4.3.3 Precompute reused expensive expressions

If the same expensive parsing or normalization logic is repeated across many downstream queries, consider materializing the derived value at an appropriate stage. This trades additional storage and write work for less repeated CPU computation.

Measure the total pipeline, not just the query that becomes faster. That whole-pipeline view matters even more when the workload writes results, because the next bottleneck may appear in MERGE rather than in the transformation itself.

4.4 Bottleneck 4: MERGE scans or rewrites too much data

The bottleneck can also move from reading and computation to writing. Incremental pipelines often process a small source dataset but still force a MERGE to inspect or rewrite a large part of the target table.

You will usually see the following signs:

  • MERGE duration grows faster than source volume.

  • Target read bytes are much larger than expected.

  • Many files are rewritten.

  • Frequent updates produce small files.

  • Downstream reads become slower after repeated incremental writes.

The following sections explain how to reduce MERGE work and validate its impact on the whole pipeline.

4.4.1 Constrain the target search space

The MERGE match condition defines the business logic and determines which target rows can match source rows. Valid constraints can reduce the target data scanned, but a row-dependent condition such as t.event_date >= s.min_event_date does not by itself guarantee target-file pruning.

When the business rules support it, a proven batch-wide date bound can help limit the target search. Dynamic file pruning for MERGE requires Photon-enabled compute; verify the actual scan metrics to confirm whether the expected pruning occurs.

-- Assumes every existing match is dated on or after this bound.
-- Prepare the source so each target row matches at most one source row.
 
MERGE INTO catalog.schema.target AS t
USING catalog.schema.source_changes AS s
ON t.business_key = s.business_key
AND t.event_date >= DATE '2026-08-01'
 
WHEN MATCHED THEN UPDATE SET
t.event_date = s.event_date,
t.metric_value = s.metric_value
 
WHEN NOT MATCHED THEN
INSERT (business_key, event_date, metric_value)
VALUES (s.business_key, s.event_date, s.metric_value);


Use explicit column assignments so source helper fields, such as min_event_date, are not unintentionally included in updates or schema-evolution paths.

Only add constraints that are logically correct. An overly aggressive predicate can make a correct MERGE incorrect. Performance optimization never overrides data correctness.

4.4.2 Low-shuffle MERGE and runtime behavior

Databricks runtimes include MERGE optimizations, including low-shuffle behavior in supported configurations. Check the runtime and current defaults before you add custom repartitioning or complex write workarounds.

4.4.3 Optimized writes, compaction, and table maintenance

A better write can make later reads faster. Poorly sized files increase metadata and scheduling work and can weaken scan performance. Databricks table management features can improve file sizing for eligible managed tables. OPTIMIZE and predictive optimization can also reduce maintenance work.

After a period of frequent MERGE operations, use the inspection commands in Section 6 with your target table’s full name to review its details and history. That section also explains which storage and maintenance signals to examine.

Do not automatically add manual coalesce or repartition calls before every write. Such controls can be useful in specific workloads, but they can also reduce parallelism or create a new bottleneck.

4.4.4 Whole-pipeline MERGE validation

A faster MERGE can still be a poor trade if it leaves the table badly fragmented. Include downstream query performance in the validation window when other workloads use the target table. Record the following measures to assess the change across the whole pipeline.

  • Measure the MERGE runtime.

  • Measure the target read bytes.

  • Measure the files that were read and written.

  • Measure shuffle bytes and spill bytes.

  • Measure downstream query runtime after the MERGE completes.

Then check whether the application creates avoidable work through repeated scans, wide rows, unnecessary actions or repeated computation.

4.5 Bottleneck 5: Application code performs unnecessary work

Not every problem starts in the table or the engine. Some problems begin in the application itself. Look for the following patterns:

  • The application can scan the same data more than once.

  • Wide rows with unneeded columns can pass through the pipeline.

  • Actions may run even when the business result does not need them.

  • The application may recompute the same result across multiple actions.

  • Data may be cached without evidence that the cache will help.

The following sections explain how to address these patterns.

4.5.1 Explicit column projection

SELECT * is convenient during exploration, but it can make production pipelines more expensive. Unneeded columns increase input and output, memory use, serialization, shuffle and sometimes write volume.

The example below selects three columns instead of using SELECT * and applies a date filter. Replace the table and column names and adjust the date filter to match your workload.

-- Prefer an explicit projection in production
SELECT business_key, event_date, metric_value
FROM catalog.schema.fact_table
WHERE event_date >= DATE '2026-08-01';

4.5.2 Repeated Spark actions and recomputation

During development, notebooks often include count, display, collect, and write actions. Each Spark action can start execution. When production code repeats actions against the same lineage, the workload may run the same expensive stages several times.

Use the Spark UI to confirm whether the same stages run more than once. Then decide whether to combine the work, materialize the result or cache it for a clear reason.

4.5.3 Evidence-based caching

Caching is not a universal acceleration switch. It consumes memory and can change the normal storage and data skipping path. For Delta workloads, first ask whether better table layout and pruning can remove the repeated scan. Cache an expensive intermediate result only when the pipeline reuses it often enough to justify the storage cost. Once the technical work is complete, judge the result against the business objective. Decide whether the workload needs to be faster, cheaper, or both.

5. Check factors outside the execution plan

After a change improves the main bottleneck, check whether the workload became more efficient or simply used more compute. A job that runs twice as fast while using three times the resources may still meet a strict service level agreement, but it is not automatically a price-performance win.

To evaluate this tradeoff, measure cost alongside performance. System billing data can help attribute DBU usage to products, warehouses, clusters, jobs, and runs, depending on the available metadata.

The query below summarizes net recorded DBU usage over the past 30 days, including corrections received so far. It aggregates signed usage quantities across original records, retractions, and restatements, and keeps workspace and SKU details to help distinguish resources and pricing contexts. Adjust the date filter and use the available identifiers to focus on the workload you are investigating.

SELECT
usage_date,
billing_origin_product,
usage_metadata.warehouse_id,
usage_metadata.cluster_id,
usage_metadata.job_id,
usage_metadata.job_run_id,
product_features.is_serverless,
product_features.is_photon,
SUM(usage_quantity) AS dbus
FROM system.billing.usage
WHERE usage_date >= current_date() - INTERVAL 30 DAYS
AND record_type = 'ORIGINAL'
GROUP BY ALL
ORDER BY usage_date DESC, dbus DESC;

Compare the cost of similar successful runs. Daily totals can include several workloads, retries, idle time and unrelated compute. Connect the cost signal to the workload you are investigating.

5.1 Evaluate cost and price-performance

The table below summarizes the four common runtime and cost outcomes. Use it to judge whether a faster run represents a genuine price-performance improvement or an intentional service-level tradeoff.

Runtime

Cost

Interpretation

Lower

Lower

The optimization is strong because the workload is faster and cheaper.

Lower

Same

Good speed improvement with neutral cost.

Lower

Higher

Faster but potentially a poor price-performance tradeoff.

Same

Lower

Useful cost optimization even without an SLA gain.

State the optimization target before judging the result. A strict SLA workload may accept higher cost for a required latency reduction, while a nightly batch with a generous SLA may prioritize DBU reduction. Once the tradeoff is clear, verify any remaining storage signal against the Delta table’s current layout, file behavior, statistics, and maintenance history.

6. Verify the table when storage signals remain

Cost tells you whether the optimization was worthwhile, but the profile tells you whether more investigation is needed. If the evidence still points to file count, layout, clustering, statistics, or maintenance history, inspect the Delta table directly before changing more query code. This inspection applies the earlier scan guidance to the table’s current physical state.

The commands below return the table’s current details, operation history, and extended metadata. Replace catalog.schema.table_name with the full name of the table you are investigating.

DESCRIBE DETAIL catalog.schema.table_name;
DESCRIBE HISTORY catalog.schema.table_name;
DESCRIBE TABLE EXTENDED catalog.schema.table_name;


Use the results to inspect sizeInBytes, numFiles, clustering configuration, table properties, maintenance operations, and recent MERGE, OPTIMIZE, and ANALYZE activity. The following checks help interpret this evidence. If they point to a layout problem, assess whether the liquid clustering guidance and examples in Section 4.1.2 fit the workload.

  • Review the table size, number of files, and partitioning or clustering configuration.

  • Examine the frequency of MERGE, UPDATE, DELETE, and INSERT operations and look for evidence of repeated small writes.

  • Review recent OPTIMIZE operations and the predictive optimization configuration where applicable.

  • Check statistics availability and recent ANALYZE activity.

  • Compare the maintenance history with the period when performance degraded.

A table is part of the execution plan even when it is not visible in the SQL text. Data layout, file sizes, clustering, and statistics determine how much physical work the query must do. The decision matrix brings these signals together so you can move from an observed symptom to the next investigation, the likely cause, and the metric that should prove the fix.

7. Use the decision matrix to choose the next step

Use this matrix when you need to move quickly from an observed symptom to the next investigation, likely cause, first change, and proof metric. It is a compact synthesis of the method, not a replacement for Query Profile or Spark UI.

What you observe

Investigate

Likely cause

Try first

Prove with

High read bytes

Scan operator, pruning

Poor layout/stats

Clustering, statistics, predictive optimization

Lower read bytes and higher pruning

Many small files

Table detail/ history

Fragmented writes

OPTIMIZE / automatic maintenance

Lower file count and scan overhead

Large shuffle

Exchange/ join stages

Join, aggregation, repartition

Reduce input, AQE, broadcast where eligible

Lower shuffle bytes/time

One task much slower

Task distribution

Skewed partition/key

AQE skew handling, targeted strategy

Lower max task time

High spill

Spark UI

Memory pressure

Reduce shuffle, redesign join, right-size compute

Lower spill bytes

High CPU

Task time, execution path

UDFs/ expensive expressions

Built-ins, Photon, precompute

Lower CPU/task time

Slow MERGE

Target scan/ rewrite

Broad match or layout

Constrain match, modern MERGE behavior, layout

Lower MERGE duration and file work

Faster but costlier

Billing + runtime

Oversized compute

Right-size compute

Lower DBU per successful run

High waiting time

Query history

Capacity/ queueing

Capacity or sizing investigation

Lower waiting duration

8. See the full method in one end-to-end example

The decision matrix helps select the next investigation. This example shows how to apply that choice through the full process, from baseline and diagnosis to change, validation, and the decision to stop.

The scenario and figures below are illustrative rather than benchmarks, and actual results will vary by workload, data, and configuration. In this example, a daily incremental pipeline reads a large event table, filters the current processing window, joins reference data and merges the result into a curated Delta table.

The initial baseline shows the following results:

Metric

Observed

Wall-clock runtime

18 minutes

Execution duration

16 minutes

Waiting duration

2 minutes

Read bytes

4.8 TB

Files read

1.9 million

Shuffle

640 GB

Spill

85 GB

Longest task

9.4 minutes

DBU proxy

42

Do not label the problem from one metric. A long-running task may suggest skew, and a large shuffle may suggest an expensive join. Start with the profile and find the signal that feeds the rest of the plan. In this example, the scan is the strongest signal.

The team forms a hypothesis: the source event table is poorly organized for the pipeline’s selective filters, causing the scan to read more data than necessary.

They make one combined intervention on that source table: apply an appropriate clustering strategy and refresh its Delta statistics. They do not resize compute or change the join in the same experiment.

The team reruns the same processing window and sees the following results:

Metric

Before

After

Result

Runtime

18 min

7 min

Improved

Read bytes

4.8 TB

620 GB

Strong improvement

Files read

1.9M

240K

Strong improvement

Shuffle

640 GB

625 GB

Mostly unchanged

Spill

85 GB

12 GB

Improved

Longest task

9.4 min

3.1 min

Improved

DBU proxy

42

17

Improved

The rerun supports the scan-reduction hypothesis: read bytes fell from 4.8 TB to 620 GB, and runtime fell from 18 to 7 minutes. Shuffle volume remained broadly similar, so this experiment does not establish that the join was free of bottlenecks. Spill also declined, but operator-level row counts, partition metrics, and task details are needed to explain that change.

In this illustrative example, runtime decreased by about 61%, read bytes by 87%, and the DBU proxy by 60%. These figures describe the example, not a measured benchmark. The DBU proxy is not a monetary cost calculation; include maintenance cost and applicable SKU prices before claiming net savings.

After documenting the result, the team decides whether further optimization is worthwhile. If the new runtime meets the service level agreement, investigating the remaining shuffle may add little business value.

The investigation is complete when the team can explain the evidence for the bottleneck, show how the expected metrics changed, and decide whether to keep the intervention. The remaining sections turn the method into a reusable operating model with guardrails and a review checklist.

9. Avoid shortcuts that hide the real cause

The evidence-first method also depends on avoiding changes that obscure causality or move the bottleneck elsewhere. Keep the following guardrails in place throughout the investigation:

  • Do not resize compute before checking whether the workload is actually compute-bound.

  • Do not run OPTIMIZE as a reflex without checking table health and workload behavior.

  • Do not add partition columns because they are popular filters without considering cardinality and write behavior.

  • Do not add broadcast hints without verifying the broadcast side is appropriately small and stable.

  • Do not salt keys before proving that skew is the bottleneck.

  • Do not add repartition calls simply because the job has many workers.

  • Do not cache every DataFrame in a notebook and assume it will improve production performance.

  • Do not combine a query rewrite, table rewrite, cluster resize, and runtime upgrade into one test if you need to understand causality.

  • Do not declare success from runtime alone.

  • Do not optimize a workload beyond its actual SLA or cost objective without a reason.

10. Use the review checklist on every investigation

The guardrails above help keep an investigation focused on the cause of the problem. This checklist turns those guardrails and the worked example into a repeatable review. Before making a change, confirm that you have captured the baseline, identified the bottleneck, and selected an optimization that addresses it.

  • I captured runtime, execution and waiting times, read bytes, files read and pruned, shuffle, spill, task skew, and a cost proxy, and recorded the workload inputs and compute configuration.

  • I inspected Query Profile and Spark UI.

  • I wrote the bottleneck hypothesis in one sentence and selected one optimization mapped directly to it.

With the baseline and hypothesis in place, use the following checks to keep the experiment focused while making the change.

  • I changed one meaningful variable without mixing unrelated optimizations into the experiment.

  • I kept input data and execution conditions comparable and preserved correctness constraints.

After making the change, rerun the workload and use the following checks to assess the result and decide what to do next.

  • I reran the same or a representative workload, compared the same metrics before and after, and confirmed that the predicted metric moved.

  • I measured performance relative to cost, not just runtime, and checked for downstream effects such as table fragmentation or slower subsequent queries.

  • I documented whether to keep, revert, or continue.

Conclusion

As data volumes and workload demands grow, businesses need predictable performance while keeping compute costs under control. Adding compute may reduce delays, but it can leave the underlying cause unresolved and does not, on its own, demonstrate better performance relative to cost.

Use the diagnostic workflow and decision matrix in this white paper to identify what is holding your workload back and prioritize changes that address the cause. Focus your effort on improvements that support your performance targets and cost objectives rather than speed alone.

Bring the baseline template, SQL examples, and review checklists into your engineering workflow to compare results consistently and validate each change. Use that evidence to retain improvements without compromising correctness or shifting problems elsewhere in the pipeline.

Judge success by your ability to meet service commitments at an appropriate cost and stop tuning when further work no longer serves a clear business need. Applied consistently, this approach gives your team a repeatable basis for delivering reliable Azure Databricks performance.

See how Fractal and Databricks help enterprises move from data to impact

Recognition and achievements

Select Fractal accolades

Leader

The Forrester Wave: Customer Analytics Services Q2, 2025

Representative vendor

Gartner Hype Cycle for Consumer Goods, 2026

Great Place to Work

Great Place to Work® across four regions: India (9th year), USA (5th year), UK (5th year) and UAE (2nd year)

Recognition and achievements

Select Fractal accolades

Leader

The Forrester Wave: Customer Analytics Services Q2, 2025

Representative vendor

Gartner Hype Cycle for Consumer Goods, 2026

Great Place to Work

Great Place to Work® across four regions: India (9th year), USA (5th year), UK (5th year) and UAE (2nd year)