Kubernetes Executor Deep Dive
Architecture Diagram
Formal Definitions
Detailed Explanation
What is the Kubernetes Executor?
The Kubernetes executor creates a separate pod for each task in your DAG. This provides complete isolation between tasks and dynamic resource allocation.
Key insight: Each task gets its own container with dedicated CPU, memory, and network resources, so no task can interfere with another task's execution, and the cluster returns every resource the moment the task ends. The price of that isolation is pod startup: image pull, scheduling and container boot are paid before a single line of task code runs.
How It Works
- Task Submission: Scheduler tells the K8s executor to run a task
- Pod Creation: Executor creates a new pod with the task's requirements
- Task Execution: Pod runs the task in isolation
- Cleanup: Pod is deleted after task completion (success or failure)
Basic K8s Executor Configuration
# airflow.cfg - Kubernetes executor configuration
[core]
executor = KubernetesExecutor
[kubernetes]
# Namespace for worker pods
namespace = airflow
# Worker pod image
worker_container_image = apache/airflow:2.8.0
# Service account name
worker_service_account_name = airflow-worker
# Resource limits for worker pods
worker_resource_request_cpu = 500m
worker_resource_request_memory = 1Gi
worker_resource_limit_cpu = 1000m
worker_resource_limit_memory = 2Gi
# Pod template file
pod_template_file = /opt/airflow/pod_templates/default_template.yaml
# Delete worker pods on success
delete_worker_pods = True
# Delete worker pods on failure
delete_worker_pods_on_failure = True
# Pod creation timeout (seconds)
pod_creation_timeout = 600
# Maximum number of pods per task
max_pod_pending_timeout = 600
# Image pull policy
image_pull_policy = IfNotPresent
# Node selector for worker pods
# worker_node_selector = {"node-type": "worker"}
# Tolerations for worker pods
# worker_tolerations = [{"key": "dedicated", "operator": "Equal", "value": "worker", "effect": "NoSchedule"}]
Pod Template Configuration
# pod_templates/default_template.yaml
apiVersion: v1
kind: Pod
metadata:
labels:
app: airflow-worker
component: worker
spec:
serviceAccountName: airflow-worker
containers:
- name: base
image: apache/airflow:2.8.0
command:
- "airflow"
- "serve-logs"
resources:
requests:
cpu: 500m
memory: 1Gi
limits:
cpu: 1000m
memory: 2Gi
env:
- name: AIRFLOW__CORE__EXECUTOR
value: "KubernetesExecutor"
- name: AIRFLOW__DATABASE__SQL_ALCHEMY_CONN
valueFrom:
secretKeyRef:
name: airflow-secrets
key: database-url
volumeMounts:
- name: airflow-config
mountPath: /opt/airflow/airflow.cfg
subPath: airflow.cfg
- name: dags
mountPath: /opt/airflow/dags
securityContext:
runAsUser: 50000
runAsGroup: 0
fsGroup: 0
volumes:
- name: airflow-config
configMap:
name: airflow-config
- name: dags
persistentVolumeClaim:
claimName: airflow-dags-pvc
nodeSelector:
node-type: worker
tolerations:
- key: "dedicated"
operator: "Equal"
value: "worker"
effect: "NoSchedule"
restartPolicy: Never
Custom Pod Templates per Task
from airflow.decorators import task, dag
from datetime import datetime
from kubernetes.client import models as k8s
def pod_with_resources(cpu_request, memory_request, cpu_limit, memory_limit):
"""Build an executor_config whose container name matches the pod template."""
return {
'pod_override': k8s.V1Pod(
spec=k8s.V1PodSpec(
containers=[
k8s.V1Container(
name='base',
resources=k8s.V1ResourceRequirements(
requests={'cpu': cpu_request, 'memory': memory_request},
limits={'cpu': cpu_limit, 'memory': memory_limit},
),
)
],
)
),
}
heavy_pod = pod_with_resources('2', '4Gi', '4', '8Gi')
light_pod = pod_with_resources('250m', '512Mi', '500m', '1Gi')
@dag(
schedule_interval="@daily",
start_date=datetime(2024, 1, 1),
catchup=False,
tags=['kubernetes', 'custom-pods'],
)
def custom_pod_dag():
@task(executor_config=heavy_pod)
def heavy_computation():
"""Task running in a pod sized for compute-heavy work."""
import time
time.sleep(10)
return {"status": "completed"}
@task(executor_config=light_pod)
def light_task():
"""Task running in a pod sized for short, cheap work."""
return {"status": "completed"}
heavy_computation() >> light_task()
custom_pod_dag()
Pod Lifecycle States
| State | Description | Next State |
|---|---|---|
| Pending | Pod created, waiting for scheduling | Scheduled |
| Scheduled | Node assigned to pod | Running |
| Running | Container started, task executing | Success or Failed |
| Succeeded | Task completed successfully | Cleanup |
| Failed | Task encountered an error | Retry (if retries > 0) |
| Cleanup | Pod resources being released | Deleted |
Anatomy of a Worker Pod
The pod template file is not a suggestion; the executor enforces two structural rules on it. First, spec.containers must begin with a container named base, and that container must carry an image, because Airflow merges per-task overrides into it by name and assumes the worker process lives in the first array position. Sidecar containers may follow. Second, metadata.name must be present even though the executor rewrites it on every launch to guarantee uniqueness â leaving it blank fails the template check. The scheduler then overwrites spec.containers[0].args with the command that runs the task, so a template that hard-codes its own arguments has them discarded.
Everything else in the template is yours: service account, node selector, tolerations, volumes, security context with the non-root user identifier that Airflow images expect, and environment values sourced from Kubernetes secrets rather than pasted plaintext. Overrides flow in three layers â the template is read first, the task's executor_config is merged on top of it, and configuration values such as the worker image win where the executor is designed to force them. That ordering explains why an image pinned in airflow.cfg can appear to ignore the image written in the template.
Two operational details decide whether the executor feels fast or slow. Pod creation rate is capped per heartbeat by worker_pods_creation_batch_size, which defaults to 1, so a DAG that releases two hundred tasks at once starts them one pod at a time and makes the cluster look idle while tasks sit in scheduled. The other detail is logging: worker pods are deleted when the task finishes, taking their local log files with them, while the webserver still tries to read those files. Without a remote logging backend, the Grid view shows log entries that no longer exist anywhere.
What Cannot Be Chosen at Run Time
Per-task pod shape is fixed when the DAG file is parsed. executor_config is serialized with the DAG and read by the scheduler when the task is queued, so it cannot be templated from an upstream XCom value, cannot depend on the logical date, and cannot vary between runs of the same task id. Choose one pod shape per task id, or push the variability somewhere else: run genuinely dynamic work through the KubernetesPodOperator, which launches a pod with whatever image and arguments you pass and does not require Airflow to be installed in that image.
Pod startup also sets a floor on task duration. A task that executes for eight seconds inside a pod that needs forty seconds to pull an image and boot has an effective throughput far below what the task metrics suggest. Mitigations are concrete: keep image_pull_policy at IfNotPresent, pre-warm nodes with a DaemonSet that pulls the worker image, host the registry close to the cluster, and merge short tasks into fewer, longer-running ones so the startup cost is amortized across real work rather than paid per tiny step.
Common Mistakes
The pod template names the worker container runner instead of base, and the template has no metadata.name
Fix: Name the first container base, give it an image, and set metadata.name to any placeholder value: Airflow merges per-task overrides by the base container name and rewrites the pod name at launch, but both fields must exist for the template to be accepted.
Hundreds of queued tasks sit in scheduled while the cluster has spare capacity
Fix: Raise worker_pods_creation_batch_size, which defaults to 1 pod per heartbeat, and lower the resource requests on the worker pod: a pod whose CPU request exceeds allocatable capacity stays Pending no matter how much room exists.
Task logs vanish moments after the pod finishes
Fix: Worker pods are deleted once the task completes, taking their local log files with them. Point logging at a remote backend such as S3, GCS or Azure Blob and grant the webserver read access, or delay deletion with delete_worker_pods set to False while you migrate.
Key Concepts Table
| Component | Purpose | Configuration | Impact |
|---|---|---|---|
| Executor | Task dispatch | executor = KubernetesExecutor | Core |
| Namespace | Isolation | namespace = airflow | Security |
| Pod Template | Pod configuration | pod_template_file | Flexibility |
| Resources | CPU/Memory limits | worker_resource_* | Performance |
| Node Selector | Pod placement | worker_node_selector | Cost |
| Tolerations | Schedule on tainted nodes | worker_tolerations | Availability |
| Service Account | RBAC | worker_service_account_name | Security |
Code Examples
Advanced K8s Executor Configuration
# k8s_executor_advanced.py
from airflow.configuration import conf
from airflow.kubernetes.pod_generator import PodGenerator
from kubernetes.client import V1Pod, V1Container, V1ResourceRequirements
def create_custom_pod_template():
"""Create custom pod template for specific workloads."""
container = V1Container(
name='base',
image='apache/airflow:2.8.0-python3.10',
command=['airflow', 'serve-logs'],
resources=V1ResourceRequirements(
requests={'cpu': '1', 'memory': '2Gi'},
limits={'cpu': '2', 'memory': '4Gi'},
),
env=[
{'name': 'AIRFLOW__CORE__EXECUTOR', 'value': 'KubernetesExecutor'},
],
volume_mounts=[
{'name': 'dags', 'mountPath': '/opt/airflow/dags'},
],
)
pod = V1Pod(
metadata={'labels': {'component': 'worker', 'workload': 'heavy'}},
spec={
'containers': [container],
'volumes': [
{'name': 'dags', 'persistentVolumeClaim': {'claimName': 'airflow-dags'}},
],
'nodeSelector': {'node-type': 'compute-optimized'},
'tolerations': [
{'key': 'workload', 'operator': 'Equal', 'value': 'heavy', 'effect': 'NoSchedule'},
],
},
)
return PodGenerator.serialize_pod(pod)
# Use in airflow.cfg
# pod_template_file = /opt/airflow/pod_templates/heavy_computation.yaml
Pod Monitoring and Cleanup
# pod_monitoring.py
from kubernetes import client, config
from datetime import datetime, timedelta
import logging
logger = logging.getLogger(__name__)
class PodMonitor:
"""Monitor and manage Airflow worker pods."""
def __init__(self, namespace='airflow'):
config.load_incluster_config()
self.v1 = client.CoreV1Api()
self.namespace = namespace
def list_worker_pods(self):
"""List all Airflow worker pods."""
pods = self.v1.list_namespaced_pod(
namespace=self.namespace,
label_selector='component=worker',
)
return pods.items
def get_pod_status(self, pod_name):
"""Get status of a specific pod."""
pod = self.v1.read_namespaced_pod(
name=pod_name,
namespace=self.namespace,
)
return {
'name': pod.metadata.name,
'status': pod.status.phase,
'start_time': pod.status.start_time,
'node_name': pod.spec.node_name,
}
def cleanup_old_pods(self, max_age_hours=24):
"""Clean up pods older than max_age_hours."""
cutoff_time = datetime.now() - timedelta(hours=max_age_hours)
pods = self.list_worker_pods()
cleaned = 0
for pod in pods:
if pod.status.start_time and pod.status.start_time.replace(tzinfo=None) < cutoff_time:
if pod.status.phase in ['Succeeded', 'Failed']:
try:
self.v1.delete_namespaced_pod(
name=pod.metadata.name,
namespace=self.namespace,
)
cleaned += 1
logger.info(f"Deleted pod: {pod.metadata.name}")
except Exception as e:
logger.error(f"Failed to delete pod {pod.metadata.name}: {e}")
return cleaned
def get_pod_metrics(self):
"""Get metrics for all worker pods."""
pods = self.list_worker_pods()
metrics = {
'total': len(pods),
'running': 0,
'pending': 0,
'succeeded': 0,
'failed': 0,
}
for pod in pods:
status = pod.status.phase
if status == 'Running':
metrics['running'] += 1
elif status == 'Pending':
metrics['pending'] += 1
elif status == 'Succeeded':
metrics['succeeded'] += 1
elif status == 'Failed':
metrics['failed'] += 1
return metrics
if __name__ == "__main__":
monitor = PodMonitor()
# Get pod metrics
metrics = monitor.get_pod_metrics()
print(f"Pod metrics: {metrics}")
# Cleanup old pods
cleaned = monitor.cleanup_old_pods(max_age_hours=12)
print(f"Cleaned up {cleaned} pods")
Resource-Aware Scheduling
from airflow.decorators import task, dag
from kubernetes import client, config
from kubernetes.client import models as k8s
from datetime import datetime
# Pod shapes are declared at parse time: executor_config is serialized with the
# DAG and is never templated from an upstream XCom value.
medium_pod = {
'pod_override': k8s.V1Pod(
spec=k8s.V1PodSpec(
containers=[
k8s.V1Container(
name='base',
resources=k8s.V1ResourceRequirements(
requests={'cpu': '1', 'memory': '2Gi'},
limits={'cpu': '2', 'memory': '4Gi'},
),
)
],
)
),
}
@dag(
schedule_interval="@hourly",
start_date=datetime(2024, 1, 1),
catchup=False,
tags=['kubernetes', 'resource-aware'],
)
def resource_aware_k8s_dag():
@task
def check_cluster_resources():
"""Check available cluster resources."""
config.load_incluster_config()
v1 = client.CoreV1Api()
# Get node resources
nodes = v1.list_node()
total_cpu = 0
total_memory = 0
available_cpu = 0
available_memory = 0
for node in nodes.items:
if node.status.allocatable:
total_cpu += int(node.status.allocatable.get('cpu', 0))
total_memory += int(node.status.allocatable.get('memory', '0Gi').replace('Gi', ''))
# Get resource requests from running pods
pods = v1.list_namespaced_pod(namespace='airflow')
for pod in pods.items:
if pod.status.phase == 'Running' and pod.spec.containers:
for container in pod.spec.containers:
if container.resources.requests:
available_cpu -= int(container.resources.requests.get('cpu', '0').replace('m', '') or 0) / 1000
available_memory -= int(container.resources.requests.get('memory', '0Gi').replace('Gi', '') or 0)
return {
'total_cpu': total_cpu,
'total_memory': total_memory,
'available_cpu': max(0, total_cpu - available_cpu),
'available_memory': max(0, total_memory - available_memory),
}
@task
def adaptive_resource_allocation(resources: dict):
"""Allocate resources based on cluster availability."""
if resources['available_cpu'] > 4:
return {'cpu': '2', 'memory': '4Gi', 'priority': 'high'}
elif resources['available_cpu'] > 2:
return {'cpu': '1', 'memory': '2Gi', 'priority': 'medium'}
else:
return {'cpu': '500m', 'memory': '1Gi', 'priority': 'low'}
@task(executor_config=medium_pod)
def process_with_adaptive_resources(resources: dict):
"""Run in a fixed medium pod and record what the sizing task decided."""
return {
'requested_cpu': resources['cpu'],
'requested_memory': resources['memory'],
'allocated_cpu': '1',
'status': 'processing',
}
cluster_resources = check_cluster_resources()
resource_allocation = adaptive_resource_allocation(cluster_resources)
process_with_adaptive_resources(resource_allocation)
resource_aware_k8s_dag()
Performance Metrics
K8s Executor vs Other Executors
| Metric | Sequential | Local | Celery | Kubernetes |
|---|---|---|---|---|
| Startup Time | 0s | 0s | 10-30s | 30-60s |
| Isolation | None | Process | Container | Pod |
| Scaling | Manual | Manual | Static | Dynamic |
| Resource Efficiency | Low | Medium | Medium | High |
| Cost | Low | Low | Medium | Variable |
| Multi-tenancy | No | No | Limited | Yes |
Pod Resource Optimization
| Workload Type | CPU Request | Memory Request | Cost/Pod-Hour |
|---|---|---|---|
| Light Task | 250m | 512Mi | $0.02 |
| Medium Task | 1 CPU | 2Gi | $0.08 |
| Heavy Task | 2 CPU | 4Gi | $0.16 |
| GPU Task | 2 CPU + 1 GPU | 8Gi | $1.50 |
Best Practices for K8s Executor
- Set resource requests and limits to prevent pods from consuming excessive cluster resources
- Use pod templates to customize worker configurations for different workload types
- Enable pod cleanup (
delete_worker_pods = True) to prevent resource leaks - Configure node selectors to place pods on appropriate node pools
- Use service accounts with minimal RBAC permissions for security
- Monitor pod metrics to optimize resource allocation and costs
See Also
- Executors Comparison â Comparing all executor types
- Performance Tuning â Optimizing executor performance
- Monitoring and Alerting â Monitoring pod metrics
- Multi-Tenancy â Isolating workloads with K8s