03 / 16 · Data
Data pipelines and orchestration
How raw events become reliable daily datasets: batch against streaming, ETL against ELT, a pipeline as a graph of tasks, idempotent tasks over date partitions, backfills, late data and watermarks, orchestrator abstractions, and data contracts.
Designing an ML system · Data frames with pandas · Builds and dependencies
On this page 10
An upload arrives after yesterday’s preview report was published. Rerunning a script that appends rows adds yesterday’s other uploads again, yet ignoring the upload leaves the report incomplete. The problem is the meaning of a result: which events it includes, what it knew at the time, and how a revised result replaces the previous one.
Our running case is a fictional preview service. Five delivered messages below are authored inputs, not production traffic. The complete example uses the Python standard library and a temporary directory; it does not connect to a scheduler, object store or database.
A retry must not create another fact#
A scheduled command can run twice because a worker crashes after writing output but before reporting success. The scheduler cannot infer from silence whether the write happened. Appending the same row on the retry duplicates its effect. Refusing to retry instead risks losing work that never finished.
Separate the identity of the event from the identity of its delivery. A card-upload event keeps the same event ID when a broker redelivers it. An attempt has its own operational ID. Deduplicating by attempt would preserve both copies; deduplicating by card alone could incorrectly erase a later edit to the same card. The correct key follows the event contract.
In the fixture, an ID with conflicting content raises an error. Silently choosing whichever delivery arrived last would conceal data corruption or an undefined update rule. A legitimate correction needs an explicit new version or correction event and a defined effect on downstream snapshots.
Batch and streaming describe when work is evaluated#
A batch job receives a bounded snapshot and finishes. A streaming computation updates state as events arrive. Either can calculate the number of uploads per event day. They differ in when they expose intermediate answers and how long they retain state for corrections.
A daily batch is convenient when the product can wait and a complete snapshot fits the processing window. A stream is useful when a new upload must affect a queue promptly. Streaming still needs checkpoints, replay and a rule for late events. Batch processing still needs a cutoff and a rule for data discovered after that cutoff. Neither execution mode makes a mutable input reproducible by itself.
The same logical transformation should produce the same answer from the same identified input. If an online path uses a different interpretation of an event, reconciling its output with the nightly job becomes a semantic problem before it becomes a speed problem.
ETL and ELT place the transformation boundary#
Extraction reads the source, transformation interprets or reshapes records, and loading writes a destination. ETL transforms before loading into the analytical destination; ELT loads first and transforms there. For previews, a restricted raw-event store can preserve the original event while a separate table exposes only the fields needed for evaluation.
Preserving raw input makes a later correction possible only if retention and access rules permit it. It is not a reason to retain every uploaded document indefinitely. A raw store also does not excuse downstream ambiguity: record the parser version, units, event-ID rule and accepted schema. Otherwise two runs can read the same bytes and disagree about their meaning.
Choose the boundary according to trust, available execution and required reprocessing. A malformed or unauthorized payload can be rejected before the analytical store. A valid record with a later corrected interpretation can produce a new derived version while the permitted original remains identifiable.
A dependency graph is a claim about required inputs#
For this service, define the following small directed acyclic graph:
| Task | Required inputs | Produced artifact |
|---|---|---|
| Select arrivals | Immutable event log and observation cutoff | Delivered messages visible at cutoff |
| Validate and deduplicate | Selected messages and event schema | Unique event records or a failure report |
| Partition by event day | Unique records and day-boundary rule | One ordered record set per day |
| Publish snapshot | Validated partition and transform revision | Identified snapshot and publication pointer |
| Join mature labels | Published snapshot and label cutoff | Evaluation cohort with coverage count |
An edge means the consumer must use the indicated producer’s successful output. Starting the label join after a failed publish and reading yesterday’s pointer would satisfy a loose time schedule while violating this dependency. Record the actual input artifact IDs, not merely that the producer task ran recently.
Independent day partitions can run concurrently if they write separate destinations. Two writers publishing the same partition need coordination or a compare-and-swap rule on the pointer. A DAG alone supplies no protection against a second process outside the scheduler.
Replace a partition instead of appending a retry#
Hours are measured from the start of day zero. Event day is event_hour // 24; observation time is when the pipeline receives the delivery.
| Event ID | Card | Event hour | Observed hour |
|---|---|---|---|
| e1 | A | 9 | 9 |
| e3 | C | 29 | 29 |
| e2 | B | 15 | 31 |
| e1 | A | 9 | 32 |
| e4 | D | 33 | 33 |
At observation cutoff 30, day zero contains only A. At cutoff 36, it contains A and B. The second delivery of e1 contributes no new event. Repeating the cutoff-36 computation produces the same ordered records, including when the delivered input list is reversed before selection. This is an explicit determinism check, not a claim that arbitrary distributed operators are deterministic.
An idempotent publication has the same visible result when repeated with the same identified inputs. The fixture writes the complete revised JSON to a staging file and then calls os.replace on a destination in the same temporary directory. Before replacement, the old snapshot is still readable. After replacement, the new snapshot is visible. Publishing the same bytes again leaves the result identical.
Python documents that a successful replacement is atomic and that crossing filesystems can fail. This gives an atomic file-name transition; it is not a database transaction, a cross-file commit or a guarantee of persistence after power loss. Durable publication needs the storage system’s flush, commit and concurrency guarantees. An object store might instead write an immutable object and conditionally update a manifest pointer.
The early and revised snapshot SHA-256 values begin 3ad8eae81c05 and 5c4466021604. They differ because the accepted event set changed. Keep both identities if the earlier published result must remain explainable. Reusing the same human-readable day label without a revision would hide that change.
A backfill is a new computation over old event time#
A backfill recomputes historical partitions. It may use newly arrived data, a repaired transform or both. Specify those two changes separately. In the fixture, recomputing days zero and one with cutoff 36 yields two unique events in each. Replaying the old cutoff 30 should reproduce the earlier knowledge state, not silently include records first observed at hour 31.
Keep the original run’s source snapshot and transformation revision. If the input table was edited in place, a date parameter alone cannot recreate its former contents. When historical records must be removed under a retention policy, record that a past run is no longer fully reproducible rather than claiming the missing data can still be recovered.
Backfills compete with current work for workers, database connections and write capacity. Airflow’s documented backfill concurrency limit is a concrete control for that problem. It does not make a task idempotent or validate its outputs. Before enabling concurrency, decide whether one partition depends on the preceding partition’s state and whether a later run can overwrite a newer result.
Event time, observation time and completeness differ#
A watermark estimates how far event time has progressed for a stream. Beam distinguishes that estimate from processing time and provides policies for late data. It is not a universal guarantee that no older event will ever arrive.
To inspect the mechanism without running Beam, define our own policy: watermark equals the largest event hour observed so far minus four hours. After e3 arrives, the watermark is 25, beyond the end of day zero at hour 24. Event e2 then arrives with event hour 15 and is late under this policy. The redelivery of e1 is late too, but deduplication distinguishes a repeated event from newly discovered data.
Closing a window at its first watermark crossing yields a prompt initial answer. Allowing later updates needs retained state, a finality rule and a way for downstream consumers to recognize revised outputs. A consumer that adds every revised total as if it were a new increment double-counts. Decide whether an update replaces a prior total, adds a delta or retracts an earlier contribution.
An allowed-lateness interval is an event-time state-retention policy, not simply a sleep on the wall clock. A stalled input can stall watermark progress; a source with an incorrect future timestamp can advance a naive maximum-based estimate too far. Our four-hour heuristic is intentionally simple and is not presented as Beam’s watermark implementation.
Labels add another availability boundary#
The upload event may be known immediately while a repair label arrives days later. Feature availability, event date and label availability therefore need separate timestamps. For an evaluation cutoff, join only labels available by that cutoff and report the unlabeled population. Treating missing labels as negative fabricates successful predictions.
For training, distinguish information allowed at prediction time from the later label used as a target. A historical rebuild can correctly use a later label while still forbidding later feature values. The feature consistency note develops this point-in-time boundary.
An orchestrator manages execution, not meaning#
Airflow models scheduled DAG runs and backfills. Dagster emphasizes materialized data assets and their dependencies. Prefect uses flows and tasks to coordinate execution. These are examples of abstractions, not a current product ranking. Their primary documentation is useful when selecting the interface that matches the workflow.
Whichever tool is used, give an attempt a durable ID, capture input/output identities, preserve a useful failure reason and set a retry budget. A transient connection failure may be retryable; an invalid schema usually needs a changed input or policy. Retrying a deterministic validation failure a hundred times only consumes the backfill budget.
Separate computation from publication. A successful calculation that has not passed validation should remain staged. A failed notification after publication must not make an otherwise successful retry republish duplicate side effects. Notifications and other external writes need their own idempotency keys or reconciliation process.
A data contract makes a silent assumption explicit#
For each field, specify type, units, missing-value meaning and availability. Define the event key, correction rule and ordering guarantee. The preview contract uses hours from an agreed origin, a stable event ID and a unique payload for that ID. Another source might require timezone-aware timestamps and an explicit schema version.
Assign an owner for contract changes. Adding a field may be backward compatible for a reader that ignores it; changing the meaning of event_hour from event time to arrival time is not. Run a candidate parser against permitted fixtures before promoting it, and preserve old parsing code or a migration when old snapshots must remain readable.
What changed#
The late upload now produces an identified revision of day zero. Redelivery does not add a second card, and a retry publishes the same bytes. The graph records what each task consumed, while separate timestamps explain why two correct reports can differ.
Limitations#
The fixture uses one process, integer hours, a complete local event list and small JSON files. It does not test distributed transactions, storage durability, timezones, concurrent writers or a production scheduler. Exactly-once visible effects require cooperation at the sink; successful local deduplication cannot establish that guarantee for a remote payment, notification or write.
What to retain#
Identify events separately from deliveries. Pin input knowledge and transform versions. Write complete outputs before publishing them. Make retries idempotent at the effect boundary. Keep event time, observation time and label maturity separate. A backfill needs resource limits and a revision policy.
Reproduce the example#
The pipeline function in the original Python source executes the snapshot selection, reversed-input check, local atomic replacement, retry equality and watermark arithmetic. Saved results include the exact events and hashes. Run it without external packages; its filesystem writes are confined to a temporary directory.
Next#
Data quality and versioning places explicit acceptance rules before that publication boundary and connects the accepted bytes to their provenance.
References#
- Apache Airflow contributors. Backfill, documentation 3.4.0, read 13 November 2026: historical DAG runs, reprocessing and concurrency. The local fixture is not Airflow code.
- Apache Beam contributors. Programming Guide: Watermarks and late data, read 13 November 2026: event/processing time, watermarks and late-state retention. The five-event trace and maximum-minus-four policy are independently specified.
- Python Software Foundation.
os.replace, documentation 3.15.2: atomic successful rename and filesystem boundary. No documentation code copied. - Dagster contributors. Assets, documentation 1.13.30, read 13 November 2026: asset-oriented abstraction.
- Prefect contributors. Flows, version 3 documentation, read 13 November 2026: flow execution and task composition.