---
title: 'Best Practices for Designing Clean, Maintainable, and Auditable Agent Graphs'
date: '2026-12-02T08:24:49+07:00'
description: 'A practical guide to designing ADK graph workflows that stay readable and reviewable: single-purpose nodes, typed boundaries, deterministic/LLM separation, isolated tests, and an audit trail from events and state deltas.'
author: 'AI Assistant'
image: 'https://blog.redlinesoft.net/images/post/adk-clean-maintainable-auditable-agent-graphs.jpg'
alt: 'A tidy modular workflow graph with clearly named nodes and typed boundaries'
tags: ['google-adk', 'adk-2-0', 'workflows', 'design', 'testing']
---

The first version of a graph workflow is always readable: five nodes, one branch, a comment on each line. The version that ships six months later has a 400-line `edges=[...]` list, a router that returns eleven different strings, and a node called `step2_final_v3` that nobody will delete because nobody knows what it does. Nothing about ADK forces that decay — but nothing prevents it either.

Graph workflows are a design surface, and like any design surface they reward conventions: small nodes, names that mean something, typed boundaries, deterministic code separated from probabilistic reasoning, and a topology you can draw on a whiteboard. This article is a set of practices — plus a review checklist — for keeping a graph legible to the next person, who may be you at 2 a.m.

## Prerequisites

- ADK Python v2.0.0+ and comfort with `Workflow`, `edges`, `START`, `Event(route=...)`, and `JoinNode`.
- Familiarity with Pydantic `BaseModel` for schema definitions.
- An existing multi-node graph to refactor, or willingness to build the examples here first.

## 1. One node, one job

A node should do one thing well enough that you can describe it in a single sentence without using the word "and." Small nodes give you four compounding benefits:

- **Retries become meaningful.** A retry policy attached to a node re-runs *that node*. If the node does three things, a transient failure on the third re-does the first two.
- **Timeouts become meaningful.** `timeout=10.0` on a node that only calls the flaky API is a real budget; on a node that also post-processes and writes to three tables, it is a guess.
- **Tests become cheap.** A pure function node with one input and one output needs no API key, no fixture, and no mocking of a model client.
- **Failures become attributable.** When the graph fails, the node name in the event history tells you where — not a 60-line function's stack trace.

The corollary: **do not use one node as a place to hide a procedure.** If you find yourself writing `# step 1: ... # step 2: ...` inside a node body, you have at least two nodes.

## 2. Names are documentation

Node names surface in event history, in traces, in error messages, and in the `edges` list that reviewers actually read. Conventions that pay off:

- **`snake_case`, verb-first, specific**: `fetch_customer_record`, `classify_intent`, `record_dead_letter` — not `step2`, `handler`, `process`.
- **Names match the underlying function or agent.** If the node wraps `lookup_time_function`, name it `lookup_time_function`. Divergent names force reviewers to hold two mappings in their head.
- **Route values are `SCREAMING_SNAKE_CASE` and enumerable**: `"OK"`, `"FAILED"`, `"NEEDS_REVIEW"`. You will write them in tests and in dispatch dicts; make typos obvious.
- **State keys are namespaced and consistent**: `intent`, `order_ids`, `user:preferred_language`, `temp:scratch_matrix`. A key's prefix should tell you its lifetime before you read any code.
- **`DEFAULT_ROUTE` always has a real handler.** A default branch of `pass` is a silent failure path; route it to a handler that degrades visibly.

## 3. Typed schemas at every boundary

The single highest-leverage practice for maintainability is putting a Pydantic model on the data that crosses a node boundary:

```python
from datetime import date

from google.adk import Agent
from pydantic import BaseModel


class FlightSearchInput(BaseModel):
    origin: str              # Airport code "SFO"
    destination: str         # Airport code "CDG"
    departure_date: date     # date(2026, 3, 15)
    passengers: int = 1


class Flight(BaseModel):
    carrier: str
    price: float


class FlightSearchOutput(BaseModel):
    flights: list[Flight]
    cheapest_price: float


flight_searcher = Agent(
    name="flight_searcher",
    instruction="Search for available flights.",
    input_schema=FlightSearchInput,
    output_schema=FlightSearchOutput,
    tools=[search_flights_api],
    mode="single_turn",
)
```

A schema at a boundary buys you four things at once: **validation at runtime** when the contract is broken, **a self-describing interface** for whoever reads the graph, **a natural test fixture** (`FlightSearchInput(origin="SFO", ...)`), and **a prompt constraint** — `output_schema` forces the model to answer in that shape rather than free-form prose you will parse with regex.

The docs' instruction templating supports this directly: `{Class.field}` reads a field from *this node's input*, and `<Class.field from source_node>` reads a named predecessor's output when several upstream nodes share a field name. Both are distinct from `{state_key}`, which reads session state. Using them keeps the data flow visible in the instruction instead of implied.

Remember the edge rule: **one `Event.output` per node execution.** Bundle structured results into a single schema-typed object rather than emitting several outputs.

## 4. Keep deterministic and LLM nodes visibly separate

A graph's value is that it lets you say, in code, *which* decisions are probabilistic and which are not. Make that split obvious in the topology:

- **LLM nodes classify, draft, extract, and summarize.** They are `Agent`/`LlmAgent` instances running in `single_turn` mode (the default inside a graph; `chat` mode is only allowed directly after `START`).
- **Deterministic nodes route, validate, compute, and persist.** They are plain functions — keyword rules, thresholds, database lookups — and they are unit-testable without an API key.
- **The router returns a value, not a next node.** `Event(route=...)` plus a dispatch dict keeps the decision *logic* in one place and the decision *table* in another, so the table can be reviewed as data.

```python
def router(node_input: str):
    """Pure-code dispatch: no model call on this path."""
    if not node_input.strip():
        return Event(route="EMPTY")
    if node_input.startswith("URGENT"):
        return Event(route="ESCALATE")
    return Event(route="NORMAL")
```

Resist the temptation to let a model decide structural things — ordering, branching, retry policy. Hoping the model follows your procedure is not a control-flow primitive.

## 5. Flat first, nested on purpose

Flat is the default. Reach for nesting only when a branch is genuinely a *sub-process* with its own internal topology:

- A branch target can be any node-like value, **including another `Workflow`**. While the child runs, its node events bubble up to the parent for traceability; when it completes, its terminal output becomes the output of the nested-workflow node on the outer edge.
- **One terminal output per workflow.** If two parallel branches both end in an output, the graph fails with a `ValueError`. Merge them with a `JoinNode` first.
- **Every cycle must contain at least one routed, conditional edge.** An unconditional cycle is rejected at construction time — a feature, since it guarantees every loop has an escape hatch you can read.
- Nesting has a cost: the parent sees one value, and the child's internals disappear behind that boundary. Over-nesting produces exactly the opacity you were trying to avoid.

A useful rule: if a sub-graph has more than about five nodes or needs its own router, nest it. Otherwise keep it inline and let reviewers see the whole path at once.

## 6. Test nodes in isolation, then test the topology

Because nodes are values in a list, the test pyramid writes itself:

```python
def test_classify_intent_routes_urgent():
    event = router("URGENT: payment failed")
    assert event.route == "ESCALATE"


def test_classify_intent_default():
    event = router("")
    assert event.route == "EMPTY"


def test_dispatch_table_covers_all_routes():
    emitted = {r for r in SAMPLE_INPUTS for r in [router(r).route]}
    assert emitted <= set(DISPATCH.keys())
```

Three layers, in increasing cost:

1. **Unit-test pure function nodes** as ordinary functions — no ADK runtime, no key, milliseconds per test.
2. **Unit-test the dispatch table as data**: every route the router can emit has a key, `DEFAULT_ROUTE` exists, and no branch points at a node that is not in the graph.
3. **Run one end-to-end happy path and one end-to-end failure path** through a real `Workflow` with an in-memory session service, asserting on the *sequence of node names* in the event history rather than on prose output.

Layer 3 is where auditability and testing meet: the event history is already a machine-readable execution trace, so asserting on it tests both behavior and observability at once.

## 7. Document the topology outside the code

The `edges` list is executable, but it is not a diagram. Keep three artifacts:

- **A diagram (ASCII or drawn)** in the module docstring showing `START`, routers, branches, and terminal nodes. The docs' own examples use one; so should you.
- **A short "why" comment per router**, not per node. Nodes are self-evident from their names; the *reason a route exists* is the non-obvious part.
- **A changelog of topology changes.** Adding an edge is a behavior change; note it the way you would note an API change.

```python
"""Support triage workflow.

  START -> classify_intent -> router
                                |-- ESCALATE -> page_oncall   (terminal)
                                |-- NORMAL   -> draft_reply   (terminal)
                                `-- EMPTY    -> ask_clarifying (terminal)

Why ESCALATE exists: billing disputes must never be auto-answered.
"""
```

## 8. Auditability: events and state deltas are your trail

ADK gives you an audit trail for free if you do not fight it. The `Runner` receives each yielded event, commits its `actions` — `state_delta`, `artifact_delta` — through the `SessionService`, and *then* lets your node resume. The consequences:

- **Every state change is an event.** Because state should always be updated as part of appending an event (via `output_key` or an explicit `EventActions.state_delta`), the history records not just *what* the agent said but *what it changed and when*.
- **Ordering is guaranteed.** Since execution pauses at each `yield` until the `Runner` commits, the event sequence is a faithful, linear record of the run — including which node ran, which route was taken, and what the input was.
- **Never mutate a `Session` object you fetched from the `SessionService`.** Writing to `my_session.state[...]` directly bypasses event tracking and can lose data. Modify `state` on the `Context` you were handed, or emit a `state_delta`; the framework records it.
- **Authors matter.** Events carry an `author` (the node or agent name), so "who did this" is answerable from history alone.

If your domain has compliance requirements, this is the mechanism: the session's event list *is* the audit log, and its integrity comes from the fact that your code cannot change state without going through it.

## 9. One more thing: pick the right workflow style

ADK offers three complementary composition styles, and choosing wrongly is its own maintainability problem:

- **Graph-based workflows** — a declarative graph with explicit routing. Best for deterministic, structured processes. (This article's subject.)
- **Dynamic workflows** — programmatic orchestration in your own loops, conditionals, and recursion. Best when control flow is too iterative for a static graph.
- **Prebuilt template workflows** — `SequentialAgent`, `ParallelAgent`, `LoopAgent`. Note that **these are deprecated in Python and TypeScript**: constructing one emits a deprecation warning, and new code should express those patterns with a graph. One current constraint: a `Workflow` cannot yet be used as an `LlmAgent` sub-agent.

Also check the documented limitation that graph-based workflows are **not compatible with some third-party integrations** before committing a design to them.

## Review checklist

Before a graph workflow passes review:

- [ ] Every node does one thing; procedures are split across nodes.
- [ ] Names are verb-first `snake_case`, and route values are enumerable `SCREAMING_SNAKE_CASE`.
- [ ] Every boundary crossing a node has a Pydantic `input_schema` / `output_schema`.
- [ ] Each node emits at most one `Event.output` per execution.
- [ ] Routers are pure functions; LLM nodes are `single_turn` and sit where reasoning is genuinely needed.
- [ ] `DEFAULT_ROUTE` exists and points at a real handler.
- [ ] Exactly one terminal output per workflow; parallel ends merged with a `JoinNode`.
- [ ] Every cycle contains a routed edge.
- [ ] Function nodes have unit tests; the dispatch table has a coverage test; one end-to-end run asserts on event authors.
- [ ] A topology diagram and router rationale live in the module docstring.
- [ ] No code mutates a `Session` fetched from the `SessionService` directly.
- [ ] State changes go through `output_key` or `EventActions.state_delta` so they are auditable.

## Conclusion

Clean graphs are not a matter of taste — they are what make retries bounded, tests fast, failures attributable, and decisions auditable. ADK supplies the machinery: typed node boundaries, a routing table you can diff, and an event history that records every state delta in order. The conventions above are what keep that machinery legible as the graph grows from five nodes to fifty. Design for the reviewer, and the runtime will thank you too.

## References

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