Post

Getting Started with GCP Dataflow for Batch Pipelines

In this article, let us build a simple batch pipeline using Apache Beam and run it on GCP Dataflow. We will read CSV files from a GCS bucket, perform a small transformation, and write the result into BigQuery. This approach is useful when the processing is more involved than a direct file load and we want GCP to manage the workers needed for the job.

For our demo, the input contains sales records with order_id, customer_id, amount, and order_date. We will filter invalid records and calculate the total order amount for each customer.

What are Apache Beam and Dataflow?

Apache Beam is the programming model we use to define the pipeline. Dataflow is the GCP service that runs it. The same Beam pipeline can run locally with the Direct Runner or on GCP with the Dataflow Runner. This is useful because we can test with a small file locally before paying for cloud workers.

OptionWhere it runsGood for
Direct RunnerLocal systemDevelopment and small tests
Dataflow RunnerGCP-managed workersProduction batch and streaming jobs
BigQuery load jobGCPLoading files with little or no transformation

If we only need to copy a correctly formatted CSV into BigQuery, a load job is simpler. Dataflow starts making sense when we need validation, joins, enrichment, custom parsing, or the same pipeline pattern for many inputs.

1. Create the GCP resources

We need a GCP project with billing enabled, a GCS bucket for input and temporary files, and a BigQuery dataset. We also need the Dataflow, Compute Engine, Cloud Storage, and BigQuery APIs enabled.

1
2
3
4
5
6
7
8
gcloud config set project my-data-project
gcloud services enable dataflow.googleapis.com compute.googleapis.com \
  storage.googleapis.com bigquery.googleapis.com

gcloud storage buckets create gs://my-dataflow-batch-demo \
  --location=australia-southeast1

bq --location=australia-southeast1 mk -d my-data-project:sales_demo

Create a file named sales.csv with a header and a few rows.

order_id,customer_id,amount,order_date
1001,C101,25.50,2026-11-20
1002,C102,10.00,2026-11-20
1003,C101,14.50,2026-11-21

Upload it to the bucket.

1
2
gcloud storage cp sales.csv gs://my-dataflow-batch-demo/input/sales.csv
gcloud auth application-default login

For a production setup, I would use a dedicated Dataflow worker service account and avoid user credentials or downloaded service account keys.

2. Set up the Python project

Create a virtual environment and install Apache Beam with GCP support.

1
2
3
python3 -m venv .venv
source .venv/bin/activate
pip install 'apache-beam[gcp]'

It is a good idea to pin the Beam version in requirements.txt. Dataflow workers need compatible dependencies, and an unplanned package upgrade can make a pipeline that worked yesterday fail today.

3. Write the pipeline

Create a file named pipeline.py. The code below skips the CSV header, parses each row, filters records without a customer ID or with a negative amount, and groups the amount by customer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import argparse
import csv
import io

import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions

def parse_row(line):
    values = next(csv.reader(io.StringIO(line)))
    return {
        'order_id': values[0],
        'customer_id': values[1],
        'amount': float(values[2]),
        'order_date': values[3],
    }

def is_valid(row):
    return bool(row['customer_id']) and row['amount'] >= 0

def to_bigquery_row(item):
    customer_id, total_amount = item
    return {'customer_id': customer_id, 'total_amount': round(total_amount, 2)}

def run(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', required=True)
    parser.add_argument('--output_table', required=True)
    known_args, pipeline_args = parser.parse_known_args(argv)
    options = PipelineOptions(pipeline_args, save_main_session=True)

    with beam.Pipeline(options=options) as pipeline:
        rows = (
            pipeline
            | 'Read CSV' >> beam.io.ReadFromText(
                known_args.input, skip_header_lines=1)
            | 'Parse rows' >> beam.Map(parse_row)
            | 'Keep valid rows' >> beam.Filter(is_valid)
        )
        totals = (
            rows
            | 'Customer and amount' >> beam.Map(
                lambda row: (row['customer_id'], row['amount']))
            | 'Sum per customer' >> beam.CombinePerKey(sum)
            | 'Create BigQuery rows' >> beam.Map(to_bigquery_row)
        )
        totals | 'Write BigQuery' >> beam.io.WriteToBigQuery(
            known_args.output_table,
            schema='customer_id:STRING,total_amount:FLOAT',
            write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE,
            create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,
        )

if __name__ == '__main__':
    run()

The named pipeline steps are not compulsory, but they make the Dataflow graph and logs much easier to understand. When a production pipeline has several transforms, names like Map and Map2 are not very useful during an incident.

4. Test with the Direct Runner

Before submitting the job to GCP, run it locally against the GCS input. Beam uses the Direct Runner when we do not provide another runner.

1
2
3
python pipeline.py \
  --input gs://my-dataflow-batch-demo/input/sales.csv \
  --output_table my-data-project:sales_demo.customer_totals

We can verify the output using SQL.

1
2
3
SELECT customer_id, total_amount
FROM `my-data-project.sales_demo.customer_totals`
ORDER BY customer_id;

For the sample data, customer C101 should have a total of 40.00, and C102 should have 10.00. Testing locally catches parsing and schema issues quickly, although it does not reproduce worker networking, IAM, or scaling behaviour.

5. Run it on Dataflow

Now run the same file with the Dataflow Runner. Keep the GCS bucket and Dataflow workers in the same region where possible.

1
2
3
4
5
6
7
8
9
python pipeline.py \
  --runner DataflowRunner \
  --project my-data-project \
  --region australia-southeast1 \
  --temp_location gs://my-dataflow-batch-demo/temp \
  --staging_location gs://my-dataflow-batch-demo/staging \
  --job_name sales-batch-$(date +%Y%m%d-%H%M%S) \
  --input gs://my-dataflow-batch-demo/input/sales.csv \
  --output_table my-data-project:sales_demo.customer_totals

The command packages the pipeline, uploads the required files, and creates a Dataflow job. From the GCP Console, open Dataflow and select the job. We could see the transform graph, worker logs, throughput, and any failed stage from there.

Startup takes some time even for a tiny file, so Dataflow is not cost-effective for every small task. For recurring pipelines, we could package this code as a Flex Template and start it from Cloud Scheduler, Workflows, Airflow, or an event-driven service. A template also means the scheduler does not need a machine with the Beam code checked out.

Things to be careful about

The demo uses WRITE_TRUNCATE, which replaces the destination table on every run. That keeps repeated demo runs simple, but it is usually not what we want in production. A production pipeline may write into a staging table and then use a BigQuery MERGE, or write into date-partitioned tables with a clear replay strategy.

Malformed rows are another concern. Here, a badly formatted amount will fail the transform. In a real pipeline, I would catch parsing errors, send rejected records to a separate GCS path or BigQuery dead-letter table, and add a metric so that failures are visible.

Also review worker service account permissions, private networking, worker machine type, autoscaling limits, and temporary file retention. Do not give the worker service account Project Editor just to make the first run work. Grant access only to the required buckets, datasets, and Dataflow services.

Finally, batch pipelines must be safe to rerun. File naming, duplicate records, partially completed writes, and late files should be decided before scheduling the job. Dataflow manages compute, but it cannot decide the business rules for us.

Conclusion

We created a Beam pipeline locally and then ran the same code as a managed Dataflow batch job. For a simple copy into BigQuery, I would still choose a load job. When validation and custom transformations start growing, Dataflow gives us a practical path without managing a Spark cluster. The next step would be to turn this pipeline into a Flex Template and add proper rejected-record handling before using it in production.

This post is licensed under CC BY 4.0 by the author.