Sub topic 12
Scheduling and orchestrating the flow with jobs
This chapter assumes you can run the bronze, silver, and gold steps from earlier chapters by hand. It also assumes you know what a Databricks notebook is and what a Delta table is. Here you will turn those steps into a repeatable flow that runs on a schedule, in the right order, and tells you when it fails.
Why a flow needs orchestration
Each layer depends on the one before it. Silver reads what bronze wrote, and gold reads what silver wrote. If you run the steps by hand, or schedule them independently at fixed times, three problems appear:
- Silver can start before bronze finishes, so it processes stale or partial data.
- A failed bronze run goes unnoticed, and silver and gold keep running on old data.
- Nobody knows which run produced which table state.
Orchestration is the practice of running tasks in a defined order, passing control from one to the next, and handling failures. On Databricks, the tool for this is a job. A job is a named, saved definition of one or more tasks, their dependencies, a compute choice, and a trigger. Each execution of a job is a run.
The parts of a job
A job is built from a few pieces.
| Piece | What it is | Medallion example |
|---|---|---|
| Task | One unit of work | A notebook that runs the Auto Loader code |
| Dependency | A rule that a task waits for others | Silver depends on bronze |
| Compute | What runs the task | Serverless compute or a job cluster |
| Trigger | What starts a run | A daily schedule or a file arrival |
| Parameters | Values passed into tasks | A catalog name such as `main` |
| Notifications | Who is told about outcomes | The data engineering team on failure |
Task types you will meet most often are notebook, Python script, SQL, and pipeline. A pipeline task runs a declarative pipeline, which is useful if you built the layers as in the previous chapter on declarative pipelines. A job can mix task types, so one job can run a pipeline task and then a SQL task.
Mapping layers to tasks
The simplest design uses one task per layer. Task dependencies form a directed graph, and for the medallion flow it is a straight line.
If a task fails, the tasks that depend on it do not run. They are marked as upstream failed. This is the behavior you want for a medallion flow. Silver should not merge from a bronze table that was left half updated, and gold should not publish numbers from a silver step that errored.
Splitting by layer also gives you precise reruns. If gold fails because of a bad SQL expression, you can repair the run and rerun only gold. Bronze and silver keep their results.
Making tasks safe to rerun
Orchestration will run tasks more than once. A schedule fires again, a person repairs a run, or a retry kicks in. Each task must be idempotent, meaning that running it twice gives the same table state as running it once.
The earlier chapters already gave you this property in each layer:
- Bronze uses Auto Loader with a checkpoint, so each file is ingested once even if the task is rerun.
- Silver uses
MERGEkeyed onorder_id, so a rerun updates existing rows instead of duplicating them. - Gold uses
CREATE OR REPLACE TABLE, so a rerun rebuilds the same result from silver.
The bronze code uses trigger(availableNow=True). This matters for jobs. With that trigger the stream processes everything that is available and then stops, so the task ends and the job can move on to the next task. A stream with a continuous trigger never finishes, so a downstream task would wait forever.
One more detail: availableNow=True can return before the write is finished if you do not wait for it. In a notebook task, the notebook may end while the stream is still running, depending on how the code is written. Call awaitTermination() on the query so the task only succeeds after the write completes.
query = (
raw.writeStream
.option("checkpointLocation", "/Volumes/main/sales/checkpoints/orders_bronze")
.trigger(availableNow=True)
.toTable("main.bronze.orders")
)
query.awaitTermination()Passing parameters
Hard-coded names make a flow hard to move between environments. A common pattern keeps one set of code and changes the catalog per environment, such as dev, staging, and main. Job parameters supply the value, and notebook widgets read it.
dbutils.widgets.text("catalog", "main")
catalog = dbutils.widgets.get("catalog")
spark.sql(f"""
CREATE OR REPLACE TABLE {catalog}.gold.daily_revenue AS
SELECT
CAST(order_ts AS DATE) AS order_date,
COUNT(*) AS orders,
SUM(amount) AS revenue
FROM {catalog}.silver.orders
WHERE status = 'completed'
GROUP BY CAST(order_ts AS DATE)
""")Job-level parameters are visible to every task, so you set catalog once and each layer's task uses it. Only interpolate values you control into SQL strings like this. Do not build SQL from values that users can supply.
Defining the job
You can build a job in the Jobs UI, but a definition kept in source control is easier to review and repeat. Databricks Asset Bundles describe jobs in YAML, and you deploy them with the Databricks CLI. The example below defines the three-task flow.
resources:
jobs:
orders_medallion:
name: orders_medallion
parameters:
- name: catalog
default: main
schedule:
quartz_cron_expression: "0 0 2 * * ?"
timezone_id: "UTC"
pause_status: UNPAUSED
email_notifications:
on_failure:
- [email protected]
tasks:
- task_key: bronze_ingest
notebook_task:
notebook_path: ../src/bronze_ingest.py
max_retries: 2
- task_key: silver_merge
depends_on:
- task_key: bronze_ingest
notebook_task:
notebook_path: ../src/silver_merge.py
- task_key: gold_aggregate
depends_on:
- task_key: silver_merge
notebook_task:
notebook_path: ../src/gold_aggregate.pyThe schedule uses Quartz cron syntax, which has a seconds field first. 0 0 2 * * ? means 02:00:00 every day. Always set the timezone explicitly. Without it, a daylight saving change can move the run time when you expected it to stay put.
Compute is omitted here, so the tasks use serverless compute where it is available for your workspace. If your workspace needs a cluster, define a job cluster and refer to it from each task with job_cluster_key. A job cluster is created when the run starts and ends when it finishes, which costs less than an always-on cluster for a daily flow.
Choosing a trigger
A schedule is not the only way to start a run. The right choice depends on how data arrives.
| Trigger | Use it when | Trade-off |
|---|---|---|
| Scheduled | Consumers need fresh data at known times | Data that arrives just after a run waits for the next one |
| File arrival | New files land in a volume at unpredictable times | Runs may be frequent if files arrive in many small bursts |
| Continuous | You need low latency and always-on processing | Compute runs all the time, so it costs more |
| Manual or API | An external system or a person decides | Needs someone or something to call it |
File arrival triggers watch a storage location and start the job when new files appear. They fit the landing folder in this tutorial well. Even then, keep Auto Loader in the bronze task. The trigger only decides when to run, and the checkpoint still decides which files to read.
Retries, timeouts, and failure handling
Not every failure deserves the same response. Transient problems, such as a brief cloud storage error, are fixed by a retry. Logic errors, such as a failed cast in silver, are not fixed by a retry and need a person.
- Set
max_retrieson tasks that touch external systems, such as bronze. Add a retry interval so the retry does not hit the same outage. - Set a timeout on each task or on the job. A stuck task otherwise holds compute until someone notices.
- Send failure notifications to a team address, a chat webhook, or an on-call tool, not to a single person.
- Use repair run after you fix the cause. It reruns the failed task and the tasks that did not run, and it keeps successful results.
Retrying a non-idempotent task is dangerous because it can double-count data. That is another reason to keep the idempotency rules from the previous section.
Data quality interacts with orchestration. Expectations that drop rows do not fail a task, so the job stays green even when many rows are dropped. If a bad batch should stop the flow, use a fail-on-violation rule, or add a SQL check task between silver and gold that raises an error when a condition is broken. Then the dependency graph blocks gold from publishing.
Monitoring runs
Each run records task status, duration, and output. Check these over time and not only when something breaks.
- Run history shows whether duration is creeping up, which often points to a table that needs maintenance.
- Notifications can also fire on long duration, not only failure.
- System tables in Unity Catalog hold job and run history that you can query with SQL, so you can build a dashboard of success rate per job.
A pipeline task instead of three notebooks
If you expressed the layers as a declarative pipeline, the job can be much smaller. The pipeline handles the order between bronze, silver, and gold itself, because it infers dependencies from the code. The job then holds one pipeline task, plus any tasks outside the pipeline, such as a downstream refresh or a check.
Choose between the two styles by how much control you need. Separate tasks give you per-layer retries, per-layer compute, and explicit checks between layers. A pipeline task gives you less setup and built-in handling of incremental updates and expectations.
Common errors
- Downstream tasks never start. A upstream stream does not stop. Use
availableNow=TrueandawaitTermination(). - Duplicates after a retry. A task was not idempotent. Use
MERGEor a replace in silver and gold. - Run time shifts twice a year. The schedule has no explicit timezone. Set
timezone_id. - Green job, wrong numbers. Expectations dropped rows silently. Monitor drop counts or add a check task.
- Failure with no alert. No notification is configured on the job. Add
on_failurerecipients.
Exercise
A nightly job has three tasks: bronzeingest, silvermerge, and gold_aggregate. Bronze uses Auto Loader with a continuous stream and never finishes, so silver never runs. What two changes make the job work, and why is it safe to rerun bronze afterward?
Show answer
Change the write to trigger(availableNow=True) and call awaitTermination() on the query. With that trigger the stream processes all available files and then stops, and the task succeeds only after the write completes, so silver can start. Rerunning bronze is safe because the checkpoint records which files were already ingested, so each file is read once.
Exercise
Silver drops rows that fail an expectordrop rule, and last night 40 percent of rows were dropped. The job run shows success. Name one way to make the job fail in that case, and one reason to put the check before the gold task.
Show answer
Add a SQL check task between silvermerge and goldaggregate that raises an error when the dropped-row share exceeds a limit, or change the rule to fail on violation. Placing it before gold means gold depends on the check, so it will not run and publish revenue numbers built from incomplete data.