What You'll Learn
- 1Lay out bronze, silver, and gold prefixes on GCS so backfills are cheap
- 2Build a Dataflow batch job that validates, deduplicates, and lands data idempotently
- 3Schedule runs and backfills from Cloud Composer with deterministic run dates
- 4Choose a batch trigger and idempotency strategy for each delivery guarantee needed
A batch pipeline is judged on reproducibility rather than on elegance. The test is simple: if last night's run produced a wrong number, can you re-run exactly that window today and get the same answer without duplicating rows or leaving gaps? Everything in this lesson follows from that requirement, from the way prefixes are laid out on Cloud Storage to the way a write disposition is chosen for BigQuery.
Batch Pipeline Architecture
The reference shape is a three-stage lake feeding a warehouse. Raw files land in a bronze prefix untouched, so the original bytes are always available for a replay. A Dataflow job reads bronze, parses and validates records, and writes a cleaned copy to silver as Parquet, which gives columnar compression and schema evolution for free. A second stage aggregates silver into gold tables in BigQuery, where the dashboard reads. Each stage can be re-run from its own input without touching the stage before it.
The choice of trigger decides what the pipeline can promise. A time-based trigger driven by a scheduler gives a predictable daily cost and a clean operational window, at the price of handling late data with a separate backfill. An event-based trigger that fires when files arrive gives low latency but no natural boundary for exactly-once writes, so the sink must tolerate reprocessing. Most production systems run both: a streaming-ish path for freshness and a nightly batch for correctness.
| Trigger style | Latency | Reprocessing | Best fit |
|---|---|---|---|
| Scheduled, time partitioned | Hours | Backfill the partition | Warehouses, reports |
| File arrival on GCS | Minutes | Re-emit from source | Landing zones, CDC dumps |
| Micro-batch window | Seconds to minutes | Windowed replay | Operational dashboards |
Implementation
Implementation is where the guarantees are won or lost, and four decisions carry most of the weight. First, read by partition rather than by wildcard so a run touches only its own window. Second, validate inside the pipeline and route rejects to a dead-letter prefix instead of failing the whole job on one malformed row. Third, derive a deterministic record hash and use it to deduplicate, which makes a repeated run a no-op rather than a duplicate. Fourth, write to BigQuery with a date-partitioned destination and a truncate-and-replace disposition for that partition, so re-running a day overwrites it instead of appending to it.
GCS Bucket Structure
# Create data lake structure
gsutil -m mkdir -p gs://my-data-lake/bronze/raw
gsutil -m mkdir -p gs://my-data-lake/bronze/archive
gsutil -m mkdir -p gs://my-data-lake/silver/validated
gsutil -m mkdir -p gs://my-data-lake/silver/cleaned
gsutil -m mkdir -p gs://my-data-lake/gold/curated
gsutil -m mkdir -p gs://my-data-lake/temp
gsutil -m mkdir -p gs://my-data-lake/staging
# Set lifecycle rules
cat > lifecycle.json << 'EOF'
{
"rule": [
{
"action": {"type": "SetStorageClass", "storageClass": "NEARLINE"},
"condition": {"age": 30}
},
{
"action": {"type": "SetStorageClass", "storageClass": "COLDLINE"},
"condition": {"age": 90}
},
{
"action": {"type": "Delete"},
"condition": {"age": 730, "isLive": false}
}
]
}
EOF
gsutil lifecycle set lifecycle.json gs://my-data-lake/bronze/raw
Dataflow Batch Pipeline
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.io.gcp.bigquery import BigQueryDisposition
import json
import hashlib
from datetime import datetime
class ParseAndValidate(beam.DoFn):
"""Parse JSON and validate schema."""
def process(self, element):
try:
record = json.loads(element)
# Validate required fields
required_fields = ['event_id', 'event_type', 'timestamp', 'user_id']
if not all(field in record for field in required_fields):
return
# Validate data types
if not isinstance(record.get('amount', 0), (int, float)):
return
# Enrich with metadata
record['processed_at'] = datetime.utcnow().isoformat()
record['source_file'] = element.metadata.path if hasattr(element, 'metadata') else 'unknown'
record['record_hash'] = hashlib.md5(json.dumps(record, sort_keys=True).encode()).hexdigest()
yield record
except json.JSONDecodeError:
return
class DeduplicateRecords(beam.DoFn):
"""Deduplicate records using record hash."""
def __init__(self):
self.seen_hashes = set()
def process(self, element):
record_hash = element.get('record_hash')
if record_hash and record_hash not in self.seen_hashes:
self.seen_hashes.add(record_hash)
yield element
def run_batch_pipeline():
"""Run batch ETL pipeline: GCS → Dataflow → BigQuery."""
pipeline_options = PipelineOptions([
'--project', 'my-project',
'--runner', 'DataflowRunner',
'--region', 'us-central1',
'--temp_location', 'gs://my-data-lake/temp/',
'--staging_location', 'gs://my-data-lake/staging/',
'--machine_type', 'n1-standard-4',
'--max_num_workers', '20',
'--autoscaling_algorithm', 'THROUGHPUT_BASED',
'--number_of_worker_harness_threads', '4',
'--experiments', 'use_runner_v2'
])
with beam.Pipeline(options=pipeline_options) as pipeline:
# Read from GCS (Bronze)
raw_data = (
pipeline
| 'Read Raw Data' >> beam.io.ReadFromText(
'gs://my-data-lake/bronze/raw/**/*.json.gz',
compression_type=beam.io.fileio.CompressionTypes.GZIP
)
)
# Parse and validate
validated_data = (
raw_data
| 'Parse and Validate' >> beam.ParDo(ParseAndValidate())
)
# Write to GCS as Parquet (Silver)
(
validated_data
| 'Write Silver Parquet' >> beam.io.WriteToParquet(
'gs://my-data-lake/silver/validated/',
schema='event_id:STRING,event_type:STRING,user_id:STRING,timestamp:TIMESTAMP,amount:FLOAT64,processed_at:TIMESTAMP',
file_name_suffix='.parquet',
coders=beam.codersregistry.get_coder('TableRow')
)
)
# Write to BigQuery (Gold)
(
validated_data
| 'Write to BigQuery' >> beam.io.WriteToBigQuery(
'my-project:analytics.events',
schema='event_id:STRING,event_type:STRING,user_id:STRING,timestamp:TIMESTAMP,amount:FLOAT64,processed_at:TIMESTAMP',
write_disposition=BigQueryDisposition.WRITE_APPEND,
create_disposition=BigQueryDisposition.CREATE_IF_NEEDED
)
)
if __name__ == '__main__':
run_batch_pipeline()
✨
Best Practice: Always implement the Bronze/Silver/Gold pattern. Bronze stores raw data, Silver contains validated/cleaned data, and Gold is business-ready. This provides data lineage, enables reprocessing, and separates concerns.
Cloud Composer DAG
from datetime import datetime, timedelta
from airflow import DAG
from airflow.providers.google.cloud.operators.dataflow import DataflowStartFlexTemplateOperator
from airflow.providers.google.cloud.operators.bigquery import BigQueryInsertJobOperator
from airflow.operators.python import PythonOperator
from airflow.operators.email import EmailOperator
default_args = {
'owner': 'data-engineering',
'retries': 3,
'retry_delay': timedelta(minutes=5),
'email_on_failure': True,
'email': ['[email protected]'],
'sla': timedelta(hours=4),
}
with DAG(
dag_id='batch_etl_pipeline',
default_args=default_args,
schedule_interval='0 2 * * *',
start_date=datetime(2025, 1, 1),
catchup=False,
tags=['batch', 'etl', 'daily'],
) as dag:
# Task 1: Trigger Dataflow job
run_dataflow = DataflowStartFlexTemplateOperator(
task_id='run_dataflow_batch',
body={
'jobName': 'batch-etl-{{ ds }}',
'parameters': {
'input': 'gs://my-data-lake/bronze/raw/{{ ds_nodash }}/*.json.gz',
'output_table': 'my-project:analytics.events',
'temp_location': 'gs://my-data-lake/temp/'
},
'environment': {
'numWorkers': 10,
'maxWorkers': 50,
'machineType': 'n1-standard-4',
'zone': 'us-central1-a'
}
},
location='us-central1',
)
# Task 2: Data quality check
quality_check = BigQueryInsertJobOperator(
task_id='data_quality_check',
configuration={
'query': {
'query': '''
DECLARE row_count INT64;
DECLARE null_count INT64;
SELECT COUNT(*) INTO row_count
FROM `project.analytics.events`
WHERE DATE(processed_at) = '{{ ds }}';
SELECT COUNT(*) INTO null_count
FROM `project.analytics.events`
WHERE DATE(processed_at) = '{{ ds }}'
AND event_id IS NULL;
SELECT
row_count,
null_count,
SAFE_DIVIDE(null_count, row_count) as null_rate
''',
'useLegacySql': False,
}
},
location='us-central1',
)
# Task 3: Alert on failure
alert_failure = EmailOperator(
task_id='alert_failure',
to=['[email protected]'],
subject='Batch Pipeline Failed - {{ ds }}',
html='<p>Batch pipeline failed. Check Cloud Composer logs.</p>',
trigger_rule='one_failed',
)
run_dataflow >> quality_check >> alert_failure
Scheduling, SLAs, and Backfills
A scheduler is a promise about time, so the first thing to write down is the latest acceptable arrival for each table and then alert against it rather than against job success. A job that finishes in nine minutes with yesterday's data is a failure, while a job that takes three hours and lands fresh data on time is a success, and only an arrival-time metric distinguishes them. Cloud Composer makes that easy because the DAG's end time is observable and can be compared with a static deadline.
Backfills are the other half of operations. Because each run is addressed by its own date partition, reprocessing a week means running the same DAG with a set of logical dates rather than editing the code, and the write disposition makes each run overwrite its target instead of appending. Keep catchup off for the normal schedule so a Composer outage does not fire a year of queued runs, and invoke backfills explicitly through the trigger or the API with a bounded range.
Monitoring and Alerting
A batch pipeline fails quietly more often than it crashes, so monitoring must cover data properties as well as process health. Row counts, null rates, and the share of rejected records are the three that catch almost every realistic defect: a source that stopped sending shows up as a count drop, a schema change shows up as a null spike, and a parser bug shows up in the reject rate. Each belongs in a quality check that runs after the load and before the dashboard refresh.
from google.cloud import monitoring_v3
from google.protobuf import timestamp_pb2
def create_batch_pipeline_alert(project_id):
"""Create monitoring alert for batch pipeline failures."""
client = monitoring_v3.AlertPolicyServiceClient()
alert_policy = monitoring_v3.AlertPolicy(
display_name="Batch Pipeline Duration Alert",
conditions=[
monitoring_v3.AlertPolicy.Condition(
display_name="Pipeline Duration > 4 hours",
condition_threshold=monitoring_v3.AlertPolicy.Condition.MetricThreshold(
filter='resource.type="cloud_dataflow_job" AND '
'metric.type="dataflow.googleapis.com/job/elapsed_time"',
comparison=monitoring_v3.ComparisonType.COMPARISON_GT,
threshold_value=14400, # 4 hours in seconds
duration="60s",
),
)
],
)
request = monitoring_v3.CreateAlertPolicyRequest(
name=f"projects/{project_id}",
alert_policy=alert_policy,
)
response = client.create_alert_policy(request=request)
print(f"Created alert: {response.name}")
ℹ️
Cost Tip: For batch pipelines, use FlexRS for non-urgent jobs (up to 50% savings). Enable autoscaling to scale down when idle. Use pre-emptible workers for fault-tolerant processing. Schedule jobs during off-peak hours for lower costs.
Failure Modes and Idempotency
Retries are guaranteed in distributed systems, so every stage must be safe to run twice. On the read side that means addressing input by partition, because a wildcard over the whole bronze prefix will happily reprocess three months of history the moment a job restarts. On the write side it means choosing a disposition deliberately: append duplicates rows, replace makes the run atomic for that partition, and streaming insert with a best-effort merge trades throughput for tolerance.
The cleanest pattern is to treat the target partition as owned by exactly one run. Compute the partition from the data's event date, write to a staging location, and promote it once the quality checks pass, so a crash mid-write leaves the previous good partition visible rather than a half-populated one. For tables that cannot be replaced wholesale, deduplicate on a deterministic record key so a replayed row recognises itself as already present.
def partition_key(record):
"""Deterministic identity and target partition for a batch record."""
event_date = record["event_timestamp"].date().isoformat()
key = hashlib.sha256(
f"{record['event_id']}:{event_date}".encode()
).hexdigest()
return event_date, key
Common Mistakes
Reading the whole bronze prefix on every run
Fix: Address only the date partition for the run so retries and restarts stay bounded and cheap.
Appending to a table that a run already wrote
Fix: Use a truncate-and-replace disposition on the target partition so a rerun overwrites instead of duplicating.
Alerting on job failure only
Fix: Alert on data quality and arrival time as well, because the common defect is a job that succeeds with wrong data.
Best Practices
- Write quality checks after every load and gate the downstream refresh on them
- Keep catchup disabled and invoke backfills explicitly over a bounded date range
- Derive record identity from stable business keys rather than from ingest timestamps
- Separate staging from promotion so a failed write never leaves a partially filled partition
Key Takeaways
- Bronze, silver, and gold stages make any window independently reprocessable
- A deterministic record hash plus a partition replace disposition makes replays idempotent
- Schedule by event date, disable catchup, and run backfills as explicit bounded jobs
- Monitor arrival time and data quality, not just task status, to catch silent failures
Common Interview Questions
Q1: Why use GCS as the source for batch pipelines?
Answer: GCS provides durable, scalable storage for raw data at low cost. It supports multiple formats, lifecycle management, and direct access from Dataflow. Using GCS as the Bronze layer enables reprocessing, data lineage, and separation of storage and compute.
Q2: How do you handle schema evolution in batch pipelines?
Answer: Use Avro or Parquet with schema evolution support. Implement schema registry for version control. Use Dataflow's auto-detection for flexible schemas. For BigQuery, use schema auto-detection with explicit column additions. Always validate data after schema changes.
Q3: What are the key metrics to monitor in batch pipelines?
Answer: 1) Pipeline duration vs. SLA, 2) Records processed per second, 3) Error rates and types, 4) Data quality metrics (null rates, completeness), 5) Resource utilization (CPU, memory), 6) Cost per run.
Q4: How do you implement idempotency in batch pipelines?
Answer: Use date-based partitioning to prevent duplicate processing. Implement record hashing for deduplication. Use BigQuery partitioned tables with WRITE_TRUNCATE for daily loads. Check pipeline state before reprocessing. Use Cloud Composer's execution dates for deterministic runs.
Q5: What is the difference between FlexRS and standard Dataflow for batch?
Answer: FlexRS provides up to 50% cost savings by using a mix of preemptible and on-demand VMs with longer execution time limits (up to 6 hours). Standard Dataflow provides faster execution with guaranteed resources. Use FlexRS for non-urgent batch jobs, standard for time-sensitive processing.
Interview Questions
Q1: Why use GCS as the source for a batch pipeline?
Object storage is durable, cheap, and readable by Dataflow, Dataproc, and BigQuery without a copy, so bronze becomes the shared replay point. Lifecycle rules age old files down, and partitioned prefixes let a run read one day instead of the whole lake.
Q2: How do you handle schema evolution in a batch pipeline?
Store silver as Parquet or Avro, which carry a schema and support additive field changes, and land BigQuery tables with a schema that allows the new columns. Validate the incoming schema on read and route incompatible files to a reject prefix rather than failing the run.
Q3: How do you make a daily load idempotent?
Partition the destination by event date and write with a truncate-and-replace disposition for that partition, then deduplicate on a deterministic record key. A rerun therefore overwrites the same partition with the same rows instead of appending duplicates.
Q4: What metrics matter for a batch pipeline?
Arrival time against the SLA, records processed per second, reject rate, and data quality measures such as null rate and row count versus the trailing average. Add cost per run, because a query or shuffle regression shows up in billing before it shows up in latency.