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

Dataflow Batch: Splittable DoFn & Autoscaling

GCP Data EngineeringDataflow BatchđŸŸĸ Free Lesson

Dataflow Batch Processing Deep Dive

Master Dataflow batch processing including Splittable DoFn, autoscaling, FlexRS, and batch optimization patterns.

18 min readAdvanced

What You'll Learn

  • 1Explain what a Splittable DoFn restricts and how restrictions enable parallelism
  • 2Configure throughput-based autoscaling with sane min and max worker bounds
  • 3Decide between standard Dataflow and FlexRS from the job's latency requirement
  • 4Eliminate the usual batch bottlenecks: skew, small files, and chatty sinks

Dataflow batch jobs are Beam pipelines executed on the managed runner with a batch-specific optimiser: unbounded inputs become bounded collections, fusion collapses chained steps, and work is distributed across workers as parallel bundles. The batch runner is mature enough that most performance problems trace back to input shape and sink behaviour rather than to the framework. This lesson covers the batch-specific machinery: splittable elements, autoscaling, FlexRS pricing, and the tuning sequence that actually moves wall time.

When Dataflow Beats the Alternatives

Dataflow's advantages in batch are the absence of cluster management and dynamic work rebalancing, which keeps stragglers from dominating stage time. Dataproc remains the better fit for existing Spark codebases or workloads that need custom clusters and GPUs. Cloud Run or Cloud Functions suit event-driven micro-batches measured in seconds, not hours.

Workload traitDataflowDataproc
Cluster managementnone, serverless workersyou own node pools
Best fit codeBeam, SQL, Flex TemplatesSpark, Hive, existing jars
Straggler handlingdynamic work rebalancingmanual repartition
Pricing modelper vCPU-second, FlexRS optionper VM-second, spot pools
Migration costrewrite to Beamusually near zero for Spark teams

Splittable DoFn and Restrictions

A plain DoFn processes one element per call and the runner cannot subdivide it. A Splittable DoFn advertises a restriction: a serialisable description of the work inside a single element, such as a byte range of a file or an index interval. The runner can then split the restriction into subranges, assign them to different workers, and re-split stragglers at runtime. This is how a single 40 GB file becomes dozens of parallel tasks instead of one worker reading it end to end.

python
import apache_beam as beam
from apache_beam.transforms.splittablefn import RestrictionTracker
from apache_beam.options.pipeline_options import PipelineOptions

class IndexRangeTracker(RestrictionTracker):
    """Tracks progress over an integer interval restriction."""

    def __init__(self, restriction):
        self._start, self._stop = restriction
        self._cursor = self._start

    def try_claim(self, position):
        if position >= self._stop:
            return False
        self._cursor = position + 1
        return True

    def current_restriction(self):
        return (self._cursor, self._stop)

    def try_split(self, fraction):
        remaining = self._stop - self._cursor
        split_at = self._cursor + int(remaining * fraction)
        if split_at <= self._cursor or split_at >= self._stop:
            return None
        primary = (self._cursor, split_at)
        self._cursor = split_at
        return primary, (split_at, self._stop)

class GenerateRecords(beam.DoFn):
    """Emits synthetic records over the claimed index range."""

    def process(self, element, restriction_tracker=beam.DoFn.RestrictionParam(
            IndexRangeTracker((0, 1_000_000)))):
        start, stop = restriction_tracker.current_restriction()
        for i in range(start, stop):
            yield {"record_id": i, "value": i % 100}

options = PipelineOptions([
    "--project", "my-project",
    "--runner", "DataflowRunner",
    "--region", "us-central1",
    "--temp_location", "gs://my-bucket/temp",
    "--experiments", "use_runner_v2",
])

with beam.Pipeline(options=options) as pipeline:
    (
        pipeline
        | beam.Create([None])
        | beam.ParDo(GenerateRecords())
        | beam.io.WriteToBigQuery(
            "my-project:analytics.synthetic",
            schema="record_id:INTEGER,value:INTEGER",
            write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,
        )
    )

For file-based work you rarely write a tracker yourself: beam.io.ReadFromText and the Avro and Parquet readers are already splittable and use byte-range restrictions. Reach for a custom Splittable DoFn when the element is an opaque blob that only your code knows how to subdivide, such as a proprietary index format. The runner's contract with a tracker is strict: claims must move forward, splits must produce non-overlapping ranges, and checkpointing persists the current restriction so a worker failure resumes mid-element instead of restarting it. Honour that contract and dynamic rebalancing works for free; violate it, usually by claiming a position twice, and the job fails with assertion errors that look exotic but are really just progress bookkeeping gone wrong.

Autoscaling in Batch Mode

Batch pipelines autoscale on backlog: the runner measures remaining work in the sharded source and adds workers until the backlog drains at the target rate. Throughput-based autoscaling is the algorithm to use; static worker counts waste money when a job is front-loaded and stall when it is not.

python
options = PipelineOptions([
    "--runner", "DataflowRunner",
    "--project", "my-project",
    "--region", "us-central1",
    "--temp_location", "gs://my-bucket/temp",
    "--autoscaling_algorithm", "THROUGHPUT_BASED",
    "--num_workers", "2",
    "--min_num_workers", "1",
    "--max_num_workers", "50",
    "--worker_machine_type", "e2-standard-4",
    "--disk_size_gb", "100",
    "--experiments", "use_runner_v2",
])

Set max workers from the data volume, not from hope: if a stage shuffles 500 GB and a worker sustains roughly 50 MB per second of shuffle, you need on the order of ten workers to finish in 15 minutes, so a max of twelve leaves headroom without inviting a runaway scaling bill. min workers above one are justified only when job start latency matters more than cost, because idle workers between runs are pure spend.

FlexRS versus Standard Execution

FlexRS routes batch jobs onto spare capacity at a discount, and in exchange the runner may delay start and use preemptible workers internally. Google documents that FlexRS jobs can take up to about six hours longer than standard jobs, which makes the trade-off crisp: accept a wider completion window or pay for determinism.

PropertyStandard batchFlexRS
Discountnoneup to roughly 50 percent
Start timeimmediatemay wait for capacity
Completion risklowcan be delayed up to hours
Typical jobsSLA-bound ETL, backfills before a deadlinenightly aggregates, weekend recomputes
Worker typeson-demandlow-cost and preemptible mix

Enable FlexRS with the flexrs_goal option, usually set to COST_OPTIMIZED. Do not combine FlexRS with tight sensor timeouts upstream, or the scheduler will pile retries while the job waits for capacity.

Sinks, File Layout, and Skew

The BigQuery sink has two modes: streaming inserts per bundle and load jobs per trigger window. Batch pipelines should use load jobs, which write Avro or Parquet files to a temporary GCS location and then load them, because load jobs are atomic and far cheaper per byte than inserts. The companion problem is output file count: one tiny file per bundle turns a cheap load into thousands of metadata operations, so coalesce or use the sink's sharding control to target files in the tens of megabytes to low gigabytes.

Skew shows up as one task running for hours while siblings idle. Diagnose it from the worker windmill or shuffle metrics, then fix it structurally: salt hot keys for aggregations, replace a skewed join with a skewed-join hint or a broadcast of the small side, or pre-aggregate the hot key's source before the join. Dynamic work rebalancing hides mild skew automatically because unstarted work migrates to faster workers, but it cannot help once a single in-flight bundle owns the hot key.

python
# Two-stage aggregation with a salted key to neutralise hot users.
import random

def add_salt(event):
    salt = random.randint(0, 9)
    return (event["user_id"], salt), event["amount"]

def remove_salt(key_amount):
    (user_id, _salt), total = key_amount
    return {"user_id": user_id, "total": total}

(
    pipeline
    | beam.Map(add_salt)
    | beam.CombinePerKey(sum)
    | beam.Map(remove_salt)
)

Dynamic Work Rebalancing and Runner V2

Dynamic work rebalancing transfers unstarted portions of a restriction or bundle from a slow worker to a fast one while the stage is running. It is most effective when input is naturally splittable, which is one more reason to prefer splittable sources. Runner v2 executes steps in portable containers with improved worker harness threads, and enabling use_runner_v2 is now the default recommendation for new pipelines; combine it with number_of_worker_harness_threads when a job has many small steps whose per-bundle overhead would otherwise dominate.

Cost and Quota Checks

Per-second billing means wasted wall time is wasted money. The three cost sinks in batch are over-provisioned max workers during shuffle-heavy stages, load-job file sprawl, and repeated reprocessing caused by failing assertions downstream. Before calling a pipeline done, run it twice: once to populate caches and catch cold-start effects, once to measure steady state, and compare the billed vCPU-seconds from the job metrics against the estimate you made from input size.

Common Mistakes

Using streaming inserts from a batch pipeline

Fix: Switch the BigQuery sink to load jobs; inserts cost more per byte and forfeit load-job atomicity for no latency benefit in batch.

Setting max workers to the cluster maximum just in case

Fix: Derive max workers from input size and shuffle throughput so autoscaling has a ceiling that matches the job rather than the account quota.

Writing one DoFn that parses a whole multi-gigabyte file

Fix: Use a splittable source or a Splittable DoFn with a range tracker so the runner can parallelise and rebalance the work.

Best Practices

  • Prefer splittable, columnar inputs so autoscaling and rebalancing have room to work
  • Target output files in the tens of megabytes to low gigabytes per file before BigQuery load
  • Reserve FlexRS for jobs whose deadline tolerates multi-hour delay

Key Takeaways

  • A Splittable DoFn exposes a restriction the runner can split, which converts one giant element into parallel work
  • Throughput-based autoscaling sizes batch workers from backlog; max workers should come from an estimate, not a quota
  • FlexRS trades up to about 50 percent discount for completion times that may stretch hours longer
  • Load-job sinks, coalesced outputs, and salted aggregations remove the three classic batch bottlenecks

Interview Questions

Interview Questions

Q1: What is a Splittable DoFn and when do you need one?

It is a DoFn whose single element carries a restriction describing subranges of work; the runner splits restrictions across workers and re-splits stragglers. You need one when the native readers cannot subdivide your input, such as a proprietary binary index.

Q2: How does dynamic work rebalancing help a skewed job?

Unstarted work migrates from slow workers to fast ones during the stage, so mild input skew does not translate into wall-clock skew; severe in-flight skew still needs structural fixes like salting.

Q3: When is FlexRS the wrong pricing mode?

When the job feeds a deadline-bound downstream, because FlexRS may delay start and run on preemptible capacity, stretching completion by hours in the worst case.

Q4: How do you choose max workers for a nightly batch job?

Estimate shuffle volume divided by per-worker throughput to hit the completion window, then set max workers slightly above that estimate so autoscaling has headroom without inviting runaway cost.

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