← BuildandTeach Tech Tutorials posts

Published · By Henry Palma

Databricks Data Engineer Associate Exam Prep, Lesson 14: Jobs Control Flow with Retries, If/Else and For Each (Retry Only What Is Safe to Rerun)

Databricks Data Engineer Associate exam prep: use retries, If/else condition and For each tasks in Lakeflow Jobs, and avoid retrying a load that is not idempotent.

Databricks Data Engineer Associate Exam Prep, Lesson 14: Jobs Control Flow with Retries, If/Else and For Each (Retry Only What Is Safe to Rerun)

Exam-style question: The nightly orders job from Lesson 13 should run silverorders and golddailysales only on nights when ingestorders loaded new orders. The ingest notebook already saves the number of new rows as a task value named newrows. What should you add to the job? Add an If/else condition task that checks {{tasks.ingestorders.values.newrows}} > 0, and make silverorders depend on its true outcome. The branch then lives in the job's task graph, where the run details show the condition and which way it went, instead of being hidden inside notebook code. This post follows Lesson 14 of the Databricks Data Engineer Associate exam prep series, in Section 4 of the August 2026 exam guide, Working with Lakeflow Jobs (16% of the exam).

Watch on YouTube

Video thumbnail
Video thumbnail

The job definition, notebooks and cheat sheet are in the A14 folder on GitHub. The PDF cheat sheet is in the same folder. This is independent study material, not official Databricks training.

The exam objective

Section 4 of the exam guide lists this objective: implement control flows (retries and conditional tasks such as branching and looping) using Lakeflow Jobs for pipeline orchestration.

Lakeflow Jobs gives you a tool for each part of that sentence:

| Control flow | Lakeflow Jobs feature | What it does | |---|---|---| | Retries | Retry policy on a task | Re-runs a failed task up to a set number of times | | Branching | If/else condition task | Runs the true branch or the false branch based on a comparison | | Branching on failure | Run if conditions | Runs a task based on whether its dependencies succeeded or failed | | Looping | For each task | Runs one nested task once per item in an input list |

Free Edition works for this lesson. Free Edition jobs run on serverless compute, and the jobs limit is a maximum of 5 concurrent job tasks per account (Databricks "Free Edition limitations" page, checked Nov 30, 2026). Keep that number in mind when you set a For each concurrency.

The scenario: the nightly orders job grows up

The retail orders data from Lessons 8 to 13 continues. In Lesson 13 the nightly job was a straight chain: ingestorders -> silverorders -> golddailysales. Tonight it needs three new behaviors:

  1. Retry the ingest twice. Reading the landing folder sometimes fails for a passing reason, and a restart fixes it.
  2. If new order files arrived, run silver and gold. On a quiet night, skip them.
  3. For each region, land a regional file. The regions are the customer states in this dataset: TX, CO and OK. Each region gets its own daily sales file for its team.

Plus one task that should only run when something breaks: notifyonfailure.

Here is the finished graph:

ingest_orders (retries: 2)
  --> has_new_orders (If/else: new_rows > 0)
        true --> silver_orders --> gold_daily_sales
                   --> land_region_files (For each: TX, CO, OK)
notify_on_failure (Run if: At least one failed)

Retries: first make the task safe to run twice

A retry policy re-runs a task when it fails. In the Jobs UI you open the task, click Add next to Retries, and set the number of retries and the wait between them. In the Jobs API the same settings are maxretries and minretryintervalmillis on the task. Facts from the Databricks docs that the exam likes:

  • For most job configurations, the default is no retries.
  • Serverless jobs auto-optimize retries by default. That means a serverless task can be retried even if you never set a retry policy. Databricks recommends leaving this on, but for a task that must run at most once, for example a task that is not idempotent, you can uncheck Enable serverless auto-optimization (may include additional retries) in the Retry Policy dialog. Free Edition is serverless only, so this applies there too.
  • The retry interval is measured from the start of the failed run to the start of the retry.
  • If you set both a timeout and retries, the timeout applies to each retry.
  • In the Jobs API, max_retries: 0 means never retry and -1 means retry without limit.

Now the trap. Idempotent means that running the task twice leaves the same result as running it once. A retry re-runs the whole task from the start, so a task that is not idempotent can do its work twice. This ingest is not safe to retry:

# NOT safe to retry:
# a second run appends the same rows again
spark.sql("""
  INSERT INTO bronze.orders
  SELECT * FROM read_files(
    '/Volumes/workspace/bronze/landing/orders/',
    format => 'csv', header => true,
    schema => 'order_id INT, customer_id INT,
               order_date STRING, amount DOUBLE')""")

If the task fails after the insert has committed, for example in a later cell, the retry inserts the same orders again. The run ends green, and bronze.orders now has every order from last night twice. More retries make it worse, not better.

Make the task idempotent first, then add the retries. A MERGE on order_id only inserts orders that are not already in the table, so a second run adds nothing. The notebook also counts the new rows and saves the count as a task value for the If/else task:

# 01_ingest_orders (A14): safe to retry
before = spark.table("bronze.orders").count()
spark.sql("""
  MERGE INTO bronze.orders AS t
  USING (SELECT * FROM read_files(
    '/Volumes/workspace/bronze/landing/orders/',
    format => 'csv', header => true,
    schema => 'order_id INT, customer_id INT,
               order_date STRING, amount DOUBLE')) AS s
  ON t.order_id = s.order_id
  WHEN NOT MATCHED THEN INSERT *""")
new_rows = spark.table("bronze.orders").count() - before
dbutils.jobs.taskValues.set(key="new_rows",
                            value=new_rows)

This example reads the whole landing folder each night to stay short. For real volumes of files, COPY INTO (Lesson 3) and Auto Loader (Lesson 4) are also safe to re-run, because they keep track of the files they already loaded and skip them.

If/else: branch in the graph, not in the notebook

An If/else condition task compares two operands with one operator: ==, !=, >, >=, < or <=. An operand can be a fixed value, a job parameter such as {{job.parameters.runmode}}, or a task value such as {{tasks.ingestorders.values.new_rows}}.

Task values are how one task hands a small result to later tasks. You set them with dbutils.jobs.taskValues.set() in a Python notebook, and the value must be valid JSON no larger than 48 KiB. Other task types can read them through the {{tasks.<taskname>.values.<valuename>}} reference.

Two details about the comparison come straight from the docs:

  • == and != compare as strings. 12.0 == 12 is false.
  • >, >=, < and <= compare as numbers. 12.0 >= 12 is true.

So new_rows > 0 is a numeric comparison, which is what you want here.

To build the branch in the UI, add the If/else condition task, then select it and click Add task. The new task's Depends on defaults to hasneworders (true). Choose hasneworders (false) for a task that should run on the false branch instead. In the Jobs API, the branch is an outcome on the dependency:

{"task_key": "has_new_orders",
 "depends_on": [{"task_key": "ingest_orders"}],
 "condition_task": {"op": "GREATER_THAN",
                    "left": "{{tasks.ingest_orders.values.new_rows}}",
                    "right": "0"}},
{"task_key": "silver_orders",
 "depends_on": [{"task_key": "has_new_orders", "outcome": "true"}],
 "sql_task": {"file": {"path": "/Workspace/Shared/a14/02_silver_orders.sql", "source": "WORKSPACE"},
              "warehouse_id": "WAREHOUSE_ID"}}

silverorders and golddailysales run the same SQL files as Lesson 13. On a quiet night, newrows is 0, the condition is false, and the true branch is skipped. After the run, the job run details show the condition result and how the expression was evaluated.

One more thing to know: an If/else condition task fails if the upstream task that provides its condition value is disabled.

Run if: the fail path

If/else branches on a value. Run if branches on what happened to the upstream tasks. Lesson 13 covered the options. For the fail path you need one task with At least one failed:

  • notifyonfailure depends on ingestorders, silverorders, golddailysales and landregionfiles, with Run if set to At least one failed.
  • On a good night none of them failed, so the condition is not met and the task is marked Excluded and skipped.
  • Upstream tasks marked Excluded are treated as successful when Databricks evaluates Run if conditions. On a quiet night nothing fails, so the alert stays quiet too.
  • If ingest_orders still fails after both retries, the notification runs. Retries come first, then the fail path.

For each: loop in the graph, not in the notebook

The tempting way to land the regional files is a loop inside one notebook:

# Hidden loop: one task, one status, one retry for all regions
for region in ["TX", "CO", "OK"]:
    land_region_file(region)

It works on a good night. On a bad night, the job shows one failed task. You have to read the notebook output to learn which region failed, and a retry re-runs every region, including the ones that already finished.

A For each task puts the loop in the job instead. It has two parts: the For each task, which holds the list of inputs, and a nested task, which runs once per input. In the UI:

  1. Click Add task and choose For each as the type.
  2. In Inputs, enter a JSON array, for example ["TX", "CO", "OK"]. Inputs can also come from a task value or a job parameter.
  3. Optionally set Concurrency, the number of iterations that can run at the same time. The default is 1.
  4. Click Add a task to loop over and configure the nested task. It can be any standard task type, but not another For each task.
  5. In the nested task's parameters, use {{input}} for the current item. For a list of objects, use {{input.field}}, for example {{input.table}}.
{"task_key": "land_region_files",
 "depends_on": [{"task_key": "gold_daily_sales"}],
 "for_each_task": {
   "inputs": "[\"TX\", \"CO\", \"OK\"]",
   "concurrency": 3,
   "task": {"task_key": "land_region_file",
            "notebook_task": {"notebook_path": "/Workspace/Shared/a14/04_land_region_file",
                              "base_parameters": {"region": "{{input}}"}}}}}

The nested notebook handles one region and overwrites only that region's folder, so running it twice gives the same file. That keeps each iteration safe to retry too:

# 04_land_region_file (A14): one region per iteration
region = dbutils.widgets.get("region")
(spark.sql("""
    SELECT o.order_date, COUNT(*) AS orders,
           SUM(o.amount) AS sales
    FROM silver.orders o JOIN silver.customers c
    USING (customer_id) WHERE c.state = :region
    GROUP BY o.order_date""", args={"region": region})
  .write.mode("overwrite").option("header", True)
  .csv("/Volumes/workspace/gold/exports/daily_sales/"
       f"region={region}"))

What you get from the graph version:

  • Each iteration is its own task run. The run page shows a table of iterations, so you see TX, CO and OK separately.
  • Concurrency is a setting, not code. Three regions with a concurrency of 3 stay under the Free Edition limit of 5 concurrent job tasks per account. A longer list, such as one entry per table, works the same way, but keep the concurrency at 5 or fewer.
  • Downstream tasks depend on the For each task itself, not on the nested task. They can still read the task values each iteration set, as one list in iteration order.

The JSON array typed into Inputs is limited to 5,000 characters. A task value reference can stand for a list of up to 48 KB. So a longer list, such as every table in a schema, should come from a task value set by an earlier task. And like the If/else task, a For each task fails if the upstream task that provides its inputs is disabled.

The checklist: retry-and-branch review

Before you save a job with control flow, check these five things:

  1. Idempotent retries. For every task with retries, ask: if it runs twice, is the result the same? If not, fix the task (MERGE on a key, COPY INTO, Auto Loader, overwrite one partition) or remove the retries. On serverless, also decide whether auto-optimization retries are acceptable.
  2. Branch in the graph. Decisions the job makes go in an If/else condition task that reads a task value or job parameter. Check which tasks hang off the true outcome and which off the false outcome.
  3. Fail path. One task with Run if At least one failed (or All failed) that tells someone. It runs only after the retries are used up.
  4. Loop grain. One For each iteration per independent unit, such as one region or one table. Each iteration should do its own unit only, so it can fail and be retried alone.
  5. Concurrency. For each concurrency plus everything else running in the account stays at 5 or fewer on Free Edition.

The reusable snippet checks a job's task list against points 1, 3 and 5 before you save it. It is plain Python and does not call Databricks:

def check_control_flow(tasks, idempotent, max_parallel=5):
    problems = []
    keys = {t["task_key"] for t in tasks}
    nested = [t["for_each_task"]["task"] for t in tasks if "for_each_task" in t]
    for t in list(tasks) + nested:
        if t.get("max_retries", 0) != 0 and t["task_key"] not in idempotent:
            problems.append(f"{t['task_key']} retries but is not idempotent")
    for t in tasks:
        fe = t.get("for_each_task")
        if fe and fe.get("concurrency", 1) > max_parallel:
            problems.append(f"{t['task_key']} runs {fe['concurrency']} iterations at once")
        if "condition_task" in t:
            outcomes = {d.get("outcome") for u in tasks
                        for d in u.get("depends_on", []) if d["task_key"] == t["task_key"]}
            if "true" not in outcomes:
                problems.append(f"{t['task_key']} has no task on its true branch")
    if not any(t.get("run_if") in ("AT_LEAST_ONE_FAILED", "ALL_FAILED") for t in tasks):
        problems.append("no fail path: add a task that runs when something fails")
    for t in tasks:
        for d in t.get("depends_on", []):
            if d["task_key"] not in keys:
                problems.append(f"{t['task_key']} depends on unknown task {d['task_key']}")
    return problems

Run against the full nightly job with idempotent={"ingestorders", "landregionfile"}, it returns an empty list. Leave ingestorders out of the idempotent set and it returns ['ingestorders retries but is not idempotent']. Remove notifyonfailure and raise the concurrency to 8, and it returns ['landregion_files runs 8 iterations at once', 'no fail path: add a task that runs when something fails']. The snippet cannot tell whether your code is really idempotent. That is still your call, which is why you pass the set in yourself.

Practice exam-style question

A nightly job's ingestorders task runs INSERT INTO bronze.orders from the night's order files and has a retry policy of 2 retries. Some mornings, last night's orders appear twice in bronze.orders. The run history shows that on those nights ingestorders failed once in a later step and then succeeded on a retry. What is the best fix?

  • A) Raise the retries to 5 so the task always succeeds on the first night
  • B) Make the ingest idempotent, for example a MERGE on order_id, and keep the retries
  • C) Move the ingest into a For each task with a concurrency of 1
  • D) Set the downstream tasks' Run if to All done

Answer: B. A retry re-runs the whole task. The first attempt's insert had already committed, so the retry inserted the same orders again. A MERGE on order_id inserts only orders that are not in the table yet, so a retry is harmless and you keep the protection against passing failures. A adds more chances to duplicate. C changes nothing about the insert. D changes when downstream tasks run, not what the ingest writes.

Key takeaways

  • Section 4 control flow means three tools: retries (retry policy), branching (If/else condition task, plus Run if for failures) and looping (For each task).
  • A retry re-runs the whole task, so only retry tasks that are idempotent. On serverless jobs, retries are auto-optimized by default, and you can turn that off for a task that must run at most once.
  • If/else compares two operands. == and != compare strings, while >, >=, < and <= compare numbers. Dependent tasks follow the true or the false outcome.
  • For each runs one nested task per input, passes the item as {{input}}, and has a default concurrency of 1. Keep loops and branches in the job graph, not hidden in notebook code.
  • Memory trick: safe to rerun, safe to retry. And branch and loop in the graph, not in the notebook.

Next lesson (Lesson 15): Job triggers: scheduled, file arrival, and table update.

Check your understanding

1. An If/else condition task compares {{job.parameters.batch_size}} == 12, and the job parameter is set to 12.0. What is the result?

  • A) True, because 12.0 and 12 are the same number
  • B) False, because == compares the operands as strings
  • C) The task fails, because job parameters cannot be used as operands
  • D) True, because If/else converts both operands to integers

2. In a For each task with the inputs ["TX", "CO", "OK"], how does the nested task get the current region?

  • A) With the {{input}} reference in the nested task's parameters
  • B) With {{job.parameters.input}}
  • C) It reads all three values and must pick one itself
  • D) With {{tasks.landregionfiles.values.region}}

3. You add a For each task and leave Concurrency empty. How many iterations run at the same time?

  • A) All of them
  • B) 5, the Free Edition limit
  • C) 1, the default
  • D) 10

4. A serverless job has a task that must run at most once, because running it twice would send a payment twice. What should you change?

  • A) Nothing, because serverless tasks are never retried unless you add a retry policy
  • B) Set the task's Run if to All done
  • C) Wrap the task in a For each task with one input
  • D) In the Retry Policy dialog, uncheck Enable serverless auto-optimization (may include additional retries)

5. A publishexports task must wait until every iteration of the landregion_files For each task has finished. What should it depend on?

  • A) The nested task landregionfile
  • B) The For each task landregionfiles
  • C) A separate dependency on each iteration
  • D) Nothing, because For each iterations always finish before any other task starts

Answer key

  1. B. The == and != operators compare strings, so 12.0 == 12 evaluates to false.
  2. A. {{input}} holds the current item. For a list of objects you use {{input.field}}.
  3. C. Concurrency defaults to 1, so iterations run one at a time unless you raise it.
  4. D. Serverless jobs auto-optimize retries by default. Turning that off is the documented setting for tasks that must run at most once.
  5. B. Downstream tasks depend on the For each task itself. A task cannot set the nested task as a dependency directly.

Have an idea, question, or feedback?

We'd genuinely like to hear from you.