Sub topic 15
Looping over inputs with For each tasks
A For each task runs one nested task once for every item in a list of inputs. This chapter shows how to define the loop, feed it a list, control how many iterations run at once, and handle failures. It assumes you can already define a multi-task job with depends_on, pass task values with dbutils.jobs.taskValues, and set max_retries on a task.
When to use a loop
Suppose you need to process 40 customer regions with the same notebook, and only one parameter differs. You have three options:
- Copy the task 40 times. The job definition becomes unreadable.
- Loop inside the notebook with
for region in regions:. Everything runs in one task, so one failure fails all of it, you can't retry one region, and the Jobs UI shows no per-region status. - Use a For each task. Each region becomes its own iteration with its own status, retries, and logs. A repair run can rerun only the failed ones.
The third option is usually the best fit when the iterations are independent and each is a meaningful unit of work.
How a For each task is built
A For each task is a wrapper. It has three fields:
| Field | Meaning |
|---|---|
| `inputs` | The list to iterate over. A static JSON array string, or a reference to a task value. |
| `concurrency` | The maximum number of iterations that run at the same time. The default is 1. |
| `task` | The nested task that runs once per input. It has its own `task_key` and a task type such as `notebook_task`. |
Inside the nested task, the placeholder {{input}} holds the current item. You usually pass it to the notebook as a parameter.
[
{
"task_key": "list_regions",
"job_cluster_key": "etl_cluster",
"notebook_task": {"notebook_path": "/Workspace/Shared/list_regions"}
},
{
"task_key": "process_regions",
"depends_on": [{"task_key": "list_regions"}],
"for_each_task": {
"inputs": "{{tasks.list_regions.values.regions}}",
"concurrency": 4,
"task": {
"task_key": "process_region",
"job_cluster_key": "etl_cluster",
"notebook_task": {
"notebook_path": "/Workspace/Shared/process_region",
"base_parameters": {"region": "{{input}}"}
},
"max_retries": 1
}
}
}
]The first task produces the list. The For each task depends on it in the usual way, then reads the list from the task value named regions.
Producing the input list
The upstream notebook publishes a list with dbutils.jobs.taskValues.set. The value must be JSON-serializable.
# Notebook for task "list_regions"
regions = [
r["region"]
for r in spark.sql("SELECT DISTINCT region FROM sales.raw_orders").collect()
]
dbutils.jobs.taskValues.set(key="regions", value=regions)The receiving notebook reads its parameter as a widget:
# Notebook for the nested task "process_region"
dbutils.widgets.text("region", "")
region = dbutils.widgets.get("region")
df = spark.table("sales.raw_orders").where(f"region = '{region}'")
df.write.mode("overwrite").saveAsTable(f"sales.summary_{region.lower()}")
print(f"Processed {df.count()} rows for {region}")For a fixed list, skip the upstream task and write the array as a string: "inputs": "[\"emea\", \"apac\", \"amer\"]".
Inputs that are objects
Each item can be a JSON object instead of a string. You then read its fields with {{input.field_name}}. This is useful when each iteration needs several values, such as a table name and a date range.
{
"for_each_task": {
"inputs": "[{\"table\": \"orders\", \"days\": 7}, {\"table\": \"returns\", \"days\": 30}]",
"concurrency": 2,
"task": {
"task_key": "compact_table",
"job_cluster_key": "etl_cluster",
"notebook_task": {
"notebook_path": "/Workspace/Shared/compact",
"base_parameters": {
"table": "{{input.table}}",
"days": "{{input.days}}"
}
}
}
}
}Execution flow
The iterations are not ordered by dependencies. They start in list order as concurrency slots free up, and they may finish in any order. A downstream task such as publish depends on the For each task as a whole, so it starts only when every iteration has finished.
Concurrency and compute
concurrency is the main tuning knob, and its default of 1 surprises people: the loop runs sequentially unless you raise it. The Jobs API accepts values up to 100.
Concurrency only helps if there is compute to run on. If the nested task uses the job cluster that the other tasks share, all concurrent iterations compete for that one cluster. Four concurrent notebook runs on a two-worker cluster can finish no faster than running them one at a time. Two options:
- Size the cluster for the concurrency you set.
- Give the nested task its own job cluster. Each iteration then starts its own compute, which adds startup time per iteration. Prefer a shared cluster when iterations are short.
If iterations write to the same table, also consider write conflicts. Concurrent writes to different partitions are usually fine. Concurrent overwrites of the same table are not.
Failures, retries, and repair
Retries and timeouts set on the nested task apply to each iteration separately. With max_retries: 1, a failing region is retried once without affecting the others.
If an iteration still fails after its retries, the For each task is marked failed, and tasks that depend on it with the default run_if rule (ALL_SUCCESS) are skipped. The other iterations still run to completion.
A repair run reruns only what failed. It reruns the failed iterations and the downstream tasks that were skipped, not the iterations that succeeded. This is a major benefit over looping inside one notebook.
Limits to know
- The nested task must be a single task. You cannot nest a For each task inside another For each task.
- The list passes through task values, which have a size limit (the Databricks documentation gives it as 48 KiB). Very large lists should be split into batches, or each iteration should read its own slice from a table.
- Check the current documentation for the maximum number of iterations. Very large loops create many runs and are better handled by batching items.
Common mistakes
- Leaving
concurrencyat 1 and wondering why the loop is slow. - Passing a Python list string that is not valid JSON, such as single-quoted items. Task values serialize correctly. Hand-written
inputsstrings must be valid JSON. - Referencing
{{input}}outside the nested task. It exists only inside thetaskblock. - Expecting a downstream task to see per-iteration task values as if they were separate tasks. Downstream tasks depend on the For each task as one unit.
Exercise
A For each task has 12 inputs, concurrency 3, and a nested task with maxretries 2. Iteration 7 fails on every attempt, and the other 11 succeed. What is the status of a downstream task that uses the default runif rule, and what does a repair run rerun?
Show answer
The For each task fails once iteration 7 has used its two retries, so the downstream task with the default ALL_SUCCESS rule is skipped. The other 11 iterations still run to completion. A repair run reruns only iteration 7 and then the skipped downstream task. It does not rerun the 11 successful iterations.