Design: the daily batch
Part of the free LogicWiz Data Engineering course, Module 17: Pipeline design. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is Tuesday, 2 p.m., and this is your second design review with Nora. Finance wants a daily sales table: revenue and orders by day and country, ready by 7 a.m., matching the payment provider to the cent. Then Tess adds the bad news. Orders keep changing for days after they are placed. One export arrived twice last week. Another came two days late. And a bug fix will soon mean rebuilding March.
You'll learn to
- Apply the seven steps to a nightly warehouse load
- Handle late changes with a lookback and writes safe to rerun
- Backfill by date, and prove each choice with SQL
- Turn the 7 a.m. deadline into a time budget
Learn
Steps 1 to 3: what finance needs
You start where Lesson 17.1 said to start: with questions. After twenty minutes with Tess, the requirement fits in a few lines.
- Users: finance and analysts. Grain: one row per order line, summed to day and country.
- Freshness: yesterday complete by 07:00. History: 3 years.
- Correctness: revenue reconciles with captured payments.
- Change: statuses move for up to 3 days (shipped, delivered, returned); exports can repeat or be late; a month may need rebuilding.
- Source: the shop's Postgres (
orders,order_items,payments,customers), read from a replica so checkout never slows down. Sink: adaily_salestable for the BI tool.
Step 2: size it
orders_per_day = 50_000 # assumption: SwiftKart next year
lines_per_order = 2.5
bytes_per_fact_row = 200
lookback_days = 3
lines_per_day = orders_per_day * lines_per_order
fact_mb_per_day = lines_per_day * bytes_per_fact_row / 1e6
fact_gb_per_year = fact_mb_per_day * 365 / 1000
rows_reread = orders_per_day * lookback_days # the lookback re-reads 3 days
mart_rows_per_year = 365 * 30 # days x countries
print(f'fact lines a day: {lines_per_day:,.0f}, about {fact_mb_per_day:.0f} MB')
print(f'fact a year: {fact_gb_per_year:.1f} GB before compression')
print(f'orders re-read each night: {rows_reread:,}')
print(f'mart rows a year: {mart_rows_per_year:,}')
Small: any warehouse handles it. A day of facts is about 25 MB, so do not partition by day: three years would be 1,095 tiny partitions. Databricks advises no partitioning at all under about 1 TB (cluster on order_date instead); in a warehouse, partition or cluster by month at most.
Step 4: the sketch, one box at a time
The numbers say this is not a size problem. Nora agrees: "Then it is a correctness problem. Draw it, and give me a reason for every box."
The plan is a nightly batch. Airflow runs it once a day, one run per date, and dbt holds the SQL. Step through it below: each step adds a box and says why it is there.
The nightly batch, built box by box
A graph built one box at a time: the shop's read replica and the BI tool, then the 02:00 extract, the raw landing files, the silver table, the gold fact table and daily_sales mart, and last a reconciliation gate fed by the payment provider's export.
The two ends. The shop's Postgres on one side, the BI tool finance opens at 07:00 on the other. You read a replica, a copy of the database that follows it, so checkout never slows down.
Extract at 02:00. One Airflow task reads orders, lines and payments whose
updated_atfalls in the last 3 days. Those 3 days are the lookback: statuses keep moving for that long.Land it raw. The result is written unchanged as files under
landing/<table>/<run date>/and appended to bronze with the extract date. If a later step has a bug, you rebuild from here without asking the source again.Silver: one row per order. Keep the latest version of each order (the newest
updated_at), clean the types, and MERGE intosilver_ordersonorder_id. Running it twice changes nothing.Gold: the numbers finance reads. The star schema from Module 5, and
daily_sales, rebuilt for every order date the run touched.A gate before the publish. Tests run between the layers. The last one compares revenue with the payment provider's export of captured payments. If they differ by a cent, nothing is published.
Grey boxes are not drawn yet. Each step colours in the next box and gives the reason for it, the way you would say it in a review.
The finished design, with its numbers
A graph from the shop's read replica and the payment provider's export, through the 02:00 extract with a 3-day lookback, Parquet landing files, the silver MERGE, the fact table and the daily_sales mart, to a reconciliation gate that publishes to the BI tool by 07:00.
Follow the arrows from the two sources to the BI tool. Every arrow is a dated, idempotent step, so a rerun or a backfill is the same DAG run for another date. The red gate is the reason finance can trust the number.
Bronze, silver and gold for a few SwiftKart orders: raw rows in bronze including a retried file's duplicates and bad values, one clean row per order in silver with bad rows set aside, and revenue per country per day in gold.
Step through the three layers and watch the rows change. Bronze keeps every copy, silver keeps one row per order, gold keeps one row per day and country. Each layer can be rebuilt from the one before it.
The design, component by component
| Component | Tool I would pick | Why |
|---|---|---|
| Extract | Airflow task with SQL on a read replica (or Fivetran) | Incremental on updatedat with a 3-day lookback; never load the primary |
| Landing and bronze | Parquet files in S3 or ADLS, by extract date | Raw and cheap: replay, debug and backfill without asking the source again |
| Silver orders | Delta or warehouse table, MERGE on orderid | Latest status per order; a rerun changes nothing |
| Gold | Fact table clustered on order date; dailysales mart | Pruning without tiny files; a small table for BI |
| Transform | dbt models and tests | SQL in Git, tests and lineage |
| Orchestration | Airflow, daily at 02:00, 3 retries, alert at 06:30 | Dependencies, retries, backfill by date |
| Quality | dbt tests and a payments reconciliation | Stop wrong numbers before 07:00 |
A typical stack in real teams: Fivetran or Airbyte (or an Airflow task) for the extract, dbt incremental models with a unique_key (they become MERGEs) on Snowflake, BigQuery or Databricks, and an Airflow DAG with an alert before the deadline.
Step 5: an order that changes three days later
Nora points at the first arrow. "An order placed on 1 June is placed in the 2 June extract and delivered in the 5 June one. What if a night only reads yesterday?" Then a late export or a failed run loses changes for good. That is why each run reads the last 3 days again.
The overlap has a price: the same order arrives again and again. So the load must be idempotent. First cut the batch down to one row per order, the one with the newest updated_at. Then MERGE on order_id, updating only when the incoming row is newer.
Below, bronze holds 14 copies of 5 orders.
Dedup the 5 June batch and MERGE it into silver
SELECT COUNT(*) AS bronze_rows, COUNT(DISTINCT order_id) AS orders
FROM bronze_orders;
CREATE VIEW batch AS
SELECT order_id, status, updated_at
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY updated_at DESC) AS rn
FROM bronze_orders
WHERE extract_date = DATE '2025-06-05'
) ranked
WHERE rn = 1;
MERGE INTO silver_orders AS t
USING batch AS s
ON t.order_id = s.order_id
WHEN MATCHED AND s.updated_at > t.updated_at THEN
UPDATE SET status = s.status, updated_at = s.updated_at
WHEN NOT MATCHED THEN
INSERT (order_id, status, updated_at) VALUES (s.order_id, s.status, s.updated_at);
SELECT * FROM silver_orders ORDER BY order_id;
Copy the MERGE block and run it a second time before the last SELECT: the five rows do not change. That is the proof that a rerun is safe.
Silver before and after the 5 June run
| orderid | Before (after 3 June) | In the 5 June batch | After |
|---|---|---|---|
| 1002 | shipped | shipped | |
| 1003 | placed | delivered (4 June) | delivered |
| 1006 | shipped | shipped | |
| 1008 | placed | shipped (3 June, late) | shipped |
| 1016 | placed (late order) | placed (new row) |
The late changes land because of the lookback; the duplicates vanish because of the dedup and the MERGE.
The append trap. With a lookback, every night re-reads rows already loaded. INSERT INTO ... SELECT (or mode("append")) then adds them again, and revenue creeps up a little every day: the hardest bug to spot. A lookback is only safe with a MERGE or an overwrite.
Gold: rebuild every date the run touched
Gold needs a different kind of safe write. A change to an order placed on 1 June changes 1 June's totals. So tonight's run must rebuild every order date it touched, not only yesterday.
The write is: delete that date, insert it again, in one transaction. That is an overwrite by partition.
Write the step as a function of a date. A rerun is the same call again. A backfill is the same call for each date in a range: in Airflow, a backfill creates one DAG run per date.
A rebuild function, a rerun, and a backfill
CREATE FUNCTION rebuild_daily_sales(d DATE) RETURNS void LANGUAGE sql AS $$
DELETE FROM daily_sales WHERE order_date = d;
INSERT INTO daily_sales
SELECT o.order_ts::date, c.country, COUNT(DISTINCT o.order_id), SUM(i.qty * i.unit_price)
FROM orders o
JOIN customers c ON c.customer_id = o.customer_id
JOIN order_items i ON i.order_id = o.order_id
WHERE o.order_ts >= d AND o.order_ts < d + 1
AND o.status <> 'cancelled'
GROUP BY 1, 2;
$$;
SELECT rebuild_daily_sales(DATE '2025-06-03'); -- tonight's run
SELECT rebuild_daily_sales(DATE '2025-06-03'); -- a rerun: same result
SELECT rebuild_daily_sales(d::date) -- a backfill of 1 to 7 June
FROM generate_series(DATE '2025-06-01', DATE '2025-06-07', INTERVAL '1 day') AS d;
SELECT order_date, SUM(orders) AS orders, SUM(revenue) AS revenue
FROM daily_sales
GROUP BY order_date
ORDER BY order_date;
The stale 3 June rows are replaced, not added to. Each date is rebuilt from the source on its own, so running it twice cannot double anything.
Do not flood the source
"One more arrow," says Nora. "The one into Dana's database." In a batch, the part that cannot take more load is the source. Three guards:
- Read the replica, and check its lag first. A replica 40 minutes behind silently lacks the last 40 minutes of changes. Postgres reports the lag on the replica:
now() - pg_last_xact_replay_timestamp(). Over a few minutes, wait (an Airflow sensor) and alert. - Cap parallel reads. Spark's JDBC reader splits a table into
numPartitionsqueries, and that is also the most JDBC connections it opens at once. Eight connections on a replica is polite; 200 is an incident. - Cap the backfill. A 30-day backfill is 30 runs. Limit how many run at once (
max_active_runson the DAG), or the replica receives 30 extracts in the same minute.
Step 5, all of it: the failure modes, answered
| What goes wrong | Without a plan | The design answer |
|---|---|---|
| An export arrives twice | Orders doubled | Dedup by orderid, MERGE |
| An order changes 3 days later | Old totals stay wrong | 3-day lookback; rebuild touched dates |
| An export is late | A day is missing at 07:00 | Next run's lookback; freshness alert |
| The DAG is rerun | Appends double the rows | MERGE in silver, overwrite by date in gold |
| A month must be rebuilt | Hand-written fixes | Backfill: the same task per date |
| The source adds a column | Load fails or drops it | Bronze keeps raw; change silver on purpose |
| Revenue differs from payments | Finance stops trusting it | Reconciliation test blocks the publish |
| The replica falls behind | Last night's changes silently missing | Check replica lag before extracting; wait and alert |
The replay plan: rebuild March beside the old table
The bug fix is coming, and March will have to be rebuilt. Plan it now, with numbers.
- Keep the raw extracts. Bronze grows about 25 MB a night: three years is under 30 GB, well under a dollar a month at $0.023 per GB-month. It is the cheapest insurance in the design.
- Rebuild beside, then swap. Backfill March into
daily_sales_v2, compare totals per day with the old table and with captured payments, then swap the names in one transaction. - In dependency order: silver before gold, because gold reads silver.
- Time it. One date takes 15 minutes and four run at once, so a 31-day month is 8 waves: 2 hours. Run it in the afternoon, not inside the nightly window, and tell finance which days will change.
Rebuilding March: 31 dates, four at a time
A timeline of four run slots over 120 minutes: each slot rebuilds one date of March after another, 15 minutes each, so the 31 dates finish in eight waves.
Each row is one of the four runs allowed at once, and each bar is one date of March (the number is the day), 15 minutes long. 31 dates in waves of 4 is 8 waves: 120 minutes.
Seven o'clock is a budget
Now the deadline. Finance reads at 07:00 and the run starts at 02:00. A deadline is a budget: you have 300 minutes.
- One clean run takes about 70: extract 20, land 5, silver MERGE 15, gold 20, tests and reconciliation 10.
- Budget one full retry, another 70, because the most common failure is transient: the replica restarting, a throttled API.
- 300 - 140 leaves 160 minutes of slack for a slow day.
Two numbers fall out. The alert fires at 06:30, while a human can still act. The latest safe start is 07:00 minus 140 minutes: 04:40. If the payment export has not arrived by then, page someone instead of waiting.
Where the 300 minutes go
A bar of 300 minutes from 02:00 to 07:00 split into the extract, landing, silver merge, gold rebuild and tests of one clean run, one full retry, and the remaining slack.
Read the bar left to right: one clean run, then the room kept for a retry, then the slack. Measure the stage times from the last 30 runs and use the slowest, not the average. When the slack shrinks below one retry, the deadline is at risk before anything has failed.
Write the promise down
Last, the promise to finance, written as SLOs (Lesson 17.1).
- Freshness: yesterday's
daily_salescomplete by 07:00 UTC on 98% of days. Over a 90-day quarter the budget is 1.8 days: one late morning. 99% sounds better, but it allows 0.9 days, which means none. Nobody can promise that for a job whose source they do not control. - Correctness: revenue matches captured payments to the cent on 100% of published days. A wrong number is worse than a late one, so the reconciliation blocks the publish.
Finance in Tokyo and Toronto want "yesterday" in their own time zone. Keep facts in UTC with the local order date as a column, and publish each region at its own 07:00. If EU customers' data must stay in an EU region, run extract and silver there and ship only the aggregated mart.
Remember: four phrases carry this design. A lookback for late changes. MERGE on the key for reruns. Overwrite by date for gold and backfills. Reconciliation against the source of truth. Say each one with its reason.
Numbers to remember
| Number | Value | Where it comes from |
|---|---|---|
| Facts a day | 125,000 lines, about 25 MB | 50,000 orders x 2.5 lines x 200 bytes |
| Partitioning | none under about 1 TB (Databricks advice) | cluster on orderdate; in a warehouse, by month at most |
| Lookback | 3 days | statuses move for up to 3 days |
| Replica lag | now() - pglastxactreplaytimestamp() | over a few minutes: wait and alert |
| Spark JDBC numPartitions | 8 is polite, 200 is an incident | the table is split on partitionColumn between lowerBound and upperBound; it is also the maximum number of concurrent JDBC connections |
| Bronze for 3 years | under 30 GB | well under a dollar a month at $0.023 per GB-month |
| One clean run | 70 minutes | with one retry 140; latest safe start 04:40; alert at 06:30 |
| Freshness SLO | 98% of days | 1.8 days of budget in a 90-day quarter |
What changed at SwiftKart
Nora signs off on the design. Each night at 02:00 the extract reads three days back from the replica. Silver holds one row per order, however many copies arrive. Gold rebuilds exactly the dates that changed. And nothing reaches Tess unless revenue matches the payments to the cent.
The export that arrives twice no longer doubles anything. The one that arrives late is picked up by the next lookback. Rebuilding March is the same task, run 31 times into a new table.
That was a batch with a 7 a.m. deadline. In Lesson 17.3 marketing wants to watch a flash sale while it happens: clickstream to a dashboard, 15 minutes behind at most.
In one line
Daily batch: extract with a lookback, land raw, dedup and MERGE into silver, rebuild gold for the order dates touched, and backfill by running the same dated task again.
Interview corner
Design a daily batch pipeline for an e-commerce warehouse.
"Each night at 2 am I'd extract orders, lines and payments changed in the last three days from a read replica, land them unchanged as Parquet in bronze, then dedup to the latest version per order and MERGE into silver. Gold is a star schema plus a daily sales mart, rebuilt for every order date the run touched. Airflow runs it with retries and an alert before 7 am, dbt holds the SQL and tests, and a reconciliation against captured payments has to pass before the mart is published."
How do you handle late-arriving changes in a daily batch?
"With a lookback: each run re-reads a few days of changes, sized to how late changes really arrive. Because that re-reads rows I already loaded, the writes must be idempotent: MERGE on the key with a newer-wins check in silver, and delete-then-insert of the affected dates in gold. Anything later than the lookback is caught by a periodic wider reload."
How do you make sure this batch meets its 07:00 deadline every day?
"I treat the deadline as a budget. One clean run is about 70 minutes of measured worst-case stage times; I reserve one full retry, so the latest safe start is 04:40, and anything upstream that is late past that pages someone. I alert at 06:30, check the replica's lag before extracting, and cap the JDBC connections so the source never becomes the bottleneck. The SLO I would sign is 98% of days by 07:00, one late morning a quarter, with correctness at 100% because the reconciliation blocks a wrong publish."
How would you backfill a month after fixing a bug?
"Every task takes the date it is for and overwrites only that date, so a backfill is the same task run once per date in the range: in Airflow, a backfill over those dates or clearing those runs. I'd run it into a copy of the table first if it is risky, compare totals with the old numbers, then swap or rerun in place."