Cloud Composer - Managed Airflow for Orchestration
What You'll Learn
- 1Map each Cloud Composer component to the managed Airflow piece it replaces
- 2Size an environment from DAG count and task concurrency, then create it with gcloud
- 3Write production DAGs with retries, timeouts, and templated parameters that survive the scheduler
- 4Choose between connections, variables, and environment variables for each kind of configuration
Cloud Composer is Google Cloud's managed Apache Airflow. Google runs the web server, scheduler, workers, and metadata database on your behalf inside a Google Kubernetes Engine cluster, while you focus on DAG code and the GCP services those DAGs drive. The managed surface removes the undifferentiated work of patching Airflow, but it introduces its own constraints: environment sizes, package limits, and a metadata database you are not allowed to query directly. This lesson covers the components, environment sizing, DAG development, configuration storage, and monitoring you need to run Composer in production.
How the Managed Components Fit Together
Every Composer environment is an Airflow deployment with five moving parts. The web server renders the Airflow UI and exposes the REST API. The scheduler evaluates schedules, resolves dependencies, and pushes task instances onto workers. Workers execute tasks, usually by launching pods that run the Google provider operators. Cloud SQL stores Airflow metadata: DAG runs, task instances, logs, connections, and variables. A Cloud Storage bucket holds DAG files, plugins, and environment configuration, and it doubles as the staging area for Python packages you install at environment build time.
Composer 2 runs these components on GKE with one pod per task by default, so worker pods scale with task concurrency rather than a fixed worker count. That shift matters for capacity planning: instead of reasoning about worker slots, you reason about environment size and maximum workers. It also means a crashed task takes down only its own pod, not a shared worker process.
| Component | Managed service | What you control | Typical failure you will debug |
|---|---|---|---|
| Web server | GKE service | Airflow version, plugins | Slow UI from oversized task logs |
| Scheduler | GKE deployment | Schedule intervals, parsing timeout | DAGs with heavy module-level imports |
| Workers | GKE pods | Machine type, worker count | OOM kills on large XCom payloads |
| Metadata DB | Cloud SQL | Disk size, backups | Growth from uncleaned task history |
| DAG bucket | Cloud Storage | Folder structure, CI/CD sync | DAGs not visible because of folder nesting |
Creating and Sizing Environments
Environment size, not node count, is the primary sizing lever in Composer 2. Small suits development with a handful of DAGs; Medium covers most production workloads; Large supports thousands of DAGs and heavy scheduling. You also choose the Airflow version and Python version at creation, and those choices lock until an in-place upgrade, so pick versions your provider packages support.
# Development environment: small size, single node group.
gcloud composer environments create dev-composer \
--location=us-central1 \
--airflow-version=2.6.3 \
--python-version=3.11 \
--environment-size=small \
--node-count=3
# Production environment: medium size, private IP, custom service account.
gcloud composer environments create prod-composer \
--location=us-central1 \
--airflow-version=2.6.3 \
--python-version=3.11 \
--environment-size=medium \
--node-count=4 \
--machine-type=e2-standard-4 \
--disk-size-gb=100 \
--service-account=composer-worker@my-project.iam.gserviceaccount.com \
--network=projects/my-project/global/networks/composer-net \
--subnetwork=regions/us-central1/subnetworks/composer-subnet \
--cloud-composer-network-ip-range=172.30.0.0/16 \
--enable-private-endpoint
Node count is the floor for the GKE cluster that hosts the environment; task pods schedule above that floor and are billed like any other GKE workload. Keep the worker service account minimal: it needs BigQuery job user on target projects, storage object admin on pipeline buckets, and nothing else. Broad editor roles on the worker identity are the most common privilege escalation path in Composer environments.
Writing DAGs That Behave in Production
A production DAG is defined by what happens when things go wrong. Set retries and retry delay in default args, cap task runtime with execution timeout, and turn off catchup unless you genuinely want backfill on every deploy. Use Airflow 2 scheduling semantics: schedule_interval defines the cadence, and data intervals mean a daily DAG at 02:00 UTC covers the previous calendar day, which is what your BigQuery partition filters should assume.
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.providers.google.cloud.operators.bigquery import BigQueryInsertJobOperator
default_args = {
"owner": "data-engineering",
"depends_on_past": False,
"email_on_failure": True,
"email": ["[email protected]"],
"retries": 3,
"retry_delay": timedelta(minutes=5),
"execution_timeout": timedelta(hours=2),
"start_date": datetime(2024, 1, 1),
}
dag = DAG(
"daily_sales_pipeline",
default_args=default_args,
description="Load and transform daily sales data",
schedule_interval="0 2 * * *",
catchup=False,
max_active_runs=1,
tags=["production", "sales"],
)
def extract(**context):
ds = context["ds"]
print(f"Extracting partition {ds}")
extract_task = PythonOperator(task_id="extract", python_callable=extract, dag=dag)
transform_task = BigQueryInsertJobOperator(
task_id="transform",
configuration={
"query": {
"query": """
CREATE OR REPLACE TABLE `my-project.analytics.daily_sales` PARTITION BY sale_date
AS SELECT * FROM `my-project.staging.sales`
WHERE sale_date = @ds
""",
"useLegacySql": False,
"queryParameters": [
{
"name": "ds",
"parameterType": {"type": "DATE"},
"parameterValue": {"value": "{{ ds }}"},
}
],
}
},
location="US",
dag=dag,
)
extract_task >> transform_task
Two details in that DAG earn their keep under audit. max_active_runs=1 stops a slow run from stacking a second concurrent execution that double-writes the table. The templated query parameter binds the partition date through Jinja, so the SQL never interpolates a raw string that a malformed run date could inject.
Connections, Variables, and Environment Variables
Configuration in Composer splits across three stores with different security properties. Connections hold credentials and endpoints, support secret backends, and are what provider hooks resolve by gcp_conn_id. Variables hold non-secret runtime settings such as table names and thresholds, and they are visible to anyone with Airflow UI access. Environment variables are set at the environment level and visible in DAG code as plain strings, which makes them the right place for project ids and regions that are not secret but must be identical across every DAG.
from airflow.models import Variable
# Non-secret configuration lives in Variables, read at task runtime.
project = Variable.get("target_project", default_var="my-project")
lookback_days = Variable.get("sales_lookback_days", default_var="7", deserialize_json=False)
# Secrets belong in Connections backed by Secret Manager, not in Variables.
# Define once in the Airflow UI or with the REST API, then reference by id:
# gcp_conn_id="google_cloud_default"
Never store service account keys in Variables or in DAG files. Composer supports Workload Identity so the GKE pods impersonate a Google service account directly, which removes key material from the environment entirely. If a legacy tool requires a key file, mount it from Secret Manager at task start and delete it in the same task.
Operators Worth Knowing
The Google provider ships operators that wrap each GCP API, and picking the right one removes boilerplate. BigQueryInsertJobOperator runs a SQL job and waits for completion, which is the default for transformations. GCSToBigQueryOperator loads files without writing glue code. DataflowStartPythonPipelineOperator launches a Flex Template and can wait for the job, while DataprocSubmitJobOperator runs Spark or Hadoop on an existing cluster. For anything the operators do not cover, use the generic GoogleCloudBaseHook in a PythonOperator rather than shelling out to gcloud, because hooks inherit connection handling and retry configuration.
from airflow.providers.google.cloud.operators.dataproc import DataprocSubmitJobOperator
spark_job = {
"reference": {"project_id": "my-project", "job_id": None},
"placement": {"cluster_name": "etl-cluster"},
"spark_job": {
"mainJarFileUri": "gs://my-bucket/jobs/etl.jar",
"args": ["--date", "{{ ds }}"],
},
}
submit_spark = DataprocSubmitJobOperator(
task_id="submit_spark",
job=spark_job,
region="us-central1",
project_id="my-project",
dag=dag,
)
Monitoring and Alerting
Composer publishes metrics to Cloud Monitoring under the composer.googleapis.com namespace, including dag_run durations, failed task counts, and environment-level signals such as worker pod restarts and Cloud SQL disk usage. The two that trigger real pages are the failed task count, which should alert on any sustained nonzero rate, and the metadata database storage fill percentage, which grows silently until Cloud SQL refuses writes and every scheduler tick fails.
from google.cloud import monitoring_v3
client = monitoring_v3.AlertPolicyServiceClient()
project_name = "projects/my-project"
policy = monitoring_v3.AlertPolicy(
display_name="Composer failed tasks",
conditions=[
monitoring_v3.AlertPolicy.Condition(
display_name="Failed task rate",
condition_threshold=monitoring_v3.AlertPolicy.Condition.MetricThreshold(
filter='metric.type="composer.googleapis.com/environment/failed_task_count" '
'resource.type="composer_environment"',
comparison=monitoring_v3.ComparisonType.COMPARISON_GT,
threshold_value=0,
duration={"seconds": 300},
aggregations=[
monitoring_v3.Aggregation(
alignment_period={"seconds": 300},
per_series_aligner=monitoring_v3.Aggregation.Aligner.ALIGN_RATE,
)
],
),
)
],
alert_strategy=monitoring_v3.AlertPolicy.AlertStrategy(
auto_close={"seconds": 1800}
),
)
client.create_alert_policy(request={"name": project_name, "alert_policy": policy})
Pair the alert with log-based metric extraction for task failures so on-call sees which DAG and which task id broke, not just that something did. The Airflow UI remains the first stop for root cause, but Cloud Logging is where you query across DAG runs to answer questions such as how often the same task has retried this week. Log volume in Composer is itself a cost and a noise problem: task logs land in Cloud Storage and in the metadata database, so teams that print entire DataFrames into task logs pay twice, once in storage and once in the minutes an engineer spends scrolling. Prefer structured summaries in task logs and ship heavy diagnostics to a bucket path recorded in the task instance.
Common Mistakes
Installing packages at DAG parse time with pip
Fix: Declare PyPI packages in the environment software config so they bake into the image; runtime installs slow parsing and vanish on pod restart.
Storing secrets in Airflow Variables
Fix: Use Connections backed by Secret Manager or Workload Identity; Variables are plaintext and readable by anyone with UI access.
Leaving catchup enabled on newly created DAGs
Fix: Set catchup=False unless you intend a backfill; a forgotten start_date can schedule dozens of surprise runs that overwrite tables.
Best Practices
- Keep module-level imports light because the scheduler re-parses every DAG file on a short interval
- Pin the Airflow and provider versions together and upgrade in a development environment first
- Tag every DAG with an owner and environment so the UI filter doubles as an accountability map
Key Takeaways
- Composer 2 runs each task in its own GKE pod, so sizing is about environment size and max workers, not Airflow slots
- Environment size, Airflow version, and Python version are set at creation and constrain every later package choice
- Connections hold secrets, Variables hold non-secret config, and Workload Identity removes keys from the picture entirely
- Alert on failed task counts and metadata database disk usage, the two signals that precede every Composer outage
Interview Questions
Interview Questions
Q1: How does Composer 2 differ from Composer 1 operationally?
Composer 2 runs the control plane and task execution on GKE with one pod per task, adds environment autoscaling, and supports private endpoints; Composer 1 used Compute Engine VMs with fixed worker pools and longer environment creation times.
Q2: Where should DAG code live and how does it reach the environment?
In a Git repository; a CI/CD step syncs the DAG folder into the environment's Cloud Storage bucket. The scheduler picks up files within a minute and the web UI lists them once parsing succeeds.
Q3: Why is a DAG running but its tasks stuck in queued forever?
Usually the environment has no worker capacity left or the task pods cannot pull the image; check the GKE node pool, the worker service account permissions, and max_active_tasks limits on the environment.
Q4: How do you keep credentials out of DAG files?
Store them in Airflow Connections backed by Secret Manager, or eliminate them with Workload Identity so pods impersonate a Google service account; DAG code then references only the connection id.