---
title: 'Error Handling and Dead Letter Queues in ADK Workflows'
date: '2026-12-02T08:24:49+07:00'
description: 'Catch node failures in ADK graph workflows with RetryConfig and timeouts, then build a dead-letter branch that records the error payload for replay and alerting.'
author: 'AI Assistant'
image: 'https://blog.redlinesoft.net/images/post/adk-workflow-error-handling-dead-letter-queues.jpg'
alt: 'A task graph where a failing node diverts to a dead-letter node that records the error payload'
tags: ['google-adk', 'adk-2-0', 'workflows', 'error-handling', 'reliability']
---

A workflow that runs perfectly in a demo will still meet a model API that returns a 429, a CRM that times out, and a database connection that drops mid-write. The question is never *whether* a node fails — it is what your graph does in the second after it fails. If the answer is "the whole run explodes with a stack trace and the input is gone," you have an outage instead of a retry.

ADK 2.0 gives you two layers of defense: a declarative **retry policy and timeout per node**, and — because a graph is just code — a **failed-branch node** you can build yourself that captures the error payload, alerts a human, and parks the input for replay. In this tutorial you will learn exactly what the framework does with an unhandled exception, how `RetryConfig` decides what to retry, and how to pattern a dead-letter queue on top of the routing primitives you already have.

## Prerequisites

- ADK Python v2.0.0 or newer (`pip install google-adk`), since `RetryConfig`, `node()`, and graph `Workflow` are ADK 2.0 APIs.
- Familiarity with graph workflows: `Workflow`, `edges`, `START`, and `Event(route=...)` dispatch. If those are new, start with the [graph workflows overview](https://adk.dev/graphs/) and the conditional-routing guide.
- An `Event`-yielding mental model of the runtime: the `Runner` receives each yielded event, commits its actions through the `SessionService`, and only then lets your node resume.

## 1. What the framework does when a node throws

Start with the baseline, because everything else is a refinement of it:

- **A node with no retry policy is not retried.** One exception, and that node fails immediately.
- **When a node with a retry policy exhausts its attempts, it fails with the error from the last attempt, and the workflow fails with it.** The error propagates out of the run — there is no automatic branch to a recovery path.
- **Events already yielded stay committed.** The `Runner` processes and commits each event *before* your execution logic resumes, so everything the workflow reported up to the failure point is durably in session history. You can always reconstruct how far a run got.

That third point matters for operations: a crash does not erase the trail. What ADK does *not* give you is a built-in dead-letter node or an `on_failure` edge. Failed-node routing is something you compose out of the same routing primitives you use for normal branching.

## 2. Retry-then-fail: attach a policy to the node

A retry policy lives on the node that can fail, declared with the `node()` decorator alongside its timeout:

```python
import random

from google.adk import Context, Event, Workflow
from google.adk.workflow import NodeTimeoutError, RetryConfig, node


class ServiceUnavailableError(Exception):
    """Stands in for a transient failure from a remote service."""


@node(
    retry_config=RetryConfig(
        max_attempts=3,             # 1 original attempt + 2 retries
        initial_delay=1.0,          # seconds before the first retry
        exceptions=[ServiceUnavailableError, NodeTimeoutError],
    ),
    timeout=10.0,                  # seconds allowed for each attempt
)
async def fetch_forecast(ctx: Context):
    """Simulates an unreliable call to a forecast service."""
    yield Event(message=f"Fetching forecast, attempt {ctx.attempt_count}")
    if random.random() < 0.5:
        raise ServiceUnavailableError("Forecast service unavailable")
    yield "sunny"


def report_forecast(node_input: str):
    return Event(message=f"The forecast is {node_input}.")


root_agent = Workflow(
    name="forecast_workflow",
    edges=[("START", fetch_forecast, report_forecast)],
)
```

Three behaviors are worth pinning down:

- **`max_attempts` counts the original attempt.** A value of 3 allows 2 retries; 0 or 1 disables retries.
- **Backoff is exponential by default.** The defaults are an initial delay of 1 second, a backoff factor of 2.0, a maximum delay of 60 seconds, and a jitter factor of 1.0 — so base waits of 1, 2, 4, 8 seconds, each jittered so that a fleet of failing nodes does not retry in lockstep. Set `jitter=0` in tests for deterministic timing.
- **`ctx.attempt_count` starts at 1**, so your node can log or branch on which attempt is running.

### Timeouts are per attempt, not per node

`timeout` limits a *single* attempt; the waits between attempts do not count toward it. When an attempt overruns, ADK stops it and raises `NodeTimeoutError` — which your policy only retries if you listed it in `exceptions`. A timeout without a retry policy fails the node the first time it fires.

## 3. Retry only the errors that can succeed later

The single most valuable line in a `RetryConfig` is `exceptions=[...]`. By default a retry policy retries *almost every error*, and that is usually wrong:

> An error caused by bad input or a bug fails the same way on every attempt. Retrying it only delays the failure.

List connection errors, rate limits, and timeouts. Leave `ValueError`, schema-validation failures, and programming bugs out so they fail fast. In Python the `exceptions` setting takes exception classes (or class names), and a listed class also matches its subclasses — so listing a broad `TransientError` base class is a legitimate strategy if your code raises typed subclasses.

Put the policy on the node that actually calls the unreliable service, not on a parent. You can attach a retry policy to a nested workflow so that a failure of any node inside it retries the whole child graph, but that re-runs far more work than retrying one flaky call.

## 4. Make retried work idempotent

A retry runs the **whole node again**. If your node writes to an external system before it fails, that write can happen twice — the classic double-charge, double-email, double-row bug.

Two options, straight from the reliability playbook:

1. **Design the side effect to be repeating-safe.** An `UPDATE ... WHERE id = ?` with the same value, an idempotency key on the API call, an upsert keyed on a natural key — anything where a second execution has no extra effect.
2. **Split the node.** Put the unreliable read in one node and the write in a *separate* node that only runs after the read succeeds. Now the retry re-runs the read, and the write happens exactly once.

Option 2 is the cleaner graph design, and it costs you one edge.

## 5. The dead-letter branch: catching failures yourself

Since an unhandled error fails the workflow, the pattern for a dead-letter queue is to *catch inside the node and route out of it*. A guarded node turns an exception into a route value plus an error payload:

```python
from google.adk import Event, Workflow
from google.adk.workflow import DEFAULT_ROUTE


def fetch_customer_record(node_input: str):
    """Calls an unreliable API but never lets the exception escape."""
    try:
        record = crm_api.get(node_input)
    except Exception as exc:
        return Event(
            route="FAILED",                       # dispatch key
            output={"input": node_input,          # error payload for replay
                    "error": repr(exc)},
        )
    return Event(route="OK", output=record)


def handle_success(record: dict):
    return Event(message=f"Updated {record['id']}.")


def record_failure(payload: dict):
    """Dead-letter node: persist, alert, acknowledge."""
    dead_letter_queue.push(payload)
    alert_oncall(payload)
    return Event(
        state={"last_failure": payload},
        message="We hit a problem and saved your request for replay.",
    )


root_agent = Workflow(
    name="guarded_workflow",
    edges=[
        ("START", fetch_customer_record),
        (fetch_customer_record, {
            "OK": handle_success,
            "FAILED": record_failure,
            DEFAULT_ROUTE: record_failure,   # fail safe, not fail silent
        }),
    ],
)
```

Notice that `route` and `output` are independent fields on the same `Event`, so one return selects the branch *and* hands the error payload to it. The dead-letter node is an ordinary function node — it could just as easily be an `Agent` that drafts a status update, or an entire nested `Workflow` that runs a triage procedure.

Two structural rules still apply: `DEFAULT_ROUTE` should always be present (classifiers and guard conditions botch things your tests never imagined), and if both branches must produce an `output` for a downstream node, merge them with a `JoinNode` before the graph ends — a workflow may have at most one terminal node that produces output.

## 6. Record the payload, then replay it idempotently

A dead-letter node that only logs to stdout is a tombstone, not a queue. Persist the *replayable input*, not just the exception string:

```python
def replay_failure(payload: dict):
    """Re-drive a dead-lettered input through the happy path."""
    return Event(output=payload["input"])
```

Replay safety comes from two directions:

- **The recorded payload is the original node input**, so replaying is just feeding that value back into `START` of the guarded graph — no guessing at partial state.
- **The happy path is idempotent** (section 4), so a replay that races with a half-completed original run converges instead of duplicating.

Add a replay guard — a `replay_count` in the payload, a maximum of three re-drives, then escalate to a human — because a deterministically broken input will fail forever and you do not want an infinite replay loop.

## 7. Alerting without a monitoring stack

You do not need a separate observability pipeline to get paged. The dead-letter node is code:

```python
def alert_oncall(payload: dict) -> None:
    """POSTs to your on-call webhook; swap for Slack/PagerDuty/Opsgenie."""
    requests.post(
        os.environ["ONCALL_WEBHOOK"],
        json={"text": f"Workflow failure: {payload['error']}"},
        timeout=5,
    )
```

Keep the alert *inside* the dead-letter branch rather than in a `finally` block around the whole workflow: you want one alert per failed input, deduplicated by the queue, not one per retry attempt. The state write (`state={"last_failure": ...}`) and the user-facing `message` ride along on the same event, so the audit trail, the queue entry, and the user acknowledgment are all one committed transaction.

## 8. The attempt-count limitation you must design around

One documented limitation bites hard in production:

> ADK keeps the attempt count in memory for the current run of the node. If the workflow pauses — for example for human input — or the application restarts, a node that runs again after the workflow resumes starts from attempt 1 with all of its attempts available.

In practice this means a restart can grant a node a fresh set of attempts. If that matters (a node with expensive side effects, a strict rate-limit budget), enforce your own budget in state — a `temp:retry_budget` key decremented per attempt — rather than trusting `ctx.attempt_count` to survive a process boundary.

## Checklist

Before you ship a graph that can fail:

- [ ] Every node that calls a remote service has an explicit `exceptions=[...]` list of *transient* errors only.
- [ ] Timeouts are set on each flaky node, and `NodeTimeoutError` is listed if you want timeouts retried.
- [ ] Retried nodes are idempotent, or the side effect lives in a separate downstream node.
- [ ] A guarded node catches broadly and returns `Event(route="FAILED", output=<error payload>)`.
- [ ] The dispatch dict covers every route plus `DEFAULT_ROUTE`, and the default branch is the dead-letter node — not `pass`.
- [ ] The dead-letter node persists the replayable input, alerts once, and acknowledges the user.
- [ ] Replay is bounded (max re-drives) and the happy path is safe to re-run.
- [ ] Your retry budget does not depend on `ctx.attempt_count` surviving a restart.

## Conclusion

Retries buy you resilience against the failures you can predict; a dead-letter branch buys you correctness for the failures you cannot. ADK gives you the first as configuration and the second as composition — a `try`/`except` that becomes a route value, a dispatch table that names the failure path explicitly, and an event history that already recorded every step before the crash. Build both layers, and a bad hour becomes a queue item instead of an incident.

## References

- https://adk.dev/graphs/retry/
- https://adk.dev/workflows/
- https://adk.dev/runtime/event-loop/
- https://adk.dev/graphs/
- https://adk.dev/graphs/data-handling/
