---
title: "Handling Sub-Agent Failures: Partial Success and Circuit Breakers"
date: "2026-11-30T10:17:02+07:00"
description: "Make ADK multi-agent runs survive failure: record partial success in session state, add a circuit breaker around flaky sub-agents, and retry only transient errors."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-sub-agent-failures-circuit-breakers.jpg"
alt: "Multi-agent pipeline with a circuit breaker guarding a failing sub-agent branch"
tags: ['google-adk', 'error-handling', 'circuit-breaker', 'multi-agent', 'reliability']
---

A four-stage research pipeline runs beautifully in development and then, on the first real production day, the enrichment service returns 503 for eleven minutes. What happens next defines whether your system is an agent or a liability: either the exception bubbles up and the *entire* invocation dies with no usable output, or worse, a sub-agent fails quietly, writes nothing to state, and the next stage happily summarizes an empty string as if it were the answer.

Neither outcome is acceptable, and neither is inevitable. This tutorial covers three layers of defense for sub-agent failures in the Google Agent Development Kit (ADK): making every stage produce an explicit **partial-success envelope**, wrapping flaky dependencies in a **circuit breaker** that fails fast instead of hammering a dead service, and choosing **where retries belong** — including ADK's built-in `RetryConfig` for workflow nodes.

---

## 1. A Failure Taxonomy Worth Coding Against

Not all failures deserve the same response, so name them before you handle them:

```
┌──────────────────────────────────────────────────────────────────┐
│ Failure class        │ Example                  │ Response       │
├──────────────────────┼──────────────────────────┼────────────────┤
│ Transient            │ 503, timeout, rate limit  │ retry + jitter │
│ Deterministic        │ bad input, 404, schema err │ never retry    │
│ Partial              │ 3 of 5 sources fetched    │ continue + flag│
│ Catastrophic         │ model auth failure        │ abort cleanly  │
│ Dependency down      │ enrichment API 503 x N     │ circuit open   │
└──────────────────────┴──────────────────────────┴────────────────┘
```

The core mistake is treating "the sub-agent threw" as a single category. Retrying a deterministic error just delays the same failure; swallowing a catastrophic error produces confident garbage.

---

## 2. Partial Success Is a Data Model, Not an Exception

The single highest-leverage change: **every stage writes a result envelope instead of raw output.** The envelope says what happened, how much of it happened, and what downstream stages should do.

```python
import json
from google.adk.agents import Agent
from google.adk.tools import ToolContext

def fetch_enrichment(record_id: str, tool_context: ToolContext) -> dict:
    """Fetch enrichment data for one record.

    Never raises: returns an envelope the calling model can act on.
    """
    try:
        data = enrichment_client.get(record_id, timeout=10)   # may raise
        status = "ok"
    except TimeoutError:
        status = "transient_error"
        data = None
    except NotFound:
        status = "not_found"          # deterministic — do not retry
        data = None

    # Track per-stage outcome in session state so the orchestrator can audit it.
    history = tool_context.state.get("enrichment:results", {})
    history[record_id] = status
    tool_context.state["enrichment:results"] = history

    return {"status": status, "record_id": record_id, "data": data,
            "retry_advised": status == "transient_error"}
```

Two properties make this work. First, **the tool never raises** — the model receives a structured status it can reason about ("retry this one", "skip this one"). Second, the outcome is persisted in session state, so a partial run remains visible after the fact, not just in the moment it happened.

Scale the same idea up to whole stages. Give every sub-agent an `output_key` pointing at an envelope:

```python
analyst = Agent(
    name="analyst",
    model="gemini-flash-latest",
    instruction="""
    Analyze the records in {records?}.
    ALWAYS answer with a JSON object: {"status": "ok" | "partial" | "failed",
    "completed": <int>, "total": <int>, "summary": "<text>", "errors": ["..."]}
    Even when nothing can be analyzed, you must still emit this object with
    status "failed" and an explanation — never produce an empty response.
    """,
    output_key="analyst_result",
)
```

Downstream, the aggregator reads the envelope rather than the content:

```python
aggregator = Agent(
    name="aggregator",
    model="gemini-flash-latest",
    instruction="""
    Inputs: {analyst_result?}, {report_result?}.
    Each is an envelope with a "status" field.
    - ok: incorporate normally
    - partial: incorporate what exists, and state which parts are missing
    - failed: state plainly that this section is unavailable
    Never present missing data as if it were present. Never invent a substitute.
    """,
    output_key="final_report",
)
```

A pipeline that *knows* it is partially complete produces an honest report. A pipeline that doesn't know produces fiction.

---

## 3. The Circuit Breaker

Retries are the right tool for a service that blinks. They are the wrong tool for a service that is down: after five failures per request across a busy pipeline, you have multiplied load on a struggling dependency and burned your own latency budget.

A circuit breaker tracks consecutive failures per dependency and, past a threshold, **opens** — calls fail immediately with a `circuit_open` envelope instead of hitting the network. After a cool-down it enters **half-open** state, allows one probe through, and closes again on success.

State must be serializable, so store plain data in session state (session-scoped by default, or `app:`-prefixed if the breaker should be shared across all sessions of the app):

```python
import time

THRESHOLD = 5          # consecutive failures to trip
COOLDOWN_SECONDS = 60

def breaker_snapshot(tool_context: ToolContext, dep: str) -> dict:
    return tool_context.state.get(f"{dep}:breaker",
                                  {"failures": 0, "opened_at": None, "state": "closed"})

def breaker_record(tool_context: ToolContext, dep: str, ok: bool) -> None:
    snap = breaker_snapshot(tool_context, dep)
    if ok:
        snap = {"failures": 0, "opened_at": None, "state": "closed"}
    else:
        snap["failures"] += 1
        if snap["failures"] >= THRESHOLD:
            snap["state"] = "open"
            snap["opened_at"] = time.time()
    tool_context.state[f"{dep}:breaker"] = snap    # travels as a state_delta

def guarded_enrichment(record_id: str, tool_context: ToolContext) -> dict:
    """Circuit-breaker wrapper around the enrichment dependency."""
    dep = "enrichment"
    snap = breaker_snapshot(tool_context, dep)

    if snap["state"] == "open":
        cooled = time.time() - (snap["opened_at"] or 0) > COOLDOWN_SECONDS
        if not cooled:
            return {"status": "circuit_open", "retry_advised": False,
                    "record_id": record_id,
                    "message": f"{dep} skipped: breaker open, fails fast by design"}
        snap["state"] = "half_open"                 # allow a single probe
        tool_context.state[f"{dep}:breaker"] = snap

    try:
        data = enrichment_client.get(record_id, timeout=10)
        breaker_record(tool_context, dep, ok=True)
        return {"status": "ok", "data": data, "record_id": record_id}
    except Exception as exc:
        breaker_record(tool_context, dep, ok=False)
        current = breaker_snapshot(tool_context, dep)
        return {"status": "circuit_open" if current["state"] == "open" else "transient_error",
                "retry_advised": current["state"] != "open",
                "error": str(exc)[:200], "record_id": record_id}
```

Design notes that matter in practice:

- **Fail fast, not silently.** An open breaker still returns a *labeled* envelope. The model is told the dependency is being skipped — that is what keeps the aggregator from writing a confident sentence about data it never received.
- **Serializability.** Everything written to state is numbers, strings, and booleans. ADK's `SessionService` can persist that anywhere; it cannot persist a live connection or a class instance.
- **Half-open is one probe, not a thundering herd.** In a `ParallelAgent` fan-out, the half-open probe naturally becomes whichever branch reaches the guard first; the others see the open breaker and skip.

---

## 4. Where Retries Belong

With a breaker in place, retries become surgical. The rule from ADK's own workflow guidance: **retry only errors that can succeed on a second attempt** (connection resets, rate limits, timeouts) and fail immediately on deterministic errors (bad input, missing record, schema violations).

For ADK 2.0 graph-based workflows this is a first-class feature — a per-node retry policy with backoff, jitter, and timeout:

```python
from google.adk import Workflow
from google.adk.workflow import RetryConfig, node, NodeTimeoutError

class ServiceUnavailableError(Exception):
    """Transient failure from a remote service."""

@node(
    retry_config=RetryConfig(
        max_attempts=3,                        # 1 attempt + 2 retries
        initial_delay=1.0,                     # seconds before first retry
        exceptions=[ServiceUnavailableError, NodeTimeoutError],
    ),
    timeout=10.0,                              # per attempt, not total
)
async def fetch_stage(ctx):
    return await enrichment_client.fetch_all()
```

Backoff defaults multiply the wait between attempts (1s, 2s, 4s, …) with random jitter, so parallel branches that fail together do not retry together. Two caveats worth internalizing: **default retry policies are broad** — list your transient exception types explicitly — and **a retry re-runs the whole node**, so any external side effect inside it must be idempotent or moved to a separate node that runs after the unreliable call succeeds.

Outside graph workflows, keep retries at the tool boundary (as in `guarded_enrichment`) rather than wrapping `run_async` in a loop. Re-running an entire invocation re-executes every stage, re-sending every token — the most expensive retry you can buy.

---

## 5. Watching the Run: Observability for Partial States

Partial success is only useful if you can see it. Because stage outcomes are stored through state updates, they arrive as `state_delta`s on events in the stream:

```python
async for event in runner.run_async(user_id=uid, session_id=sid, new_message=msg):
    delta = getattr(event.actions, "state_delta", None) or {}
    for key, value in delta.items():
        if key.endswith(":breaker") or key.endswith("_result"):
            print(f"[{event.author}] {key} -> {str(value)[:160]}")
    if event.is_final_response() and event.content:
        final = "".join(p.text for p in event.content.parts if getattr(p, "text", None))
```

An `open` breaker or a `partial` envelope in this log is not a crash — it is the system doing its job: degrading to the best honest answer available and leaving an audit trail of exactly which dependency was skipped and when.

---

## 6. Checklist

- [ ] Every tool returns a structured envelope; raising is reserved for truly catastrophic, unrecoverable errors.
- [ ] Every stage writes an `output_key` envelope with `status`, counts, and an explanation — including on failure.
- [ ] The aggregator is instructed to distinguish `ok` / `partial` / `failed` and never fabricate missing sections.
- [ ] Circuit-breaker state is serializable, threshold + cooldown are configurable, and half-open allows a single probe.
- [ ] An open breaker returns a *labeled* skip, so downstream agents know data is missing.
- [ ] Retries list only transient exception types, use backoff with jitter, and sit on idempotent units of work.
- [ ] Dashboard/alerting reads the same `state_delta` stream so a tripped breaker is visible within one run.

**Takeaway:** reliability in a multi-agent system comes from making failure *informative*. A partial success envelope tells the next stage what exists; a circuit breaker protects the dependency that caused it; bounded, typed retries recover the ones that can recover. The run then finishes — smaller, honest, and intact — instead of dying or lying.

## Sources
- Google ADK Documentation: https://adk.dev/
- Handle node failures with retries and timeouts: https://adk.dev/graphs/retry/
- State: The Session's Scratchpad: https://adk.dev/sessions/state/
