9: Debugging and Deploying

    Debugging and Troubleshooting

    When a production Databricks workload fails, the cost of guessing root cause is significant. Re-running a 90-minute pipeline against the same bad upstream file repeats the same failure and burns DBUs without producing new evidence.

    The Databricks Data Engineer Professional exam frames this surface as a triage discipline:

    • walk a fixed sequence of evidence layers,
    • narrow the failure class (job orchestration, task code, Spark execution, infrastructure),
    • and only then choose a remediation path (code fix and full re-run, repair run with parameter override, pipeline full refresh, cluster-config change).

    The wrong answer pattern in this domain is almost always "re-run the job" without first reading the diagnostic surface that already contains the failure cause.

    How it works

    The four diagnostic surfaces map to four different timescales and abstraction levels.

    • The Spark UI shows you the physical execution of a single Spark application: which stage failed, which task in that stage, which executor ran the failed task, what the GC time, shuffle read, and spill looked like, and what the full stack trace was.
    • Cluster logs are the lower-level driver and executor stdout/stderr, plus log4j output and the init-script log; they pick up the failures Spark itself cannot report (OutOfMemory before Spark can surface the exception, init-script timeout, container kill by YARN-equivalent).
    • System tables aggregate across workloads: system.lakeflow.job_run_timeline tells you the orchestration outcome of every job run, system.query.history shows every SQL warehouse statement with its files-read and spilled-bytes counters, system.billing.usage ties failures to DBU spend so you can prioritize remediation.
    • The Query Profile UI is the SQL-warehouse-specific deep dive into a single SELECT statement, with the operator graph annotated by per-node bytes-read, rows-produced, and time-in-node.

    Triage Order: Start at the Outermost Layer

    The instinct to "open the Spark UI" first is the most common triage error on the exam. The correct entry point depends on the workload type.

    • For a failed Lakeflow Jobs run, the entry point is the run page in the Lakeflow Jobs UI or the equivalent row in system.lakeflow.job_run_timeline, because that surface shows which task failed and links from that task to the underlying Spark application (which is what the Spark UI exposes).
    • Walking into the Spark UI directly skips the question "which task in the DAG actually failed", and on a 12-task job that question matters before any low-level investigation.
    • For a failed Lakeflow SDP run, the entry point is the pipeline update page (or the published event log table), not the Spark UI, because the SDP event log is the only surface that carries flow-level metadata (which flow, which expectation, which APPLY CHANGES key range).
    • For a failed BI query on a SQL warehouse, the entry point is the Query Profile UI, not the Spark UI, because the Query Profile is the SQL-warehouse-tailored evidence surface.
    # Triage entry-point lookup for a failed job run from the CLI.
    # Step 1: find the run by job ID and the failed result_state.
    # Step 2: drill from the run into the failed task and its Spark UI link.
    
    from databricks.sdk import WorkspaceClient
    
    w = WorkspaceClient()
    
    job_id = 4287913201
    failed = [
     r for r in w.jobs.list_runs(job_id=job_id, expand_tasks=True, limit=10)
     if r.state and r.state.result_state and r.state.result_state.value == "FAILED"
    ]
    
    for run in failed[:1]:
     print(f"run_id={run.run_id} start={run.start_time} state={run.state.state_message}")
     for t in run.tasks or []:
     if t.state and t.state.result_state and t.state.result_state.value != "SUCCESS":
     print(f" task={t.task_key} attempt={t.attempt_number} cluster={t.cluster_instance.cluster_id}")
     print(f" spark_ui={t.cluster_instance.spark_context_id}")
     print(f" run_page_url={t.run_page_url}")
    

    The run_page_url is the deterministic link into the per-task Spark UI; from there you traverse Jobs → Stages → the failed stage → the failed task → its stack trace.

    The exam will sometimes describe a job where two tasks failed in parallel; the correct first action is to inspect each task's Spark application separately, because two failed tasks can have unrelated root causes (one OOM, one missing file path) that demand different fixes.

    The Spark UI Triage Flow

    Key points

    The Spark UI exposes five tabs relevant to debugging: Jobs, Stages, SQL / DataFrame, Executors, and Structured Streaming. The DE Professional level expects fluent navigation across all five.

    The Jobs tab is the entry point because it lists the Spark Jobs the application launched, with their success/failure state and duration. A failed Spark Job carries a status of "Failed" with a red bar; clicking it opens the per-Job page, which lists the Stages that the Job launched.

    The Stages page is where you spot the bottleneck stage:

    • long Duration
    • high Shuffle Read or Shuffle Write
    • high Input Size
    • a non-zero failed-tasks count

    Each Stage has a "Summary Metrics for Completed Tasks" table that lets you compare the median task with the max task across five metrics: Duration, GC Time, Shuffle Read Size, Shuffle Write Size, Spill (Disk).

    A max-over-median ratio above roughly 3 on Duration or Shuffle Read Size is the textbook signal of partition skew, the failure class where one task processes much more data than its peers. The fix is upstream of the failure:

    • either repartition with a salt before the join
    • lower spark.sql.adaptive.skewJoin.skewedPartitionFactor so Adaptive Query Execution splits the skewed partition more aggressively
    • or convert a fact-times-fact join into a broadcast-times-fact join when the small side fits under spark.sql.autoBroadcastJoinThreshold

    The Spark UI does not directly recommend any of these; it surfaces the evidence and the engineer chooses the remedy.

    The Executors tab tells you which executors had GC pressure, OOM kills, or evictions.

    An executor with > 30% of its lifetime in GC is a memory-pressure signal; the fix is either a larger executor (more memory per task) or fewer tasks per executor (lower spark.executor.cores).

    The Storage tab shows cached datasets and their fraction-in-memory; when a .cache() block evicts to disk on a high-pressure job, the downstream stages slow down dramatically.

    The SQL / DataFrame tab shows the physical plan as an operator graph; the most common debugging use is to confirm that a filter pushed down past a join (the filter operator appears below the Exchange and below the join, not above it) and that a Sort-Merge Join was not turned into a Broadcast Hash Join when one side has crossed the broadcast threshold.

    # Cluster logs: where the driver and executor stdout/stderr live.
    # Lakeflow Jobs writes log artifacts under the cluster log destination
    # configured on the job cluster spec, or to the default workspace storage.
    
    databricks clusters list --output JSON | jq -r '.[] | select(.cluster_name | test("^job-")) | .cluster_id'
    
    # Pull driver logs for a specific cluster_id (run_id-bound for job clusters).
    databricks clusters spark-logs-deliver \
     --cluster-id 0719-220437-pluck123 \
     --destination dbfs:/cluster-logs
    
    # Driver log layout under the destination:
    # <dest>/<cluster_id>/driver/log4j-active.log
    # <dest>/<cluster_id>/driver/stderr
    # <dest>/<cluster_id>/driver/stdout
    # <dest>/<cluster_id>/executor/<executor_id>/{stderr,stdout,log4j-active.log}
    # <dest>/<cluster_id>/init_scripts/<script_name>.{log,stderr,stdout}
    

    The driver log4j-active.log is the file that records the full Spark application lifecycle:

    • when the SparkContext was created,
    • when each job was submitted,
    • every WARN and ERROR thrown by the application,
    • the final job status.

    Init-script logs are critical when a job fails at cluster startup:

    • a missing PyPI dependency,
    • a wheel that fails to install,
    • a broken environment variable.

    These never surface in the Spark UI because the SparkContext was never created.

    💡 Exam Trap: When a Lakeflow Jobs task fails with state_message containing "Cluster terminated unexpectedly", the Spark UI is gone (the cluster was reclaimed). The correct evidence surface is the cluster log destination set on the job cluster: the init-script log shows install failures, the driver stderr shows the OOM kill or container-kill reason. If no log destination is configured on the job cluster, the logs are not retrievable after the cluster termination; the remediation is to add a cluster_log_conf block to every production job cluster spec.

    📊 Limit: Spark UI history for an active cluster lives in driver memory and is lost when the cluster terminates. Cluster log delivery to S3, ADLS Gen2, GCS, or a Unity Catalog Volume is the only durable path; logs are flushed roughly every 5 minutes (spark.databricks.clusterUsageTags.cluster_log_destination_max_delay_seconds controls the upper bound) and on cluster termination.

    System Tables as the Aggregated Evidence Surface

    System tables are the cross-job, cross-workspace evidence layer. They answer questions the Spark UI cannot:

    • "which job has failed most often this billing period"
    • "which task has the highest mean retry count"
    • "which SQL warehouse statement spilled the most bytes"
    • "which user ran the failed query"

    The four system tables relevant to debugging are system.lakeflow.job_run_timeline, system.lakeflow.job_task_run_timeline, system.query.history, and system.access.audit.

    job_run_timeline carries one row per job run with result_state, termination_code, and the duration.

    job_task_run_timeline carries one row per task attempt (so a task that ran twice via repair produces two rows).

    The result_state column takes values SUCCESS, FAILED, CANCELED, TIMEDOUT, plus the compound state SUCCESS_WITH_FAILURES for multi-task jobs where some tasks succeeded and some failed but the job itself was not retried.

    termination_code is finer-grained: USER_REQUEST for a user cancellation WORKSPACE_CANCELED_RUN DRIVER_ERROR EXECUTOR_FAILURE LIBRARY_INSTALLATION_FAILURE CLUSTER_ERROR MAX_CONCURRENT_RUNS_REACHED and dozens more, each pointing at a different remediation.

    -- Find the top-10 most-failed job tasks in the last billing window,
    -- broken out by termination_code so the next investigation step is unambiguous.
    
    SELECT
     jt.job_id,
     jt.task_key,
     jt.termination_code,
     COUNT(*) AS failed_attempts,
     AVG(unix_timestamp(jt.period_end_time)
     - unix_timestamp(jt.period_start_time)) AS avg_seconds_in_attempt,
     MAX(jt.period_end_time) AS last_failure
    FROM system.lakeflow.job_task_run_timeline jt
    WHERE jt.result_state = 'FAILED'
     AND jt.period_start_time >= current_date() - INTERVAL 14 DAYS
    GROUP BY jt.job_id, jt.task_key, jt.termination_code
    ORDER BY failed_attempts DESC
    LIMIT 10;
    

    The query above lets a data engineer triage at fleet scale:

    • A LIBRARY_INSTALLATION_FAILURE cluster trends are usually a missing wheel in the cluster init scripts (fix in the job cluster spec).
    • A CLUSTER_ERROR cluster is a sign of regional capacity pressure or a too-aggressive autotermination policy.
    • A MAX_CONCURRENT_RUNS_REACHED cluster means max_concurrent_runs is set too low for the trigger cadence.
    • The EXECUTOR_FAILURE termination is the one that demands the deepest Spark UI follow-up: it indicates a task crash that Spark itself could not recover from after retries.

    system.query.history is the SQL-warehouse equivalent for debugging: every statement gets a row keyed by statement_id, with status (FINISHED, FAILED, CANCELED), error_message, total_duration_ms, compilation_duration_ms, execution_duration_ms, read_bytes, read_rows, spilled_local_bytes, and result_cache_hit.

    A FAILED status with a error_message of MAX_QUERY_DURATION_EXCEEDED points at the warehouse timeout (default 172800 seconds). A high spilled_local_bytes suggests insufficient memory on the warehouse size. result_cache_hit = true means the query never actually executed and the failure is unrelated to data.

    The Query Profile UI for SQL Warehouse Statements

    For a failed or slow SQL warehouse statement, the Query Profile UI is the deep dive.

    It is reached from system.query.history.statement_id via a deep link or from the Query History UI.

    The Query Profile shows the physical query plan as a tree of operators, each annotated with Files Read, Files Pruned, Bytes Read, Rows Produced, and Time in Node.

    The "most expensive node" (highest time-in-node) is the entry point for optimization.

    Examples

    Common patterns the exam tests:

    • A Sort-Merge Join with both inputs hot (right answer: convert to a Broadcast Hash Join by pre-filtering the small side or hinting BROADCAST)
    • A Filter operator above an Exchange instead of below it (right answer: rewrite the query so the predicate is on the source table before the shuffle)
    • A Files Read count equal to the total file count of the table with Files Pruned of zero (right answer: add a Liquid Clustering column on the filter predicate or add CLUSTER BY so per-file statistics let the scan prune)

    🎯 Scenario: A nightly Silver-layer job has failed three nights in a row. The Lakeflow Jobs UI shows result_state = FAILED on task clean_orders with termination_code = EXECUTOR_FAILURE. The engineer's first move is NOT to open the Spark UI; it is to query system.lakeflow.job_task_run_timeline for the last 14 days, group by termination_code, and confirm the failure cluster is consistent. The query shows EXECUTOR_FAILURE seven times this month, with avg attempt duration 47 minutes; the run-page Spark UI shows one stage with a 12:1 max-over-median skew ratio. Root cause: a single retailer's customer_id produces 60% of the data after the join. Fix: salt the key before the join with concat(customer_id, lit('_'), cast(rand()*16 as int)) on the fact side, then unsalt on the dimension side; the next run completes in 9 minutes.

    Lakeflow SDP Event Logs for Pipeline Debugging

    For Lakeflow Spark Declarative Pipelines, the Spark UI shows the underlying Spark application but does NOT show flow-level metadata. A pipeline with eight flows where one flow fails on an expectation will show, in the Spark UI, a successful Spark application; the failure lives in the SDP event log.

    The event log is a Delta table that every pipeline writes; it is queried either through the event_log(<pipeline_id_or_target>) table-valued function (the convenient path) or, when event_log is published to a Unity Catalog table via the pipeline configuration, by direct SQL. The published path is the recommended one in production because it lets long-running monitoring dashboards point at a stable UC table without holding a reference to the pipeline ID.

    -- Query the SDP event log for the last failed update of a pipeline.
    -- The event_log() TVF accepts a pipeline ID, a pipeline name, or a UC table reference.
    
    SELECT
     timestamp,
     event_type,
     level,
     message,
     details:flow_progress.flow_name AS flow_name,
     details:flow_progress.status AS flow_status,
     details:flow_progress.metrics.num_output_rows AS output_rows,
     details:flow_progress.data_quality.dropped_records AS dropped,
     details:flow_progress.data_quality.expectations AS expectations
    FROM event_log("3d6f2c1e-4a8b-4f0a-9d12-ab7a2c4e9b91")
    WHERE event_type IN ('flow_progress', 'update_progress', 'data_quality')
     AND timestamp >= current_timestamp() - INTERVAL 1 HOUR
    ORDER BY timestamp DESC
    LIMIT 200;
    

    The event_type column drives the lens.

    update_progress records pipeline-level state transitions: INITIALIZING RUNNING STOPPING COMPLETED FAILED CANCELED

    A FAILED row's details:update_progress.error field carries the top-level error.

    flow_progress records per-flow state with details:flow_progress.status taking values: QUEUED STARTING RUNNING IDLE COMPLETED FAILED EXCLUDED SKIPPED STOPPED

    For streaming flows, details:flow_progress.metrics.backlog_bytes and backlog_files show backlog accumulation.

    data_quality rows expose expectation outcomes: passed_records, failed_records, dropped_records, and per-expectation name, dataset, passed_records, failed_records.

    planning_information rows expose the pre-execution plan, including which materialized views were detected as fully recomputable vs incrementally maintainable; this is the surface that explains "why did my MV do a full recompute when only 1 row changed".

    cluster_resources rows expose autoscaling events on classic SDP clusters.

    In practice

    The exam expects you to know which event_type to filter on for a given symptom.

    "Pipeline ran but no rows landed" is a data_quality lens: did dropped_records jump and expectations show a regex-quarantine rule rejecting everything.

    "Pipeline ran but materialized view recomputed when only a few rows changed" is a planning_information lens: the planner emits a row with details:planning_information.technique_information.maintenance_type of FULL_REFRESH vs INCREMENTAL, with a reason such as NON_DETERMINISTIC_QUERY or UNSUPPORTED_OPERATION_FOR_INCREMENTAL_MV.

    "Streaming flow falling behind" is a flow_progress lens combined with cluster_resources: if backlog is growing but no autoscale event fired, the autoscaler is throttled by max_workers.

    ⚠️ Anti-Pattern: Treating the Spark UI as the only debugging surface for a Lakeflow SDP pipeline. The Spark UI shows the Spark execution of the materialization, but the expectation failure that dropped 95% of the rows lives in data_quality events in the event log. Engineers who only look at the Spark UI see "the job succeeded" and never spot the data-quality regression. The published event log table plus a SQL Alert on dropped_records > threshold is the production-grade pattern.

    Job Repair Runs and Parameter Overrides

    When a multi-task Lakeflow Job fails at task 6 of 10, the engineer does not want to re-execute tasks 1 through 5; those have already committed their writes (Delta is ACID at the table level, not at the job level), and re-running them risks double-write, idempotency violations, or wasted compute.

    The Lakeflow Jobs repair-run feature solves this by re-running ONLY the failed task and its downstream dependencies. The repair-run UI lets you:

    • pick which failed tasks to repair
    • optionally set per-task parameter overrides for that specific repair
    • optionally select a different cluster spec

    A repair run is a NEW attempt of the same run_id. It does not get a new run_id; instead, job_task_run_timeline shows multiple rows for the repaired task with incrementing attempt_number.

    The exam frequently tests this point: the answer to "how many run_id values does a job with two repair runs have" is "one"; the answer to "how many rows in job_task_run_timeline" is "one per task per attempt".

    # Repair a failed run by re-running only the failed task with a parameter override.
    # The repair-run REST endpoint is /api/2.2/jobs/runs/repair.
    
    databricks jobs repair-run \
     --json '{
     "run_id": 891234,
     "rerun_tasks": ["clean_orders"],
     "rerun_dependent_tasks": false,
     "notebook_params": {
     "ingest_date": "2026-04-12",
     "source_path": "s3://corp-bronze/orders/2026/04/12/",
     "max_files_per_trigger": "5000"
     },
     "performance_target": "STANDARD"
     }'
    

    The rerun_tasks array is the list of task keys to repair; rerun_dependent_tasks controls whether downstream tasks are re-run after the repaired task succeeds.

    The parameter override block (notebook_params, python_params, jar_params, sql_params, pipeline_params, spark_submit_params) replaces the task's job-level parameters for this attempt only; the job definition is not modified.

    This is the right pattern for "the ingest task failed because the source partition was empty; re-run it with a different date".

    Editing the job definition would change the steady-state behaviour; the parameter override fixes only the failed attempt.

    When to use

    rerun_dependent_tasks = false is the right answer when the failed task's downstream tasks were skipped (they never ran, so there is nothing to re-do) AND you only want to verify the repaired task succeeds in isolation.

    rerun_dependent_tasks = true is the right answer when the downstream tasks did run, partially succeeded, and now need fresh inputs from the repaired upstream.

    The exam tests the distinction: a four-task DAG where task 2 failed and tasks 3 and 4 were skipped should be repaired with rerun_dependent_tasks = true so tasks 3 and 4 run on the repaired task 2's output.

    💡 Exam Trap: Repair runs do NOT roll back the writes that successful upstream tasks made. If task 1 wrote to a Bronze table, then task 2 failed, then a repair run re-ran task 2, the Bronze writes from task 1 are still present. Designing tasks to be idempotent at the table level (MERGE INTO with a deterministic key, INSERT OVERWRITE with a partition predicate, Delta txnAppId / txnVersion writes) is the only way to make a repair safe under retried-upstream scenarios.

    📊 Limit: A repair run cannot reset the start_time of the original run, but the original run_id accumulates duration across attempts. The system.lakeflow.job_run_timeline row for the repaired run shows a single period_start_time from the original attempt and a final period_end_time from the last successful repair, so SLA calculations on run_duration must subtract pre-repair time when the repair was operator-triggered hours after the original failure.

    Parameter Override Patterns

    Parameter overrides on a repair are scoped to that repair only. They are the right tool for one-off fixes:

    • a bad ingest_date
    • a poisoned source path
    • a regression in a feature flag that needs to be temporarily disabled
    • a temporary lift of max_files_per_trigger to drain a backlog

    They are the wrong tool for permanent fixes: changing the job's notebook parameters in the override field every run is a sign that the job definition needs updating in the bundle and a redeploy.

    The exam tests this distinction; the parameter override is for ad-hoc remediation, the bundle re-deploy is for code-as-data permanent change.

    The override is applied as a merge over the existing parameters, not a replacement of the entire parameter set.

    A job with {"ingest_date": "2026-04-11", "source_system": "pos"} repaired with {"ingest_date": "2026-04-12"} runs the repaired task with {"ingest_date": "2026-04-12", "source_system": "pos"}.

    This merge semantics is consistent with the run-now REST endpoint behaviour, so an engineer who already understands run-now can predict repair behaviour without reading new docs.

    🎯 Scenario: A scheduled Lakeflow Job ingests yesterday's partition every morning at 02:00. On 04-12 the run failed because the upstream system delivered no data for 04-11; the ingest task threw AnalysisException: Path does not exist. The wrong remediation is to mark the run as a success and forget it; the right remediation is to repair the failed task with notebook_params = {"ingest_date": "2026-04-10"} to backfill the missing partition once the upstream system delivers it, then trigger a fresh run-now for 04-11 once data arrives. The job definition does not change. The repair preserves the 04-12 run_id for SLA accounting and the parameter override keeps the fix scoped to that attempt.

    Tying It Together: Pipeline Debugging Workflow

    For a Lakeflow SDP pipeline failure, the practitioner workflow is:

    • open the pipeline update page
    • identify the failed flow from the flow graph (the failed flow shows a red badge)
    • click into the flow to see the Spark application's UI link
    • query the event log filtered by the failed flow's name to read the exception
    • decide whether the fix is in the pipeline code (push through DABs) or in the input data (run a repair with full_refresh = false and a refresh_selection of just the affected flow, or a full_refresh = true on a single table for a clean rebuild).

    The refresh_selection and full_refresh_selection knobs on the SDP update REST endpoint let you scope a re-run to a subset of tables without re-running the whole pipeline; the equivalent of a Lakeflow Job repair.

    # Trigger a partial pipeline update that refreshes only one streaming table
    # and one materialized view, without touching the rest of the pipeline.
    
    from databricks.sdk import WorkspaceClient
    
    w = WorkspaceClient()
    
    update = w.pipelines.start_update(
     pipeline_id="3d6f2c1e-4a8b-4f0a-9d12-ab7a2c4e9b91",
     full_refresh=False,
     refresh_selection=["silver_clean_orders"],
     full_refresh_selection=["gold_daily_revenue"],
    )
    print(update.update_id)
    

    refresh_selection adds the listed tables to the incremental refresh set; full_refresh_selection triggers a full rebuild on the listed tables (drops state for streaming tables, recomputes materialized views from scratch).

    Both lists are applied additively.

    This is the SDP equivalent of a Lakeflow Job repair with rerun_dependent_tasks; the engineer can choose a surgical fix without re-paying the cost of the whole DAG.

    Combined with validate_only=True (which runs the pipeline planner without executing flows, returning a dry-run plan), the practitioner can verify a pipeline code change does not break the planner before the full update fires.

    ⚠️ Anti-Pattern: Using full_refresh = true on the entire pipeline when only one materialized view returned wrong results. A full refresh drops state on every streaming table, forcing them to re-read from the source from the beginning; on a Bronze streaming table reading from cloud storage with cloudFiles.includeExistingFiles = false, the practitioner can lose all historical events. The surgical fix is full_refresh_selection = ["affected_mv_name"] to rebuild only the broken table, leaving streaming-table checkpoints intact.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Databricks - Data Engineer Professional learning hub.