Dataflow in Google Cloud: One Engine for Batch and Streaming Data Pipelines
A complete, plain-English guide to Google Cloud Dataflow: how Apache Beam pipelines, windows, triggers, autoscaling, templates and the managed service fit together, and how to design, secure, monitor and budget for reliable data processing at any scale.
Imagine a huge factory with a conveyor belt. Raw materials arrive at one end, workers at stations along the belt clean them, sort them, combine them and package them, and finished goods leave at the other end. Some days a truck delivers a mountain of materials all at once; on other days, items trickle in non-stop all day long. A good factory manager does not rebuild the factory for each case. The same line handles both, and extra workers appear when the belt gets busy and go home when it quiets down. Google Cloud Dataflow is that factory for data. You describe the stations once, and Dataflow runs them on as many machines as needed, whether your data arrives as a big file or as a never-ending stream. In this guide we start from the first idea and build up to the choices that decide whether a pipeline is cheap, correct and easy to run.
1What Is Dataflow?
Before diving into settings and concepts, let us understand what Dataflow is and what job it does.
The one-sentence definition
Dataflow is Google Cloud’s fully managed service for running data processing pipelines. You write your pipeline using the open-source Apache Beam programming model, and Dataflow takes care of starting machines, dividing the work, recovering from failures and scaling up or down. It handles both batch processing, where the data is a fixed, finite set such as yesterday’s log files, and streaming processing, where the data keeps arriving and the pipeline never finishes, such as clicks on a website.
Think of a restaurant kitchen. The recipe is your pipeline: chop, cook, plate. The kitchen staff are the worker machines. On a quiet Tuesday the manager sends most cooks home; on a packed Saturday more cooks are called in. You wrote the recipe once, and the manager (Dataflow) decides how many cooks are needed and replaces any cook who falls ill mid-dinner.
What is a data pipeline?
A data pipeline is a series of steps that moves data from a source, changes it in useful ways, and delivers it to a destination. Typical steps include reading, cleaning, filtering, joining with other data, counting, grouping and writing results. Pipelines power dashboards, alerts, recommendations, fraud checks and machine learning features.
Where Dataflow fits
Dataflow often sits between data sources and data stores. Messages come in from services such as Pub/Sub or Kafka, files come from Cloud Storage, and results go to BigQuery, Bigtable, Spanner, Cloud Storage or other systems. Because it is serverless in feel, you manage the pipeline logic, not the servers.
Dataflow is the service; Apache Beam is the programming model. Beam is open source and can run on several engines. Dataflow is Google’s managed engine for it. This separation means your pipeline code is not tied to one product.
2Why Dataflow Exists: A Short History
Understanding the problem Dataflow was born to solve makes its design choices feel natural.
In the early days of big data, processing large datasets meant writing batch jobs that ran overnight. If you also wanted live results, you built a second, separate system for streaming. Teams ended up maintaining two code bases for the same logic, and the results from the two systems often disagreed. Google faced this problem at huge scale and developed internal systems and research, including a well-known paper on the Dataflow Model, that argued for one unified approach: treat batch as a special case of streaming, and give users clear tools to reason about time and late-arriving data.
Google then made Dataflow available as a cloud service, and later donated the programming model to the Apache Software Foundation as Apache Beam. Today, Dataflow runs Beam pipelines, and Beam has become one of the most popular ways to write portable data pipelines.
Batch-Only Era
Large jobs run on a schedule and results arrive hours later. Live views of data are not possible.
Two Systems Problem
Teams add a separate streaming system. Logic is duplicated and results often disagree between the two.
The Unified Model
Google proposes one model for batch and streaming, built around event time, windows and triggers.
Dataflow Service and Apache Beam
The model becomes the open-source Apache Beam project, and Dataflow becomes a managed runner for it on Google Cloud.
A Richer Platform
Offline and online improvements, such as service-side shuffle, a streaming engine, templates, GPU support and machine learning inference, make it a broad data processing platform.
3Core Concepts: The Beam Programming Model
A few simple ideas explain almost everything you will meet in a Dataflow pipeline.
Pipeline
The entire workflow from reading data to writing results. It is a description of the work, not the work itself.
PCollection
A dataset inside the pipeline. It may be bounded, with a known end, or unbounded, with no end. It is immutable: each step creates a new one.
PTransform
A processing step that takes one or more PCollections and produces new ones, such as filter, map or count.
ParDo
The general-purpose “do something to each element” step. Many other steps are built on top of it.
GroupByKey
Gathers all values that share a key so they can be combined or analyzed together. It is the basis of counting, joining and summing.
Combine
An efficient way to merge many values into one, such as a sum, an average or a maximum, partly done on each machine before the final merge.
Side Input
A small extra dataset made available to every worker, such as a lookup table of country names.
I/O Connector
Ready-made code for reading from and writing to systems such as Pub/Sub, BigQuery, Cloud Storage and Kafka.
Imagine a mail sorting office. Each letter is an element, the whole stack is a PCollection, and each sorting station is a PTransform. GroupByKey is the station that puts all letters for the same city into one bin. Combine is the clerk who counts how many letters are in each bin without opening them one by one.
Bounded versus unbounded data
A bounded dataset has a clear beginning and end, such as a file of last month’s orders. An unbounded dataset has no end, such as a live feed of sensor readings. Beam treats both with the same transforms, which is what lets one pipeline design serve batch and streaming. The main difference is that with unbounded data you cannot wait for “all the data”, so you need extra tools to decide when to produce results. We cover these tools in the chapter on time.
A pipeline is a graph
Behind the scenes, your pipeline becomes a directed graph of steps. Dataflow looks at the graph and optimizes it, for instance by fusing neighboring steps so data does not have to travel between machines more than necessary. This graph is what you see in the Dataflow monitoring page, with each box representing a step and arrows showing data flowing between them.
flowchart LR
A[Read from Source] --> B[Parse and Clean]
B --> C[Filter Invalid Records]
C --> D[Key by Customer]
D --> E[Group and Combine]
E --> F[Write to Destination]
C --> G[Write Rejects to Dead-Letter Store]
Beginners often think that writing a pipeline runs it. In Beam, writing the pipeline only builds the plan. Nothing runs until you submit it to a runner such as Dataflow. This is why errors in your logic may only appear after the job starts on workers.
4Architecture and Components
When you submit a pipeline, several pieces of Google Cloud cooperate to run it.
The main pieces
Your Pipeline Code
Written with the Beam SDK in Java, Python or Go. It runs on your machine only to build and submit the plan.
Dataflow Service
The managed control plane that validates, optimizes and schedules your job, and tracks its health.
Worker Machines
Compute Engine virtual machines that do the real processing. Dataflow creates, grows and deletes them for you.
Staging and Temp Locations
Cloud Storage locations where your code packages and temporary files are kept during the job.
Shuffle Service
A service-side system that moves and groups data between steps, taking this heavy work off the workers.
Streaming Engine
For streaming jobs, moves state storage and event scheduling from the workers to a managed back end.
flowchart TD
A[Developer Pipeline Code] --> B[Dataflow Service Control Plane]
B --> C[Worker VM 1]
B --> D[Worker VM 2]
B --> E[Worker VM N]
C --> F[Shuffle or Streaming Engine Back End]
D --> F
E --> F
C --> G[Sources and Sinks]
D --> G
E --> G
B --> H[Monitoring and Logging]
What happens when you submit a job
Build and Package
Your code builds the pipeline plan and packages the required files, which are staged in Cloud Storage.
Submit to the Service
The plan is sent to the Dataflow service, which checks permissions and settings and rejects obvious errors.
Optimize the Graph
The service fuses steps, chooses how to split work and prepares an execution plan.
Start Workers
Worker machines are created in your project, in the chosen region, using the worker service account.
Process and Monitor
Workers pull pieces of work, process them and report progress. The service scales workers and replaces any that fail.
Finish or Keep Running
A batch job ends when all data is processed and workers are shut down. A streaming job keeps running until you stop it.
It is like handing a recipe to a catering company. The head office (the service) reads the recipe, plans the kitchen layout, hires the right number of cooks (workers), and manages the shared pantry (shuffle and storage). You, the customer, never see the hiring.
5Batch and Streaming Pipelines
Dataflow handles two styles of processing with the same basic building blocks. Knowing when to use each is the first design decision.
| Aspect | Batch | Streaming |
|---|---|---|
| Input data | Bounded, a fixed set | Unbounded, continuously arriving |
| Job lifetime | Finishes when data is processed | Runs continuously until stopped |
| Result timing | After the whole dataset is processed | Continuously, as data arrives |
| Typical sources | Cloud Storage files, database exports, BigQuery tables | Pub/Sub, Kafka, change feeds |
| Typical uses | Nightly reports, migrations, backfills, model training data | Live dashboards, alerts, fraud detection, event enrichment |
| Cost pattern | Pay while the job runs | Pay continuously while workers run |
When to choose batch
Choose batch when results are needed on a schedule, when the data is naturally a set of files or tables, or when you must reprocess history. Batch jobs can use cheaper scheduling options and are simpler to reason about, because the whole dataset is available.
When to choose streaming
Choose streaming when freshness matters, such as when you must react within seconds to an event, update a dashboard live, or keep a store continuously in sync. Streaming jobs cost more over time because they run all day, but they deliver answers while they are still valuable.
The same logic, two modes
A strength of Beam is that the same transform logic can often be reused for both. A team may use a streaming job for live data and the same logic in a batch job to backfill history or fix past mistakes. This keeps results consistent and avoids the two-systems problem described earlier.
Ask how fresh the result really needs to be. Many teams build streaming pipelines when an hourly batch would do, and pay more for freshness that nobody uses. Match the pipeline style to the real business need.
flowchart TD
Q1{Must results be available within seconds or minutes?} -->|Yes| S[Streaming pipeline]
Q1 -->|No| Q2{Is data a fixed set of files or tables?}
Q2 -->|Yes| B[Batch pipeline]
Q2 -->|No| Q3{Can you process in small scheduled chunks?}
Q3 -->|Yes| B
Q3 -->|No| S
6Time, Windows, Watermarks and Triggers
This is the chapter that separates beginners from confident Dataflow users. Time in data pipelines is trickier than it looks.
Event time versus processing time
Event time is when something actually happened, for example when a user tapped a button. Processing time is when the pipeline sees the event. These can differ a lot: a phone with no signal may send events minutes or hours late. If you count events by the time they arrive, a tunnel on a train could distort your numbers. Beam lets you work in event time so results reflect reality.
Think of postcards. The date written on the postcard is the event time; the date the mail carrier delivers it is the processing time. If you want to know what happened in July, you read the date written on the card, even if some cards arrive in August.
Windows: cutting an endless stream into pieces
You cannot compute “the total” of data that never ends, so you divide it into windows, finite slices of time, and compute results per window.
Fixed Windows
Equal, non-overlapping slices, such as every five minutes. Good for regular reports like counts per minute.
Sliding Windows
Overlapping slices, such as the last ten minutes updated every minute. Good for moving averages and trend detection.
Session Windows
Windows that group events by bursts of activity separated by a gap of silence, like a visit to a website. Window length varies per key.
Global Window
One window containing everything. This is the default, and it is the usual choice for batch work.
Watermarks: how the pipeline estimates completeness
A watermark is the system’s best guess of how far event time has progressed, meaning the point before which it believes all data has arrived. It is an estimate, not a promise. When the watermark passes the end of a window, the pipeline considers the window mostly complete and can produce a result. Data that shows up after the watermark has passed is called late data.
Triggers: when to emit results
A trigger decides when results for a window are produced. The default is to emit when the watermark passes the end of the window. You can also emit early, giving partial results before the window is complete, or emit again when late data arrives. Triggers let you balance freshness against accuracy.
| Concept | Question It Answers | Everyday Analogy |
|---|---|---|
| Event time | When did it really happen? | The date written on the postcard |
| Window | Which slice of time does this belong to? | Sorting postcards into monthly boxes |
| Watermark | How complete do we think the data is? | The post office saying “all July mail has probably arrived” |
| Trigger | When should we publish a result? | Deciding when to announce the monthly count |
| Allowed lateness | How long do we still accept stragglers? | Accepting July postcards until mid-August |
| Accumulation mode | Do updates replace or add to earlier results? | Issuing a corrected total versus a supplement |
Late data and accumulation
You choose how long to accept late data, called allowed lateness. Data later than this is dropped. When late data arrives within the allowed time, the pipeline can fire the window again. The accumulation mode decides whether the new output replaces the old result or contains only the new changes. Downstream systems must be ready for corrections, for instance by overwriting a row rather than appending a duplicate.
sequenceDiagram
participant E as Events
participant W as Window 12:00 to 12:05
participant T as Trigger
participant O as Output
E->>W: Events arrive with event times
T->>O: Early result before window is complete
Note over W: Watermark passes 12:05
T->>O: Main result when window is considered complete
E->>W: Late event arrives within allowed lateness
T->>O: Updated result for the window
Ignoring late data. If your pipeline drops data that arrives after the watermark and you never noticed, your counts are quietly wrong. Decide your lateness tolerance deliberately and monitor how much data is dropped.
7Internal Working: How Dataflow Executes Your Pipeline
A peek under the hood explains why some pipelines are fast and others stall.
Splitting work into bundles
Dataflow divides your data into small chunks called bundles and hands them out to workers. Each worker processes bundles independently. If a worker fails or is slow, its bundle is retried or given to another worker. This is why a failed machine rarely ruins a job: the system just replays the work.
Fusion: keeping steps together
Moving data between machines is expensive. When several steps can run back to back on the same data, Dataflow fuses them into one stage so each element flows through all steps on the same worker without being written out in between. This is a big speed-up, though it can sometimes limit parallelism, which we discuss under performance.
Shuffle: regrouping data
Steps like GroupByKey and Combine need all values for the same key to end up in the same place. This regrouping is called a shuffle, and it is one of the most costly parts of any pipeline. In Dataflow, the shuffle for batch jobs is handled by a managed service rather than by the workers’ own disks, and streaming jobs can use the Streaming Engine for a similar benefit. This makes jobs faster, makes autoscaling smoother, and reduces the load and disk needs of workers.
flowchart LR
A[Input Splits] --> B[Fused Stage: Read Parse Filter]
B --> C[Shuffle by Key]
C --> D[Fused Stage: Combine and Format]
D --> E[Write Output]
Exactly-once processing
Dataflow aims to give exactly-once processing semantics for the data flowing through the pipeline, meaning each element’s effect is reflected once in the pipeline’s internal state even if a bundle is retried. This is different from guaranteeing that outside systems receive exactly one copy. If your code writes to an external system that does not recognize duplicate writes, a retry could cause a duplicate there. Using sinks that support idempotent writes, or including unique identifiers, protects you.
Imagine a cashier whose register always counts each sale exactly once, even if a receipt printer jams and reprints the receipt. The register is correct, but a customer might receive two paper receipts. Dataflow is the register; the printer is the outside system you write to.
At-least-once streaming mode
For some streaming jobs where occasional duplicates are acceptable, Dataflow offers an at-least-once mode that can lower cost and latency by skipping some of the work needed for exactly-once guarantees. It suits workloads like simple event counting where small duplication is tolerable, or where the sink removes duplicates anyway.
When a job fails over or you update it, Dataflow uses checkpoints and its state storage so work resumes rather than restarts from scratch. State, such as running counts per window, is part of what must be preserved, which is why changes to a running streaming pipeline need care.
8Sources and Sinks: Connecting to Other Services
A pipeline is only useful if it can read from and write to the places your data lives.
| System | Typical Role | Notes |
|---|---|---|
| Pub/Sub | Streaming source and sink | The most common source for streaming pipelines on Google Cloud |
| Cloud Storage | Batch source and sink | Reads and writes files in formats like text, Avro and Parquet |
| BigQuery | Source and sink | Common destination for analytics; supports batch loads and streaming writes |
| Bigtable | Sink or source | Low-latency serving of processed results |
| Spanner | Source and sink | Relational data at scale, including change streams |
| Kafka | Streaming source and sink | For teams using Kafka on Google Cloud or elsewhere |
| JDBC databases | Source and sink | Relational databases such as MySQL and PostgreSQL |
Reading and writing carefully
Connectors have settings that affect cost and correctness. For example, writing to BigQuery can use bulk file loads, which are cheaper and suit batch-like patterns, or a streaming write method for low latency at a different price. Choosing the right method is part of pipeline design.
Dead-letter handling
Real data is messy. Some records will be malformed or fail validation. Rather than letting one bad record crash the pipeline, a common practice is to send failed records to a separate destination, often called a dead-letter location, with the error details. Teams can inspect and replay them later.
Problem
Letting a pipeline throw an error on every bad record, or silently dropping bad records with no trace.
Why It’s Harmful
Repeated failures cause constant retries and stalled streaming jobs; silent drops cause quiet data loss that nobody notices until reports are wrong.
Correct Approach
Catch errors per record, route bad records with their error reason to a dead-letter destination, and monitor its volume.
Not every flow needs a custom pipeline. For simple cases, such as sending Pub/Sub messages straight into BigQuery, a built-in subscription feature may be simpler and cheaper. Use Dataflow when you need real transformation, enrichment, windowing or complex logic.
9Templates and Ways to Launch Jobs
You do not always need to write code. Templates let you launch common pipelines or package your own for reuse.
Google-provided templates
Google offers a library of ready-made templates for popular tasks, such as streaming from Pub/Sub to BigQuery, copying data between Cloud Storage and BigQuery, or moving data between databases. You pick a template, fill in parameters like source and destination, and launch it from the console or through automation. This is perfect for standard jobs and for teams without Beam experience.
Custom templates
You can also package your own pipelines as templates so others can launch them without touching the code. Flex Templates are the modern approach: your pipeline is packaged in a container image with its dependencies, and users launch it by supplying parameters. This separates the people who build the pipeline from the people who run it, and it fits well with automation and release processes.
Direct Launch from Code
Run your pipeline program with Dataflow as the runner. Good for development and one-off jobs.
Google-Provided Template
Launch a ready-made pipeline by choosing it and giving parameters. No coding needed.
Custom Flex Template
Package your own pipeline as a container image for repeatable, parameterized launches.
Scheduled or Orchestrated
Trigger launches from a scheduler or a workflow tool such as Cloud Composer, so batch jobs run on time and in the right order.
A template is like a meal kit. The chef (pipeline author) prepares the recipe and ingredients in a box. Anyone can then cook the dish by following a few simple instructions, without knowing how to design the recipe.
Running production pipelines by launching them manually from a developer’s laptop. Use templates and automated launches so jobs are repeatable, reviewed and not dependent on one person’s machine.
10Autoscaling, Resources and Performance
One of Dataflow’s main promises is that it adjusts resources for you. Knowing how helps you get the best result.
Horizontal autoscaling
Dataflow can automatically add or remove worker machines based on how much work is waiting. In batch jobs it looks at the remaining work and the speed of progress. In streaming jobs it looks at backlog and CPU use. You set a maximum number of workers as a safety limit, so a surprise spike cannot create unlimited cost.
Dataflow Prime and vertical autoscaling
Dataflow Prime is an enhanced version of the service that adds features such as vertical autoscaling, which adjusts the memory of workers to the actual need to avoid out-of-memory failures, and better right-fitting of resources for individual steps. It can also help with resource needs that differ per step, for example a step that needs a GPU while others do not.
What affects speed
Parallelism
The more independent pieces of work, the more workers can help. A step that must process everything on one machine becomes a bottleneck.
Hot Keys
If one key has far more data than others, one worker is overwhelmed while others sit idle. Spread work or pre-combine to relieve it.
Shuffle Volume
Moving huge amounts of data between stages is costly. Combine early to shrink data before the shuffle.
External Calls
Calling a slow outside service for each element slows everything. Batch calls, cache results or limit concurrency.
Machine Type
Memory-heavy steps need machines with more memory; compute-heavy steps need more CPU.
Data Format
Compact, columnar or well-structured formats read faster than large text files.
Problem
Grouping all records under one key, or a few very popular keys, in a large pipeline.
Why It’s Harmful
All the grouped data lands on a single worker. The job slows down, memory runs out, and adding more workers does not help.
Correct Approach
Use combine operations that pre-aggregate on every worker, add a random sub-key to spread heavy keys, and then merge the partial results.
If adding workers does not speed up a job, suspect a bottleneck that cannot be parallelized, such as a hot key, a single-threaded step or a slow external service, rather than a shortage of machines.
11Managing Running Jobs: Update, Drain, Cancel and Snapshots
Streaming jobs run for weeks or months. You need safe ways to change and stop them.
Update
Replace a running streaming job with a new compatible version while keeping its state, so processing continues without losing progress.
Drain
Stop reading new input but finish processing everything already received, then shut down cleanly. Preferred for planned stops.
Cancel
Stop immediately without finishing buffered work. Data in flight may be lost, so use it for tests or emergencies.
Snapshot
Save the state of a streaming job at a point in time so you can restore it or start a new job from it, useful for upgrades and recovery.
Prepare the New Version
Test the changed pipeline with sample data and confirm it is compatible with the running job’s state.
Take a Snapshot if Needed
Capture current state as a safety net before risky changes.
Update or Drain and Replace
Use an in-place update for compatible changes. For incompatible changes, drain the old job and start a new one.
Verify
Watch backlog, latency and error metrics to confirm the new job is healthy.
Cancelling a streaming job to deploy a change. Anything buffered inside is lost, and window state is thrown away. Prefer update or drain so results stay correct.
12Security and Networking
Pipelines often touch sensitive data, so security deserves attention from the start.
Identity and permissions
Two identities matter. The first is the person or system that submits the job and needs permission to create Dataflow jobs. The second is the worker service account, the identity the worker machines run as, which needs permission to read sources, write sinks and perform Dataflow work. Use a dedicated service account for each pipeline with only the permissions it needs, rather than the broad default account.
Least-Privilege Roles
Grant the worker account only access to the specific buckets, topics and datasets it uses.
Private Workers
Run workers without external IP addresses inside your own VPC subnet, using Private Google Access to reach Google services.
Customer-Managed Keys
Use your own encryption keys through Cloud KMS for data at rest in the service and its storage where required.
Network Controls
Choose the network and subnetwork for workers, and use firewall rules that allow the workers to communicate with each other.
Service Perimeters
VPC Service Controls can reduce the risk of data leaving approved boundaries.
Audit Logging
Audit logs record who created, changed or stopped jobs.
Leaving every pipeline on the default compute service account with broad permissions. A bug or compromise in one pipeline then has wide reach. Create separate, narrowly scoped worker accounts.
Handling sensitive data inside pipelines
Pipelines often process personal data. Reduce risk by removing or masking fields you do not need, tokenizing identifiers, and never logging full records. Be careful with error messages and dead-letter outputs, since they may contain the very data you are trying to protect.
13Monitoring, Logging and Troubleshooting
A pipeline that nobody watches will eventually fail quietly. Dataflow provides built-in tools to see what is happening.
| Tool or Metric | What It Shows | What To Do |
|---|---|---|
| Job graph | Each step, its throughput and where time is spent | Find the slowest or most backlogged stage |
| System lag | How long the oldest unprocessed item has been waiting | Alert if it grows steadily, meaning the job is falling behind |
| Data freshness (watermark age) | How far the pipeline is behind real time | Compare with your freshness goal |
| Backlog | Amount of data waiting in the source, such as Pub/Sub | Scale up or fix bottlenecks |
| CPU and memory use | How busy workers are | Tune machine types and autoscaling limits |
| Worker and job logs | Errors, warnings and messages from your code | Diagnose failures and bad records |
| Hot key detection and insights | Suggestions about skew and inefficiencies | Redesign the problem step |
| Error and dropped data counts | Records rejected or dropped as late | Alert and investigate unexpected rises |
Custom metrics
You can add your own counters and distributions inside the pipeline, for example the number of records rejected for each reason. These appear in the monitoring tools and are among the best ways to see data quality problems early.
A simple troubleshooting routine
Check Job State and Errors
Did the job fail to start, or is it running but unhealthy? Read the error logs.
Look at Lag and Backlog
Is the job keeping up with the input?
Find the Slow Step
Use the job graph to see which stage has the highest wall time or accumulating data.
Check Workers and Limits
Are workers at their maximum, out of memory, or limited by quotas, permissions or network rules?
Check Sources and Sinks
Is the destination rejecting writes, throttling, or slow to respond?
Alert on rising lag and on freshness, not only on job failure. A running job that quietly falls hours behind is just as damaging as a crashed one.
14Dataflow for Machine Learning and Advanced Uses
Beyond classic data processing, Dataflow supports several newer workloads.
Model Inference in Pipelines
Beam includes support for running machine learning models on each element as it flows through, so you can score events in real time or in bulk.
GPU-Accelerated Steps
Steps that need heavy computation, such as image or language processing, can run on workers with GPUs.
Feature Preparation
Compute and write features for training and serving, keeping batch and streaming logic consistent.
Change Data Capture
Read change streams from databases and apply them to analytics stores, keeping systems in sync.
Large-Scale Data Migration
Move and transform huge datasets between systems, using batch jobs with controlled parallelism.
Imagine adding a quality inspector to the end of the conveyor belt who looks at every item and stamps a grade on it. Model inference in Dataflow is that inspector, working on every record as it passes by.
Loading a model on every worker uses memory and takes time. Share the model across elements within a worker and size workers accordingly so that inference is efficient and does not run out of memory.
15Cost and Pricing
Dataflow is billed for resources used, so understanding the meters helps you keep bills predictable.
Worker CPU and Memory
Billed for the virtual CPUs and memory of worker machines, typically by the second while they are running.
Worker Storage
Persistent disks attached to workers are billed. Using managed shuffle or Streaming Engine often allows smaller disks.
Shuffle and Streaming Engine
These managed services are billed by the amount of data processed, usually offset by smaller, cheaper workers.
GPUs
If you use accelerators for a step, they are billed in addition to the machine.
Connected Services
Pub/Sub, BigQuery, Cloud Storage, network transfer and logging each have their own charges, which often exceed expectations.
Ways to reduce cost
Right-Size Workers and Limits
Choose appropriate machine types and set a sensible maximum number of workers.
Use Flexible Scheduling for Batch
Flexible Resource Scheduling, called FlexRS, runs delay-tolerant batch jobs at a lower price by using a mix of lower-cost capacity, with the job starting within a window rather than immediately.
Consider At-Least-Once Streaming
When occasional duplicates are acceptable, this mode can reduce streaming cost.
Reduce Shuffle Volume
Filter and pre-combine early so less data is moved between stages.
Choose Efficient Formats and Write Methods
Use compact file formats and cost-effective sink methods, such as batch loads where latency allows.
Review Commitments
For steady, long-running workloads, check whether committed use discounts apply.
A streaming job bills continuously. Forgetting to stop a test streaming job over a weekend is a classic source of surprise bills. Pricing varies by region and changes over time, so check the official Dataflow pricing page before budgeting.
16Dataflow Compared with Other Google Cloud Tools
Several services overlap with Dataflow in some way. Picking the right one saves effort and money.
| Service | What It Is | Best Fit |
|---|---|---|
| Dataflow | Managed Beam pipelines for batch and streaming | Custom transformations, windowing, enrichment, unified batch and stream logic |
| Dataproc | Managed Hadoop and Spark clusters | Existing Spark or Hadoop jobs and ecosystem tools |
| BigQuery | Serverless analytics warehouse | SQL-based transformation and analysis of data already in the warehouse |
| Pub/Sub | Messaging service | Transporting events; it moves messages, while Dataflow processes them |
| Cloud Data Fusion | Visual, code-free data integration | Teams that prefer drag-and-drop pipeline building |
| Cloud Composer | Managed workflow orchestration | Scheduling and sequencing many jobs, including Dataflow jobs |
If data work were a city, Pub/Sub is the road system that carries goods, Dataflow is the factory that transforms them, BigQuery is the giant warehouse where goods are stored and studied, and Composer is the dispatcher who decides when each factory shift starts.
Dataflow or Dataproc?
If you already have Spark code and skills, Dataproc lets you keep them. If you are starting fresh, need streaming with strong event-time handling, or want a fully managed experience with minimal cluster care, Dataflow is often the more natural choice.
Dataflow or just SQL in BigQuery?
If your data is already in BigQuery and your transformations can be written in SQL, using BigQuery directly is usually simpler and cheaper. Choose Dataflow when you need to process data before it lands, handle continuous event streams with complex timing, call outside services, or work with sources and sinks beyond the warehouse.
flowchart TD
Q1{Is the data already in BigQuery and SQL enough?} -->|Yes| A1[Use BigQuery SQL]
Q1 -->|No| Q2{Existing Spark or Hadoop code?}
Q2 -->|Yes| A2[Consider Dataproc]
Q2 -->|No| Q3{Need streaming, windowing or custom logic?}
Q3 -->|Yes| A3[Use Dataflow]
Q3 -->|No| Q4{Prefer visual, code-free building?}
Q4 -->|Yes| A4[Consider Cloud Data Fusion]
Q4 -->|No| A3
17Design Patterns and Anti-patterns
Patterns capture what experienced teams repeatedly find works; anti-patterns capture what repeatedly goes wrong.
Helpful patterns
Streaming Ingestion Pipeline
Pub/Sub feeds a streaming Dataflow job that parses, validates and enriches events, then writes clean data to BigQuery and rejects to a dead-letter location. This is the standard foundation for real-time analytics.
Lambda-Free Unified Design
One set of transform logic is used in both a streaming job for fresh data and a batch job for reprocessing history. This avoids maintaining two diverging code bases.
Enrichment with Side Inputs
A small reference dataset, such as product details, is loaded as a side input and used to enrich each event, avoiding a slow outside call per record.
Dead-Letter and Replay
Failed records go to a dead-letter store with their error details. After fixing the cause, a small batch job replays them into the main flow.
Pre-Aggregation Before Shuffle
Combine values on each worker before the big regrouping so far less data crosses the network, which improves speed and cost.
Template-Based Operations
Pipelines are packaged as Flex Templates, launched by automation, and promoted through development, test and production with the same artifact.
Anti-patterns to avoid
Problem
Making a slow network call to an outside service for every single element, with no batching, caching or limits.
Why It’s Harmful
Throughput collapses, the outside service may be overwhelmed, and costs rise because workers spend their time waiting.
Correct Approach
Batch requests, cache repeated lookups, use side inputs for small reference data, and apply backoff and rate limits.
Problem
Treating processing time as event time in streaming jobs, so windows reflect arrival time rather than when events happened.
Why It’s Harmful
Delays, outages or retries distort counts and trends, giving results that look precise but are wrong.
Correct Approach
Attach correct event timestamps, choose windows, triggers and allowed lateness deliberately, and monitor late data.
Problem
Writing to an external system in a way that is not safe to repeat, and assuming exactly-once behavior extends to it.
Why It’s Harmful
Retries can create duplicate rows or double-counted amounts in the destination.
Correct Approach
Use idempotent writes or unique identifiers, and choose sink methods that deduplicate.
Problem
Running a streaming pipeline for data that is only used once a day.
Why It’s Harmful
You pay for workers around the clock while nobody uses the fresh results.
Correct Approach
Use a scheduled batch job, possibly with flexible scheduling, and save the streaming design for cases that need freshness.
18Advantages, Disadvantages and Trade-offs
An honest summary of what Dataflow gives you and what it asks in return.
Advantages
- One model for batch and streaming reduces duplicated logic
- Fully managed: no clusters to size, patch or recover
- Autoscaling matches resources to the workload
- Strong event-time features: windows, watermarks and triggers
- Exactly-once processing within the pipeline
- Portable, open-source Beam code that is not locked to one engine
- Rich connectors and ready-made templates
Disadvantages / Trade-offs
- The Beam model, especially time concepts, has a real learning curve
- Streaming jobs cost money around the clock
- Debugging distributed jobs is harder than debugging a single program
- Startup time for new jobs and workers can take minutes
- Skewed data and hot keys can erase the benefits of scaling
- Overkill for simple movements that built-in features can handle
When to choose Dataflow
Choose Dataflow when you need to transform or enrich large or continuous data, want one approach for both batch and streaming, need accurate handling of event time and late data, or want to run pipelines without managing infrastructure.
When not to choose it
Avoid it when SQL in a warehouse is enough, when a built-in connection feature already moves your data, when you must run existing Spark code unchanged, or when the volume is so small that a simple scheduled script would do.
19Real-World Examples
Seeing how organizations use Dataflow makes the concepts easier to remember.
Real-Time Clickstream Analytics
A retailer sends website and app events into Pub/Sub. A streaming Dataflow job cleans them, groups them into user sessions, computes live metrics and writes results to BigQuery for dashboards that update within seconds, while a copy goes to cheap storage for history.
Fraud Detection for Payments
A payments company scores each transaction as it arrives, comparing it with recent activity per card using sliding windows. Suspicious items are sent to an alert topic within moments, and all decisions are stored for audit.
IoT Sensor Processing
A manufacturer receives readings from thousands of machines. A pipeline smooths the data, detects abnormal patterns, handles sensors that send data late after losing connection, and writes the results to Bigtable for fast lookups and to BigQuery for analysis.
Nightly Data Warehouse Loads
A company exports files from several systems into Cloud Storage each night. A batch Dataflow job standardizes formats, removes duplicates, joins reference data and loads clean tables into BigQuery before business hours.
Database Change Replication
A pipeline reads change streams from an operational database and applies them to an analytics store, so reports reflect recent changes without putting heavy query load on the production database.
Machine Learning Scoring at Scale
A media company runs a model across millions of articles in a batch job to produce tags and embeddings, then keeps new articles current with a streaming job using the same inference logic.
20Best Practices and Common Mistakes
A short checklist to carry into every Dataflow project.
Best Practices
- Decide freshness needs first; choose batch or streaming accordingly
- Use correct event timestamps and deliberate window, trigger and lateness settings
- Route bad records to a dead-letter destination and monitor it
- Pre-aggregate before shuffles and watch for hot keys
- Use a dedicated, least-privilege worker service account
- Run workers privately when possible, inside your own network
- Package production pipelines as templates and launch through automation
- Alert on lag, freshness and dropped data, not just failures
- Set a maximum worker limit to cap cost
- Test pipelines with small samples and test update compatibility before production changes
- Use drain or update rather than cancel for streaming jobs
Common Mistakes
- Using a pipeline where SQL or a built-in feature would do
- Ignoring late data and event time
- Letting one bad record break the whole job
- Hot keys and unbatched external calls
- Using broad default permissions
- Launching production jobs by hand
- Forgetting to stop test streaming jobs
- Assuming exactly-once reaches outside systems automatically
- Changing running streaming jobs without checking compatibility
21Frequently Asked Questions
Apache Beam is the open-source programming model you use to write pipelines. Dataflow is Google Cloud’s managed service that runs Beam pipelines, handling machines, scaling and recovery.
Beam supports Java, Python and Go, and Dataflow can run pipelines written in them. Some connectors and features are more mature in certain languages, so check current documentation for your needs.
The same transform logic can often be reused in both modes. The main difference is the source, bounded or unbounded, and the need to think about windows and triggers for streaming.
It is the system’s estimate of how far event time has progressed, meaning the point before which it believes nearly all data has arrived. It helps decide when a window is ready to produce results.
If it arrives within the allowed lateness, it can update the window’s result. If it arrives later than that, it is dropped, so choose your lateness setting deliberately and monitor drops.
It provides exactly-once processing semantics inside the pipeline. For outside systems you write to, you need idempotent writes or deduplication, because retries could otherwise create duplicates.
Drain stops reading new input and finishes processing what has already been received before shutting down. Cancel stops immediately, and buffered data may be lost.
Dataflow adds or removes workers based on backlog and utilization, within the maximum you set. Dataflow Prime adds vertical autoscaling for memory as well.
No. Google provides ready-made templates for common jobs, which you launch by supplying parameters. Writing your own Beam code is needed only for custom logic.
Common causes are hot keys, steps that cannot be parallelized, slow external services, or too much shuffled data. Use the job graph and metrics to find the bottleneck.
Yes. You can run workers with private addresses in your own subnet and use Private Google Access to reach Google services, which is a common security practice.
Set a maximum worker count, right-size machines, use FlexRS for delay-tolerant batch work, reduce shuffle volume, consider at-least-once streaming where suitable, and stop jobs you no longer need.
22Summary and Key Takeaways
Dataflow is Google Cloud’s managed engine for running Apache Beam pipelines, giving you one programming model for both batch and streaming data. You describe what should happen to your data as a graph of transforms, and the service handles machines, scaling, shuffling, failures and monitoring. The hardest and most valuable ideas to learn are about time: event time, windows, watermarks, triggers and late data. Good results then come from sound design habits: choosing batch or streaming for real business reasons, pre-aggregating before shuffles, handling bad records with dead-letter paths, using least-privilege identities and private networking, packaging pipelines as templates, and watching lag and freshness. Used for the right jobs, it makes large-scale data processing dependable and surprisingly calm to operate.
Key Takeaways
- Dataflow runs Beam pipelines — Beam is the portable open-source model; Dataflow is the managed service that executes it and handles scaling and recovery.
- One model, two modes — bounded data gives batch jobs, unbounded data gives streaming jobs, and much of the logic can be shared.
- Time is the key idea — use event time, windows, watermarks, triggers and allowed lateness deliberately, and monitor late data.
- Mind the shuffle and the keys — pre-aggregate early, avoid hot keys and batch calls to outside services for speed and low cost.
- Exactly-once stops at the pipeline’s edge — use idempotent writes or deduplication for external systems, and route bad records to a dead-letter store.
- Operate with care — use templates and automation, update or drain streaming jobs rather than cancelling them, and alert on lag and freshness.
- Secure and budget from day one — least-privilege worker accounts, private workers, maximum worker limits, FlexRS for batch and prompt shutdown of test jobs.