Jobs and workflows

Part of the free LogicWiz Data Engineering course, Module 13: The lakehouse on Databricks. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 6:40 on Thursday, and it has been a bad week. On Tuesday the bronze step timed out, silver ran anyway on Monday's data, and Tess's dashboard showed stale numbers as if they were fresh. On Wednesday someone reran everything by hand while the 06:00 run was still going, and the two runs collided on silver.orders. Nora has had enough: "Nobody should be pressing Run. Make it a job, and make it safe to run twice."

You'll learn to

  • Say what a job adds to a notebook
  • Use Run if conditions so no task runs on stale data
  • Make a task safe to retry, repair and backfill
  • Stop two runs colliding with a concurrency limit and a queue

Learn

A notebook needs you. A job does not.

Your medallion notebook works when you press Run. Tess needs gold refreshed by 06:00 every day, Sunday included, when nobody is pressing anything.

A job is the notebook plus standing instructions. On Databricks the product is called Lakeflow Jobs (it used to be called Workflows). A job holds:

  • tasks: a notebook, a Python file, a SQL query, a pipeline, a dbt project
  • dependencies: silver waits for bronze, gold waits for silver
  • a trigger: a schedule, a file arriving, or a table being updated
  • parameters such as run_date, plus retries, timeouts and notifications
  • the compute it runs on (serverless in Free Edition)

You build one on the Jobs & Pipelines page, or as a file kept in Git, like the one below.

A job as code (a Databricks Asset Bundle)

Runs on Databricks:

resources:
  jobs:
    swiftkart_daily:
      name: swiftkart-daily
      max_concurrent_runs: 1
      queue:
        enabled: true
      schedule:
        quartz_cron_expression: "0 0 6 * * ?"   # 06:00 every day
        timezone_id: UTC
      parameters:
        - name: run_date
          default: "{{job.start_time.iso_date}}"
      email_notifications:
        on_failure:
          - [email protected]
      tasks:
        - task_key: bronze
          notebook_task:
            notebook_path: ../notebooks/bronze.py
          max_retries: 2
          min_retry_interval_millis: 60000
          timeout_seconds: 1800
        - task_key: silver
          depends_on:
            - task_key: bronze
          notebook_task:
            notebook_path: ../notebooks/silver.py
        - task_key: gold_daily
          depends_on:
            - task_key: silver
          notebook_task:
            notebook_path: ../notebooks/gold_daily.py
        - task_key: notify_on_call
          depends_on:
            - task_key: bronze
            - task_key: silver
            - task_key: gold_daily
          run_if: AT_LEAST_ONE_FAILED
          notebook_task:
            notebook_path: ../notebooks/page_on_call.py

Read the four tasks at the bottom first, then the schedule at the top. The schedule is written in Quartz cron, which puts seconds first: seconds, minutes, hours, day of month, month, day of week. Deploy the file with databricks bundle deploy and start it with databricks bundle run swiftkart_daily. Kept in Git, the job is reviewed in a pull request like any other code (Module 10).

Tuesday: silver ran on stale data

On Tuesday nothing told silver that bronze had failed. Each step ran at its own time, whatever had happened to the one before it. A job is stricter. Its tasks form a DAG, the graph of who waits for whom from Module 9, and every task has a Run if condition.

The default is All succeeded: a task starts only when every task it depends on succeeded. If bronze fails, silver and gold do not run. Their status reads Upstream failed.

An alert task wants the opposite, so its condition is At least one failed. On a good day that condition is not met, and the task ends Excluded.

Before a task counts as failed, the job can retry it. That helps with failures that go away by themselves: a timeout, a throttled request, a lost node.

Tuesday again, this time as a job

The daily job as a graph: bronze feeds silver, which feeds two gold tasks, and an alert task hangs off them. Bronze fails after three tries, silver and gold end upstream failed, the alert task runs; then a good day where everything succeeds and the alert is excluded.

  1. 06:00: bronze starts. Silver waits for bronze. The two gold tasks wait for silver. The alert task waits for all of them.

  2. Bronze times out three times. max_retries: 2 means one try plus two retries. After the third timeout the task ends Failed.

  3. Silver and gold never start. Their condition, All succeeded, is not met, so they end Upstream failed. Nobody builds gold from yesterday's silver.

  4. The alert task runs. Its condition is At least one failed, and bronze failed. A person is told within minutes, and the gold tables still hold the last good numbers.

  5. A good day, for comparison. Bronze succeeds and silver follows. The two gold tasks share only silver, so the job starts them at the same time. The alert task ends Excluded.

Solid arrows mean "wait for me to succeed". Dashed arrows lead to the alert task, which runs only when something failed. Follow the colours along the arrows in each step.

A job run, simulated

tasks = {                    # task: the tasks it depends on
    'bronze': [],
    'silver': ['bronze'],
    'gold_daily': ['silver'],
    'gold_by_country': ['silver'],
}
calls = {}

def run_task(name):
    """Pretend work: bronze times out on its first try."""
    calls[name] = calls.get(name, 0) + 1
    if name == 'bronze' and calls[name] == 1:
        raise TimeoutError('storage request timed out')

def run_job(tasks, max_retries=2):
    state = {}
    while len(state) < len(tasks):
        for name in sorted(tasks):
            deps = tasks[name]
            if name in state or any(d not in state for d in deps):
                continue                          # done, or not ready yet
            if any(state[d] != 'SUCCESS' for d in deps):
                state[name] = 'UPSTREAM_FAILED'
            else:
                for attempt in range(1, max_retries + 2):
                    try:
                        run_task(name)
                        state[name] = 'SUCCESS'
                        break
                    except TimeoutError as e:
                        print(f'{name}: attempt {attempt} failed ({e})')
                else:
                    state[name] = 'FAILED'
            print(f'{name}: {state[name]}')
    return state

run_job(tasks)

Here bronze times out once and the retry saves the run. Now change calls[name] == 1 to calls[name] >= 1 so bronze fails every time, and run it again: bronze ends FAILED after three attempts, and the other three tasks end UPSTREAM_FAILED without running.

The run, task by task

TaskAttemptResultWhy
bronze1failedstorage timed out: a transient error
bronze2successthe retry worked
silver1successbronze succeeded, so it may start
goldbycountry1successwaits only for silver
golddaily1successthe two gold tasks could run side by side

The two gold tasks do not depend on each other, so a real job starts them at the same time. That is why the dependencies, not the order you list tasks in, define the job.

Remember: dependencies decide the order. Run if decides whether a task runs at all.

Run it twice, get the same table

A retry runs the task again. So does a manual rerun. That is only safe if running twice leaves the same table as running once. Such a task is called idempotent (Lesson 6.3). Two habits get you there.

Pass the day in. Never let a task ask for "today". Give the job a parameter, run_date, and read it in the notebook with dbutils.widgets.get("run_date"). Its default, {{job.start_time.iso_date}}, is a dynamic value reference: a placeholder filled in when the run starts. A rerun for 3 June then processes 3 June, whenever it runs.

Replace the day, never add to it. Delta's replaceWhere deletes and inserts one day in a single commit.

A daily load you can run twice

import minidelta

def load_day(table, run_date):
    """Replace one day's orders. Safe to rerun: the day is deleted first."""
    if table.version() >= 0:
        table.delete(f"CAST(order_ts AS DATE) = DATE '{run_date}'")
    table.write(f"SELECT * FROM 'data/orders.csv' WHERE CAST(order_ts AS DATE) = DATE '{run_date}'")

daily = minidelta.DeltaTable('lake/orders_by_day')
load_day(daily, '2025-06-03')
load_day(daily, '2025-06-03')      # the job retried after a timeout
load_day(daily, '2025-06-04')
print(daily.count(), 'rows')
print([h['operation'] for h in daily.history()])

3 June has 6 orders and 4 June has 5, so 11 is right: the retry replaced 3 June instead of doubling it. minidelta needs two commits (delete, write); replaceWhere does both in one, so no reader ever sees the day missing.

The gold notebook, idempotent on Databricks

Runs on Databricks:

from pyspark.sql import functions as F

run_date = dbutils.widgets.get("run_date")      # passed in by the job

day = (spark.table("workspace.silver.orders")
         .withColumn("order_date", F.to_date("order_ts"))
         .where(F.col("order_date") == F.lit(run_date)))

(day.write
    .mode("overwrite")
    .option("replaceWhere", f"order_date = '{run_date}'")
    .saveAsTable("workspace.gold.orders_by_day"))

Both habits in ten lines: the day comes from the parameter, and the write replaces only that day. mode("overwrite") with replaceWhere overwrites only the rows matching the condition, in one atomic commit. Without replaceWhere, overwrite would wipe every other day.

The trap: retries on a task that appends. A task that appends and then fails on its last step appends again on the retry: revenue doubles at 02:00 with nobody watching. Make each task replace its slice (replaceWhere, MERGE, overwrite), give it a timeout so a hung run fails instead of blocking tomorrow, and send failure alerts somewhere a person reads.

Small facts between tasks

Gold does not need to rebuild the whole month every morning. It needs to know which order dates bronze touched today. That is a small fact, and one task can hand it to a later one as a task value.

Bronze sets it: dbutils.jobs.taskValues.set(key="changed_dates", value=[...]). Gold reads it: dbutils.jobs.taskValues.get(taskKey="bronze", key="changed_dates", debugValue=[]). The debugValue is what get returns when you run the notebook by hand, outside a job.

Pass facts, never data. A list of 30 dates is fine. A million order ids belongs in a table.

Task values from bronze to gold

Runs on Databricks:

# In the bronze notebook: record which order dates this run touched
rows = spark.sql("""
    SELECT DISTINCT CAST(order_ts AS DATE) AS d
    FROM workspace.bronze.orders
    WHERE _source_file IN (SELECT path FROM workspace.bronze.files_loaded_today)
""").collect()
dbutils.jobs.taskValues.set(key="changed_dates", value=sorted(str(r["d"]) for r in rows))

# In the gold notebook, a later task in the same run
dates = dbutils.jobs.taskValues.get(taskKey="bronze", key="changed_dates", debugValue=["2025-06-03"])
print(dates)
['2025-06-03', '2025-06-04']

Gold now rebuilds two days, not thirty. get needs the upstream task's name. Avoid its default argument: it hides a misspelt key or task name by returning the default instead of failing.

Fix what failed, keep what worked

Say bronze fails at 06:32 and you fix the cause by 07:00. You do not have to run everything again. Repair run reruns only the tasks that did not succeed, and the tasks that depend on them. The successful ones are kept. The repair keeps the run's parameters, so it processes the same run_date.

Repair does not make a task idempotent, and Databricks says so plainly: a task that half-wrote before it failed writes again. That is why the two habits come first.

A failed run, then a repair

A timeline in minutes: bronze times out three times and the run fails at minute 32, with silver and both gold tasks marked upstream failed; at minute 60 a repair run reruns bronze, then silver, then the two gold tasks side by side.

Read it left to right, in minutes after 06:00. Bronze has max_retries: 2, so three tries with a minute between them. After the repair at minute 60, the green bars follow the same order as the DAG.

Wednesday: two runs at once

On Wednesday someone ran the notebook again by hand at 06:20, while the 06:00 run was still going. Two runs wrote to silver.orders at the same time, and one of them failed.

A job has a setting for this: max_concurrent_runs. Its default is 1. A second run that would break the limit is not started. With queue: enabled, it waits in a queue until the first run finishes.

Raise the limit only for a backfill, and only when the runs for different days touch different data. Two runs writing one Delta table are two concurrent writers, and Lesson 13.8 shows which one loses.

The same manual rerun, without and with a queue

A timeline: the scheduled run takes minutes 0 to 40; a manual rerun started at minute 20 overlaps it when there is no limit, but with one concurrent run and a queue it waits until minute 40 and then runs alone.

Compare the two bottom lanes: the same rerun, started at the same minute. The run times are made up for the example.

Runs over days: retries, catchup, backfill

A scheduler run grid over several days showing successful runs, a failed run with retries, catchup turned on and off, and a backfill over a date range.

Fail a day and watch the retries, then backfill a date range. Each square is one run for one date, which is why the date has to be a parameter.

Numbers to remember

SettingValueWhat it means
quartzcronexpression0 0 6 ?06:00 every day. Quartz cron puts seconds first: second 0, minute 0, hour 6
Run ifAll succeeded (the default), At least one succeeded, None failed, All done, At least one failed, All failedA success-based condition that is not met ends Upstream failed. A failure-based one ends Excluded
maxretries: 23 triesWith minretryintervalmillis: 60000, a minute between them
timeoutseconds: 180030 minutesA hung task fails instead of blocking tomorrow
{{job.starttime.isodate}}A dynamic value referenceFilled in when the run starts. A backfill run can use {{backfill.isodate}}
A task valueValid JSON, at most 48 KiB once serialisedAlso readable in a task parameter as {{tasks.bronze.values.changeddates}}
Repair runNeeds a job with two or more tasksYou can override parameters for the repair
maxconcurrentruns1Runs of one job that may be active at once
QueueingOn for jobs created in the UI since April 2024A run over the limit waits, for up to 48 hours, instead of being skipped
Free Edition5 running tasksThe cap across the whole account

Many teams orchestrate inside Databricks with Lakeflow Jobs. Others keep Airflow (Module 9) or Azure Data Factory as the conductor and call Databricks jobs from it, for example with Airflow's DatabricksRunNowOperator. Either way the job definitions live in Git and are deployed by CI, so a change to the schedule is reviewed like a change to the code.

What changed at SwiftKart

Friday, 06:00. Nobody is at a keyboard. Bronze times out once, the retry works, silver and gold follow, and Tess's dashboard is fresh when she opens it.

Had bronze failed for good, gold would have kept its last good numbers and the on-call phone would have rung. A rerun by hand now waits in the queue, and it processes the day it is given, not "today".

The job writes tables that hold customer names and emails, and it spends money every morning. Lesson 13.7 asks the two questions that follow: who may read what, and what is the bill made of?

In one line

A job is a notebook plus standing instructions: tasks that wait for each other, a schedule, a date passed in, retries and an alert; it is only safe to retry, repair or backfill when every task replaces its own day and one run goes at a time.

Interview corner

How do you orchestrate a pipeline on Databricks?

With a Lakeflow Job: one task per step with dependencies and Run if conditions, a Quartz cron schedule, file-arrival or table-update trigger, job parameters such as run_date defaulting to {{job.start_time.iso_date}}, retries and timeouts per task, and failure notifications or an alert task that runs if at least one task failed. I keep the definition in Git as an asset bundle and deploy it from CI. If the company already runs Airflow or Data Factory, those can trigger the Databricks job instead.

What makes a task safe to retry, repair or backfill?

Idempotency: running it twice leaves the same result as running it once. For a daily load that means processing the date passed in and replacing that slice with replaceWhere, MERGE or a partition overwrite, never a blind append; for streaming or foreachBatch writes, Delta's txnAppId and txnVersion make a replayed batch a no-op. The platform does not add idempotency for you: Repair run reruns failed tasks as they are.

A job failed half-way at 03:00. What do you do in the morning?

Read the failed task's error and classify it: transient (timeout, throttling, lost node) or a real bug or data problem. Fix the cause, then use Repair run so only the failed task and its dependents rerun with the same parameters, overriding a parameter if needed. Because tasks are idempotent, rerunning is safe; then I check row counts and freshness against the source before telling users the data is ready.

Two runs of the same job overlap and one fails with a Delta conflict. How do you prevent it?

Keep max_concurrent_runs at 1 with queueing on, so a manual or delayed run waits instead of overlapping, for up to 48 hours. When a backfill needs parallel runs, make each run write disjoint data (different partitions or replaceWhere ranges) so the commits do not conflict, and put retry logic on the MERGE or DELETE that loses, not on plain appends. Lesson 8 covers which operations conflict and the exception each raises.