Skip to content
Blog

Graph Execution Cycles: Designing Bounded Cyclic Graphs and Retry Loops

Build review-retry cycles as back-edges in ADK graph workflows, guarantee termination with attempt counters, and know when a dynamic workflow while loop is the better tool.

Published on • December 2, 2026

AI Assistant

A code-review loop is the canonical agent workflow: draft, review, fix, review again, ship when clean. It is also the canonical way to burn a budget. An unbounded loop with an LLM inside does not fail loudly — it fails expensively, one token charge at a time, until someone notices the bill. And a loop whose exit condition lives only in a prompt (“stop when you are satisfied”) is not a loop at all; it is a hope.

ADK 2.0 gives you two honest ways to iterate: a back-edge in a graph workflow, and a plain while loop inside a dynamic workflow. Both can terminate — but only if you bound them. In this tutorial you will learn how cycles are expressed and validated in graph workflows, how to build a bounded review-retry cycle with an attempt counter, how dynamic while loops compare, and how graph cycles differ from per-node RetryConfig retries.

Prerequisites

  • ADK 2.0 (pip install google-adk)
  • Familiarity with conditional routing: Event(route=...) and dispatch dicts (graph routes)
  • Comfort with Event(state=...) and reading ctx.state

1. Anatomy of a graph cycle

In a graph workflow, a loop is a back-edge: a downstream node routes back to an earlier node instead of forward to a terminal one.

from google.adk import Event, Workflow


def router(node_input: str):
    """Exit the loop when the task is done, otherwise iterate again."""
    if condition(node_input):
        return Event(route="DONE")
    return Event(route="RETRY")


root_agent = Workflow(
    name="looping_workflow",
    edges=[
        ("START", task_A_node, router),
        (router,
          {
            "RETRY": task_A_node,   # back-edge: re-runs task_A_node
            "DONE": final_task_node,
          },
        ),
    ],
)

Three mechanics are worth internalizing:

  • The router decides, the edge re-runs. The router emits a route value; the dispatch dict decides whether that value means “iterate” or “exit.”
  • Each iteration gets a fresh lifecycle. As the docs put it, the engine “re-activates [the target] node with a fresh lifecycle on each iteration” — so per-run bookkeeping restarts, and anything you want carried across iterations must live in state or be forwarded as output.
  • The cycle must contain a routed edge. This is enforced at build time (next section).

2. The build-time guarantee: every cycle needs an escape hatch

ADK rejects a cycle made only of unconditional edges when the Workflow is constructed. A loop without a conditional route is a while True with no break, and the graph compiler refuses to build it.

This single rule is the foundation of termination in graph workflows: every loop must express its exit condition in code, on an edge you can read in review. The router is the loop condition — which also means the router is unit-testable as a pure function of its input, without an API key and without running the graph.

But a routed edge only guarantees an escape hatch exists. It does not guarantee the router ever takes it. If the reviewer agent keeps saying “needs changes,” the router will keep returning RETRY — correctly, by its own logic — forever. Bounding is your job.

3. Bounding a review-retry cycle with an attempt counter

The standard pattern: keep a counter in session state, and let the router consult it before consulting the reviewer.

from google.adk import Context, Event, Workflow

MAX_REVIEW_ROUNDS = 3


async def review_router(ctx: Context, node_input: str):
    """Exit on success, on the round cap, or on a real give-up signal."""
    attempts = int(ctx.state.get("attempts", 0)) + 1
    ctx.state["attempts"] = attempts          # committed with this node's events

    if attempts > MAX_REVIEW_ROUNDS:
        return Event(route="GAVE_UP", output=node_input)
    if reviewer_accepts(node_input):
        return Event(route="APPROVED", output=node_input)
    return Event(route="RETRY", output=node_input)


root_agent = Workflow(
    name="review_workflow",
    edges=[
        ("START", draft_node, reviewer, review_router),
        (review_router,
          {
            "RETRY": draft_node,        # back-edge
            "APPROVED": publish_node,
            "GAVE_UP": escalate_node,   # bounded exit: a human, not a hang
          },
        ),
    ],
)

Design points that make this pattern hold up in production:

  1. The cap is enforced in the router, not the prompt. The reviewer’s opinion can be wrong forever; the counter cannot.
  2. GAVE_UP is a real handler, not a crash. Hitting the bound should degrade into escalation — a human review node, a “best effort” branch — rather than a failed run with no output.
  3. The counter lives in state because it must survive the back-edge. A local variable does not; each iteration re-activates the node with a fresh lifecycle.
  4. Prefer temp: for the counter (ctx.state["temp:attempts"]) if the bound should reset per invocation rather than persisting for the whole session.

A useful variation: make the router take the reviewer’s verdict and the cap as two independent inputs — success exits early, the cap exits late, and both paths are testable in isolation.

4. Graph cycles versus dynamic-workflow while loops

When the iteration logic outgrows a router — nested conditions, multiple loop variables, work between checks — dynamic workflows let you write the loop the way you would in any Python function:

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

MAX_FIX_ROUNDS = 3


@node(rerun_on_resume=True)  # workflow node
async def code_workflow(ctx: Context, node_input: str):
    code = await ctx.run_node(coder_agent, node_input)
    check = await ctx.run_node(compile_lint_check, code)

    rounds = 0
    while check.findings and rounds < MAX_FIX_ROUNDS:
        yield Event(state={"code": code, "findings": check.findings})
        code = await ctx.run_node(
            fixer_agent, {"code": code, "findings": check.findings}
        )
        check = await ctx.run_node(compile_lint_check, code)
        rounds += 1

    yield Event(output=code)

The trade-offs:

Graph back-edgeDynamic while
Loop conditionRouter + dispatch dictOrdinary Python expression
StateIteration values must go through stateLocal variables just work
VisibilityTopology is inspectable in edgesLogic is readable in one function
BoundingAttempt counter in stateLoop condition itself (rounds < N)
Best forFixed-shape loops with few branchesComplex or nested iteration

In the dynamic form, the loop is bounded by its loop condition — rounds < MAX_FIX_ROUNDS sits right next to the while, so the cap and the exit are the same statement. State writes (Event(state=...)) happen only where an agent’s instruction template needs to read a value back; everything else stays in locals.

Two dynamic-workflow specifics matter for retries-in-loops: an orchestrator that calls ctx.run_node() must set rerun_on_resume=True so that on resume, already-finished children are replayed from checkpoints rather than executed again. And unlike a graph cycle — where each iteration is a fresh activation — the dynamic orchestrator body itself re-runs on resume.

5. Graph cycles are not RetryConfig retries

These two mechanisms are easy to conflate and serve different failures:

  • A graph cycle iterates because the task is not done yet — the draft needs another pass. The router decides; each iteration is a full node activation; the bound is your attempt counter.
  • RetryConfig on a node re-runs a node because the attempt failed — a connection error, a timeout. The policy decides; retries happen inside one logical step; the bound is max_attempts.

A review loop does not need RetryConfig to re-run the reviewer when the verdict is “needs changes” — that is not a failure, it is a result. Conversely, a transient 503 from the model API is not a review round. Keep the two knobs on the failures they each own, and remember that per-node retries and cycle iterations multiply: three review rounds times five retry attempts is fifteen model calls before your bound means anything.

6. Termination checklist

Before shipping a cyclic workflow:

  • Every cycle contains at least one routed edge (the engine enforces this at build time — do not fight it).
  • The router has an explicit cap check independent of the model’s opinion.
  • The cap’s exit route leads to a real handler (escalate, best-effort, human), not a dead end.
  • Iteration counters live in state with the right scope (temp: if per-invocation).
  • The router is unit-tested as a pure function: success path, retry path, cap path.
  • RetryConfig retries are reserved for transient failures, not for “not good enough yet.”
  • In dynamic loops, the bound appears in the while condition itself.

Termination in an agent workflow is not a property you can prompt your way into. It is a counter, a routed exit, and a handler for the case where the model never says “done” — and with those three in place, the loop becomes an ordinary piece of engineering instead of an open-ended conversation with a bill attached.

References