Linear or Graph: How to Run Many Agents Without an Eternal Loop

One agent with twenty tools gets messy fast. Once several agents revise each other, you need a graph that allows cycles and a number that makes it stop.

Read in Indonesian

Give one agent twenty tools and a novel-length system prompt, and the first output usually looks convincing. The trouble shows up later: the agent starts picking the wrong tool, forgets what it read three steps ago, then invents a step that was never in the instructions. No red error, just results that drift further off course.

Once the task grows (write backend code, draft unit tests, audit security, fix compile errors, ask for human approval before deploy), one agent is no longer enough. The fix is to split the work across several agents with narrow roles: Coder Agent, Reviewer Agent, Tester Agent, Deployment Agent. Short prompts, few tools, clear responsibility.

What is left open is the question after that: who manages the turns? If every agent is let loose to chat freely, the only limit is the token bill you pay. If you wire them into a rigid chain, revision becomes impossible.

Key takeaways

  • An acyclic graph has no place for revision to come back to, so a flow that needs a review cycle has to use a cyclic graph with conditional edges.
  • recursion_limit counts super-steps, not the number of review cycles, and its default is 10007 in LangGraph 1.2.16. The revision limit you actually want still has to live inside state.
  • Checkpoints are saved at super-step boundaries, so when an execution is resumed, the in-flight node is replayed from the top of the function and its side effects must be idempotent.
  • AutoGen was declared archived as of October 16, 2026, with no bug or security fixes; its successor is Microsoft Agent Framework, whose workflows come in both functional and graph-based styles.

A linear chain dies at the first revision

Early workflow engines used the chain model: agent A drafts, agent B reviews, agent C ships. Apache Airflow sits in this camp. The flow is a DAG, so it can branch as much as it likes, but it cannot form a cycle. As long as everything moves forward, this model is clean and easy to trace.

Review in the real world is rarely that tidy. The reviewer finds a gap, the code goes back to the coder, the coder fixes it, then it returns to the reviewer. Cycles like this are normal, usually two or three rounds before the code counts as clean.

Inside a DAG, that cycle does not exist by definition. Acyclic is the whole name. If you force it with a while in Python and state passed as ordinary variables, three things vanish at once: state changes without a trace, no record of who changed what, and if the worker dies midway there is no point to resume from.

A graph needs only four parts

The paradigm LangGraph uses now is actually simple:

  • Node: an isolated unit of work. It can be an LLM call with a custom prompt, or a plain Python function.
  • Edge: the path from one node to the next.
  • Conditional edge: a small function that reads state and decides where the flow turns. Review APPROVED? Straight to deploy. Notes still open? Back to the coder.
  • Shared state: one object with a strict schema (usually TypedDict or a Pydantic model). Each node returns the slice it changed, and a reducer merges them.
Diagram
flowchart LR subgraph lin["linear chain"] A["coder"] --> B["reviewer"] B --> C["deploy"] end subgraph sik["cyclic graph"] D["coder"] --> E["reviewer"] E -- "revision" --> D E -- "pass" --> F["deploy"] E -- "more than 3 revisions" --> G["escalation"] end

Those four parts are enough to describe a flow that has cycles, branches, and stops on its own.

Ping-pong that never ends

The most expensive scenario: the coder sends code with a bug, the reviewer rejects, the coder changes the wrong line, the reviewer rejects again. This cycle can run dozens of times with nobody noticing, and the bill only shows up the next morning 💸

So how do you bound it? The mitigation has two layers. The first layer is the runtime: recursion_limit. One thing often misquoted in tutorials: this number counts super-steps (each node that runs), not the number of review cycles. Its default is not 25 anymore either. So why is the number 10007? It moved three times: 25 in 1.0.0, 10000 in 1.0.6 through 1.1.x, then 10007 since 1.2.0. In LangGraph 1.2.16, the one I use here, DEFAULT_RECURSION_LIMIT holds 10007, and you can override it through the LANGGRAPH_DEFAULT_RECURSION_LIMIT environment variable or config at invoke.

When I tried it on a graph with a cycle and no stop condition, GraphRecursionError only appeared after 10007 steps. An empty graph like that finishes in two seconds, but those two seconds are wasted if every step is an LLM call. So the 25 that used to be the default is now yours to set. Which is what you want.

The second layer is design: a counter inside state, say iterasi <= 3. Past that, the flow diverts to an escalation node for a human. recursion_limit cannot replace this role, because that number only says "too many steps", not "review failed three times, stop".

AutoGen has a similar safety shape, just a different name. A group chat without termination_condition really does run forever, and the docs say so plainly. What people usually use is max_turns or TextMentionTermination.

Context that balloons

The second danger looks trivial: each agent appends the whole conversation history to state. After ten cycles, the context window is full of raw transcript that is no longer relevant, and the cost of each call keeps climbing.

The cure is pruning in the reducer: store only the latest artifact (the newest code file, a summary of review notes), not the full transcript. This is a design decision from the start, not a switch you flip later.

Checkpoint: why an agent can be paused

Modern graph frameworks save a snapshot of state every time execution moves between nodes. That snapshot is bound to thread_id and checkpoint_id in a persistent database: PostgresSaver for Postgres, RedisSaver for Redis, InMemorySaver for playing around locally.

From that checkpoint, three things become possible. If the container restarts in the middle of a forty-minute job, execution is resumed from the last checkpoint. For human approval before the release node, execution is paused via interrupt, state is saved, and the graph waits for resume. For debugging, an old state can be read back, edited, then replayed from that point.

One detail rarely mentioned: checkpoints are saved at super-step boundaries, not in the middle of a function. The consequence is that when an execution is paused and then resumed, the in-flight node is replayed from the top of the function. So its side effects are mandatory to be idempotent. Sending an email twice, cutting a balance twice: that is not theory, that really happens when the node is not prepared.

The code, in the version that runs today

Now let's look at the code. This is a revision graph with a safety catch. The reviewer deliberately uses fixed rules instead of an LLM, so it can be tested without an API key.

PYTHON
from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver

class TimState(TypedDict):
    tugas: str
    draf: str
    catatan_review: str
    iterasi: int

MAKS_REVISI = 3

def coder(state: TimState) -> dict:
    iterasi = state.get("iterasi", 0) + 1
    print(f"[coder] menulis draf ke-{iterasi}")
    return {"draf": f"def bayar(): return True  # versi {iterasi}", "iterasi": iterasi}

def reviewer(state: TimState) -> dict:
    lolos = state["iterasi"] >= 2   # in production this is an LLM call
    print(f"[reviewer] draf ke-{state['iterasi']} -> {'lolos' if lolos else 'ditolak'}")
    return {"catatan_review": "APPROVED" if lolos else "belum ada error handling"}

def deploy(state: TimState) -> dict:
    print("[deploy] disetujui, lanjut rilis")
    return {}

def eskalasi(state: TimState) -> dict:
    print("[eskalasi] batas revisi habis, lempar ke manusia")
    return {}

def arah_setelah_review(state: TimState) -> Literal["coder", "deploy", "eskalasi"]:
    if state["catatan_review"] == "APPROVED":
        return "deploy"
    if state["iterasi"] >= MAKS_REVISI:
        return "eskalasi"
    return "coder"

builder = StateGraph(TimState)
builder.add_node("coder", coder)
builder.add_node("reviewer", reviewer)
builder.add_node("deploy", deploy)
builder.add_node("eskalasi", eskalasi)

builder.add_edge(START, "coder")
builder.add_edge("coder", "reviewer")
builder.add_conditional_edges("reviewer", arah_setelah_review, ["coder", "deploy", "eskalasi"])
builder.add_edge("deploy", END)
builder.add_edge("eskalasi", END)

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

config = {"configurable": {"thread_id": "tugas-1"}}
app.invoke({"tugas": "tulis endpoint pembayaran"}, config)
print("state akhir:", app.get_state(config).values)

The output, run on LangGraph 1.2.16 and Python 3.12:

TEXT
[coder] menulis draf ke-1
[reviewer] draf ke-1 -> ditolak
[coder] menulis draf ke-2
[reviewer] draf ke-2 -> lolos
[deploy] disetujui, lanjut rilis
state akhir: {'tugas': 'tulis endpoint pembayaran', 'draf': 'def bayar(): return True  # versi 2', 'catatan_review': 'APPROVED', 'iterasi': 2}

If you make your reviewer always reject, the cycle stops at the third iteration and the flow moves to the escalation node. That is the core of the safety: the graph may still have cycles, but a number decides when to stop.

One note so you are not confused reading old tutorials: MemorySaver can still be imported, but it is now only an alias for InMemorySaver. Both work, one is behind the times.

What about AutoGen?

AutoGen often gets mentioned in the same breath as LangGraph, though the shape is different. AutoGen is closer to structured conversation: several agents with roles, one termination condition that decides when to stop. You do not define the graph yourself.

The status you need to know: since October 16, 2026 the project declares itself archived. That is firmer than merely stopping new features, because Microsoft states it provides no bug fixes, no security fixes, and no support for the project. Its last release, 0.7.5, can still be installed from PyPI, but do not expect patches after it.

The successor is Microsoft Agent Framework, built by the core teams of AutoGen and Semantic Kernel. Its workflow part offers two styles at once, functional and graph-based, and as of October 2026 the Python package is already stable (agent-framework 1.22.0).

One note for precision: what was archived is the project, not its GitHub repo. The page still opens and you can still star it today. And this is the claim most likely to go stale in the whole article, so check the date yourself before quoting it.

So linear or graph?

If the flow really is straight and nothing needs to come back, a linear chain is enough, and a graph only adds parts to maintain. A graph earns its keep once there is revision, branching, and a human who has to approve midway.

So does everything have to move to a graph? Not really. A sane multi-agent system does not mean letting several models chat freely. What makes it sane is a short list: narrow roles, state with a schema, an explicit cycle limit (you pick the number), and checkpoints that let the work be resumed whenever. ⚙️

If your agent starts running in an endless loop, the first thing to check is not the model, but whether a number bounds the cycle. The rest is tidying state and patiently reading traces. May your bill not surprise you at the end of the month 😄

Get better at shipping code.

Join the other developers getting tech updates, tips, and relaxed tutorials in their inbox every week.

Stay in the loop

Tech updates, coding tips, and relaxed insights straight to your inbox every week.

No spam. Unsubscribe anytime.

Read next

See all

For developers who learn by struggling

© 2026 Inva.dev.