Lesson 4 of 11
Chapter 18 . LangGraph . Lesson 4 of 11

Retries with a limit

An edge can point back to an earlier node. That makes a loop, and every loop needs a cap.

01Real-world example

Illustration: Like Playwright's retries: rerun a failing test up to three times. A pass after a failure marks the test as flaky.
Like Playwright's retries: rerun a failing test up to three times. A pass after a failure marks the test as flaky.

02The graph

Retries with a limit as a graph
should_retry() sends a failed test back to run_test, three times at most.

03How the code does it

  • should_retry() returns "run_test" to loop back or "report" to stop: an edge that points backwards.
  • MAX_ATTEMPTS is the cap. Without it a broken test loops until the recursion limit, which is 10007 steps by default on langgraph 1.2.12.
  • scripted_outcomes makes the run repeatable: the same input gives the same verdict every time, so the demo can show flakiness on purpose.

Key points

  • A loop is an edge that points back
  • Keep the counter in the state
  • Set recursion_limit as a backstop

04Run it

terminal
cd chapter_18_LangGraph/src/chapters
python 004_Loop_Retry.py
output
login_redirect (flaky)
   attempt 1: failed
   attempt 2: failed
   attempt 3: passed
   => FLAKY: passed on attempt 3 after 2 failure(s)