Stopping Loops
Exit conditions.
A loop that waits for success might wait forever, if success never comes. So good loops have two exits. One when the job is done, and one when we've tried enough times.

- Success may never come
- Two exits
- Done, or tried enough
Retry with a limit
Call service pretends to call a flaky stock service. It takes the next result from a list, and counts the attempts. The router has three outcomes. Done if it worked, give up after three attempts, otherwise try again. Run it. The first run succeeds on the third try. The second never succeeds, so it gives up after three.
from typing import TypedDict
from langgraph.graph import StateGraph, START, END
class State(TypedDict):
results: list[str]
attempts: int
status: str
def call_service(s):
status, rest = s["results"][0], s["results"][1:]
return {"status": status, "results": rest, "attempts": s["attempts"] + 1}
def route(s):
if s["status"] == "ok" or s["attempts"] >= 3: return END
return "call_service"
b = StateGraph(State); b.add_node(call_service); b.add_edge(START, "call_service")
b.add_conditional_edges("call_service", route)
for results in [["timeout", "timeout", "ok"], ["timeout"] * 5]:
out = b.compile().invoke({"results": results, "attempts": 0})
print(out["status"], "after", out["attempts"], "attempts")ok after 3 attempts timeout after 3 attempts
Exit conditions
Every loop needs an exit you can prove. A success check. A counter, with a maximum. Or a list that gets shorter each time, like our packing loop. Store the counter in the state, so the router can see it.
| key | value |
|---|---|
| Success | stop when done |
| Counter | stop at a maximum |
| Shrinking list | stop when empty |
| In state | so the router sees it |
Summary
Good loops stop on success, or after a maximum number of tries. Keep the counter in the state. Next, LangGraph's own safety net for loops.
Key takeaways- Success exit
- Max attempts
- Counter in state