Google Cloud Dataflow for Batch and Stream Processing
What You'll Learn
- 1Explain the roles of PCollections, transforms, pipelines, and runners in an Apache Beam program
- 2Choose a window type and trigger that match how the business defines a period of measurement
- 3Configure watermarks and allowed lateness so late data is corrected instead of silently dropped
- 4Use keyed state and timers to build an exact aggregation that survives unbounded input
Apache Beam Programming Model
Apache Beam provides a unified programming model for batch and stream processing. Dataflow is Google's managed service for running Beam pipelines.
The model exists so that one program can serve both execution modes without a rewrite. A pipeline written as a graph of transforms behaves the same whether the input is a bounded set of files or an unbounded Pub/Sub topic, and the differences between batch and stream are expressed through windowing, triggers, and state rather than through separate codebases. For a team maintaining years of batch jobs, that means the reasoning behind them transfers directly to streaming work instead of starting over.
A runner decides where the graph executes. The DirectRunner runs locally for tests and is fast enough for fixtures, the DataflowRunner hands the graph to the managed service and adds autoscaling, monitoring, and managed shuffling, and other runners target Spark or Flink clusters where those already exist. Choosing a runner is a deployment decision rather than a programming one, which is why a pipeline can move from a laptop to production without changing a line of transform logic.
Core Concepts
PCollection: Immutable, distributed dataset PTransform: Operation that processes PCollections Pipeline: Series of PTransforms applied to PCollections Runner: Execution engine (Dataflow, DirectRunner, SparkRunner)
Pipeline Structure
Basic Pipeline Examples
Both examples below follow the same four stages, and most production pipelines are a longer version of this shape: read from a source, transform and validate, group or window, and write to a sink with an explicit schema. The transform steps are pure functions over elements, which is what makes them testable without any infrastructure at all. The only parts that touch the outside world are the read and write steps, so unit tests cover everything in between while integration tests focus on whether the source and sink behave the way the pipeline assumes.
Notice what the BigQuery write specifies: a schema, a write disposition, and a create disposition. Stating those explicitly turns an accidental overwrite into a decision somebody made on purpose, and it makes the contract of the pipeline visible to the next engineer who opens the file. Pipelines that leave dispositions to defaults are the ones that surprise a reviewer during an incident.
Batch Processing Pipeline
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
def parse_csv(line):
"""Parse CSV line into dictionary."""
fields = line.split(',')
return {
'id': fields[0],
'name': fields[1],
'amount': float(fields[2]),
'timestamp': fields[3]
}
def format_for_bigquery(element):
"""Format element for BigQuery insertion."""
return {
'id': element['id'],
'name': element['name'],
'amount': element['amount'],
'processed_at': element['timestamp']
}
def run_batch_pipeline():
options = PipelineOptions([
'--project', 'my-project',
'--region', 'us-central1',
'--runner', 'DataflowRunner',
'--temp_location', 'gs://my-bucket/temp',
'--staging_location', 'gs://my-bucket/staging',
'--num_workers', '4',
'--max_num_workers', '8',
'--autoscaling_algorithm', 'THROUGHPUT_BASED'
])
with beam.Pipeline(options=options) as pipeline:
(
pipeline
| 'Read CSV' >> beam.io.ReadFromText('gs://my-bucket/input/*.csv')
| 'Parse CSV' >> beam.Map(parse_csv)
| 'Filter Valid' >> beam.Filter(lambda x: x['amount'] > 0)
| 'Format for BQ' >> beam.Map(format_for_bigquery)
| 'Write to BQ' >> beam.io.WriteToBigQuery(
'my-project:analytics.processed_data',
schema='id:STRING,name:STRING,amount:FLOAT64,processed_at:TIMESTAMP',
write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND,
create_disposition=beam.io.BigQueryDisposition.CREATE_NEVER
)
)
if __name__ == '__main__':
run_batch_pipeline()
Stream Processing Pipeline
import apache_beam as beam
from apache_beam.transforms.window import FixedWindows, Sessions
from apache_beam.transforms.trigger import (
AfterWatermark, AfterProcessingTime, AccumulationMode
)
from apache_beam.options.pipeline_options import StandardOptions
def parse_pubsub_message(message):
"""Parse Pub/Sub message."""
import json
data = json.loads(message.data.decode('utf-8'))
return {
'user_id': data['user_id'],
'action': data['action'],
'amount': data.get('amount', 0),
'timestamp': data['timestamp']
}
def run_streaming_pipeline():
options = PipelineOptions([
'--project', 'my-project',
'--region', 'us-central1',
'--runner', 'DataflowRunner',
'--temp_location', 'gs://my-bucket/temp',
'--streaming'
])
options.view_as(StandardOptions).streaming = True
with beam.Pipeline(options=options) as pipeline:
(
pipeline
| 'Read from Pub/Sub' >> beam.io.ReadFromPubSub(
topic='projects/my-project/topics/user-events'
)
| 'Parse Messages' >> beam.Map(parse_pubsub_message)
| 'Window into 1-minute' >> beam.WindowInto(
FixedWindows(60),
trigger=AfterWatermark(
early=AfterProcessingTime(10)
),
accumulation_mode=AccumulationMode.DISCARDING
)
| 'Aggregate by User' >> beam.CombinePerKey(sum)
| 'Format Results' >> beam.Map(lambda x: {
'user_id': x[0],
'total_amount': x[1],
'window_start': str(x[2])
})
| 'Write to BigQuery' >> beam.io.WriteToBigQuery(
'my-project:analytics.user_totals',
schema='user_id:STRING,total_amount:FLOAT64,window_start:TIMESTAMP',
write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND
)
)
Windowing Strategies
Windowing divides streaming data into finite groups for processing. Without windows, an aggregation over an unbounded source never produces a result at all, because there is no moment at which the group can be considered complete. Windows define that moment by assigning each element to one or more groups according to its event time rather than the moment it happened to be processed.
The four families differ in what they optimise for. Fixed windows slice time into equal intervals and suit periodic reporting such as hourly revenue. Sliding windows overlap, so each element lands in several windows, which suits a rolling average that must update more often than it resets. Session windows close after a gap of silence and fit activity that has no natural period, such as bursts of clicks from one user. The global window gathers everything and emits only when a trigger says so, which is how ordinary batch behaviour is expressed in a streaming pipeline.
Fixed Windows
from apache_beam.transforms.window import FixedWindows
# Fixed 5-minute windows
(
pipeline
| 'Read' >> beam.io.ReadFromPubSub(topic='topic')
| 'Window' >> beam.WindowInto(FixedWindows(300)) # 5 minutes
| 'Process' >> beam.CombinePerKey(sum)
)
Sliding Windows
from apache_beam.transforms.window import SlidingWindows
# Sliding windows: 10-minute window, advance every 1 minute
(
pipeline
| 'Read' >> beam.io.ReadFromPubSub(topic='topic')
| 'Window' >> beam.WindowInto(SlidingWindows(600, 60)) # 10min window, 1min advance
| 'Process' >> beam.CombinePerKey(sum)
)
Session Windows
from apache_beam.transforms.window import Sessions
# Session windows: gap duration of 5 minutes
(
pipeline
| 'Read' >> beam.io.ReadFromPubSub(topic='topic')
| 'Window' >> beam.WindowInto(Sessions(300)) # 5-minute gap
| 'Process' >> beam.CombinePerKey(sum)
)
Global Windows
from apache_beam.transforms.window import GlobalWindows
# Global window with custom trigger
(
pipeline
| 'Read' >> beam.io.ReadFromPubSub(topic='topic')
| 'Window' >> beam.WindowInto(
GlobalWindows(),
trigger=AfterProcessingTime(60), # Trigger every minute
accumulation_mode=AccumulationMode.ACCUMULATING
)
| 'Process' >> beam.CombinePerKey(sum)
)
Triggers
Triggers determine when to emit results from windows. The default trigger waits for the watermark to pass the end of the window and then emits a single result, which is correct when you can afford to wait and the source is rarely late. Operational needs usually push beyond that: early firings publish partial results so a dashboard is never half an hour stale, late firings revise the number when stragglers arrive, and count based triggers emit on volume instead of time, which suits bursts that have no useful clock.
Choosing between the accumulation modes decides what each firing contains. Discarding sends only what arrived since the previous firing, which is efficient for sinks that append deltas. Accumulating resends everything the window has seen so far, which is what a sink that overwrites the row for that window requires. Getting this wrong produces double counted totals, and it is the most common correctness bug in streaming work in practice.
Common Trigger Patterns
from apache_beam.transforms.trigger import (
AfterWatermark, AfterProcessingTime, AfterCount,
AccumulationMode, Repeatedly, AfterAny
)
# Early results: emit every 30 seconds
# On-time: emit when watermark passes window end
# Late results: emit up to 5 minutes late
trigger = AfterWatermark(
early=AfterProcessingTime(30),
late=AfterProcessingTime(300)
)
# Count-based trigger: emit every 1000 elements
trigger = AfterCount(1000)
# Composite trigger: emit on count OR time
trigger = AfterAny(AfterCount(1000), AfterProcessingTime(60))
# Repeated trigger: repeat the inner trigger
trigger = Repeatedly(AfterCount(100))
Accumulation Modes
from apache_beam.transforms.trigger import AccumulationMode
# Discard accumulating state (default)
# Each trigger fires with only new data since last trigger
accumulation_mode = AccumulationMode.DISCARDING
# Accumulate state
# Each trigger fires with all data since window opened
accumulation_mode = AccumulationMode.ACCUMULATING
Watermarks
Watermarks track progress through event time. They determine when windows are considered complete. The watermark is an estimate rather than a fact: it says the system believes every event timestamped earlier than this point has already arrived. A file source that knows its inputs are complete can produce an exact watermark, while a source that infers progress from arrival times produces an approximation, and that gap is exactly where lateness comes from.
Late data is therefore a design input rather than an anomaly. Allowed lateness sets how long a window stays open for corrections after its nominal end, and anything arriving later than that is either dropped or routed to a side output for separate handling. Wider lateness accepts more corrections while holding window state longer, which costs memory; narrower lateness sheds stragglers sooner and risks losing real events. The right setting depends on how late the source actually is, so measure the distribution of arrival delays before choosing a number.
Watermark Concepts
Event Time: When the event actually occurred
Processing Time: When the event is processed
Watermark: Estimate of how far behind real-time we are
Lateness: How late an event arrives after the watermark
Watermark Management
# Watermark tracking in pipeline
(
pipeline
| 'Read' >> beam.io.ReadFromPubSub(topic='topic')
| 'Add Timestamps' >> beam.Map(
lambda x: beam.window.TimestampedValue(x, x['timestamp'])
)
| 'Window' >> beam.WindowInto(
FixedWindows(60),
trigger=AfterWatermark(
early=AfterProcessingTime(10),
late=AfterProcessingTime(300)
),
allowed_lateness=300, # 5 minutes
accumulation_mode=AccumulationMode.DISCARDING
)
)
Handling Late Data
# Late data handling strategy
def handle_late_data(element):
"""Process late-arriving data."""
user_id, data = element
return {
'user_id': user_id,
'total': sum(data['amounts']),
'is_late': data['is_late'],
'window_start': data['window_start']
}
# Pipeline with late data handling
(
pipeline
| 'Read' >> beam.io.ReadFromPubSub(topic='topic')
| 'Window' >> beam.WindowInto(
FixedWindows(60),
trigger=AfterWatermark(
early=AfterProcessingTime(10),
late=AfterProcessingTime(300)
),
allowed_lateness=300,
accumulation_mode=AccumulationMode.ACCUMULATING
)
| 'Combine' >> beam.CombinePerKey(sum)
| 'Handle Late' >> beam.Map(handle_late_data)
)
Autoscaling
Dataflow automatically scales the number of workers based on throughput. It adds workers when the backlog grows and removes them once the work drains, so a pipeline that runs for twenty minutes a night does not pay for idle machines all day. Two settings bound the behaviour: the initial worker count, which decides how quickly the job starts, and the maximum, which caps the bill and protects shared quotas.
Scaling is not free of consequences. Workers added part way through a job must receive work through reshuffling, so a pipeline with expensive setup, such as a large side input, scales less gracefully than a map heavy one. The practical guidance is to let throughput based autoscaling do its job, keep the maximum tied to a budget rather than a guess, and investigate any job that sits pinned at the maximum, because that usually means the data grew or the transform lost its selectivity.
Autoscaling Configuration
# Enable autoscaling
options = PipelineOptions([
'--project', 'my-project',
'--region', 'us-central1',
'--runner', 'DataflowRunner',
'--num_workers', '2',
'--max_num_workers', '10',
'--autoscaling_algorithm', 'THROUGHPUT_BASED',
'--worker_machine_type', 'n1-standard-4',
'--disk_size_gb', '100',
'--disk_type', 'pd-ssd'
])
Autoscaling Parameters
| Parameter | Description | Default |
|---|---|---|
num_workers | Initial number of workers | 3 |
max_num_workers | Maximum number of workers | 1000 |
autoscaling_algorithm | THROUGHPUT_BASED or NONE | THROUGHPUT_BASED |
worker_machine_type | Machine type for workers | n1-standard-1 |
Monitoring Autoscaling
# Monitor autoscaling via API
from google.cloud import dataflow_v1beta3
client = dataflow_v1beta3.DataflowV1Beta3Client()
# Get job status
job = client.get_job(
project_id='my-project',
job_id='job-id',
location='us-central1'
)
# Check worker count
print(f"Current workers: {job.current_worker_count}")
print(f"Job status: {job.job_state}")
State Management
State management enables maintaining information across elements in a pipeline. State is what lets a DoFn remember something across elements, which turns an aggregation that cannot be expressed as a simple combine into something exact. The rule that keeps this safe is that state is keyed: it belongs to the key of the element being processed, it is partitioned together with that key, and it scales with the number of distinct keys rather than with the size of the input.
Timers complete the picture, because state answers what has already been seen and a timer answers when to act on it. Emitting a session summary, flushing a buffer after a period of silence, and expiring stale entries all need a callback at a specific time rather than on the arrival of an element. Used together, keyed state and timers implement patterns that would otherwise require a separate database, and they keep the correctness of the result inside the pipeline instead of in an external system that must somehow stay consistent with it.
Keyed State
from apache_beam.transforms.userstate import (
BagStateSpec, CombiningValueStateSpec, TimerSpec,
on_timer, RuntimeTimer, RuntimeState
)
# State specifications
BUFFER_STATE = BagStateSpec('buffer', beam.VarIntCoder())
COUNT_STATE = CombiningValueStateSpec('count', beam.VarIntCoder(), sum)
EXPIRY_TIMER = TimerSpec('expiry', beam.RealtimeClock())
# Stateful DoFn
class StatefulCombineFn(beam.DoFn):
def process(self, element, buffer=beam.DoFn.StateParam(BUFFER_STATE),
count=beam.DoFn.StateParam(COUNT_STATE),
timer=beam.DoFn.TimerParam(EXPIRY_TIMER)):
key, value = element
buffer.add(value)
count.add(1)
timer.set(beam.Timestamp.from_secs(300)) # 5-minute expiry
@on_timer(EXPIRY_TIMER)
def on_expiry(self, buffer=beam.DoFn.StateParam(BUFFER_STATE),
count=beam.DoFn.StateParam(COUNT_STATE)):
yield (list(buffer.read()), count.read())
buffer.clear()
count.clear()
Stateful Processing Example
# Session windowing with state
(
pipeline
| 'Read' >> beam.io.ReadFromPubSub(topic='topic')
| 'Key by User' >> beam.Map(lambda x: (x['user_id'], x))
| 'Window' >> beam.WindowInto(Sessions(300))
| 'Stateful Combine' >> beam.ParDo(StatefulCombineFn())
| 'Format Output' >> beam.Map(format_session_output)
)
Monitoring and Debugging
Dataflow publishes metrics for every job, and the ones worth watching during an incident are element counts split by outcome, system lag, pending elements, and worker count. Counters that separate successes from failures are far more useful than a single processed count, because a pipeline that silently drops elements looks perfectly healthy until somebody reconciles totals downstream. Custom metrics and distributions, such as processing latency per element, fill the gaps the platform cannot know about, and they stay inexpensive as long as they are emitted once per window rather than once per element.
Stackdriver Metrics
# Custom metrics in pipeline
from apache_beam.metrics import Metrics
class ProcessFn(beam.DoFn):
def __init__(self):
self.processed_counter = Metrics.counter(self.__class__, 'elements_processed')
self.error_counter = Metrics.counter(self.__class__, 'errors')
self.latency_histogram = Metrics.distribution(self.__class__, 'processing_latency_ms')
def process(self, element):
start_time = time.time()
try:
# Process element
result = transform(element)
self.processed_counter.inc()
yield result
except Exception as e:
self.error_counter.inc()
raise
finally:
latency = (time.time() - start_time) * 1000
self.latency_histogram.update(latency)
Monitoring Dashboard
# Create monitoring dashboard
from google.cloud import monitoring_v3
client = monitoring_v3.MetricServiceClient()
project_name = f"projects/my-project"
# Create dashboard
dashboard = monitoring_v3.Dashboard({
"display_name": "Dataflow Pipeline Dashboard",
"mosaic_layout": {
"tiles": [
{
"width": 6,
"height": 4,
"widget": {
"title": "Elements Processed",
"xy_chart": {
"data_sets": [{
"time_series_query": {
"time_series_filter": {
"filter": 'metric.type="dataflow.googleapis.com/job/element_count"',
"aggregation": {
"alignment_period": {"seconds": 60},
"per_series_aligner": "ALIGN_RATE"
}
}
}
}]
}
}
}
]
}
})
Best Practices
- Use windowing appropriately - Match window size to business requirements
- Implement triggers - Handle early, on-time, and late data
- Monitor watermarks - Track watermark lag and late data
- Enable autoscaling - Let Dataflow manage worker count
- Use stateful processing - Maintain state across elements when needed
- Implement error handling - Use dead-letter patterns for failed elements
- Monitor costs - Track slot usage and optimize query patterns
Common Mistakes
Running an aggregation over an unbounded source with the global window and the default trigger
Fix: Assign an explicit window and trigger that match the reporting period, so results are emitted when the business expects them.
Using accumulating mode with a sink that already appends deltas
Fix: Match the mode to the sink: discarding for append only outputs, accumulating only when the sink overwrites the window's row.
Setting allowed lateness from guesswork
Fix: Measure the distribution of arrival delays for the source, then choose lateness that covers the real tail and route anything beyond it to a side output.
Best Practices
- Test every pipeline with the DirectRunner on fixtures before spending time on a cloud deploy
- Keep transforms as pure functions and confine reads and writes to the edges so most logic stays unit testable
- Emit custom metrics once per window and alert on lag and failure counts rather than on CPU
Key Takeaways
- Beam separates what the pipeline does from where it runs, so the same graph moves from laptop to Dataflow unchanged
- Windowing defines when a group is complete, triggers decide when results are emitted, and accumulation mode decides what each emission contains
- The watermark is an estimate of progress, and allowed lateness is the budget you set for corrections
- Keyed state and timers keep aggregation correctness inside the pipeline instead of in an external database
Interview Questions
Q1: What is the difference between a PCollection, a transform, and a runner?
A PCollection is the immutable distributed dataset flowing through the graph, a transform is the operation applied to one or more PCollections, and a runner is the engine that executes the resulting graph, whether that is the local DirectRunner, Dataflow, or another supported engine.
Q2: How do triggers differ from windowing?
Windowing assigns each element to a group based on event time, while the trigger decides when the result for that window is emitted. The default trigger fires once the watermark passes the window end, but early firings, late firings, and count based triggers let you publish partial or revised results.
Q3: What is the watermark and why does it matter?
It is the system's estimate that all events with an earlier timestamp have arrived, and it is what allows a streaming aggregation to ever finish. Because it is an estimate, late data can still appear, which is why allowed lateness and side outputs are part of the design.
Q4: When would you use stateful processing instead of CombinePerKey?
When the result needs to be emitted on a schedule rather than on element arrival, or when the computation needs more than a single accumulator, such as buffering a session and flushing it after a gap. Keyed state stores the buffer and a timer decides when to flush it.
Q5: How does autoscaling affect a Dataflow job?
Workers are added as throughput rises and removed as it falls, bounded by the initial count and the maximum. Reshuffling cost means pipelines with heavy setup scale less smoothly, so the maximum should follow a budget and jobs pinned at it deserve investigation.