Apache Beam separates a data-processing model from its execution engine. A bounded file collection and an unbounded Pub/Sub subscription become PCollection inputs to the same transforms. That does not make batch and streaming operationally identical, but it does make the business logic, schemas, validation, and tests shareable.

This post describes a practical unification strategy for Google Cloud Dataflow: one graph, interchangeable sources, explicit event time, and runner-specific deployment around a common transform module.

One Beam pipeline with bounded and unbounded inputs

The portable boundary is a PCollection

A PCollection is a logical, potentially distributed, multi-element data set. Its elements are the only interface a transform should assume:

  • a bounded PCollection has a finite, knowable end;
  • an unbounded PCollection may continue forever;
  • a PTransform maps one or more collections to one or more collections;
  • grouping and windowing determine when and over which elements a transform observes completeness.

Keep external-system details at graph edges. A function that parses or validates a record should not inspect a Pub/Sub envelope, a file path, or runner state. Normalize the source-specific envelope into a versioned application record first.

That boundary also avoids the most common false unification: feeding streaming logic a batch file without assigning meaningful event-time timestamps. Runners can execute the same graph but cannot infer that the file name’s date is the event’s time.

Prefer one transform, not one binary

A single Beam application can expose source-specific launch options while retaining one transform library. For example, a pipeline may accept:

--input_kind=batch --input_gs_path=gs://analytics-raw/orders/2025-01-*.json

or:

--input_kind=streaming --input_subscription=projects/production/subscriptions/orders-v1

The graph after parsing is identical. The batch mode can be run by DirectRunner for a fast local check and by DataflowRunner for production. The streaming mode must account for indefinite execution, event time, retries, and source retention.

Portability means the Beam SDK translates the graph to a runner’s supported primitives. It does not mean every connector or optimization behaves identically. Before production, verify the target runner supports the transform, coder, windowing strategy, timer, and I/O connector in the chosen Beam release.

A scoped Python Beam pipeline

The following example is intentionally small but runnable. It accepts newline-delimited JSON from Cloud Storage in batch mode or Pub/Sub messages in streaming mode. It validates records, assigns event timestamps, and groups one-minute windows by currency. Only the source and sink differ: bounded output becomes JSONL file shards, while streaming output uses BigQuery.

import argparse
import datetime
import json
import logging

import apache_beam as beam
from apache_beam.metrics import Metrics
from apache_beam.options.pipeline_options import (
    PipelineOptions,
    SetupOptions,
    StandardOptions,
)
from apache_beam.transforms.window import FixedWindows, TimestampedValue


class ParseOrder(beam.DoFn):
    def __init__(self):
        self.seen = Metrics.counter(self.__class__, "records_seen")
        self.invalid = Metrics.counter(self.__class__, "records_invalid")

    def process(self, raw):
        self.seen.inc()
        try:
            if isinstance(raw, bytes):
                raw = raw.decode("utf-8")
            record = json.loads(raw)
            event_ms = int(record["event_epoch_ms"])
            order_id = str(record["order_id"])
            currency = str(record["currency"]).upper()
            amount = int(record["amount_cents"])
            if not order_id or len(currency) != 3 or amount < 0:
                raise ValueError("invalid business fields")
            return [
                TimestampedValue(
                    {
                        "order_id": order_id,
                        "currency": currency,
                        "amount_cents": amount,
                        "event_epoch_ms": event_ms,
                    },
                    event_ms / 1000.0,
                )
            ]
        except (KeyError, TypeError, ValueError, UnicodeDecodeError):
            self.invalid.inc()
            logging.warning("Rejected malformed order: %r", raw[:500])
            return []


class SumByCurrency(beam.PTransform):
    def expand(self, records):
        return (
            records
            | "WindowMinutes" >> beam.WindowInto(FixedWindows(60))
            | "CurrencyAndAmount"
            >> beam.Map(
                lambda row: (row["currency"], row["amount_cents"])
            )
            | "SumPerWindow" >> beam.CombinePerKey(sum)
            | "ShapeSummary"
            >> beam.ParDo(ShapeSummary())
        )


class ShapeSummary(beam.DoFn):
    def process(self, item, window=beam.DoFn.WindowParam):
        currency, amount_cents = item
        yield {
            "currency": currency,
            "amount_cents": amount_cents,
            "window_start": datetime.datetime.fromtimestamp(
                window.start.micros / 1e6,
                tz=datetime.timezone.utc,
            ).isoformat(),
            "window_end": datetime.datetime.fromtimestamp(
                window.end.micros / 1e6,
                tz=datetime.timezone.utc,
            ).isoformat(),
        }


def run(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("--input_kind", choices=("batch", "streaming"),
                        required=True)
    parser.add_argument("--input_gs_path")
    parser.add_argument("--input_subscription")
    parser.add_argument("--output_prefix")
    parser.add_argument("--output_table")
    known, pipeline_args = parser.parse_known_args(argv)

    if known.input_kind == "batch" and not known.input_gs_path:
        parser.error("--input_gs_path is required in batch mode")
    if known.input_kind == "streaming" and not known.input_subscription:
        parser.error("--input_subscription is required in streaming mode")
    if known.input_kind == "batch" and not known.output_prefix:
        parser.error("--output_prefix is required in batch mode")
    if known.input_kind == "streaming" and not known.output_table:
        parser.error("--output_table is required in streaming mode")

    options = PipelineOptions(pipeline_args)
    options.view_as(SetupOptions).save_main_session = True
    is_streaming = known.input_kind == "streaming"
    options.view_as(StandardOptions).streaming = is_streaming

    with beam.Pipeline(options=options) as pipeline:
        if is_streaming:
            raw = (
                pipeline
                | "ReadPubSub"
                >> beam.io.ReadFromPubSub(
                    subscription=known.input_subscription
                )
            )
        else:
            raw = (
                pipeline
                | "ReadFiles"
                >> beam.io.ReadFromText(known.input_gs_path)
            )

        summaries = (
            raw
            | "ParseAndTimestamp" >> beam.ParDo(ParseOrder())
            | "SharedBusinessLogic" >> SumByCurrency()
        )

        if is_streaming:
            summaries | "WriteBigQuery" >> beam.io.WriteToBigQuery(
                table=known.output_table,
                schema=(
                    "currency:STRING,amount_cents:INTEGER,"
                    "window_start:STRING,window_end:STRING"
                ),
                create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,
                write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,
                method=beam.io.WriteToBigQuery.Method.STREAMING_INSERTS,
            )
        else:
            (
                summaries
                | "SerializeSummary"
                >> beam.Map(
                    lambda row: json.dumps(
                        row, sort_keys=True, separators=(",", ":")
                    )
                )
                | "WriteFiles"
                >> beam.io.WriteToText(
                    file_path_prefix=known.output_prefix + "/part",
                    file_name_suffix=".jsonl",
                )
            )


if __name__ == "__main__":
    logging.getLogger().setLevel(logging.INFO)
    run()

The counters expose ingestion volume and rejected volume separately. Production validation should usually emit bad records to a durable dead-letter sink containing the raw payload, source metadata, error class, pipeline version, and processing time. Merely logging and dropping malformed records makes replay impossible to audit.

This example uses a file output only for the bounded path and BigQuery’s streaming insert method for the unbounded path. In a production design, compare that choice with Storage Write API support in the selected Beam SDK, an append-only message sink, or a Cloud Storage compactor. Beam or Dataflow exactly-once behavior inside the pipeline is not automatically an exactly-once transaction in an arbitrary external database.

DirectRunner and focused tests

Runner selection affects scale, not the transform’s contract. Start with pure tests:

import unittest

import apache_beam as beam
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that, equal_to


class SharedTransformsTest(unittest.TestCase):
    def test_valid_order_is_summed(self):
        with TestPipeline() as pipeline:
            actual = (
                pipeline
                | beam.Create([
                    '{"order_id":"o-1","currency":"usd",'
                    '"amount_cents":1200,"event_epoch_ms":1704067200000}'
                ])
                | beam.ParDo(ParseOrder())
                | SumByCurrency()
                | beam.Map(
                    lambda row: (row["currency"], row["amount_cents"])
                )
            )
            assert_that(actual, equal_to([("USD", 1200)]))

Keep unit tests deterministic by checking parse, transform, window assignment, and edge behavior. Add integration tests that launch a short Dataflow job against isolated topics, buckets, and tables. Verify at-least-once input behavior, restart behavior, and output duplicates rather than assuming a successful job launch proves data correctness.

Install and run locally

Use an isolated virtual environment and pin the SDK for the release. Beam dependency matrices move, so select a version supported by the Python runtime used in Dataflow:

python3 -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install 'apache-beam[gcp]==2.XX.0'

python pipeline.py \
  --runner=DirectRunner \
  --input_kind=batch \
  --input_gs_path=./examples/orders-*.jsonl \
  --output_prefix=./out/orders

Replace 2.XX.0 with a deliberately tested Beam version; do not leave that placeholder in an executable deployment definition. The Dataflow Runner uploads a staged SDK and application code, so commit the resolved dependency set and build from it consistently.

Build the Dataflow commands from named variables

Set these in the deployment shell without embedding project identifiers in application logic:

export PROJECT_ID='example-data-platform'
export REGION='us-central1'
export STAGING_BUCKET='gs://example-dataflow-staging'
export TEMP_BUCKET='gs://example-dataflow-temp'
export SERVICE_ACCOUNT='dataflow-jobs@example-data-platform.iam.gserviceaccount.com'
export NETWORK='projects/example-data-platform/global/networks/data-vpc'
export SUBNETWORK='regions/us-central1/subnetworks/dataflow'

A bounded run uses DataflowRunner and a file source:

python pipeline.py \
  --runner=DataflowRunner \
  --project="$PROJECT_ID" \
  --region="$REGION" \
  --temp_location="${TEMP_BUCKET}/batch-unified" \
  --staging_location="${STAGING_BUCKET}/batch-unified" \
  --service_account_email="$SERVICE_ACCOUNT" \
  --network="$NETWORK" \
  --subnetwork="$SUBNETWORK" \
  --job_name=orders-daily-$(date -u +%Y%m%d-%H%M%S) \
  --input_kind=batch \
  --input_gs_path='gs://example-orders-raw/2025/01/01/*.jsonl' \
  --output_prefix='gs://example-orders-derived/daily/2025-01-01'

For a streaming run, use a durable Pub/Sub subscription and explicitly enable streaming. Keep a deterministic job name for intentional replacement or a versioned suffix for blue-green deployment:

gcloud pubsub subscriptions create orders-v1-beam \
  --topic=orders-v1 \
  --project="$PROJECT_ID"

python pipeline.py \
  --runner=DataflowRunner \
  --project="$PROJECT_ID" \
  --region="$REGION" \
  --temp_location="${TEMP_BUCKET}/stream-unified" \
  --staging_location="${STAGING_BUCKET}/stream-unified" \
  --service_account_email="$SERVICE_ACCOUNT" \
  --network="$NETWORK" \
  --subnetwork="$SUBNETWORK" \
  --streaming \
  --job_name=orders-stream-v1 \
  --input_kind=streaming \
  --input_subscription='projects/example-data-platform/subscriptions/orders-v1-beam' \
  --output_table='example-data-platform:analytics.currency_minutes'

Check the job and recent metrics with:

gcloud dataflow jobs list \
  --project="$PROJECT_ID" \
  --region="$REGION" \
  --filter='name:orders-stream-v1' \
  --limit=5

JOB_ID="$(gcloud dataflow jobs list \
  --project="$PROJECT_ID" \
  --region="$REGION" \
  --filter='name:orders-stream-v1' \
  --limit=1 \
  --format='value(id)')"

gcloud dataflow jobs describe "$JOB_ID" \
  --project="$PROJECT_ID" \
  --region="$REGION"

Use the job ID returned by jobs list when cancellation or draining is required; a job’s human-readable name is not the stable control-plane identifier. For a release, prefer a controlled drain on the old job, confirm source lag and sink finality, then start the new graph and verify it advances the same source subscription.

Observability is a shared contract

Batch and streaming should expose the same transformation counters and data-quality dimensions:

  • records read, parsed, rejected, and emitted;
  • source bytes and batch or streaming system lag;
  • per-window record and key counts;
  • p50/p95 parse and sink latency;
  • pipeline version, Beam SDK version, and graph revision;
  • sink retry, dead-letter, and duplicate-merge counts.

At least two metrics must be measured at source boundaries. A pipeline can report zero custom failures while its source falls behind or remains idle. Alert on watermark age and backlog for streaming; alert on completion duration, skipped partitions, and reconciliation totals for batch.

Do not add event payloads, access tokens, or full stack dumps to high-volume metrics. Use a bounded sample identifier and a correlation ID in logs, with sensitive fields filtered before publishing.

Operational differences remain

Concern Bounded batch Unbounded streaming
Completion Finite run and final counters No natural completion
Source replay Rerun a range with immutable inputs Replay retained source positions
Window finality Runner completes all windows Watermark and lateness policy matter
Deployment New invocation Update, drain, or parallel deployment
Sink checks Reconciliation at job end Continuous lag and idempotency checks
Capacity Forecast input and shuffle volume Forecast steady load, bursts, and backlog catch-up

The shared graph is the unit of code reuse, but recovery is still source-specific. A rerun over Cloud Storage should not overwrite trusted historical partitions without a controlled generation and atomic promotion. A Pub/Sub replay must account for subscription retention, acknowledgment age, and output sinks that can observe a record twice.

Release checklist

Before a unified pipeline reaches production:

  1. Run unit tests against the exact transform graph.
  2. Run DirectRunner over a small, versioned fixture.
  3. Run a bounded Dataflow canary and reconcile counts and sums.
  4. Run a short streaming Dataflow canary and inject duplicate and malformed input.
  5. Prove restart or update behavior against a durable source.
  6. Pin workers, IAM roles, network routes, SDK, and connector versions.
  7. Create source-lag, custom-error, dead-letter, and sink-failure alerts.
  8. Document the source positions and output generation for rollback.

Unification is successful when the business transform has one owner and one test suite, while the bounded and unbounded deployment paths make their distinct recovery guarantees explicit.