DEV Community

Cover image for Airflow for Agent Orchestration: When DAG Schedulers Meet Non-Deterministic Workflows
mech.app
mech.app

Posted on Originally published at mech.app

Airflow for Agent Orchestration: When DAG Schedulers Meet Non-Deterministic Workflows

Apache Airflow was built to schedule data pipelines. Directed acyclic graphs (DAGs) define task dependencies, operators execute SQL or Python, and the scheduler ensures everything runs in order. The primitives are deterministic: given the same inputs, you get the same outputs.

Now teams are retrofitting Airflow to orchestrate agents. The 47,000-star project is trending because its maturity in production environments makes it a natural candidate for multi-agent coordination. But the impedance mismatch is real. Agents produce variable-length context, make non-deterministic tool calls, and follow reasoning paths that weren't known when you defined the graph.

This article examines how Airflow's plumbing holds up when you replace SQL operators with LLM-powered agents, where the failure modes shift, and what observability gaps appear.

The DAG Primitive and Agent Workflows

Airflow DAGs are Python code that declares task dependencies. Each task is an operator instance: BashOperator, PythonOperator, KubernetesPodOperator. The scheduler reads the DAG, builds a dependency graph, and queues tasks when upstream dependencies complete.

For data pipelines, this works because tasks are idempotent. Re-running a SQL transform with the same input produces the same output. Retries are safe. Task boundaries are clean.

Agent workflows break these assumptions:

  • Non-determinism: An agent calling a search tool may return different results on retry.
  • Variable outputs: One run produces 200 tokens, the next produces 2,000.
  • Dynamic branching: The agent decides which tool to call next based on runtime reasoning, not graph-time logic.

Airflow's task model assumes you know the graph structure before execution. Agents want to discover the graph as they run.

XCom and State Passing

Airflow's cross-communication (XCom) system lets tasks pass small data blobs to downstream tasks. A task pushes a value to XCom, and the next task pulls it.

def extract_data(**context):
    result = {"user_id": 123, "score": 0.87}
    context['ti'].xcom_push(key='user_data', value=result)

def process_data(**context):
    data = context['ti'].xcom_pull(key='user_data')
    # Use data
Enter fullscreen mode Exit fullscreen mode

XCom is backed by the Airflow metadata database (Postgres or MySQL). It's designed for small payloads: configuration values, file paths, row counts.

When you replace extract_data with an agent that produces a multi-turn conversation history, XCom becomes a bottleneck:

  • Size limits: XCom stores values as pickled blobs. Large context windows (32k tokens) exceed practical database column sizes.
  • Schema drift: Agents produce unstructured outputs. Downstream tasks can't assume a fixed schema.
  • Serialization: Pickle works for Python objects, but agents often return JSON, XML, or raw text that needs custom serialization.

Workarounds in Production

Teams using Airflow for agents typically bypass XCom for large state:

  • Object storage: Push conversation history to S3/GCS, pass the object key via XCom.
  • External state stores: Use Redis or a vector database for agent memory, pass only identifiers through XCom.
  • Task output truncation: Log full outputs to observability systems, pass summaries through XCom.

This works but adds latency and complexity. You're now managing state in three places: Airflow metadata, object storage, and the agent's memory layer.

Retries and Non-Deterministic Failures

Airflow's retry logic is built for transient failures: network timeouts, database locks, rate limits. You configure retries=3 and retry_delay=timedelta(minutes=5), and the scheduler re-queues the task.

For deterministic operators, retries are safe. For agents, retries introduce new failure modes:

Scenario Deterministic Operator Agent Operator
Network timeout Retry succeeds with same result Retry may call different tools or produce different reasoning
Rate limit Backoff and retry Agent context may expire, losing conversation state
Partial completion Idempotent, safe to re-run Agent may duplicate tool calls or lose partial progress
Upstream data change Detectable via checksums Agent may incorporate new data mid-reasoning without detection

The core issue: Airflow retries assume tasks are stateless or externally state-managed. Agents carry internal state (conversation history, reasoning traces) that doesn't survive a retry unless you explicitly persist it.

Handling Agent Retries

Practical approaches:

  • Checkpoint agent state: Before each tool call, persist the agent's memory to external storage. On retry, restore from the last checkpoint.
  • Idempotency tokens: Pass a unique execution ID to the agent. If the agent sees the same ID twice, it skips already-completed tool calls.
  • Retry budgets: Limit retries to 1 for agent tasks. If it fails, escalate to a human-in-the-loop task instead of retrying indefinitely.

None of these are native Airflow features. You're building them in custom operators or task wrappers.

Dynamic Branching and Graph-Time Constraints

Airflow's BranchPythonOperator lets you choose which downstream task to execute based on runtime logic:

def choose_branch(**context):
    if context['ti'].xcom_pull(key='score') > 0.8:
        return 'high_confidence_task'
    else:
        return 'low_confidence_task'

branch = BranchPythonOperator(
    task_id='branch_decision',
    python_callable=choose_branch
)
Enter fullscreen mode Exit fullscreen mode

This works when the set of possible branches is known at graph-definition time. Agents often want to branch to tasks that don't exist yet:

  • An agent decides it needs to call a new API based on search results.
  • An agent spawns a sub-agent to handle a specific subtask.
  • An agent requests human approval before proceeding, but the approval task wasn't in the original DAG.

Airflow's scheduler parses DAGs before execution. You can't add tasks mid-run without triggering a new DAG run or using dynamic task mapping (introduced in Airflow 2.3).

Dynamic Task Mapping

Airflow 2.3+ supports dynamic task mapping, where a task generates a list of inputs and Airflow creates task instances for each:

@task
def generate_agent_tasks():
    return [{"tool": "search", "query": "X"}, {"tool": "api", "endpoint": "Y"}]

@task
def run_agent(config):
    # Execute agent with config
    pass

run_agent.expand(config=generate_agent_tasks())
Enter fullscreen mode Exit fullscreen mode

This helps when an agent needs to spawn parallel subtasks, but it still requires the parent task to know the full list of subtasks upfront. True dynamic branching (where the agent discovers new tasks mid-execution) requires custom orchestration logic outside Airflow's DAG model.

Executor Models and Agent Concurrency

Airflow supports multiple executors:

  • LocalExecutor: Runs tasks as subprocesses on a single machine.
  • CeleryExecutor: Distributes tasks across worker nodes via Celery queues.
  • KubernetesExecutor: Spawns a Kubernetes pod per task.

For data pipelines, executor choice is about scale and isolation. For agents, it's about resource allocation and security boundaries.

Resource Isolation

Agents often need:

  • GPU access for local model inference.
  • Memory isolation to prevent one agent's context from leaking to another.
  • Network policies to restrict which APIs an agent can call.

KubernetesExecutor is the best fit here. Each agent task runs in its own pod with resource limits, network policies, and secrets mounted per-task. But this adds overhead: pod startup latency (5-15 seconds) and Kubernetes API load.

CeleryExecutor is faster but shares worker processes across tasks. If one agent task consumes 8GB of RAM, it affects other tasks on the same worker. You need careful worker pool segmentation and task routing.

Concurrency and Rate Limits

Agents calling external APIs (OpenAI, Anthropic, search engines) hit rate limits. Airflow's concurrency controls are coarse:

  • max_active_tasks_per_dag: Limits total tasks running for a DAG.
  • max_active_runs_per_dag: Limits concurrent DAG runs.
  • Pool slots: Assign tasks to pools with fixed concurrency limits.

These work for controlling database connections or API quotas, but agents need finer-grained rate limiting:

  • Per-model rate limits (GPT-4 vs. GPT-3.5).
  • Per-user quotas when agents act on behalf of end users.
  • Adaptive backoff when rate limits change dynamically.

You end up implementing rate limiting inside the agent operator, not relying on Airflow's pool system.

Observability Gaps

Airflow's UI shows task status, logs, and duration. For data pipelines, this is enough. For agents, you need:

  • Tool call traces: Which tools did the agent call, in what order, with what arguments?
  • Token usage: How many tokens did each agent task consume?
  • Reasoning paths: Why did the agent choose tool X over tool Y?
  • Failure attribution: Did the agent fail because of a bad LLM response, a tool error, or a logic bug?

Airflow logs capture stdout/stderr, but structured agent telemetry requires external observability:

  • OpenTelemetry spans: Instrument agent operators to emit spans for each tool call.
  • LangSmith/Weights & Biases: Log agent traces to specialized platforms.
  • Custom metrics: Push token counts, latency, and error rates to Prometheus or Datadog.

The gap: Airflow's metadata database doesn't store this telemetry. You're building a parallel observability stack and correlating it with Airflow task IDs.

Architecture: Airflow as Agent Coordinator

Here's a practical architecture for using Airflow to orchestrate agents:

┌─────────────────────────────────────────────────┐
│ Airflow Scheduler                               │
│ - Parses DAGs                                   │
│ - Queues agent tasks                            │
│ - Manages retries (limited to 1 per agent task)│
└─────────────────┬───────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────┐
│ KubernetesExecutor                              │
│ - Spawns pod per agent task                    │
│ - Mounts secrets (API keys, credentials)       │
│ - Enforces resource limits (CPU, memory, GPU)  │
└─────────────────┬───────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────┐
│ Agent Operator (Custom)                         │
│ - Loads agent state from Redis/S3               │
│ - Executes agent with tool access               │
│ - Persists state after each tool call           │
│ - Emits OpenTelemetry spans                     │
│ - Pushes summary to XCom, full output to S3    │
└─────────────────┬───────────────────────────────┘
                  │
                  ▼
┌─────────────────────────────────────────────────┐
│ External Systems                                │
│ - Redis: Agent memory and checkpoints           │
│ - S3: Large outputs (conversation history)      │
│ - LangSmith: Agent trace logs                   │
│ - Prometheus: Token usage, latency metrics      │
└─────────────────────────────────────────────────┘
Enter fullscreen mode Exit fullscreen mode

Key decisions:

  • State management: Use Redis for fast access to agent memory, S3 for archival.
  • Retry strategy: Limit retries to 1, checkpoint state before each tool call.
  • Observability: Emit OpenTelemetry spans from agent operators, correlate with Airflow task IDs.
  • Executor: KubernetesExecutor for isolation, with pod templates per agent type.

When Airflow Breaks Down

Airflow struggles when:

  • Agents need real-time interaction: Airflow's scheduler polls every few seconds. If an agent needs to respond to a user within 200ms, Airflow adds too much latency.
  • Graph structure is fully dynamic: If agents discover 90% of tasks at runtime, you're fighting Airflow's graph-time constraints.
  • State is too large: If agent memory exceeds 10MB, XCom and database storage become bottlenecks.

In these cases, consider:

  • Temporal: Workflow engine with first-class support for long-running, stateful processes.
  • LangGraph: Purpose-built for agent workflows with dynamic graphs.
  • Custom orchestration: FastAPI + Celery + Redis for full control over agent coordination.

Technical Verdict

Use Airflow for agent orchestration when:

  • You already run Airflow in production and want to add agent tasks to existing DAGs.
  • Agent workflows have predictable structure (80%+ of tasks known at graph-time).
  • You need mature scheduling features (cron, backfills, SLA monitoring).
  • Agents produce small outputs (< 1MB) or you're willing to manage external state storage.

Avoid Airflow when:

  • Agents need sub-second response times.
  • Graph structure is fully dynamic (agents discover most tasks at runtime).
  • You need built-in agent observability (tool traces, token usage, reasoning logs).
  • Your team doesn't already operate Airflow (the operational overhead is high).

Airflow is production-grade infrastructure being repurposed for a workload it wasn't designed for. It works if you're willing to build the missing pieces: external state management, custom retry logic, parallel observability, and dynamic task generation. If you're starting from scratch, purpose-built agent orchestration frameworks will save you months of plumbing work.

Source Links

Top comments (1)

Collapse
 
mickyarun profile image
arun rajkumar •

The retries row in your table has a borrowed answer available, and the borrowing is not loose.

Payments retries non-idempotent operations constantly. The mechanism is that the caller mints a key before the first attempt, scoped to the intent rather than to the attempt, and the receiving side replays the first outcome for any later call carrying that key. The retry becomes a read of a decision already made rather than a second decision.

Mapping that onto Airflow is mostly a question of where the key comes from, and there is one trap in it. It cannot come from the agent, because an agent on retry may reason its way to a different call and mint a different key, which is the duplicate you were preventing. It has to be derived from the task instance: dag_id, task_id, logical date, plus a counter of calls within the run. Specifically not try_number. Include that and every retry mints a fresh key and every external call executes again, which is the behaviour you were trying to fix.

That also gives XCom less to carry. If each consequential call has a stable key, the downstream task can read the outcome from wherever the tool recorded it rather than having state passed through the metadata database. Your object-storage workaround stays, but what sits in XCom becomes a key instead of a pointer, and a key is safe to re-read after a retry in a way that a pointer to a half-written blob is not.

Where it stops: this only works for calls with a server side willing to honour a key. A read-only search that returns different results on retry has nothing to replay, and the honest handling there is to pin the first result into the run rather than call again — which means the non-determinism moves into storage and stops being a retry problem at all.