Apache Beam Pipelines on Cloud Dataflow
Pipeline authoring
Use this section when implementing Dataflow pipeline logic using Apache Beam.
Check if existing Google Dataflow Template exists
Google provides a variety of pre-built, open source Dataflow templates that can
be used for common scenarios. Before implementing a pipeline from scratch, you
MUST follow the steps below to check whether a Dataflow template for the
pipeline logic you need to implement already exists.
Create a new pipeline from scratch
Use this section when creating a new project for a Dataflow pipeline from
scratch.
- If the user doesn't say explicitly which language (Java, Python, Go) shall
be used to write the pipeline, you MUST confirm the language.
- Determine which version of Beam SDK should be used by searching for the most
recently released version of Apache Beam, unless the user already uses a
particular version.
- Action: Run a web search for the latest Apache Beam SDK release.
- YOU MUST use same version of Apache Beam consistently throughout the project
in Dockerfiles,
requirements.txt, and other similar files where versions
are specified.
Java projects using Gradle
Use this section when configuring a Dataflow Java pipeline project using gradle.
- Shadow Jars (Fat Jars): Do NOT propose to use the Shadow plugin
(
com.github.johnrengelman.shadow) unless the user explicitly requests a
Fat Jar.
- Passing command-line parameters: Use the
application plugin for
passing command-line parameters.
- SLF4J Logging Dependency Alignment:
- Verify the
slf4j-api version pulled transitively by Apache Beam.
- You MUST configure the application logging backend (
slf4j-simple,
logback-classic, etc.) to exactly match the major/minor version of the
resolved slf4j-api.
Packaging a pipeline as a Flex Template
Use this section to package pipeline code as a Flex template.
Flex Templates offer a hermetic and reproducible launch environment for a
pipeline. They are easy to launch with gcloud or with orchestrators like Cloud
Composer. You MUST package the pipeline as a Flex Template when creating new
Dataflow pipeline projects.
Follow the steps below:
- Provide Instructions: Provide instructions on rebuilding and running
Flex Templates to the user in walkthrough.
- Use Single Docker Image for Python pipelines: For Python Flex Templates,
it is better to use a single image for the template launcher image and for
the worker runtime environment (
--sdk_container_image). Does the Python
pipeline require extra dependencies (e.g., using --requirements_file,
--setup_file, or --extra_package)? If so, YOU MUST recommend the
Single Docker Image Configuration for the Flex Template. See
python_flex_template_reference.md for details.
- Prefer Cloud Build over Local Docker:
- Do NOT assume local Docker availability on the workspace machine.
- Action: Suggest and provide
cloudbuild.yaml out-of-the-box for
building and pushing images unless local setup is explicitly requested.
- When building images with Cloud Build in the background you MUST provide
the link where the user can monitor the long-running operation.
- Providing SSL certificates and Secrets to Workers:
- If certificates or keys are stored in Secret Manager, NEVER bake
them into the Docker image layers. Instead, retrieve them dynamically at
runtime inside the Apache Beam
DoFn.setup() lifecycle using the Secret
Manager client library (writing them to ephemeral worker disk like
/tmp only if physical file paths are strictly required). Ensure the
Dataflow Worker Service Account has the
roles/secretmanager.secretAccessor role.
Configuring Google-provided templates
Use this section when the user has selected a Google-provided template (Classic
or Flex) and you need to configure it.
Step 1: Get template metadata
- Identify template type:
- Classic: Metadata files are in
gs://dataflow-templates and end
with _metadata (e.g.,
gs://dataflow-templates/latest/Word_Count_metadata).
- Flex: Metadata are embedded in the template spec file under
gs://dataflow-templates/latest/flex (e.g.
gs://dataflow-templates/latest/flex/Cloud_Datastream_to_BigQuery).
- Read the corresponding template metadata file to identify required
parameters.
- Note:
- Make sure to run a recursive search over the bucket if needed to
locate the metadata.
- If the template parameters include UDF-related fields (e.g.,
javascriptTextTransformGcsPath,
javascriptTextTransformFunctionName), refer to the
UDF guide to write and configure the UDF.
- Parameter-Based SSL / Secret Staging: If the Google-provided
template requires local SSL certificates or Secret Manager secrets,
pass comma-separated GCS paths via the
extraFilesToStage
parameter. The runner will drop them into /extra_files on worker
VMs. Refer to the SSL certificates guide for local
referencing syntax (/extra_files/...).
Step 2: Get network configuration
- Action: Run
gcloud commands to list networks and subnetworks.
- Confirm the network and subnetwork to use with the user.
Step 3: Identify required parameters and prepare resources
- Extract required parameters from the template metadata.
[!IMPORTANT]
Strict parameter validation: Any parameter in the metadata JSON
that does NOT explicitly have "isOptional": true is **strictly
required** by the Dataflow API.
This applies even if the description suggests it has a default value
(e.g., csvFormat or badRecordsOutputTable in some templates).
You must identify and supply all of them.
- Identify which parameters are provided by the user and which need to be
resolved or created by you.
- Action: Present these parameters to the user using Markdown
Key-Value (bullet points) for clarity and confirmation.
- Schema Handling: If a schema JSON parameter (like
schemaJSONPath
or JSONPath) is required:
- Action: Ask the user to provide the GCS path to an existing
schema file or the JSON content.
- If the user does not have a schema file, ask them to provide the
field names and their types. Construct the schema JSON locally and
present it to the user for validation.
- Once confirmed by the user, write the schema JSON file locally and
upload it to a GCS staging location, then supply this path to the
parameter.
- Pre-create Target Sink (Best Practice): To ensure stability and
avoid runtime creation schema mismatches:
- Action: Clarify with the user whether the target sink (e.g.,
BigQuery table, Spanner database/table) already exists. If the user
confirms it exists, proceed to the remaining steps as-is.
- If it does not exist, ask for permission to create it. If permitted,
create it yourself. Otherwise, provide the exact creation commands
to the user.
- If the sink is BigQuery, refer to
Destination-specific prerequisites for crucial table
and error table setup.
- Include additional parameters such as service accounts, network details,
and other pipeline options.
Destination-specific prerequisites
Different templates might require specific resources to be prepared in the
target sink before execution. Follow the instructions for your target sink
below.
BigQuery
When running templates that write to BigQuery, you MUST ensure the following
resources are prepared to prevent job failures:
- Pre-create Target Table: Create the target BigQuery table (e.g., using
bq mk) before launching the job. Ensure the schema matches the template's
expectations.
- Pre-create Error/Bad Records Table: Many templates that write to
BigQuery have a parameter for redirecting failed records (e.g.,
badRecordsOutputTable or outputDeadletterTable). Some templates attempt
to auto-create this table. However, pre-creating it is a best practice. This
ensures correct schema and permissions.
- How to Determine the Error Schema: Trace the schema definition in
the public DataflowTemplates GitHub repository:
- Locate the source code or README for the template you are using
(e.g., in
v1/ or v2/ directories).
- Identify the parameter name used for the error table (e.g.,
badRecordsOutputTable or outputDeadletterTable).
- Search the source code to see how the schema is defined or loaded
for that parameter:
- Example (Code Reference): In
PubSubToBigQuery.java, the
schema is set using
ResourceUtils.getDeadletterTableSchemaJson(). Tracing
ResourceUtils.java shows it loads the schema from
streaming_source_deadletter_table_schema.json on GitHub.
- Example (Documentation Reference): For simpler templates,
the schema might be listed in the official documentation, such
as the
RawContent/ErrorMsg schema shown in the
CSV to BigQuery DevSite Doc.
Configuring Custom Pipelines (Dataflow Runner)
Use this section when preparing to run a custom Apache Beam pipeline on
Dataflow.
When launching Python Pipelines without a Flex Template with
DataflowRunner, you MUST scan the pipeline project directory for the
following files:
requirements.txt:
- If found, you MUST include
--requirements_file pipeline option.
setup.py:
- If found, you MUST include
--setup_file pipeline option. This is
critical if the pipeline uses local modules or packages.
When launching Python Pipelines with a Flex Template, if the Flex Template
image is also the SDK Container image (Single Docker Image Configuration),
then you MUST supply the image in the sdk_container_image parameter.
Lookup environment resources instead of using placeholder values
- Avoid using generic placeholders (e.g.,
your-gcp-project-id) for GCP
resources when drafting run scripts or configs. Action: If values are
unknown, proactively run commands like gcloud config get-value project to
find active resources to pre-fill scripts for the user. Confirm the values
with the user before proceeding.
Job Execution
Use this section when configuration is complete and you are ready to launch any
Dataflow job (Google-provided template, Custom Flex template, or standalone
pipeline).
Universal Execution Workflow
- Construct Launch Command: Draft the full launch command based on the
pipeline type (e.g.,
gcloud dataflow flex-template run or python main.py --runner=DataflowRunner). Ensure workers default to private IP
configuration unless specified otherwise, and verify target project
permissions.
- Mandatory Pre-Launch Confirmation: Present the entire drafted command
to the user at once. Explain the purpose of all parameters (including
experimental flags) and allow the user to review and correct the command as
a batch instead of confirming piecemeal. Do NOT proceed with execution
until explicitly approved.
- Trigger Job: Once approved, execute the command and note the resulting
Job ID (displaying it to the user).
- Display Console URL: Construct and present the direct Cloud Console
monitoring URL:
https://console.cloud.google.com/dataflow/jobs//?project=
Job Monitoring
Use this section to monitor the progress of a running Dataflow job.
- Check the status of the triggered Dataflow job using the job ID.
- Run the check every 30 seconds for the first 2 minutes, then check every 3
minutes, unless specified otherwise by the user.
- Note: Do NOT perform data check queries on the sink until the job has
reached a stable
RUNNING or DONE state.
Diagnostics & Troubleshooting
[!IMPORTANT] YOU MUST use this section when the user asks about performance of
their Dataflow pipelines. This can be used to debug issues like pipeline
slowness, pipeline failures, etc.
Task Execution Workflow
Understand User Request: Extract Job ID, Project ID, Transform Name
(optional), and Time Window.
Transform Name Mapping: If the user requires transform-based debugging,
map user-provided Transform Names to actual Dataflow stage or ptransform
and apply to filters while querying:
This mapping can be extracted from gcloud dataflow jobs describe JOB_ID --full --format="json(pipelineDescription.executionPipelineStage)".
- Extract the targets:
- Get stage_id:
name property at the parent stage level. This
matches "F[digit]" (e.g. "F6").
- Get ptransform: inside the
componentTransform array, read
precisely from userName or originalTransform (e.g.
"RateLimitAndLog/ParMultiDo(RateLimitAndLog)"). and use it as
ptransform.
- Apply the filters strictly following mapping mechanics:
- For Cloud Logging queries: Apply extracted ptransform name to
filter
resource.labels.step_id="[Extracted ptransform name]".
- For Monitoring queries: Use the stage_id/ptransform filters
based on filters supported by metric:
metric.labels.ptransform="[Extracted ptransform name]" or
metric.labels.stage="[Extracted stage_id]".
Query Telemetry:
- Use Dataflow REST API to get High level Job Messages/Events that
happened in the job.
- Refer to dataflow_diagnostics_reference.md for
key metrics and logging query patterns based on Job Type.
- Use Monitoring REST API to fetch metrics.
- Use GCloud Logging command to fetch logs.
- Use Dataflow REST API to fetch current snapshot metrics when historical
time-series are not needed.
Analysis:
- For Streaming Jobs
- Overall Job Health: YOU MUST refer to
streaming_job_health to analyze
overall streaming job health.
- Analyze Bottlenecks and Parallelism. YOU MUST refer to
bottlenecks_and_parallelism_context and
interpret the bottlenecks and parallelism metrics in that context.
- Analyze Autoscaling Behavior. YOU MUST refer to
streaming_horizontal_autoscaling_analysis.md
- For Batch Jobs
- Correlate metrics spikes/drops with log errors.
- Identify Issues.
Output: Provide a synthesized diagnosis containing symptoms, root
causes, and target code links (using file:///... format). Strictly follow
the response structure appropriate for the job type:
For Streaming Jobs:
- Overall Job State: State categorization (Healthy, Mostly Healthy,
Not Healthy) per
streaming_job_health.
- High-level Job Events: Notable control plane events, errors, or
stage failures parsed from job messages.
- Data Freshness: Current data delay utilizing
job/data_watermark_age / job/per_stage_data_watermark_age and system
lag.
- Throughput: Processing rate trends utilizing
job/elements_produced_count / job/estimated_bytes_produced_count.
- Backlog: Input backlog (if source stage) or inter-stage backlog
using
job/estimated_backlog_processing_time / job/backlog_bytes.
- Bottlenecks & Parallelism: Queue delay diagnostics using
job/is_bottleneck (interpreting likely_cause / bottleneck_kind)
and key metrics job/backlogged_keys /
job/processing_parallelism_keys interpreted in the context of
bottlenecks_and_parallelism_context.
- Autoscaling Analysis: Scaling trends using
job/horizontal_worker_scaling (and label rationale), clamp limits
(job/max_worker_instances_limit / job/min_worker_instances_limit),
and utilization hints in the context of
streaming_horizontal_autoscaling_analysis.
- Recommendations: Direct remediation plans (in-flight updates,
client-side configurations, or code corrections linked via absolute
file:/// URIs).
For Batch Jobs:
- High-level Job Events: Notable control plane events, errors, or
stage failures parsed from job messages.
- Throughput: Processing rate trends utilizing
job/elements_produced_count (primary performance indicator).
- Recommendations: Direct remediation plans to future runs
(client-side configurations, or code corrections linked via absolute
file:/// URIs).
1---2name: gcp-dataflow3description: >4 Guides writing, packaging, executing, and troubleshooting Apache Beam5 pipelines on Dataflow. Use when creating new pipelines, configuring Flex6 Templates, or analyzing performance of Dataflow jobs. Capabilities include7 Java/Python/Go setup, Cloud Build integration, and deep diagnostic analysis8 of job health and autoscaling.910 Use when:11 - Creating an Apache Beam Dataflow pipeline.12 - Creating a Google Dataflow Flex Template.13 - Using an existing Google Dataflow Template.14 - Debugging Dataflow pipeline15 - Troubleshooting Dataflow pipeline16 - Analyzing Performance of Dataflow pipeline.1718 Key capabilities: Java/Python/Go project setup, Flex Templates (with19 Cloud Build), and diagnostics for streaming job health, bottlenecks,20 and autoscaling.2122 Do NOT use for:23 - General GCP resource management unrelated to Dataflow.24 - Issues with other GCP services (e.g., GCE, GCS, BigQuery) unless directly25 impacting Dataflow pipeline execution.26 - Pipeline technologies other than Apache Beam on Dataflow.2728license: Apache-2.029metadata:30 version: v431 publisher: google32---3334# Apache Beam Pipelines on Cloud Dataflow3536## Pipeline authoring3738Use this section when implementing Dataflow pipeline logic using Apache Beam.3940### Check if existing Google Dataflow Template exists4142Google provides a variety of pre-built, open source Dataflow templates that can43be used for common scenarios. Before implementing a pipeline from scratch, you44MUST follow the steps below to check whether a Dataflow template for the45pipeline logic you need to implement already exists.4647- **Step 1: Check for a matching Google Dataflow Template**4849 - Identify the **source** and **sink** (e.g., GCS to BigQuery) from the50 user's request. *Note*: You *MUST NOT* proceed until the source and sink51 are clearly identified.52 - **Action**: List templates in the public `dataflow-templates` bucket:53 * For Classic templates, check `gs://dataflow-templates/latest`.54 * For Flex templates, check `gs://dataflow-templates/latest/flex`. Use55 `gcloud storage ls` to list the contents.56 - Match templates by name or description to the source and sink.57 - If no matching template is found, go to **Create a new pipeline from58 scratch**.5960- **Step 2: Confirm template selection**6162 - Present the matched template(s) to the user with a brief explanation of63 why they match, and make a note of whether it is a Classic or Flex64 template.65 - **Action**: Ask the user for explicit confirmation to proceed with this66 template.67 - If the user rejects or prefers a custom solution, proceed to **Create a68 new pipeline from scratch**.6970### Create a new pipeline from scratch7172Use this section when creating a new project for a Dataflow pipeline from73scratch.7475- If the user doesn't say explicitly which language (Java, Python, Go) shall76 be used to write the pipeline, you MUST confirm the language.77- Determine which version of Beam SDK should be used by searching for the most78 recently released version of Apache Beam, unless the user already uses a79 particular version.80 - **Action**: Run a web search for the latest Apache Beam SDK release.81- YOU MUST use same version of Apache Beam consistently throughout the project82 in Dockerfiles, `requirements.txt`, and other similar files where versions83 are specified.8485### Java projects using Gradle8687Use this section when configuring a Dataflow Java pipeline project using gradle.8889- **Shadow Jars (Fat Jars)**: Do NOT propose to use the Shadow plugin90 (`com.github.johnrengelman.shadow`) unless the user explicitly requests a91 Fat Jar.92- **Passing command-line parameters**: Use the `application` plugin for93 passing command-line parameters.94- **SLF4J Logging Dependency Alignment**:95 - Verify the `slf4j-api` version pulled transitively by Apache Beam.96 - You MUST configure the application logging backend (`slf4j-simple`,97 `logback-classic`, etc.) to exactly match the major/minor version of the98 resolved `slf4j-api`.99100### Packaging a pipeline as a Flex Template101102Use this section to package pipeline code as a Flex template.103104Flex Templates offer a hermetic and reproducible launch environment for a105pipeline. They are easy to launch with `gcloud` or with orchestrators like Cloud106Composer. You **MUST** package the pipeline as a Flex Template when creating new107Dataflow pipeline projects.108109Follow the steps below:110111- **Provide Instructions**: Provide instructions on rebuilding and running112 Flex Templates to the user in walkthrough.113- **Use Single Docker Image for Python pipelines**: For Python Flex Templates,114 it is better to use a single image for the template launcher image and for115 the worker runtime environment (`--sdk_container_image`). Does the Python116 pipeline require extra dependencies (e.g., using `--requirements_file`,117 `--setup_file`, or `--extra_package`)? If so, **YOU MUST recommend the**118 **Single Docker Image Configuration** for the Flex Template. See119 [python_flex_template_reference.md][py-flex-ref] for details.120- **Prefer Cloud Build over Local Docker**:121 - Do NOT assume local Docker availability on the workspace machine.122 - **Action**: Suggest and provide `cloudbuild.yaml` out-of-the-box for123 building and pushing images unless local setup is explicitly requested.124 - When building images with Cloud Build in the background you MUST provide125 the link where the user can monitor the long-running operation.126- **Providing SSL certificates and Secrets to Workers**:127 - If certificates or keys are stored in Secret Manager, **NEVER** bake128 them into the Docker image layers. Instead, retrieve them dynamically at129 runtime inside the Apache Beam `DoFn.setup()` lifecycle using the Secret130 Manager client library (writing them to ephemeral worker disk like131 `/tmp` only if physical file paths are strictly required). Ensure the132 Dataflow Worker Service Account has the133 `roles/secretmanager.secretAccessor` role.134135## Configuring Google-provided templates136137Use this section when the user has selected a Google-provided template (Classic138or Flex) and you need to configure it.139140- **Step 1: Get template metadata**141142 - Identify template type:143 * **Classic**: Metadata files are in `gs://dataflow-templates` and end144 with `_metadata` (e.g.,145 `gs://dataflow-templates/latest/Word_Count_metadata`).146 * **Flex**: Metadata are embedded in the template spec file under147 `gs://dataflow-templates/latest/flex` (e.g.148 `gs://dataflow-templates/latest/flex/Cloud_Datastream_to_BigQuery`).149 - Read the corresponding template metadata file to identify required150 parameters.151 - **Note**:152 * Make sure to run a recursive search over the bucket if needed to153 locate the metadata.154 * If the template parameters include UDF-related fields (e.g.,155 `javascriptTextTransformGcsPath`,156 `javascriptTextTransformFunctionName`), refer to the157 [UDF guide][udf-guide] to write and configure the UDF.158 * **Parameter-Based SSL / Secret Staging**: If the Google-provided159 template requires local SSL certificates or Secret Manager secrets,160 pass comma-separated GCS paths via the `extraFilesToStage`161 parameter. The runner will drop them into `/extra_files` on worker162 VMs. Refer to the [SSL certificates guide][ssl-cert-guide] for local163 referencing syntax (`/extra_files/...`).164165- **Step 2: Get network configuration**166167 - **Action**: Run `gcloud` commands to list networks and subnetworks.168 - Confirm the network and subnetwork to use with the user.169170- **Step 3: Identify required parameters and prepare resources**171172 - Extract required parameters from the template metadata.173 - > [!IMPORTANT]174 - > **Strict parameter validation**: Any parameter in the metadata JSON175 - > that does **NOT** explicitly have `"isOptional": true` is **strictly176 - > required** by the Dataflow API.177 - > This applies even if the description suggests it has a default value178 - > (e.g., `csvFormat` or `badRecordsOutputTable` in some templates).179 - > You must identify and supply all of them.180 - Identify which parameters are provided by the user and which need to be181 resolved or created by you.182 * **Action**: Present these parameters to the user using Markdown183 Key-Value (bullet points) for clarity and confirmation.184 - **Schema Handling**: If a schema JSON parameter (like `schemaJSONPath`185 or `JSONPath`) is required:186 * **Action**: Ask the user to provide the GCS path to an existing187 schema file or the JSON content.188 * If the user does not have a schema file, ask them to provide the189 field names and their types. Construct the schema JSON locally and190 present it to the user for validation.191 * Once confirmed by the user, write the schema JSON file locally and192 upload it to a GCS staging location, then supply this path to the193 parameter.194 - **Pre-create Target Sink (Best Practice)**: To ensure stability and195 avoid runtime creation schema mismatches:196 * **Action**: Clarify with the user whether the target sink (e.g.,197 BigQuery table, Spanner database/table) already exists. If the user198 confirms it exists, proceed to the remaining steps as-is.199 * If it does not exist, ask for permission to create it. If permitted,200 create it yourself. Otherwise, provide the exact creation commands201 to the user.202 * If the sink is BigQuery, refer to203 [Destination-specific prerequisites][dest-prereqs] for crucial table204 and error table setup.205 - Include additional parameters such as service accounts, network details,206 and other pipeline options.207 * **Specifying Options**: For Google-provided Flex Templates, refer to208 the [Specifying options for Flex Templates][flex-template-options]209 guide for how to pass parameters and additional experiments.210211### Destination-specific prerequisites212213Different templates might require specific resources to be prepared in the214target sink before execution. Follow the instructions for your target sink215below.216217#### BigQuery218219When running templates that write to BigQuery, you MUST ensure the following220resources are prepared to prevent job failures:221222- **Pre-create Target Table**: Create the target BigQuery table (e.g., using223 `bq mk`) before launching the job. Ensure the schema matches the template's224 expectations.225- **Pre-create Error/Bad Records Table**: Many templates that write to226 BigQuery have a parameter for redirecting failed records (e.g.,227 `badRecordsOutputTable` or `outputDeadletterTable`). Some templates attempt228 to auto-create this table. However, pre-creating it is a best practice. This229 ensures correct schema and permissions.230 * **How to Determine the Error Schema**: Trace the schema definition in231 the public [DataflowTemplates GitHub repository][df-templates-repo]:232 1. Locate the source code or README for the template you are using233 (e.g., in `v1/` or `v2/` directories).234 2. Identify the parameter name used for the error table (e.g.,235 `badRecordsOutputTable` or `outputDeadletterTable`).236 3. Search the source code to see how the schema is defined or loaded237 for that parameter:238 * **Example (Code Reference)**: In `PubSubToBigQuery.java`, the239 schema is set using240 `ResourceUtils.getDeadletterTableSchemaJson()`. Tracing241 `ResourceUtils.java` shows it loads the schema from242 [streaming_source_deadletter_table_schema.json on GitHub][deadletter-schema].243 * **Example (Documentation Reference)**: For simpler templates,244 the schema might be listed in the official documentation, such245 as the `RawContent`/`ErrorMsg` schema shown in the246 [CSV to BigQuery DevSite Doc][csv-bq-doc].247248## Configuring Custom Pipelines (Dataflow Runner)249250Use this section when preparing to run a custom Apache Beam pipeline on251Dataflow.252253- When launching Python Pipelines without a Flex Template with254 `DataflowRunner`, you MUST scan the pipeline project directory for the255 following files:256 - **`requirements.txt`**:257 - If found, you MUST include `--requirements_file` pipeline option.258 - **`setup.py`**:259 - If found, you MUST include `--setup_file` pipeline option. This is260 critical if the pipeline uses local modules or packages.261262- When launching Python Pipelines with a Flex Template, if the Flex Template263 image is also the SDK Container image (Single Docker Image Configuration),264 then you MUST supply the image in the `sdk_container_image` parameter.265266### Lookup environment resources instead of using placeholder values267268- Avoid using generic placeholders (e.g., `your-gcp-project-id`) for GCP269 resources when drafting run scripts or configs. **Action**: If values are270 unknown, proactively run commands like `gcloud config get-value project` to271 find active resources to pre-fill scripts for the user. Confirm the values272 with the user before proceeding.273274## Job Execution275276Use this section when configuration is complete and you are ready to launch any277Dataflow job (Google-provided template, Custom Flex template, or standalone278pipeline).279280### Universal Execution Workflow2812821. **Construct Launch Command**: Draft the full launch command based on the283 pipeline type (e.g., `gcloud dataflow flex-template run` or `python main.py284 --runner=DataflowRunner`). Ensure workers default to private IP285 configuration unless specified otherwise, and verify target project286 permissions.2872. **Mandatory Pre-Launch Confirmation**: Present the *entire* drafted command288 to the user at once. Explain the purpose of all parameters (including289 experimental flags) and allow the user to review and correct the command as290 a batch instead of confirming piecemeal. **Do NOT proceed** with execution291 until explicitly approved.2923. **Trigger Job**: Once approved, execute the command and note the resulting293 Job ID (displaying it to the user).2944. **Display Console URL**: Construct and present the direct Cloud Console295 monitoring URL:296 https://console.cloud.google.com/dataflow/jobs/<region>/<job_id>?project=<project_id>297298## Job Monitoring299300Use this section to monitor the progress of a running Dataflow job.301302- Check the status of the triggered Dataflow job using the job ID.303- Run the check every 30 seconds for the first 2 minutes, then check every 3304 minutes, unless specified otherwise by the user.305- **Note**: Do NOT perform data check queries on the sink until the job has306 reached a stable `RUNNING` or `DONE` state.307308## Diagnostics & Troubleshooting309310> [!IMPORTANT] YOU MUST use this section when the user asks about performance of311> their Dataflow pipelines. This can be used to debug issues like pipeline312> slowness, pipeline failures, etc.313314### Task Execution Workflow3153161. **Understand User Request**: Extract Job ID, Project ID, Transform Name317 (optional), and Time Window.3182. **Transform Name Mapping**: If the user requires transform-based debugging,319 map user-provided Transform Names to actual Dataflow `stage` or `ptransform`320 and apply to filters while querying:321322 This mapping can be extracted from `gcloud dataflow jobs describe JOB_ID323 --full --format="json(pipelineDescription.executionPipelineStage)"`.324325 1. **Extract the targets**:326 * Get stage_id: **`name`** property at the parent stage level. This327 matches `"F[digit]"` (e.g. `"F6"`).328 * Get ptransform: inside the `componentTransform` array, read329 precisely from **`userName`** or **`originalTransform`** (e.g.330 `"RateLimitAndLog/ParMultiDo(RateLimitAndLog)"`). and use it as331 **`ptransform`**.332 2. **Apply the filters strictly following mapping mechanics**:333 * **For Cloud Logging queries**: Apply extracted ptransform name to334 filter `resource.labels.step_id="[Extracted ptransform name]"`.335 * **For Monitoring queries**: Use the stage_id/ptransform filters336 based on filters supported by metric:337 `metric.labels.ptransform="[Extracted ptransform name]"` or338 `metric.labels.stage="[Extracted stage_id]"`.3393403. **Query Telemetry**:341342 * Use Dataflow REST API to get High level Job Messages/Events that343 happened in the job.344 * Refer to [dataflow_diagnostics_reference.md][diag-ref] for345 key metrics and logging query patterns based on Job Type.346 * Use Monitoring REST API to fetch metrics.347 * Use GCloud Logging command to fetch logs.348 * Use Dataflow REST API to fetch current snapshot metrics when historical349 time-series are not needed.3503514. **Analysis**:352353 * For Streaming Jobs354 * Overall Job Health: YOU MUST refer to355 [streaming_job_health](references/streaming_job_health.md) to analyze356 overall streaming job health.357 * Analyze Bottlenecks and Parallelism. YOU MUST refer to358 [bottlenecks_and_parallelism_context][bottlenecks-context] and359 interpret the bottlenecks and parallelism metrics in that context.360 * Analyze Autoscaling Behavior. YOU MUST refer to361 [streaming_horizontal_autoscaling_analysis.md][autoscaling-analysis-link]362 * For Batch Jobs363 * Correlate metrics spikes/drops with log errors.364 * Identify Issues.3653665. **Output**: Provide a synthesized diagnosis containing symptoms, root367 causes, and target code links (using `file:///...` format). Strictly follow368 the response structure appropriate for the job type:369370 **For Streaming Jobs:**371372 1. **Overall Job State**: State categorization (Healthy, Mostly Healthy,373 Not Healthy) per374 [streaming_job_health](references/streaming_job_health.md).375 2. **High-level Job Events**: Notable control plane events, errors, or376 stage failures parsed from job messages.377 3. **Data Freshness**: Current data delay utilizing378 `job/data_watermark_age` / `job/per_stage_data_watermark_age` and system379 lag.380 4. **Throughput**: Processing rate trends utilizing381 `job/elements_produced_count` / `job/estimated_bytes_produced_count`.382 5. **Backlog**: Input backlog (if source stage) or inter-stage backlog383 using `job/estimated_backlog_processing_time` / `job/backlog_bytes`.384 6. **Bottlenecks & Parallelism**: Queue delay diagnostics using385 `job/is_bottleneck` (interpreting `likely_cause` / `bottleneck_kind`)386 and key metrics `job/backlogged_keys` /387 `job/processing_parallelism_keys` interpreted in the context of388 [bottlenecks_and_parallelism_context][bottlenecks-context].389 7. **Autoscaling Analysis**: Scaling trends using390 `job/horizontal_worker_scaling` (and label `rationale`), clamp limits391 (`job/max_worker_instances_limit` / `job/min_worker_instances_limit`),392 and utilization hints in the context of393 [streaming_horizontal_autoscaling_analysis][autoscaling-analysis-link].394 8. **Recommendations**: Direct remediation plans (in-flight updates,395 client-side configurations, or code corrections linked via absolute396 `file:///` URIs).397398 **For Batch Jobs:**399400 1. **High-level Job Events**: Notable control plane events, errors, or401 stage failures parsed from job messages.402 2. **Throughput**: Processing rate trends utilizing403 `job/elements_produced_count` (primary performance indicator).404 3. **Recommendations**: Direct remediation plans to future runs405 (client-side configurations, or code corrections linked via absolute406 `file:///` URIs).407408[py-flex-ref]: references/python_flex_template_reference.md409[udf-guide]: https://docs.cloud.google.com/dataflow/docs/guides/templates/create-template-udf410[ssl-cert-guide]: https://docs.cloud.google.com/dataflow/docs/guides/templates/ssl-certificates411[dest-prereqs]: #destination-specific-prerequisites412[flex-template-options]: https://docs.cloud.google.com/dataflow/docs/guides/templates/run-flex-templates#specify-options413[df-templates-repo]: https://github.com/GoogleCloudPlatform/DataflowTemplates414[deadletter-schema]: https://github.com/GoogleCloudPlatform/DataflowTemplates/blob/main/v2/common/src/main/resources/schema/streaming_source_deadletter_table_schema.json415[csv-bq-doc]: https://cloud.google.com/dataflow/docs/guides/templates/provided/cloud-storage-csv-to-bigquery#GcsCSVToBigQueryBadRecordsSchema416[diag-ref]: references/dataflow_diagnostics_reference.md417[bottlenecks-context]: references/bottlenecks_and_parallelism_context.md418[autoscaling-analysis-link]: references/streaming_horizontal_autoscaling_analysis.md