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

Cloud Composer: Environments, DAGs & GKE Workers

GCP Data EngineeringCloud Composer AdvancedđŸŸĸ Free Lesson

Cloud Composer Advanced Patterns

Master Cloud Composer including environment configuration, DAG development, GKE workers, sensors, and production patterns.

20 min readAdvanced

What You'll Learn

  • 1Contrast Composer 1 and 2 internals and pick one for a new deployment
  • 2Model cross-DAG dependencies with sensors or datasets and choose by failure behaviour
  • 3Design TaskGroups, SLAs, and timeouts that keep a production DAG debuggable
  • 4Ship DAGs through CI/CD with environment promotion and rollback

Managed Airflow removes the server babysitting but not the design decisions. Production Composer environments are judged on four things: how cleanly DAGs express dependencies, how failures surface, how releases ship, and what the environment costs at rest. This lesson covers the advanced material that shows up once an environment carries hundreds of DAGs and several on-call rotations.

Composer 1 versus Composer 2

Composer 1 runs the Airflow control plane on Compute Engine VMs inside a managed GKE cluster; Composer 2 runs each task in its own pod, adds environment autoscaling, and is where new features land. The operational consequences are concrete: pod-per-task isolation means a task OOM does not kill its neighbour, autoscaling responds to task load rather than a fixed worker count, and environment creation and upgrades are faster because there is no VM image to bake.

BehaviourComposer 1Composer 2
Task executionworker VMs with slotsone pod per task
Scaling signalworker count and slotspod demand and autoscaling
Airflow version floor1.10 with 2.x available2.x only
Environment upgrade timetens of minutesminutes
Network controlsprivate IP optionprivate IP plus private endpoint

New deployments should target Composer 2. The migration work is mostly DAG-side: Airflow 2 scheduling semantics, provider package version bumps, and testing that any operator relying on shared filesystem state has been reworked for pod isolation.

The GKE Worker Model

Under Composer 2 the worker service account is a Google identity that pods impersonate through Workload Identity, which is why permission design for DAGs happens in IAM rather than in key files. Task pods pull their image from Artifact Registry, mount the DAG bucket, and inherit environment variables set on the environment. Two limits matter when sizing: environment size determines the ceiling of concurrent task pods, and the node pool autoscaler underneath must be able to grow for bursty schedules.

# Inspect the environment's GKE cluster and current node pool shape.
gcloud composer environments describe prod-composer \
  --location=us-central1 \
  --format="value(config.gkeCluster)"

gcloud container node-pools describe $(gcloud container clusters list \
  --format="value(name)" --filter="name~composer" | head -1) \
  --cluster=$(gcloud composer environments describe prod-composer \
    --location=us-central1 --format="value(config.gkeCluster)") \
  --region=us-central1 \
  --format="table(name, config.machineType, initialNodeCount, autoscaling.enableAutoscaling)"

When tasks sit in queued for minutes without starting, the node pool is the first place to look, before blaming the scheduler or the DAG. The second place is the environment size itself, which caps concurrent task pods regardless of how much node capacity exists. Capacity incidents usually present as a single DAG hogging the environment with a fan-out of parallel tasks, so keeping broad dynamic task mapping bounded, and scheduling large backfills in their own environment, protects the interactive pipelines everyone else depends on. Networking deserves the same scrutiny: private endpoint environments cannot be reached from the public internet, which is the point, but it also means peering and firewall rules must allow CI/CD systems and monitoring agents through before a deploy will function.

Cross-DAG Dependencies: Sensors and Datasets

Airflow offers two mechanisms for cross-DAG sequencing. ExternalTaskSensor polls for a task instance in another DAG to reach success, which is explicit and flexible but adds a worker slot while it waits unless you use reschedule mode. Datasets, available from Airflow 2.4 and supported in Composer 2, declare that one DAG's output enables another's schedule, and the scheduler handles waiting without a sensor task at all.

python
from datetime import datetime, timedelta
from airflow import DAG
from airflow.datasets import Dataset
from airflow.providers.google.cloud.operators.bigquery import BigQueryInsertJobOperator
from airflow.sensors.external_task import ExternalTaskSensor

# Upstream DAG writes to a dataset the downstream schedule watches.
with DAG("upstream_extract", start_date=datetime(2025, 1, 1), schedule="0 1 * * *") as upstream:
    load = BigQueryInsertJobOperator(
        task_id="load",
        configuration={"query": {"query": "SELECT 1", "useLegacySql": False}},
        outlets=[Dataset("bq://my-project.analytics.raw_orders")],
    )

# Preferred: schedule on the dataset, no sensor slot consumed.
with DAG("downstream_transform", schedule=[Dataset("bq://my-project.analytics.raw_orders")],
         start_date=datetime(2025, 1, 1), catchup=False) as downstream:
    transform = BigQueryInsertJobOperator(
        task_id="transform",
        configuration={"query": {"query": "SELECT 1", "useLegacySql": False}},
    )

# Legacy pattern still needed when the contract is task-level, not dataset-level.
wait_sensor = ExternalTaskSensor(
    task_id="wait_for_extract",
    external_dag_id="upstream_extract",
    external_task_id="load",
    mode="reschedule",
    poke_interval=300,
    timeout=3600,
    dag=downstream,
)

Prefer datasets for table-granular contracts, which is most of them; reserve sensors for task-level handshakes such as waiting on a specific file drop or an external system's API check. In reschedule mode the sensor releases its slot between pokes, which is the difference between a patient DAG and one that starves the worker pool. The failure behaviour differs in ways that matter at three in the morning: a sensor that exceeds its timeout fails the downstream run loudly, while a dataset-driven schedule simply does not start until the upstream outlet is written, which is quieter but also safer, because nothing downstream runs on half-produced data. Choose the behaviour your incident runbook actually wants, and document it next to the DAG so the next engineer does not convert datasets back into sensors out of habit.

TaskGroups, SLAs, and Timeouts

Large DAGs become unreadable as flat lists. TaskGroups organise tasks in the UI without changing execution semantics, and SLAs plus execution timeouts bound how long a run may take before on-call is paged. An SLA is measured from the DAG run's scheduled start, so it encodes business expectations rather than task durations, which is why SLAs belong on the DAG while timeouts belong on individual tasks.

python
from datetime import datetime, timedelta
from airflow import DAG
from airflow.utils.task_group import TaskGroup
from airflow.providers.google.cloud.operators.bigquery import BigQueryInsertJobOperator

default_args = {
    "owner": "commerce",
    "sla": timedelta(hours=6),
    "execution_timeout": timedelta(hours=2),
    "retries": 2,
    "retry_delay": timedelta(minutes=10),
}

with DAG(
    "commerce_nightly",
    default_args=default_args,
    schedule="0 2 * * *",
    start_date=datetime(2025, 1, 1),
    catchup=False,
    max_active_runs=1,
    tags=["production", "commerce"],
) as dag:

    with TaskGroup(group_id="staging") as staging:
        for name in ["orders", "customers", "items"]:
            BigQueryInsertJobOperator(
                task_id=f"stage_{name}",
                configuration={
                    "query": {
                        "query": f"SELECT * FROM `raw.{name}`",
                        "useLegacySql": False,
                    }
                },
            )

    with TaskGroup(group_id="marts") as marts:
        for name in ["revenue", "retention"]:
            BigQueryInsertJobOperator(
                task_id=f"build_{name}",
                configuration={
                    "query": {
                        "query": f"SELECT * FROM `staging.{name}`",
                        "useLegacySql": False,
                    }
                },
            )

    staging >> marts

Keep execution_timeout on every task that calls an external API. Without it, a hung BigQuery call occupies a worker pod indefinitely and the SLA alert fires hours later, after the damage to dependent pipelines is done.

CI/CD and Promotion

DAGs should ship the way applications do: pull request, tests, deploy to development, promote to production. Composer's DAG folder is a Cloud Storage bucket, so the deploy step of a Cloud Build pipeline is a copy, and promotion is a second copy from a tagged artifact rather than a second build.

# cloudbuild.yaml — test, deploy to dev, promote to prod on tag.
steps:
  - id: pytest
    name: python:3.11
    entrypoint: bash
    args: ["-c", "pip install pytest apache-airflow && pytest dags/tests -q"]

  - id: deploy-dev
    name: gcr.io/google.com/cloudsdktool/cloud-sdk
    entrypoint: bash
    args: ["-c", "gcloud composer environments storage dags import --environment=dev-composer --location=us-central1 --source=dags/"]

  - id: deploy-prod
    name: gcr.io/google.com/cloudsdktool/cloud-sdk
    entrypoint: bash
    args: ["-c", "gcloud composer environments storage dags import --environment=prod-composer --location=us-central1 --source=dags/"]
    waitFor: ["deploy-dev"]

Gate prod on the dev deploy succeeding, and keep the previous DAG revision in the bucket long enough to support rollback by re-importing the last known good source. Because the scheduler picks up files within a minute, a bad deploy reaches production fast; the same speed applies to the fix. Tests belong in the same pipeline: DAG unit tests should import the module, assert that task dependencies match the intended graph, and validate that templated parameters render without hitting the network. The cheapest high-value test asserts the shape of the DAG, meaning task ids and upstream links, because most deploy regressions are structural rather than logical, and a graph assertion catches them in CI instead of in the morning dashboard review.

Cost Optimisation

Composer cost splits between environment infrastructure, which runs whether or not tasks execute, and task pods, which scale with work. The levers are environment size matched to DAG count, node pool autoscaling so bursts do not pin a permanently large pool, and DAG hygiene: light module-level imports keep parsing cheap, TaskGroups reduce the number of task instances the scheduler manages, and off-peak schedules let the node pool scale down overnight. Review the environment's CPU and memory allocation quarterly; over-sized environments are the quiet line item that doubles the bill without changing any DAG.

Common Mistakes

Using ExternalTaskSensor in poke mode for long waits

Fix: Switch to reschedule mode so the sensor releases its slot between pokes, or replace it with a dataset-triggered schedule that needs no sensor at all.

Shipping DAGs straight from a laptop to production

Fix: Route every change through the CI/CD pipeline so tests run and the deploy is reproducible; direct uploads make rollback archaeology.

Leaving execution_timeout unset on external calls

Fix: Bound every API-calling task so a hung call fails fast, retries, and surfaces before the SLA alert fires hours later.

Best Practices

  • Model table-granular dependencies as datasets and reserve sensors for true task handshakes
  • Group related tasks and set SLAs at the DAG level to encode the business deadline
  • Promote builds dev then prod from the same artifact, and keep a rollback source in the DAG bucket

Key Takeaways

  • Composer 2's pod-per-task model changes failure isolation, scaling, and how permissions are granted through Workload Identity
  • Datasets replace most sensors and move cross-DAG waiting into the scheduler where it costs no worker slot
  • SLAs measure from scheduled start and belong on the DAG; timeouts bound individual tasks and belong on the operator
  • CI/CD through the DAG bucket is the only reliable path to fast, reversible production changes

Interview Questions

Interview Questions

Q1: Composer 1 or 2 for a new production environment?

Composer 2, because pod-per-task isolation, autoscaling, faster upgrades, and Workload Identity are all production advantages; Composer 1 remains only where an existing estate already depends on it.

Q2: When is an ExternalTaskSensor still the right tool?

When the contract is task-level rather than dataset-level, such as waiting on a specific file drop or an external system check that has no natural table artefact to trigger on.

Q3: How do you roll back a bad DAG deploy?

Re-import the last known good source from the DAG bucket through the same CI/CD path; the scheduler picks up the restored file within a minute and the fix ships with the same reversibility as the break.

Q4: What is the first thing to check when tasks stay queued?

Environment and node pool capacity: with Composer 2, queued tasks usually mean the autoscaler has hit the environment size ceiling or the node pool cannot pull more nodes, not that the scheduler is stuck.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert GCP Data Engineering Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement