Azure Data Factory patterns
Part of the free LogicWiz Data Engineering course, Module 9: Orchestration. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is Monday, 10:00. SwiftKart has bought a smaller shop, and with its ERP database there are now 50 tables to land in the data lake every night. The contractor's plan is on the screen: 50 pipelines, one per table. Nora asks one question: "The day the ERP server moves, how many things do we edit?" Fifty. And someone will miss one.
You'll learn to
- Name Azure Data Factory's parts and match them to Airflow
- Copy many tables with one pipeline and a control table
- Run the watermark copy in the right order, and pick a trigger
- Size parallel copies against what the source can take
Learn
The same ideas, new names
You already know how to think about this job. Azure has its own tool for it, with its own words.
Azure Data Factory (ADF) is Azure's managed service for moving data and running steps in order. You build it in a browser, and underneath it is JSON. Its pieces:
- Pipeline: a workflow, like a DAG.
- Activity: one step: Copy, Lookup, ForEach, If Condition, Execute Pipeline, Stored Procedure, Databricks Notebook, Web.
- Linked service: how to reach a system (a connection string, a key from Key Vault).
- Dataset: the shape and place of data in that system (a table, a folder of Parquet files).
- Integration runtime: the compute that runs copies.
- Trigger: when a pipeline runs.
The pieces of a data factory
Nested boxes: a trigger starts a pipeline, which holds a Lookup activity and a ForEach activity with a Copy inside; beside it a dataset, a linked service and an integration runtime that the Copy uses.
Read it top to bottom: a trigger starts a pipeline, the pipeline runs activities, and a Copy activity needs a dataset, a linked service and an integration runtime to do its work.
The same ideas in ADF and Airflow
| Azure Data Factory | Airflow | What it is |
|---|---|---|
| Pipeline | DAG | the workflow |
| Activity (Copy, Lookup, ForEach) | Task (an operator) | one step |
| Linked service | Connection | how to reach a system, with its secrets |
| Dataset | the operator's arguments | which table or files, in what format |
| Integration runtime | Executor and workers | the compute that does the work |
| Trigger (schedule, tumbling window, event) | Schedule, data interval, sensor | when it runs |
| Dynamic content @{item().sourcetable} | Jinja {{ ds }} | values filled in per run |
Synapse pipelines are the same engine with the same pieces. Data Factory in Microsoft Fabric has the same pipelines and activities, with connections in place of linked services and datasets. So this lesson carries over to both.
One pipeline and a control table
Now Nora's question. Fifty pipelines means fifty things to edit when a server moves. The pattern every Azure data engineer meets has one pipeline and a list.
The list is a control table: one row per source table, with its schema, its name, its load type (full or incremental), its watermark column, its last watermark and an enabled flag.
The pipeline does three things. A Lookup activity reads the control table. A ForEach loops over the rows, several at a time. Inside it, one Copy activity, with blanks filled from the current row, copies that row's table.
This is called a metadata-driven pipeline. A new table is a new row. A moved server is one linked service.
The control table, and what the Lookup returns
SELECT load_type,
COUNT(*) AS tables,
COUNT(*) FILTER (WHERE enabled) AS enabled
FROM etl_control
GROUP BY load_type
ORDER BY load_type;
-- The Lookup activity's query: what the ForEach will loop over
SELECT table_id, source_schema, source_table, load_type, watermark_column, last_watermark
FROM etl_control
WHERE enabled
ORDER BY priority, table_id;
SwiftKart's six tables plus the 44 ERP tables. Switching a table off is an UPDATE, not a deployment. The last result is the list the ForEach receives.
One row's trip through the pipeline
Five boxes in a row, highlighted one at a time: the control table, the Lookup activity that reads it, the ForEach that loops over its rows, the Copy that copies one table, and the data lake folder where it lands.
The list. The control table has one row per table: where it is, how to load it, and how far the last copy got. Three of the 50 rows are switched off.
Lookup. The Lookup activity runs one query on the control table and hands the rows to the next activity as a list,
output.value.ForEach. The ForEach loops over the list. With
batchCount8 it runs up to 8 copies side by side. Inside the loop,@{item()}is the current row, like a loop variable.Copy. One Copy activity serves every table. Its query has blanks:
@{item().source_table},@{item().watermark_column},@{item().last_watermark}. The current row fills them in.The lake. The table lands as Parquet in its own folder,
erp/<table>. A new table tomorrow is one new row in the control table, and nothing else.
Follow one row of the control table from the list to the lake. The next card is the same pipeline in ADF's JSON.
The pipeline in ADF's JSON: Lookup, then ForEach with a Copy
Runs in the cloud:
{
"name": "pl_copy_erp_tables",
"properties": {
"activities": [
{
"name": "LookupTables",
"type": "Lookup",
"typeProperties": {
"source": {
"type": "AzureSqlSource",
"sqlReaderQuery": "SELECT source_schema, source_table, watermark_column, last_watermark FROM etl_control WHERE enabled = 1 AND load_type = 'incremental' ORDER BY priority"
},
"dataset": { "referenceName": "ds_control_db", "type": "DatasetReference" },
"firstRowOnly": false
}
},
{
"name": "ForEachTable",
"type": "ForEach",
"dependsOn": [ { "activity": "LookupTables", "dependencyConditions": [ "Succeeded" ] } ],
"typeProperties": {
"items": { "value": "@activity('LookupTables').output.value", "type": "Expression" },
"isSequential": false,
"batchCount": 8,
"activities": [
{
"name": "CopyTable",
"type": "Copy",
"typeProperties": {
"source": {
"type": "SqlServerSource",
"sqlReaderQuery": {
"value": "SELECT * FROM @{item().source_schema}.@{item().source_table} WHERE @{item().watermark_column} > '@{item().last_watermark}'",
"type": "Expression"
}
},
"sink": { "type": "ParquetSink" }
},
"inputs": [ { "referenceName": "ds_erp_sqlserver", "type": "DatasetReference" } ],
"outputs": [ {
"referenceName": "ds_lake_parquet",
"type": "DatasetReference",
"parameters": { "folder": "erp/@{item().source_table}" }
} ]
}
]
}
}
]
}
}
Find the three activities by their "type": Lookup, ForEach, and the Copy inside it. batchCount 8 allows up to 8 copies at a time (the default is 20, the most 50). This is the incremental branch; the full-load tables get a second Lookup and ForEach whose Copy is a plain SELECT *. The on-premises ERP is reached through a self-hosted integration runtime, which comes later in this lesson.
The same pipeline, runnable: 50 tables, one loop
import duckdb
# The acquired shop's ERP: 50 tables, each with an id and a modified_at column
duckdb.sql("create schema erp")
duckdb.sql("create schema lake")
for n in range(1, 51):
duckdb.sql(f"""
create table erp.table_{n:02d} as
select i as id, timestamp '2025-06-01' + (i % 7) * interval 1 day as modified_at
from range(1, {n} + 1) as t(i)
""")
# The control table: one row per source table (two are switched off)
duckdb.sql("""
create table control as
select 'table_' || lpad(cast(n as varchar), 2, '0') as table_name,
timestamp '1900-01-01' as watermark,
n not in (13, 26) as enabled
from range(1, 51) as t(n)
""")
def lookup():
"""Lookup activity: which tables to copy, and how far each one got."""
return duckdb.sql("select table_name, watermark from control where enabled order by table_name").fetchall()
def copy_table(table, old_wm, new_wm):
"""Copy activity: rows changed after the old watermark, up to the new one."""
duckdb.sql(f"create table if not exists lake.{table} as select * from erp.{table} limit 0")
rows = f"select * from erp.{table} where modified_at > '{old_wm}' and modified_at <= '{new_wm}'"
n = duckdb.sql(f"select count(*) from ({rows})").fetchone()[0]
duckdb.sql(f"insert into lake.{table} {rows}")
return n
def run_pipeline():
tables, copied = lookup(), 0
for table, old_wm in tables: # ForEach
new_wm = duckdb.sql(f"select max(modified_at) from erp.{table}").fetchone()[0]
copied += copy_table(table, old_wm, new_wm)
duckdb.sql(f"update control set watermark = '{new_wm}' where table_name = '{table}'")
print(f"{len(tables)} tables, {copied} rows copied")
run_pipeline() # night 1: everything
for n in (1, 2, 3): # during the day, three tables change
duckdb.sql(f"insert into erp.table_{n:02d} values (100, timestamp '2025-06-09 10:00:00')")
run_pipeline() # night 2: only what changed
duckdb.sql("select * from control where table_name in ('table_01', 'table_02', 'table_04', 'table_13') order by 1").show()
Each function is named after the ADF activity it stands for. On the second night, 48 tables are visited but only 3 rows move, because every table remembers its own watermark.
The control table, night by night
| tablename | enabled | Watermark before | After night 1 | After night 2 |
|---|---|---|---|---|
| table01 | true | 1900-01-01 | 2025-06-02 00:00 | 2025-06-09 10:00 |
| table02 | true | 1900-01-01 | 2025-06-03 00:00 | 2025-06-09 10:00 |
| table04 | true | 1900-01-01 | 2025-06-05 00:00 | 2025-06-05 00:00 (no change) |
| table13 | false | 1900-01-01 | 1900-01-01 | 1900-01-01 (switched off) |
Read each row left to right: one table's watermark over two nights. The watermark only moves after a successful copy. If a copy fails, its row keeps the old watermark and the next run tries the same range again.
Remember: one pipeline, one row per table. Adding a table is an INSERT. Switching one off is an UPDATE. Nothing is deployed.
The watermark copy: four steps, in this order
Inside the loop, every incremental table is copied the same way. Microsoft's own "delta copy" template has four activities, and their order matters:
- Lookup the old watermark from the control table.
- Lookup the new watermark:
max(updated_at)in the source, taken before copying. - Copy the rows with
updated_at > oldand<= new. - Write the new watermark back (a Stored Procedure activity), only if the copy succeeded.
Step 2 looks odd. Why ask for the new watermark before the copy has moved anything?
An order arrives while the copy runs
A sequence between the pipeline, the control table, the source orders table and the lake: the old watermark is read, the new watermark is read before copying, an order committed during the copy stays outside the range, and the new watermark is written only after the copy succeeds.
1. Read the old watermark. The control table says how far the last run got: 09:00.
2. Read the new watermark, before copying. The latest
updated_atin the source right now is 10:00. The range is fixed from this moment: after 09:00, up to 10:00.3. Copy that range. While the copy runs, the shop commits order 1081 at 10:02. It is outside the range, so this run leaves it alone.
4. Write the new watermark, only after success. The control table now says 10:00. Tomorrow's range starts after 10:00, so order 1081 is copied then. Nothing is lost, and nothing is copied twice.
Read it top to bottom; the times are made up for the picture. Had the pipeline asked for the new watermark after the copy, it would have got 10:02: order 1081 would be behind the watermark without ever being copied.
The four steps in Postgres
-- 1 and 2: the old watermark, and the new one taken before copying
CREATE TEMP TABLE wm AS
SELECT (SELECT watermark FROM etl_watermark WHERE table_name = 'orders') AS old_wm,
(SELECT MAX(updated_at) FROM orders) AS new_wm;
-- 3: copy what changed in between (MERGE: a changed order may already be in the lake)
MERGE INTO lake.orders AS t
USING (SELECT o.* FROM orders AS o, wm WHERE o.updated_at > wm.old_wm AND o.updated_at <= wm.new_wm) AS s
ON t.order_id = s.order_id
WHEN MATCHED THEN UPDATE SET status = s.status, updated_at = s.updated_at
WHEN NOT MATCHED THEN INSERT VALUES (s.order_id, s.customer_id, s.order_ts, s.status, s.currency, s.updated_at);
-- 4: move the watermark, only now that the copy worked
UPDATE etl_watermark SET watermark = (SELECT new_wm FROM wm) WHERE table_name = 'orders';
SELECT (SELECT COUNT(*) FROM lake.orders) AS lake_rows, watermark FROM etl_watermark;
Before the run the lake has the 41 orders changed up to 10 June 09:41:31; after it, all 80. A second run would copy nothing, because old_wm now equals new_wm.
Three watermark bugs to look for in any review. Reading the new watermark after the copy: rows are lost. Comparing with >= instead of >: the row exactly on the watermark is copied again every run. Moving the watermark when the copy failed, or before it finished: the failed range is skipped for good. Late rows stamped earlier than the watermark need a lookback, as in Module 6.
The copy and the watermark write, in ADF's JSON
Runs in the cloud:
{
"activities": [
{
"name": "IncrementalCopyActivity",
"type": "Copy",
"dependsOn": [
{ "activity": "LookupOldWaterMarkActivity", "dependencyConditions": [ "Succeeded" ] },
{ "activity": "LookupNewWaterMarkActivity", "dependencyConditions": [ "Succeeded" ] }
],
"typeProperties": {
"source": {
"type": "AzureSqlSource",
"sqlReaderQuery": {
"value": "SELECT * FROM orders WHERE updated_at > '@{activity('LookupOldWaterMarkActivity').output.firstRow.watermark_value}' AND updated_at <= '@{activity('LookupNewWaterMarkActivity').output.firstRow.new_watermark_value}'",
"type": "Expression"
}
},
"sink": { "type": "ParquetSink" }
}
},
{
"name": "StoredProceduretoWriteWatermarkActivity",
"type": "SqlServerStoredProcedure",
"dependsOn": [ { "activity": "IncrementalCopyActivity", "dependencyConditions": [ "Succeeded" ] } ],
"typeProperties": {
"storedProcedureName": "usp_write_watermark",
"storedProcedureParameters": {
"LastModifiedtime": { "value": "@{activity('LookupNewWaterMarkActivity').output.firstRow.new_watermark_value}", "type": "DateTime" },
"TableName": { "value": "orders", "type": "String" }
}
}
}
]
}
The dependsOn lines are the arrows of the graph: copy after both lookups, write the watermark only after the copy succeeds.
A database inside an office
The ERP database runs on a server in the acquired shop's office, with no public access. How does a cloud service copy from it?
ADF's copy compute is the integration runtime, and it comes in kinds. The Azure IR is managed by Microsoft and runs in a region. The self-hosted IR (SHIR) is a Windows service on a machine inside the private network. A third kind, Azure-SSIS, runs old SSIS packages.
The self-hosted IR opens no inbound port. It calls out to the factory over HTTPS on port 443 and asks for work. It keeps the linked-service credentials on its own machine. And it moves the data itself: straight from the source to the cloud store, never through the factory.
One copy through a self-hosted IR
A sequence: the self-hosted IR polls Data Factory over outbound HTTPS, receives a copy job, decrypts its stored credentials, queries the ERP database, and writes Parquet straight to ADLS before reporting status.
Read it top to bottom. Grey arrows are instructions and status; green arrows carry rows, and they never pass through the factory. On the ERP side, outbound HTTPS to a few Azure domains is the whole firewall change.
Eighty queries at once
Nora has one worry left: how many queries will hit the ERP server at 01:00? Three settings multiply.
- ForEach
batchCount: copies running side by side. Default 20, at most 50. It is a ceiling, not a promise. parallelCopies, inside one copy: threads that read the source and write the sink. From SQL Server it only works with a partition option, and then the default is 4.- DIUs (Data Integration Units, a bundle of CPU, memory and network) on the Azure IR, or nodes on a self-hosted IR: the machines under the threads.
The source database feels the product. batchCount 20 x parallelCopies 4 is 80 queries on one ERP server at the same moment.
Queries on the ERP server at the same moment
Bars comparing concurrent source queries: 80 with batchCount 20 and parallelCopies 4, 32 with batchCount 8 and parallelCopies 4, and 8 with batchCount 8 and no partition option.
Each bar is one choice of settings. Pick the product the source can take at night, then spend it where it helps: a few threads on the one huge table, one each on the 46 small ones.
How long the ForEach takes
import heapq
def foreach_minutes(durations, batch_count):
"""ForEach with isSequential false: up to batch_count copies at once; the next starts when one ends."""
running, clock = [], 0
for d in durations:
if len(running) == batch_count:
clock = heapq.heappop(running) # wait for the copy that ends first
heapq.heappush(running, clock + d)
return max(running) if running else 0
tables = [2 + n % 7 for n in range(47)] # 47 enabled tables, 2 to 8 minutes each
print('one after the other:', sum(tables), 'minutes')
for batch in (8, 20, 50):
print(f"batchCount {batch:>2}: {foreach_minutes(tables, batch):>3} minutes, up to {batch * 4} source queries with parallelCopies 4")
Going from 8 to 20 copies at once cuts 32 minutes to 15 and multiplies the load on the ERP by 2.5. The longest single copy (8 minutes) is the floor, whatever the batchCount: past that, only parallelCopies on the big table helps.
One big table, four threads: ID 1 to 100, bounds 20 and 80
| Thread | Rows it reads |
|---|---|
| 1 | ID <= 20 |
| 2 | 21 <= ID <= 50 |
| 3 | 51 <= ID <= 80 |
| 4 | ID = 81 |
This is Microsoft's example of the DynamicRange partition option with parallelCopies 4: each thread runs its own range query. (The other option is PhysicalPartitionsOfTable; with no partition option, one query reads the whole table.) The bounds only set the stride; no row is filtered out. A custom query must contain ?DfDynamicRangePartitionCondition, which the service replaces with each thread's range. If most rows sit in one range (IDs that grew fast lately), one thread does most of the work.
When should it run?
Last piece: what starts the pipeline. ADF has three kinds of trigger.
- A schedule trigger fires on a wall-clock schedule, like cron. It has no memory of which periods were processed.
- A tumbling window trigger cuts time into fixed, back-to-back windows and runs once per window. It passes
@trigger().outputs.windowStartTimeandwindowEndTimeto the pipeline: Airflow's data interval. It keeps the state of each window, so you can rerun or backfill past windows, set retries, and make one window depend on another. - A storage event trigger fires when a file lands in Blob Storage or ADLS: a sensor without the waiting.
For a daily load that must be right for every day, the tumbling window is the safe default.
Numbers to remember
| Setting | Number | Note |
|---|---|---|
| ForEach batchCount | default 20, at most 50 | a ForEach takes at most 100,000 items |
| parallelCopies from a partitioned SQL source | default 4 | Microsoft suggests 2 to 4 times the DIUs or nodes |
| DIUs per copy on the Azure IR | 4 to 256, Auto by default | billed as DIUs used x copy duration x the price per DIU-hour |
| Nodes in one self-hosted IR | up to 4 | DIUs do not apply: its power is its machines. CPU high and memory low: add nodes. CPU and memory idle while jobs wait: allow more concurrent jobs per node |
| Self-hosted IR control channel | outbound HTTPS, port 443 | it polls the factory's job queue through Azure Relay; credentials stay on the machine, encrypted with Windows DPAPI |
ADF's Copy Data tool can generate this whole pattern for you: its metadata-driven copy task creates the control table and the pipeline. Heavy transformations usually run elsewhere: the pipeline lands raw data in ADLS, then calls a Databricks notebook or job (Modules 13 and 14).
What changed at SwiftKart
The contractor's 50 pipelines became one pipeline and a control table with 50 rows. The night the ERP server moves, you edit one linked service.
Each table keeps its own watermark, read before the copy and written after it. The copies run 8 at a time through a self-hosted IR in the shop's office, on a tumbling window trigger, so any night can be run again.
You have now driven two orchestrators from the outside. Lesson 9.6 goes inside Airflow: what the scheduler does on every loop, and why a task can sit in scheduled while the workers are idle.
In one line
In Azure Data Factory, one pipeline driven by a control table (Lookup, ForEach, Copy) loads many tables; each table keeps a watermark that is read before the copy and moved only after it succeeds, and a tumbling window trigger makes reruns safe.
Interview corner
How would you copy 50 tables from an on-premises database to ADLS with Azure Data Factory?
One metadata-driven pipeline: a control table lists each table with its load type, watermark column and last watermark. A Lookup reads the enabled rows, a ForEach with a batchCount runs a parameterised Copy for each through a self-hosted integration runtime, incremental tables copy only rows past their watermark, and the watermark is updated only after a successful copy. Add a log of row counts per table and an alert on failure.
Explain the watermark (delta) copy and its pitfalls.
Look up the old watermark, look up the new one as the source's current max of the change column before copying, copy rows > old and <= new, then store the new watermark only if the copy succeeded. Pitfalls: reading the new watermark after the copy loses rows, >= re-copies the boundary row, moving the watermark on failure skips data, and late rows with old timestamps need a lookback.
Schedule trigger or tumbling window trigger?
A schedule trigger fires on a wall-clock schedule and keeps no state about periods. A tumbling window trigger divides time into fixed, contiguous windows, passes each window's start and end to the pipeline, tracks each window's state, and supports reruns, backfills of past windows, retries and dependencies between windows. For interval-based loads that must be correct per period, use tumbling windows.
A nightly copy from an on-premises SQL Server through a self-hosted IR takes four hours. How do you find the bottleneck and speed it up?
First see where the time goes in the copy's monitoring output (time queued against time transferring, rows and throughput), and look at the SHIR node's CPU, memory and network. If the node is saturated, add nodes (up to four) or a bigger machine; if it is idle while jobs wait, raise its concurrent jobs. If one big table is read by one query, add a partition option (physical partitions or dynamic range on an indexed key) and parallelCopies of 2 to 4 per node. Then watch the source: batchCount times parallelCopies queries hit it at once, so I would agree that number with the DBA and sort the Lookup biggest tables first.