🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

ETL Pipeline Patterns: Dataproc, Dataflow & Cloud Functions

GCP Data EngineeringETL PipelinesđŸŸĸ Free Lesson

ETL Pipeline Patterns on GCP

Master ETL patterns using Dataproc Spark, Dataflow Beam, Cloud Functions, and orchestrated workflows on GCP.

20 min readAdvanced

What You'll Learn

  • 1Explain why a pipeline transforms before loading rather than after
  • 2Pick Dataproc, Dataflow or BigQuery SQL from the workload's actual constraints
  • 3Design failure handling that quarantines bad rows instead of stalling the job
  • 4Cut a batch pipeline's cost with spot capacity, incremental reads and columnar output

Why Transform Before You Load

ETL moves data in three steps, and the reason for doing the transformation in the middle is never elegance. There are three legitimate motives. The first is protection: identifiers are masked or tokenised before the target ever sees them, so a non-production copy can be shared without a privacy review. The second is contract: the target schema is fixed, and a downstream system that cannot tolerate a new column needs the shape enforced before the write. The third is cost: if the target charges per byte stored or per byte scanned, arriving with fewer, wider, deduplicated rows is cheaper than landing raw and cleaning afterwards.

The pattern also changes how failures surface. Because the transformation runs before the load, a malformed record can be routed to a quarantine location instead of failing the write, and the job can finish with a report of what it rejected rather than leaving a partial load behind. What you give up is reprocessability: once raw has been discarded, a new business rule means going back to the source. That trade is the whole subject of the next lesson, where the load happens first precisely so the transformation can be rerun.

Dataproc Spark When You Already Speak Spark

Dataproc runs managed Spark and Hadoop clusters in roughly ninety seconds, which makes it the pragmatic home for existing jobs and for teams whose skills live in PySpark rather than in Beam.

python
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *

spark = SparkSession.builder \
    .appName("ETL_Sales_Data") \
    .config("spark.sql.adaptive.enabled", "true") \
    .config("spark.sql.shuffle.partitions", "200") \
    .getOrCreate()

# EXTRACT: read raw data from the lake
raw_df = spark.read \
    .option("header", "true") \
    .option("inferSchema", "true") \
    .csv("gs://my-data-lake/bronze/sales/*.csv")

# TRANSFORM: clean and enrich
transformed_df = raw_df \
    .withColumn("order_date", to_date(col("order_date"), "yyyy-MM-dd")) \
    .withColumn("amount", col("quantity") * col("unit_price")) \
    .withColumn("tax", col("amount") * 0.08) \
    .withColumn("total", col("amount") + col("tax")) \
    .withColumn("customer_domain", regexp_extract(col("email"), "@(.+)$", 1)) \
    .filter(col("amount") > 0) \
    .filter(col("email").isNotNull())

summary_df = transformed_df \
    .groupBy("order_date", "product_category") \
    .agg(
        count("*").alias("order_count"),
        sum("total").alias("total_revenue"),
        avg("total").alias("avg_order_value"),
        countDistinct("email").alias("unique_customers")
    )

# LOAD: write the summary to BigQuery and the detail back to the lake
summary_df.write \
    .format("bigquery") \
    .option("table", "project.analytics.sales_summary") \
    .option("temporaryGcsBucket", "my-temp-bucket") \
    .mode("overwrite") \
    .save()

transformed_df.write \
    .mode("overwrite") \
    .partitionBy("order_date") \
    .parquet("gs://my-data-lake/silver/sales/")

spark.stop()

Four configuration choices decide whether that job is cheap or expensive. Adaptive query execution and a shuffle partition count matched to the data size prevent the default of two hundred tiny tasks from dominating a small run. Spot or preemptible VMs for the worker nodes cut the compute bill substantially, with the caveat that a spot loss mid stage costs a retry, so checkpoint and size stages accordingly. The BigQuery connector writes through load jobs using a temporary bucket, which batches rows instead of streaming them one at a time. And writing both the summary and the partitioned detail means the expensive clean step never has to run twice.

Dataflow When Batch and Streaming Must Be One Codebase

Beam's pitch is a single pipeline that runs as batch today and as streaming tomorrow without a rewrite, which matters when a nightly job needs to become hourly without a second implementation.

python
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.io.gcp.bigquery import WriteToBigQuery, BigQueryDisposition
import json
from datetime import datetime

class TransformSalesData(beam.DoFn):
    def process(self, element):
        try:
            record = json.loads(element)
            yield {
                'order_id': record['order_id'],
                'customer_id': record['customer_id'],
                'product_category': record['product_category'],
                'amount': float(record['quantity']) * float(record['unit_price']),
                'order_date': record['order_date'],
                'processed_at': datetime.utcnow().isoformat()
            }
        except (KeyError, ValueError):
            yield beam.pvalue.TaggedOutput('rejected', element)

def run_etl_pipeline():
    pipeline_options = PipelineOptions([
        '--project', 'my-project',
        '--runner', 'DataflowRunner',
        '--region', 'us-central1',
        '--temp_location', 'gs://my-data-lake/temp/',
        '--machine_type', 'n1-standard-4',
        '--max_num_workers', '10',
        '--experiments', 'enable_streaming_engine'
    ])

    with beam.Pipeline(options=pipeline_options) as pipeline:
        results = (
            pipeline
            | 'Read' >> beam.io.ReadFromText('gs://my-data-lake/bronze/sales/*.json')
            | 'Transform' >> beam.ParDo(TransformSalesData()).with_outputs('rejected')
        )

        (
            results[None]
            | 'Write BQ' >> WriteToBigQuery(
                'my-project:analytics.sales',
                schema='order_id:STRING,customer_id:STRING,'
                       'product_category:STRING,amount:FLOAT64,order_date:TIMESTAMP',
                write_disposition=BigQueryDisposition.WRITE_APPEND
            )
        )

        (
            results['rejected']
            | 'Write quarantine' >> beam.io.WriteToText(
                'gs://my-data-lake/quarantine/sales/', file_name_suffix='.json'
            )
        )

if __name__ == '__main__':
    run_etl_pipeline()

The tagged output is the part interviewers look for: a record that fails parsing is not dropped and not allowed to kill the stage, it is routed so it can be inspected and replayed. Beam also gives you control over fusion, the optimizer step that merges adjacent stages to avoid materialising intermediate data, and over triggers and watermarks when the same pipeline runs in streaming mode.

Choosing the Engine

EngineSkill assumptionOperating modelCost shapeReach for it when
DataprocPySpark and SQLYou size and watch clustersNode hours, cheaper on spotExisting Spark jobs or heavy ML steps
DataflowBeam or Beam-compatibleServerless, autoscalingvCPU and shuffle per jobNew pipelines, batch to streaming later
BigQuery SQL or dbtSQL onlyNo compute to runBytes scannedThe transform is relational and the data is already there
Cloud Run jobsAny containerPer request, scaled to zeroDuration and memorySmall, event driven payloads

A useful tiebreak is where the data already sits. If the input and the output are both BigQuery tables and the logic is joins and aggregations, running Spark to move bytes out and back is pure overhead. If the input is a fleet of files in the lake and the logic needs a library that does not exist in SQL, Dataproc or a Dataflow Python transform is the honest choice.

Failure Handling That Finishes the Run

The design goal is a job that completes and reports what it rejected, rather than one that fails halfway and leaves a destination in an ambiguous state. Three mechanisms cover most cases. A dead letter output, either a tagged Beam output, a GCS prefix or a quarantine table, holds every record that could not be parsed, with the error message and the source file attached so the fix is obvious. Retry with backoff handles transient failures such as a throttled API or a briefly unavailable bucket, and it must be bounded, because an unbounded retry against a deterministic error never converges. Idempotent loading, writing through a merge keyed on the business key or staging into a temporary table and swapping, means a rerun after a mid-job failure cannot duplicate rows.

Schema drift needs its own path. When a source adds a column, the pipeline should either ignore it deliberately or route the record to quarantine, but it must never fail silently by writing nulls into a typed column. Comparing the incoming schema against a registered expectation at the start of each run converts a surprise at row nine hundred thousand into a clear message at second zero.

Orchestration, Testing and Backfills

Cloud Composer runs the DAG that sequences extraction, transformation, quality gates and load, and the structure of that DAG is where reliability comes from. Each task should be idempotent and independently retryable, with data quality checks as their own tasks that can fail the run before a bad table is published. Backfills are the test: a pipeline that cannot be rerun for an arbitrary past date is one that will be difficult to repair after a logic bug, so parameters, rather than hard coded dates, belong in every task.

Testing follows the same split the code does. Unit tests cover transforms with small fixtures, including deliberately malformed rows, integration tests run against a scratch dataset in continuous integration, and contract tests assert the output schema and row counts against expectations. A change that passes unit tests but breaks the contract still fails the build, which is the only way schema changes are caught before a consumer finds them.

Cutting the Bill

The largest levers are structural rather than tactical. Read incrementally with a watermark or a partition predicate instead of rescanning history every night, which turns a full reprocess into a delta and is usually a tenfold reduction. Keep intermediate output in columnar Parquet rather than CSV or JSON, so downstream scans read columns rather than parsing text. Right-size the cluster: a job that runs for forty minutes should not own a six node cluster for a day, so Dataproc clusters should be created for the run and deleted by the DAG, and Dataflow workers should autoscale rather than sit at a fixed maximum. Finally, move the relational part of the transformation into BigQuery, where the compute is already paid for by bytes scanned, and reserve Spark for what SQL genuinely cannot express.

✨

Best Practice: Quarantine bad records instead of failing the stage, make every load idempotent so reruns are free, and create Dataproc clusters for the duration of the DAG rather than leaving them warm. Read incrementally, write Parquet partitioned by date, and push relational transforms into BigQuery before reaching for a cluster.

Common Interview Questions

Q1: When Dataproc over Dataflow?

Answer: When you have existing Spark code, need a library that only exists in the Spark ecosystem, or want explicit control over cluster size and debugging with a familiar REPL. Dataflow wins for new pipelines, serverless operation and code that may later run in streaming mode.

Q2: How do you handle errors in an ETL pipeline?

Answer: Tag failed records into a dead letter output with the reason attached, bound retries so a deterministic error cannot loop forever, load idempotently so a rerun cannot duplicate, and alert on the quarantine rate rather than only on job failure.

Q3: ETL or ELT?

Answer: ETL transforms before the load, which is right when the target must not see raw identifiers, when the schema is a hard contract, or when the target charges per stored byte. ELT loads raw and transforms in place, which suits BigQuery where storage is cheap and reprocessing is a query.

Q4: How do you cut pipeline cost?

Answer: Process only new data using watermarks or partition predicates, use spot capacity for Spark workers, delete clusters when the DAG finishes, write Parquet instead of text, right-size shuffle partitions, and move relational work into BigQuery so it bills by bytes scanned instead of node hours.

Q5: How do you test an ETL pipeline?

Answer: Unit test transforms with fixtures including malformed rows, run an integration test against a scratch dataset in continuous integration, assert an output contract with schema and row count checks, and verify backfill for an arbitrary historical date works before the first production run.

Interview Questions

Q1: Why does a dead letter queue need the error message stored with the row?

Without the reason, replaying the quarantine means guessing at the fix; with it, the same record can be corrected and rerun through the identical code path that rejected it.

Q2: What makes a load idempotent in BigQuery?

Staging into a temporary table and merging on the business key, or writing with a write disposition that overwrites the target partition, so a rerun of the same input produces the same table rather than appended duplicates.

Q3: When is a Spark shuffle a sign of a design problem?

When it comes from a low cardinality join or an unnecessary groupBy, because every shuffle moves data across the network; a broadcast join or a pre-aggregated dimension removes it entirely.

Q4: How do you recover from a logic bug discovered a week later?

Rerun the affected dates from the raw layer with corrected parameters, which only works if the pipeline is parameterised and the raw data is retained rather than discarded at load time.

Common Mistakes

Failing the whole stage on one malformed record

Fix: Tag it into a dead letter output with the error, keep processing, and alert on the rejection rate.

Leaving Dataproc clusters running between nightly runs

Fix: Create the cluster in the DAG, run the job, and delete it, or the cluster costs more than the work it does.

Rescanning the full history every run

Fix: Read incrementally with a watermark or partition predicate and let the rare full rebuild be an explicit backfill task.

Key Takeaways

  • ETL transforms first for protection, contract or cost reasons, and gives up the ability to re-apply a new rule without returning to the source
  • Dataproc suits existing Spark and heavy libraries, Dataflow suits serverless batch that may become streaming, and BigQuery SQL wins when both ends are already tables
  • Quarantine, bounded retries and idempotent loads together mean a job finishes and reports rather than failing halfway
  • Cost levers are incremental reads, spot capacity, cluster lifetime tied to the DAG, columnar output and pushing relational work into BigQuery
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert GCP Data Engineering Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement