Cycles, feedback loops and recursion limits

Topic 2 of 5 in Advanced control flow23 min readIntermediateFree course

Overview

In the previous lesson, Parallel execution, branching and merging, you learned how LangGraph distributes independent operations across multiple branches and combines their results.

Those workflows generally moved forward until processing finished. However, intelligent applications frequently need to revisit earlier operations.

Consider an AI system that generates SQL queries. Its first query might contain an invalid column name. Instead of immediately returning an error, the system could inspect the database response, revise the query, and attempt execution again.

Other common examples include:

  • Improving a generated answer after quality evaluation.
  • Retrieving additional documents when available evidence is insufficient.
  • Repairing structured output that fails schema validation.
  • Revising generated code after failed tests.
  • Repeating document extraction until required fields are available.
  • Calling tools until an agent has enough information to answer.

These workflows require cycles.

A cycle exists when following graph edges can return execution to a previously visited node. Unlike a directed acyclic graph, a cyclic graph permits repeated execution of the same operation.

Cycles are central to agentic AI because the number of required processing steps is often unknown before execution begins.

However, flexibility introduces risk. An agent that repeatedly decides to continue can consume API credits, exhaust execution resources, and leave users waiting indefinitely.

The engineering objective is therefore not simply to create a loop, but to create a bounded loop with observable progress and predictable termination.

Environment setup

Install LangGraph 1.x:

Terminal
pip install -U "langgraph>=1.1.4,<2"

All examples use ordinary Python functions to demonstrate control flow without requiring an LLM API key. The APIs and execution semantics follow the current LangGraph documentation; the expected outputs are provided for local verification rather than claimed execution results.

Understanding cyclic execution

A conventional Python while loop repeats a block of statements while a condition remains true.

In LangGraph, equivalent behavior emerges from three components:

  1. A state field that represents progress.
  2. A node that performs work and updates that state.
  3. A conditional edge that determines whether execution should continue.

The graph runtime manages repeated node scheduling. Your application does not need to recursively call the node function or repeatedly invoke the graph.

This distinction matters because graph-level iterations create execution boundaries at which state can be observed, streamed, and checkpointed.

Building a self-loop

The simplest possible cycle is a node that conditionally routes execution back to itself.

The following example increments a counter until it reaches a target.

Python
from typing import Literal, TypedDict

from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    count: int
    target: int

def increment(state: State) -> dict:
    count = state["count"] + 1

    print(f"Current count: {count}")

    return {"count": count}

def route(state: State) -> Literal["increment", "__end__"]:
    if state["count"] >= state["target"]:
        return END

    return "increment"

builder = StateGraph(State)

builder.add_node("increment", increment)

builder.add_edge(START, "increment")
builder.add_conditional_edges("increment", route)

graph = builder.compile()

result = graph.invoke(
    {"count": 0, "target": 5},
    config={"recursion_limit": 20},
)

print("Final state:", result)

assert result["count"] == 5

Expected output:

Text
Current count: 1
Current count: 2
Current count: 3
Current count: 4
Current count: 5
Final state: {'count': 5, 'target': 5}

The routing function receives state reflecting the update returned by the increment node.

When the count is below the target, another execution of increment is scheduled. Once the target is reached, routing returns END.

Notice that the node executes before its termination condition is evaluated. This resembles a do-while loop rather than a conventional precondition-based while loop.

If the initial count already satisfies the target, the graph still increments once. When zero iterations must be possible, evaluate the condition before entering the worker node, as demonstrated in the front-matter exercise.

A feedback loop

A counter-based loop is predictable because every iteration makes measurable progress toward a fixed target.

Agentic workflows are more complex. They often decide whether to continue by evaluating the quality or completeness of an intermediate result.

This creates a feedback loop, sometimes called an evaluator-optimizer workflow.

A typical feedback loop contains:

  • A worker that produces or improves an artifact.
  • An evaluator that checks the artifact against requirements.
  • A routing decision that determines whether further improvement is needed.
  • A termination path for successful or exhausted execution.

The following diagram illustrates a feedback-driven document review workflow.

A feedback loop diagram: START to Generate draft; Generate draft to Evaluate draft; Evaluate draft to Quality acceptable?; Quality acceptable? to Finalize result (Yes); Quality acceptable? to Budget available? (No); Budget available? to Revise draft (Yes); Revise draft to Evaluate draft; Budget available? to Finalize result (No); Finalize result to END.

The evaluator must provide actionable feedback. Merely returning a Boolean rejection may not give the worker enough information to improve.

For example, feedback such as missing payment terms is more useful than a generic instruction to try again.

Building a document completion workflow

Suppose a document-processing application generates a report containing three mandatory fields:

  • Customer name.
  • Invoice identifier.
  • Total amount.

The first draft may be incomplete. A reviewer identifies missing fields, and a revision node fills them using available source data.

The following complete example implements this pattern without an LLM.

Python
from typing import Literal, TypedDict

from langgraph.graph import StateGraph, START, END

REQUIRED_FIELDS = (
    "customer",
    "invoice_id",
    "total",
)

class State(TypedDict):
    source: dict[str, str]
    draft: dict[str, str]
    missing_fields: list[str]
    attempts: int
    max_attempts: int
    status: str

def generate_draft(state: State) -> dict:
    return {
        "draft": {
            "customer": state["source"].get("customer", "")
        },
        "attempts": 1,
        "status": "in_progress",
    }

def evaluate_draft(state: State) -> dict:
    missing = [
        field
        for field in REQUIRED_FIELDS
        if not state["draft"].get(field, "").strip()
    ]

    print(
        f'Attempt {state["attempts"]}: '
        f'missing={missing}'
    )

    return {"missing_fields": missing}

def revise_draft(state: State) -> dict:
    updated = dict(state["draft"])

    # Repair one missing field per iteration.
    for field in state["missing_fields"]:
        value = state["source"].get(field, "")

        if value.strip():
            updated[field] = value
            break

    return {
        "draft": updated,
        "attempts": state["attempts"] + 1,
    }

def route(
    state: State,
) -> Literal["revise_draft", "finalize"]:
    if not state["missing_fields"]:
        return "finalize"

    if state["attempts"] >= state["max_attempts"]:
        return "finalize"

    return "revise_draft"

def finalize(state: State) -> dict:
    if not state["missing_fields"]:
        return {"status": "completed"}

    return {"status": "attempt_limit_reached"}

builder = StateGraph(State)

builder.add_node("generate_draft", generate_draft)
builder.add_node("evaluate_draft", evaluate_draft)
builder.add_node("revise_draft", revise_draft)
builder.add_node("finalize", finalize)

builder.add_edge(START, "generate_draft")
builder.add_edge("generate_draft", "evaluate_draft")

builder.add_conditional_edges(
    "evaluate_draft",
    route,
)

builder.add_edge("revise_draft", "evaluate_draft")
builder.add_edge("finalize", END)

graph = builder.compile()

result = graph.invoke(
    {
        "source": {
            "customer": "Acme Industries",
            "invoice_id": "INV-1042",
            "total": "2500.00",
        },
        "max_attempts": 4,
    },
    config={"recursion_limit": 20},
)

print("Draft:", result["draft"])
print("Status:", result["status"])

assert result["attempts"] == 3
assert result["status"] == "completed"

Expected output:

Text
Attempt 1: missing=['invoice_id', 'total']
Attempt 2: missing=['total']
Attempt 3: missing=[]
Draft: {'customer': 'Acme Industries', 'invoice_id': 'INV-1042', 'total': '2500.00'}
Status: completed

How the feedback loop works

The generation node creates an initial draft. The evaluator then compares the draft against an explicit list of requirements.

The conditional edge examines the evaluator’s findings. If the draft is incomplete and the attempt budget permits additional work, execution moves to the revision node.

The revision node consumes the feedback and returns an updated draft. Its outgoing edge sends execution back to the evaluator.

Importantly, the graph does not return to generate_draft, which would replace the draft and reset the attempt counter.

This separation establishes clear responsibilities: generation initializes the artifact, evaluation identifies deficiencies, revision improves the current artifact, and routing controls termination.

Success is not guaranteed

Suppose the source document does not contain an invoice identifier.

No amount of revision can recover information that does not exist. The workflow should terminate after a bounded number of attempts and report the missing field rather than fabricate a value.

In a real application, an LLM may replace the generation or revision functions. Nevertheless, the routing logic should retain deterministic budget checks.

Where possible, use objective validators such as JSON schema checks, database constraints, required-field verification, or automated tests rather than relying exclusively on an LLM’s subjective judgment.

Note: A model may recommend another iteration, but application code should enforce whether another iteration is actually permitted.

Recursion limits

What the recursion limit measures

LangGraph uses the Pregel execution model introduced in the previous lesson.

Execution advances through logical rounds called super-steps. Nodes that execute concurrently share a round, whereas dependent nodes execute in subsequent rounds.

The recursion limit places an upper bound on these execution rounds during a graph run.

Despite its name, it is unrelated to Python’s interpreter recursion limit. Changing sys.setrecursionlimit() does not change LangGraph’s execution budget.

Beginning with LangGraph 1.1.4, the default recursion limit is 10,007 super-steps. Earlier 1.x versions used different defaults.

This is much larger than most interactive agent workflows require. An application performing expensive model calls should therefore set an explicit, task-appropriate limit rather than relying on the default.

The following diagram shows how repeated node executions consume successive super-steps.

Recursion limits diagram: Step one worker to Step two review; Step two review to Step three worker; Step three worker to Step four review; Step four review to Step five finalize; Step five finalize to END.

Although the same worker and reviewer functions execute repeatedly, each sequential activation consumes another execution round.

Parallel workers may execute within one super-step. Consequently, the recursion limit is not equivalent to a maximum number of model calls, tool calls, or total node executions.

Business budgets versus runtime budgets

Mechanism What it controls Typical exhaustion behavior
Attempt counter Number of processing attempts Return incomplete result
Recursion limit Graph execution rounds Raise GraphRecursionError
RemainingSteps Visibility into remaining execution rounds Route toward completion
Node retry policy Reattempts after selected exceptions Retry or propagate failure
Timeout Time spent executing work Raise a timeout-related error
Token or cost budget Model usage or application spending Stop expensive operations

These mechanisms solve different problems and should be combined rather than treated as interchangeable.

For the document completion example, the initial generation and evaluation require two node rounds. Each additional revision requires another revision and evaluation round. Finalization requires one more.

With four permitted attempts, the longest ordinary path therefore contains nine user-node rounds.

A recursion limit of 20 provides sufficient headroom for that topology without permitting thousands of accidental iterations.

The appropriate value changes when additional processing nodes are introduced.

Triggering and handling GraphRecursionError

If the runtime budget is exhausted while additional graph work remains, LangGraph raises GraphRecursionError.

The following intentionally defective graph has no termination condition. A low recursion limit prevents uncontrolled execution.

Python
from typing import TypedDict

from langgraph.errors import GraphRecursionError
from langgraph.graph import StateGraph, START

class State(TypedDict):
    count: int

def repeat(state: State) -> dict:
    count = state["count"] + 1

    print("Iteration:", count)

    return {"count": count}

builder = StateGraph(State)

builder.add_node("repeat", repeat)

builder.add_edge(START, "repeat")
builder.add_edge("repeat", "repeat")

graph = builder.compile()

try:
    graph.invoke(
        {"count": 0},
        config={"recursion_limit": 5},
    )

except GraphRecursionError:
    print("Execution stopped: recursion limit reached")

Expected output contains repeated iteration messages followed by:

Text
Execution stopped: recursion limit reached

The exception prevents continued scheduling of the infinite cycle.

However, the invocation does not return a normal final state, and any intended finalization node is not automatically executed.

The recursion limit should therefore be considered an emergency safety mechanism rather than the primary termination strategy.

Inspecting state after recursion exhaustion

When checkpointing is enabled, you can inspect the saved execution state after a recursion-limit exception.

The following example demonstrates recovering the last persisted progress of an intentionally unbounded workflow.

Python
from typing import TypedDict

from langgraph.checkpoint.memory import InMemorySaver
from langgraph.errors import GraphRecursionError
from langgraph.graph import StateGraph, START

class State(TypedDict):
    processed: int

def process(state: State) -> dict:
    return {"processed": state["processed"] + 1}

builder = StateGraph(State)

builder.add_node("process", process)
builder.add_edge(START, "process")
builder.add_edge("process", "process")

graph = builder.compile(
    checkpointer=InMemorySaver()
)

config = {
    "configurable": {
        "thread_id": "document-processing-001"
    },
    "recursion_limit": 5,
}

try:
    graph.invoke(
        {"processed": 0},
        config,
        durability="sync",
    )

except GraphRecursionError:
    snapshot = graph.get_state(config)

    print("Saved progress:", snapshot.values)
    print("Pending nodes:", snapshot.next)

    assert snapshot.values["processed"] > 0
    assert "process" in snapshot.next

Expected output includes a saved processing count and a pending process node.

The exact checkpoint step numbering should not be treated as an application-level iteration counter.

Checkpoint inspection helps diagnose failures and preserve useful intermediate work. However, blindly resuming this particular graph would reproduce the problem because its topology still contains an unconditional infinite cycle.

Correct the termination logic before attempting recovery.

For production deployments, use a durable checkpointer rather than relying on process-local memory.

Finishing gracefully with RemainingSteps

A better workflow recognizes that its execution budget is running low before the runtime raises an exception.

LangGraph provides a managed state value named RemainingSteps:

Python
from langgraph.managed.is_last_step import RemainingSteps

You declare this value as a field in the graph state schema.

Unlike ordinary state fields, the runtime calculates its value. You do not initialize it in the invocation input, manually decrement it, or return updates to it.

It exposes the remaining super-step budget at the current execution position.

This enables a graph to choose a controlled completion path while enough execution capacity remains.

Building a budget-aware research loop

Consider a research agent collecting evidence from several sources.

Ideally, the agent should retrieve enough evidence to answer a question confidently. If the execution budget is nearly exhausted, it should return the evidence collected so far and explicitly identify the result as incomplete.

The following example implements a research loop with a reserved completion path.

Python
from typing import Literal, TypedDict

from langgraph.graph import StateGraph, START, END
from langgraph.managed.is_last_step import RemainingSteps

class State(TypedDict):
    sources: list[str]
    evidence: list[str]
    cursor: int
    target: int
    remaining_steps: RemainingSteps
    status: str
    answer: str

def collect(state: State) -> dict:
    remaining = state["remaining_steps"]

    print(f"Remaining steps: {remaining}")

    if len(state["evidence"]) >= state["target"]:
        return {"status": "completed"}

    if state["cursor"] >= len(state["sources"]):
        return {"status": "sources_exhausted"}

    # Reserve execution capacity for finalization.
    if remaining <= 3:
        return {"status": "step_budget_reached"}

    source = state["sources"][state["cursor"]]

    evidence = state["evidence"] + [source]

    return {
        "evidence": evidence,
        "cursor": state["cursor"] + 1,
        "status": "in_progress",
    }

def route(state: State) -> Literal["collect", "finalize"]:
    if state["status"] != "in_progress":
        return "finalize"

    return "collect"

def finalize(state: State) -> dict:
    answer = "\n".join(state["evidence"])

    if state["status"] != "completed":
        answer += (
            "\nWarning: evidence collection was incomplete."
        )

    return {"answer": answer.strip()}

builder = StateGraph(State)

builder.add_node("collect", collect)
builder.add_node("finalize", finalize)

builder.add_edge(START, "collect")
builder.add_conditional_edges("collect", route)
builder.add_edge("finalize", END)

graph = builder.compile()

def research(limit: int):
    return graph.invoke(
        {
            "sources": [
                f"Evidence from source {i}"
                for i in range(1, 11)
            ],
            "evidence": [],
            "cursor": 0,
            "target": 5,
        },
        config={"recursion_limit": limit},
    )

print("\nConstrained budget:")
partial = research(6)

print("Status:", partial["status"])
print(partial["answer"])

assert partial["status"] == "step_budget_reached"

print("\nSufficient budget:")
complete = research(20)

print("Status:", complete["status"])
print(complete["answer"])

assert complete["status"] == "completed"
assert len(complete["evidence"]) == 5

Expected behavior:

Text
Constrained budget:
Remaining steps: ...
Status: step_budget_reached
Evidence from source ...
Warning: evidence collection was incomplete.

Sufficient budget:
Remaining steps: ...
Status: completed
Evidence from source 1
Evidence from source 2
Evidence from source 3
Evidence from source 4
Evidence from source 5

The first invocation stops deliberately while retaining collected evidence. The second completes its research objective normally.

Neither invocation needs to exhaust the recursion limit.

Reserving enough steps

The threshold remaining <= 3 is a conservative application-level choice for this small graph, not a universal LangGraph requirement.

A workflow that requires separate summarization, validation, formatting, and publication nodes must reserve enough rounds for that longer completion path.

Calculate the required reserve based on the graph topology and verify boundary conditions using automated tests.

Also note that RemainingSteps represents execution capacity, not remaining seconds or remaining model tokens. A single node can still perform expensive or long-running work.

For that reason, graceful recursion handling must be combined with separate time and cost controls.

Tip: Check the execution budget before starting expensive operations, and reserve enough capacity to produce a useful final response.

Common loop bugs

Missing termination conditions

The most obvious failure is a cycle composed entirely of unconditional edges.

For example, a worker connected to a reviewer, with the reviewer always connected back to the worker, has no normal completion path.

Use conditional routing and verify that both continuation and termination outcomes are reachable.

Combining unconditional and conditional routing incorrectly

Suppose an evaluation node has an unconditional edge back to the worker and a conditional edge that sometimes returns END.

The unconditional edge still schedules the worker. Returning END through the conditional edge does not cancel separately scheduled work.

When a routing decision should exclusively determine the next destination, avoid adding an unconditional continuation edge from that same node.

Likewise, reaching END on one parallel branch does not automatically terminate other branches that still have scheduled work.

Failing to update progress

A routing condition may be completely correct while the worker fails to modify the state that condition depends upon.

A loop checking attempts >= max_attempts will not terminate normally if the attempts counter never increases.

Always identify which node owns each progress-related field.

Increment counters exactly when the corresponding business operation occurs.

Off-by-one errors

Using attempts > max_attempts instead of attempts >= max_attempts can allow an unintended additional iteration.

Establish whether the initial generation counts as an attempt and whether validation occurs before or after work.

Test budgets of zero, one, and the maximum supported value.

Incorrect reducer usage

Repeated node execution also means repeated reducer application.

If a counter uses Annotated[int, operator.add], the node should return an increment such as {"attempts": 1}.

Returning {"attempts": state["attempts"] + 1} with that reducer adds the entire calculated value to the existing counter.

Similarly, append-only message or findings reducers can accumulate duplicate information during repeated processing.

Choose reducers according to whether the field represents current state, cumulative history, or independent parallel contributions.

Resetting state inside the loop

An initialization node should not normally be revisited if it resets attempt counters, clears feedback, or discards previous results.

Separate one-time initialization from repeatable processing.

Otherwise, each iteration may erase the evidence that would allow the workflow to recognize completion.

Repeating work without improvement

A model might generate the same invalid output repeatedly. Two revision strategies might also alternate between equally defective results.

Track indicators such as repeated output fingerprints, unchanged validation errors, or consecutive iterations without improvement.

After a configured stagnation threshold, stop, select another strategy, or request human review.

This protects against loops that consume their entire budget without producing additional value.

Confusing retries with feedback iterations

A node retry policy handles selected operational failures, such as transient connection errors.

A feedback iteration is an application-level decision to perform additional work because the previous result was insufficient.

Retrying an exception does not necessarily advance the graph to another super-step. Therefore, the recursion limit alone cannot guarantee a maximum number of external service attempts.

Use separate retry and iteration budgets.

Production design practices

A production feedback loop should satisfy both correctness and operational requirements.

First, define an explicit success condition. A document might require certain fields, a generated query might need to pass execution checks, or a research response might need independently verified evidence.

Second, establish bounded work. Attempt counters and recursion limits should be chosen according to the maximum acceptable latency and expense.

Third, represent termination reasons explicitly. Useful statuses include completed, attempt_limit_reached, step_budget_reached, sources_exhausted, and no_progress.

Do not present an incomplete artifact as successfully validated.

Fourth, protect external side effects. A repeated node that creates database records or sends notifications may perform the same action multiple times. Use idempotency keys, unique database constraints, or other safeguards.

Finally, observe execution. Record attempt numbers, evaluation findings, model usage, remaining execution steps, and termination reasons in application telemetry or LangSmith traces.

The updates streaming mode is particularly useful during development because it exposes node-level state contributions, including repeated execution of the same nodes.

Automated tests should cover immediate success, eventual success, impossible objectives, repeated feedback, exhausted budgets, and unexpectedly expensive processing paths.

For additional API details, consult the official Graph API overview, control flow documentation, and GRAPH_RECURSION_LIMIT troubleshooting guide.

Connection to the next lesson

You can now combine parallel processing with iterative feedback.

In the chapter’s document-processing project, independent branches can extract metadata, identify risks, and summarize content. A subsequent evaluation stage can identify missing or invalid results and determine whether another processing round is necessary.

However, the number of documents or document sections may only become known at runtime. Defining a fixed graph node for every possible work item would be impractical.

In the next lesson, Dynamic fan-out with Send, you will learn how to distribute an arbitrary collection of work items across dynamically scheduled worker executions.

Together, dynamic fan-out, safe aggregation, and bounded feedback loops form the foundation of scalable document-processing and agentic AI workflows.

Exercise

Build a bounded document redaction loop

Build a cyclic graph that removes one sensitive email address from a document during each iteration and validates the updated document. Continue until no email addresses remain or the maximum number of redaction attempts is reached. Return an explicit completion status and use a recursion limit as an additional safety mechanism. Test successful redaction, exhausted attempts, and documents that require no redaction.

Python
import re
from typing import Literal, TypedDict

from langgraph.graph import StateGraph, START, END


EMAIL_PATTERN = (
    r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"
)


class State(TypedDict):
    document: str
    attempts: int
    max_attempts: int
    remaining_emails: int
    status: str


def validate(state: State) -> dict:
    # TODO: Count the remaining email addresses.
    # Return remaining_emails as a state update.
    raise NotImplementedError


def redact(state: State) -> dict:
    # TODO: Replace only the first email with [REDACTED].
    # Increment attempts.
    raise NotImplementedError


def route(state: State) -> Literal["redact", "finish"]:
    # TODO: Finish if no emails remain or the attempt
    # budget has been exhausted.
    raise NotImplementedError


def finish(state: State) -> dict:
    # TODO: Return completed or attempt_limit_reached.
    raise NotImplementedError


builder = StateGraph(State)

builder.add_node("validate", validate)
builder.add_node("redact", redact)
builder.add_node("finish", finish)

# TODO: Connect START to validate.
# TODO: Add conditional routing after validate.
# TODO: Connect redact back to validate.
# TODO: Connect finish to END.

graph = builder.compile()

result = graph.invoke(
    {
        "document": "Contact a@example.com or b@example.com",
        "attempts": 0,
        "max_attempts": 3,
    },
    config={"recursion_limit": 20},
)

print(result)

Summary

  • Cyclic graphs allow nodes to execute repeatedly until a state-dependent termination condition is satisfied.
  • Feedback loops use evaluation results to determine whether another processing iteration is necessary.
  • Every production loop should have a success condition and an explicit maximum-work budget.
  • The LangGraph recursion limit constrains super-steps rather than individual node calls or Python stack depth.
  • Exceeding the recursion limit raises GraphRecursionError instead of returning a normal final result.
  • RemainingSteps exposes the runtime execution budget so nodes can select a graceful completion path.
  • Reliable iterative workflows track progress, prevent repeated side effects, and distinguish successful completion from budget exhaustion.