4: Working with Lakeflow Jobs

    Implement Control Flows Using Lakeflow Jobs for Orchestration

    Production data pipelines fail.

    Bronze ingestion stalls because a connector quota throttles, a silver transformation runs out of memory because partition skew arrived in the latest batch, an external warehouse refuses a JDBC connection because a credential rotated.

    The orchestrator's first job is to make those failures recoverable without a pager call, and to express decisions in the graph rather than scattering them across notebook code. Lakeflow Jobs solves this through three control flow primitives:

    • retry policies attached to each task
    • conditional dependency rules expressed through run_if and the dedicated If/else condition task
    • bounded iteration through the For each task

    Every other control pattern (poison-message handling, conditional reruns, fan-out and fan-in) is composed from these three.

    Comparison

    The alternative path is to push control flow into the notebook body itself: wrap a Spark job in try/except, sleep and retry inline, fork on a Python if block, drive a loop in pure Python. This works for ad-hoc scripts and breaks for production.

    Inline retries do not show up as separate attempts in the run history, so a single failed attempt looks like a single succeeded attempt and on-call cannot tell the system was sick.

    Inline branching hides the decision from the task graph and from the lineage view, so the run-history UI shows a green node that secretly skipped half its work. Inline loops cannot fan out to parallel compute.

    Push the control flow up into Lakeflow Jobs, and the orchestrator records every attempt, every branch decision, and every iteration as a first-class run that you can re-run, inspect, and gate alerts on.

    Retry Policies per Task

    Every task on a Lakeflow Jobs graph carries its own retry policy.

    How it works

    The policy has three knobs:

    • max_retries (how many additional attempts to make after the first failure, with -1 meaning unlimited)
    • min_retry_interval_millis (the floor of the back-off interval between attempts)
    • retry_on_timeout (whether to count a task that hit its timeout_seconds as a retryable failure)

    These three knobs are independent. You can build a fast-fail task with max_retries: 0, a self-healing ingestion task with three retries on a two-minute floor, or a long-lived poller that retries forever until cancelled.

    Critically, the orchestrator allocates a fresh task run for each attempt, so each retry shows up as its own row in the run history with its own logs, its own duration, and its own attempt number. The run-level UI rolls those attempts up under a single task run so you can see the whole sequence at a glance, but the underlying records are separate.

    Retry semantics interact carefully with downstream depends_on edges. A task is only considered successful when an attempt succeeds. The orchestrator does not start a downstream task until the upstream's final attempt resolves. If you have a chain bronze_load -> silver_transform -> gold_publish and bronze_load fails twice and succeeds on the third attempt, silver_transform sees a single upstream success and runs once. There is no notion of partial success that triggers a downstream rerun.

    This matters because some teams reach for retries to compensate for transient infrastructure issues (rate limits, transient network failures, evicted spot instances) and other teams reach for retries to compensate for data quality issues. The first use is correct. The second is not: retrying a task because a malformed record blew up a parse function will just rerun the same parse against the same record and fail in the same place. Retries are for transient failure. Branching is for known-bad data.

    {
     "task_key": "ingest_orders",
     "notebook_task": {
     "notebook_path": "/Workspace/Repos/data_eng@acme.example/acme-pipelines/ingest/orders"
     },
     "max_retries": 3,
     "min_retry_interval_millis": 120000,
     "retry_on_timeout": true,
     "timeout_seconds": 900,
     "job_cluster_key": "ingest_cluster"
    }
    

    The configuration above declares a notebook task that will try four times in total (one initial attempt plus three retries), with each retry separated by at least two minutes, treating a timeout at fifteen minutes as a retryable failure.

    This is a sensible default for an ingestion task that reads from a flaky external API.

    For a transformation task that reads from Delta and writes to Delta, the right shape is max_retries: 1 or 2 with min_retry_interval_millis: 30000 and retry_on_timeout: false, because a Delta transformation that times out is almost always doing real work that you don't want to abandon.

    💡 Exam Trap: max_retries counts retries, not total attempts. A value of 3 means up to four total attempts (the initial run plus three retries). A value of 0 means a single attempt with no retry on failure. A value of -1 means unlimited retries, useful only for tasks that ping an external source until it answers.

    📊 Limit: Task timeout_seconds defaults to 0, which means no task-level timeout (the only ceiling is the job-level timeout). Set an explicit value for any task that calls an external service, otherwise a hung HTTP client can keep an executor pinned indefinitely.

    Conditional Task Flow with run_if

    depends_on declares the topology. run_if declares the execution rule. By default, a task with depends_on: [{"task_key": "upstream"}] runs when upstream succeeds.

    The run_if clause changes that. It accepts one of six values: ALL_SUCCESS (the default), AT_LEAST_ONE_SUCCESS, NONE_FAILED (succeed or skip is acceptable, hard failure is not), ALL_DONE (run regardless of upstream outcome), AT_LEAST_ONE_FAILED (run only if at least one upstream failed), and ALL_FAILED (run only if every upstream failed).

    The two practical patterns are the cleanup task and the alerting task. A cleanup task uses ALL_DONE to run a teardown step after the main graph, no matter how the main graph ended.

    An alerting task uses AT_LEAST_ONE_FAILED to trigger a notification only when something actually broke. Both replace the older pattern of running these steps inside the notebook body with a finally block, which had the side effect that a successful cleanup masked a failed main step in any external monitoring tool that watched only the notebook exit code.

    tasks:
     - task_key: silver_transform
     notebook_task:
     notebook_path: /Workspace/Repos/data_eng@acme.example/acme-pipelines/silver/orders
     job_cluster_key: silver_cluster
     max_retries: 2
    
     - task_key: gold_publish
     notebook_task:
     notebook_path: /Workspace/Repos/data_eng@acme.example/acme-pipelines/gold/orders
     depends_on:
     - task_key: silver_transform
     job_cluster_key: gold_cluster
    
     - task_key: alert_on_failure
     notebook_task:
     notebook_path: /Workspace/Repos/data_eng@acme.example/acme-pipelines/ops/notify
     depends_on:
     - task_key: silver_transform
     - task_key: gold_publish
     run_if: AT_LEAST_ONE_FAILED
     job_cluster_key: ops_cluster
    

    In this configuration, alert_on_failure is part of the same job as the silver and gold tasks but only runs when at least one of them fails.

    The alert is recorded as a successful task in the run history (it ran and exited cleanly) while the upstream task that failed is recorded as failed.

    The overall job result is failed, because run_if does not change how a job's overall status is computed: a job is failed if any required task fails, where "required" means a task that downstream tasks expect to succeed under their own run_if rules.

    The If/else Condition Task

    When the decision depends on data rather than upstream outcome, the right primitive is the If/else condition task. This is a zero-compute task whose job is to evaluate a boolean expression against job parameters and task values and then mark itself as True or False. Downstream tasks then attach to either the True branch or the False branch through depends_on plus a special outcome selector.

    {
     "task_key": "decide_full_refresh",
     "condition_task": {
     "op": "EQUAL_TO",
     "left": "{{job.parameters.run_mode}}",
     "right": "full_refresh"
     }
    },
    {
     "task_key": "full_refresh_bronze",
     "depends_on": [
     { "task_key": "decide_full_refresh", "outcome": "true" }
     ],
     "notebook_task": {
     "notebook_path": "/Workspace/Repos/data_eng@acme.example/acme-pipelines/bronze/full_refresh"
     }
    },
    {
     "task_key": "incremental_bronze",
     "depends_on": [
     { "task_key": "decide_full_refresh", "outcome": "false" }
     ],
     "notebook_task": {
     "notebook_path": "/Workspace/Repos/data_eng@acme.example/acme-pipelines/bronze/incremental"
     }
    }
    

    The supported operators are EQUAL_TO, NOT_EQUAL, GREATER_THAN, GREATER_THAN_OR_EQUAL, LESS_THAN, LESS_THAN_OR_EQUAL. Both sides of the comparison may be literal strings or parameter references.

    The {{...}} template expands at run start and resolves three families of values:

    • {{job.parameters.<name>}} reads a job parameter
    • {{tasks.<task_key>.values.<name>}} reads a task value emitted by an upstream task through dbutils.jobs.taskValues.set
    • {{job.run_id}}, {{job.start_time}}, and similar context variables read built-in run metadata

    The condition task pairs with task values to express data-aware branching. An upstream notebook computes a count, calls dbutils.jobs.taskValues.set(key="new_rows", value=count), and a downstream condition task compares that value against a threshold. If the threshold is met, the heavy gold_publish step runs. Otherwise, it skips.

    # Inside a notebook task with task_key 'check_new_rows'
    new_rows = spark.table("acme_prod.silver.orders") \
     .filter("ingest_date = current_date()") \
     .count()
    dbutils.jobs.taskValues.set(key="new_rows", value=new_rows)
    

    The downstream condition task then compares {{tasks.check_new_rows.values.new_rows}} against a literal like "0" using GREATER_THAN.

    💡 Exam Trap: The If/else condition task does not run user code. It is a declarative comparison. If you need to call an API, read a table, or run arbitrary Python to make the decision, do the work in an upstream notebook task and emit a task value, then point the condition task at that value. Trying to put logic inside the condition expression itself will not work.

    ⚠️ Anti-Pattern: Forking on data inside the notebook body with if new_rows > 0: do_work() looks simpler but hides the branch from the run-history UI. The DAG view will show the notebook as a single green node every time, with no signal that the heavy work was skipped. Express the branch through a condition task so the DAG shows which path executed.

    The For each Task

    The third control flow primitive is the For each task, which iterates a child task across a list of inputs and runs each iteration as its own task run. The list of inputs can be a literal JSON array, a job parameter, or a task value emitted by an upstream task. Each iteration receives its element through a template variable, which the child task references in its own configuration.

    {
     "task_key": "process_each_region",
     "for_each_task": {
     "inputs": "{{tasks.list_regions.values.regions}}",
     "concurrency": 4,
     "task": {
     "task_key": "process_region",
     "notebook_task": {
     "notebook_path": "/Workspace/Repos/data_eng@acme.example/acme-pipelines/gold/by_region",
     "base_parameters": {
     "region_code": "{{input}}"
     }
     },
     "job_cluster_key": "gold_cluster",
     "max_retries": 1
     }
     },
     "depends_on": [
     { "task_key": "list_regions" }
     ]
    }
    

    The concurrency field caps how many iterations run in parallel. Without a cap, every iteration would attempt to start simultaneously, which can exhaust cluster slots and quota. A value of 4 means at most four iterations are in flight at any moment; the orchestrator queues the rest and starts them as slots free up.

    Each iteration is a distinct task run with its own attempt count, its own retry behavior, and its own success or failure. The parent For each task succeeds when every iteration succeeds and fails as soon as one iteration fails, unless you set for_each_task.task.run_if semantics or unless the parent's own run_if is permissive.

    When to use

    For each is the right tool for parameterized fan-out:

    • per-region builds
    • per-tenant exports
    • per-table audits

    It is the wrong tool for unbounded iteration. If the iteration count is data-dependent and could be in the millions, push the loop into Spark itself through foreach or a groupBy plus a UDF and keep the orchestrator's view at a single task. The orchestrator records every iteration in the run history, which is a feature at fan-out levels of tens to low hundreds and a liability at fan-out levels of tens of thousands.

    📊 Limit: Lakeflow Jobs imposes a ceiling on the number of For each iterations per task run. The exact value is governed by the iteration-count limit documented in the job limits page. Expect the bound to live in the low hundreds in single digit thousands range, not the millions. Treat For each as a finite-fan-out operator, not as a substitute for a Spark transformation over a billion-row table.

    🎯 Scenario: A retail data team has eighteen country-specific gold marts. Each mart is a single notebook that takes a country code parameter, runs about twelve minutes, and is independent from the others. The team initially built eighteen sibling tasks in a job and got tired of maintaining eighteen near-identical task definitions. The right pattern is a single For each task with inputs set to a job parameter that lists the country codes, concurrency: 6 to bound parallel cluster usage, and a single child notebook task definition. Adding a country becomes a parameter edit instead of a graph edit.

    Combining the Primitives

    Real production graphs combine all three:

    • Retries handle transient infrastructure noise.
    • Conditional flow handles data-aware branching.
    • For each handles parameterized fan-out.

    The general shape is a sequencer chain where every task carries a retry policy sized to its failure profile, a small number of condition tasks gate expensive work, and one or two For each tasks fan out per-tenant or per-region work.

    Cleanup and alerting steps attach to the tail with ALL_DONE or AT_LEAST_ONE_FAILED semantics.

    Decision Anchor: Choose a retry policy when the failure mode is transient and a re-execution will succeed unchanged. Choose run_if when the decision depends on the success status of upstream tasks. Choose an If/else condition task when the decision depends on a data value or job parameter. Choose a For each task when the same child step must run against a bounded list of inputs in parallel.

    Choose Spark-internal iteration (groupBy, foreach) when the iteration count is unbounded or data-dependent at scale.


    Continue with the interactive course

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