🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Databricks Spark Optimization: Photon, AQE, and Delta Cache

Azure Data EngineeringDatabricks Spark⭐ Premium
Azure Data Engineering

One runtime, four optimization layers

14 min readđŸ”ŦAdvanced

Prerequisites

  • !Spark fundamentals: RDDs, DataFrames, and lazy evaluation
  • !Delta Lake table basics and ACID commits
  • !How to read a Spark UI execution plan

What You'll Learn

  • 1Explain what Photon changes relative to vanilla JVM Spark execution
  • 2Configure and verify Adaptive Query Execution on Databricks Runtime
  • 3Use Delta Cache and Z-ORDER to cut storage I/O
  • 4Diagnose slow jobs with system tables and the Spark UI

Why Spark jobs stall on Databricks

A Databricks job that "used to be fine" suddenly takes three times longer, and the cluster metrics look healthy. CPU sits at forty percent, memory is stable, yet the job idles in a single stage. Nine times out of ten the bottleneck is data movement, not computation. Spark spends most of its wall-clock time shuffling partitions between executors, re-reading files from cloud storage, and falling back to broadcast joins that no longer fit in memory. Understanding which of these three failure modes you are facing is the entire game of Spark optimization, and Databricks Runtime 11.3 and later ships three mechanisms that attack each one directly: Photon attacks compute, Adaptive Query Execution attacks planning, and Delta Cache attacks I/O.

The practical mistake interviewers look for is treating these as independent switches you flip once. They interact. Photon executes the plan AQE produces, and Delta Cache changes how fast the scan feeding that plan runs. A job tuned only at one layer usually leaves two-thirds of the available speedup on the table. The sections below walk through each layer, the exact configuration keys, and the monitoring queries that tell you whether the layer is actually doing work.

Photon: what the vectorized engine actually changes

Standard Spark executes most operators one row at a time on the JVM. Each row crosses the Java object boundary, which means pointer chasing, boxing of primitive values, and poor CPU cache locality. Photon is a native C++ engine built by Databricks that processes data in columnar batches, typically 4,096 values per vector instruction, using SIMD on modern CPUs. The same filter over a billion-row table executes in a fraction of the time because the CPU stays in tight numeric loops instead of bouncing through the garbage collector.

Photon is enabled by default on DBR 11.3+ for SQL and DataFrame workloads, but you should verify rather than assume. Not every operator has a native implementation yet; when Photon hits an unsupported operator such as certain Python user-defined functions, it hands that stage back to the JVM. That fallback is silent in the UI unless you know where to look.

python
# Verify Photon is active on the current cluster
print(spark.conf.get("spark.databricks.photon.enabled"))

# Find operators that fell back to the JVM during a specific query
df = spark.sql("""
    SELECT /*+ REPARTITION(64) */ *
    FROM lakehouse.gold.customer_360
    WHERE lifetime_value > 10000
""")
df.explain(mode="extended")   # look for "PhotonSubquery" vs "WholeStageCodegen"

# Per-operator Photon coverage from the system tables
spark.sql("""
    SELECT
        operatorName,
        count(*)                AS executions,
        sum(totalTimeMs)        AS total_ms,
        sum(photonTimeMs)       AS photon_ms,
        round(100.0 * sum(photonTimeMs) / nullif(sum(totalTimeMs), 0), 1)
                                AS photon_pct
    FROM system.query.operator_metrics
    WHERE date_sub(current_date(), 1) <= startTime
    GROUP BY operatorName
    ORDER BY total_ms DESC
""").show(truncate=False)

A healthy SQL-shaped job reports photon coverage above ninety percent on its heavy stages. If you see long-running operators with near-zero Photon time, inspect them: they are usually Python UDFs, unpivot-style generators, or shuffle readers configured to a format Photon does not yet consume.

Adaptive Query Execution at runtime

Traditional Spark plans every join and shuffle before the first byte is read, using statistics gathered during catalog analysis. Those statistics are often stale or simply wrong for semi-structured data landing in a data lake. Adaptive Query Execution (AQE) defers three decisions until runtime, once real row counts are known: whether a sort-merge join can degrade into a broadcast join, how many shuffle partitions to emit, and how to split partitions that arrive wildly skewed.

The skew case is worth emphasizing because it maps to the most common production incident. Suppose you join web sessions to a events table keyed by user_id, and one celebrity account accounts for eight percent of all traffic. The default plan assigns that key to a single partition, so one executor works while thirty-one idle. AQE detects the skew at shuffle-write time and splits the oversized partition into sub-partitions processed in parallel, then reassembles the results. You can watch each decision land in the system tables:

python
# AQE knobs (already on by default, shown here for interview clarity)
spark.conf.set("spark.sql.adaptive.enabled", "true")
spark.conf.set("spark.sql.adaptive.coalescePartitions.enabled", "true")
spark.conf.set("spark.sql.adaptive.skewJoin.enabled", "true")
spark.conf.set("spark.sql.adaptive.skewJoin.skewedPartitionFactor", "5")
spark.conf.set("spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes", "256m")
spark.conf.set("spark.sql.adaptive.advisoryPartitionSizeInBytes", "128m")

# Why did AQE rewrite my plan? Ask the query history.
spark.sql("""
    SELECT
        queryId,
        description,
        error,
        duration
    FROM system.query.history
    WHERE startDate >= date_sub(current_date(), 7)
      AND description RLIKE 'AQE'
    ORDER BY duration DESC
    LIMIT 20
""").show(truncate=False)

One honest caveat: AQE occasionally makes a plan worse when your statistics were already excellent and the advisory partition size is mis-set for your data. If a job regresses after enabling AQE, compare the final physical plans with explain() on both settings before concluding AQE is at fault.

Delta Cache and the storage layer

Delta Lake stores table data as Parquet files on ADLS Gen2. Every cold read therefore pays network latency to cloud storage. Delta Cache keeps frequently accessed Parquet fragments on each executor's local SSD transparently, so repeated scans of hot partitions become local reads. On iterative machine learning jobs or dashboards that re-query the same dimension tables, cache hit rates above eighty percent are common, and end-to-end latency drops by two to ten times without a single line of SQL changing.

The cache is per-executor and evaporates when a cluster restarts, which is fine for ephemeral acceleration but useless as a substitute for correct partitioning. Complementary storage-layer tricks matter just as much: Z-ORDER co-locates related values in the same Parquet files so selective queries skip entire file footers, and Optimize writes rewrites many small files into medium ones, reducing the per-file overhead that dominates ingest-heavy tables.

TechniqueWhat it acceleratesWhen it pays offMain cost
PhotonCPU-bound scans and joinsWide SQL and DataFrame pipelinesMinimal; included in DBR
AQE coalesceShuffle write/read overheadJobs with far too many small partitionsSlight planning overhead
AQE skew joinSkewed join keysKeyed joins with hot customers or devicesExtra shuffle sub-tasks
Delta CacheRepeated reads of hot filesDashboards, iterative ML, dimension joinsLocal SSD disk usage
Z-ORDERSelective point lookupsFiltered queries on low-selectivity columnsRewrite IO during OPTIMIZE
Liquid clusteringEvolving partition needsTables whose access pattern changes over timeOne-time migration effort
python
# Weekly maintenance job for a large fact table
spark.sql("""
    OPTIMIZE lakehouse.gold.fact_orders
    ZORDER BY (customer_id, order_ts)
""")

# Bound the cache so it cannot starve the OS page cache
spark.conf.set("spark.databricks.io.cache.enabled", "true")
spark.conf.set("spark.databricks.io.cache.maxDiskUsage", "64g")
spark.conf.set("spark.databricks.io.cache.compression.enabled", "true")

# Measure whether the cache is earning its disk
spark.sql("""
    SELECT
        path,
        bytesRead,
        cacheHits,
        cacheMisses,
        round(100.0 * cacheHits / nullif(cacheHits + cacheMisses, 0), 1)
            AS hit_rate_pct
    FROM system.query.io_metrics
    WHERE date_sub(current_date(), 1) <= startTime
    ORDER BY bytesRead DESC
    LIMIT 25
""").show(truncate=False)

Sizing partitions and shuffles the boring way

Most "we need a bigger cluster" escalations dissolve into a partition-size conversation. Spark's default of 200 shuffle partitions dates from an era of much smaller clusters, and it produces thousands of tiny tasks whose scheduling overhead exceeds their execution time. The durable rule of thumb is one partition per 128 to 256 megabytes of compressed input. Below that, task overhead dominates; above that, you lose parallelism and risk executor OOM on skewed keys.

The table below gives concrete numbers for a 100-gigabyte compressed fact table on an eight-node cluster (eight executors, four cores each, so 32 effective cores).

Partition targetPartition countTask duration estimateScheduling overhead shareRecommendation
16 MB6,400Under 1 secondOver 40 percentFar too many tasks
64 MB1,6002 to 4 secondsAround 10 percentAcceptable for bursty jobs
128 MB8004 to 8 secondsUnder 5 percentSweet spot for most pipelines
256 MB4008 to 15 secondsNegligibleGood for scan-heavy ETL
1 GB10030 to 60 secondsNegligibleRisks executor memory pressure
python
# Repartition before an expensive join instead of relying on defaults
repartitioned = orders.repartition(
    800,                      # 100 GB / 128 MB target
    orders.customer_id        # co-partition on the join key
)

# Broadcast the small side rather than shuffling it
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", "100m")
joined = repartitioned.join(
    broadcast(customer_dim),
    "customer_id",
    "left"
)

# Kill runaway jobs cleanly instead of leaving zombie executors
spark.conf.set("spark.sql.adaptive.forceApply", "false")

Reading the Spark UI and system tables like a detective

When a job runs slow, resist the urge to resize the cluster first. Open the SQL tab in the workspace, find the query, and read the plan in execution order: which stage ran longest, whether it was a scan, a shuffle, or a join, and whether Photon claimed the operators. Then check the executor metrics for garbage-collection time and shuffle spill. A JVM-heavy stage with garbage-collection above ten percent of execution time is a Photon fallback or a UDF problem. Shuffle spill to disk means partitions exceed memory and need smaller sizes or more executors. Long scan stages with low CPU mean the storage layer is the bottleneck, which points you at Delta Cache, file sizing, or Z-ORDER.

Three queries form a reliable first-response toolkit. One lists the slowest queries in the last day with their scan and shuffle volumes. Two aggregates executor health, surfacing nodes with skewed task counts. Three compares Photon coverage per query so you can spot regressions after a DBR upgrade. Commit these to muscle memory; they turn a vague "the cluster is slow" ticket into a specific, evidence-backed fix.

When Photon and AQE do not help

Three scenarios deserve honest limits. First, streaming ingest from Event Hubs into Delta is usually throttled by source throughput or network bandwidth, not the Spark engine; buying Photon horsepower will not fix an under-provisioned event hub. Second, pipelines dominated by Python UDFs for feature engineering execute outside Photon entirely, so the fix is migrating those UDFs to native SQL expressions or Pandas-on-Spark vectorized functions. Third, jobs whose bottleneck is a single low-selectivity filter over parquet metadata gain more from Z-ORDER or liquid clustering than from any engine-level knob.

There is also a cost dimension. Photon and AQE come free with DBR, but Delta Cache consumes local SSD that only exists on compute-enabled node pools, and aggressive OPTIMIZE plus Z-ORDER schedules burn DBUs during rewrite windows. Schedule maintenance jobs in off-peak hours, cap rewrite concurrency, and measure the before-and-after query latency so the optimization can justify its own cost line.

Common Mistakes

Assuming Photon covers every operator and blaming the cluster when a Python UDF dominates runtime

Fix: Check operator-level Photon coverage in system.query.operator_metrics, then rewrite hot UDFs as SQL expressions or Pandas-on-Spark vectorized functions

Setting AQE advisory partition size to 1 GB to reduce task count on a small cluster

Fix: Target 128 to 256 MB per partition and let AQE coalesce upward only when real shuffle volumes justify it

Treating Delta Cache as durable storage that survives cluster restarts

Fix: Design for cache as ephemeral acceleration; keep Z-ORDER and file compaction as the durable I/O defenses

Resizing the cluster before reading the query plan

Fix: Always inspect the SQL tab execution plan, executor GC time, and shuffle spill first; size the cluster only after the bottleneck is classified

Best Practices

  • Verify Photon coverage after every DBR upgrade and pin the DBR version in production jobs
  • Set skewJoin.skewedPartitionThresholdInBytes based on measured key distributions, not defaults
  • Run OPTIMIZE with Z-ORDER on a schedule proportional to ingest volume, typically nightly for high-write tables
  • Record baseline query durations before each tuning change so improvements are provable
  • Keep autoBroadcastJoinThreshold aligned with actual executor memory, around one third of total core memory

Interview Questions

Q1: How does Photon differ from standard Spark execution?

Standard Spark executes operators row by row on the JVM with boxing and garbage-collection overhead. Photon executes the same operators in native C++ over columnar batches using SIMD, typically delivering two to eight times faster execution on SQL-shaped workloads. Operators without a native implementation fall back to the JVM, so coverage must be verified per query.

Q2: When would you disable Adaptive Query Execution?

Almost never in production. The rare cases are reproducible performance-regression testing where a deterministic plan is required, or a specific pattern where AQE's advisory partition sizing produces worse plans than hand-tuned static configuration. In that situation, capture both final plans and justify the override with data.

Q3: Walk me through diagnosing a job that got slower after a data volume increase.

First classify the bottleneck with the Spark UI: scan, shuffle, or join stage. If scan time grew proportionally with data and CPU is low, focus on Delta Cache, Z-ORDER, and file sizing. If shuffle grew, recompute partition counts against the 128 to 256 MB target. If a single join skewed, enable and tune AQE skew handling. Only escalate cluster size once the layer-specific fix is exhausted.

Q4: What is the relationship between Delta Cache and Z-ORDER?

They attack the same I/O bottleneck from different directions. Delta Cache speeds up repeated reads of already-hot files by serving them from local SSD. Z-ORDER rewrites file layout so selective queries skip irrelevant files entirely, reducing bytes read before any cache is involved. Used together, they cut both the number of files scanned and the latency of the files that remain.

Key Takeaways

  • Photon is a native vectorized engine; verify its operator coverage rather than assuming it, because Python UDFs silently fall back to the JVM
  • AQE defers join strategy, partition coalescing, and skew handling to runtime, which fixes the most common production skew incidents automatically
  • Delta Cache is ephemeral per-executor acceleration on local SSD; combine it with Z-ORDER for durable I/O reduction
  • Size shuffle partitions to 128 to 256 MB of compressed data and partition on the join key before expensive joins
  • Diagnose before you resize: scan, shuffle, and join bottlenecks each have a different first fix, and only one of them is more executors
🔒

Premium Content

Databricks Spark Optimization: Photon, AQE, and Delta Cache

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement