Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 53/ 160
03. AI Agents

LangGraph

Graph-based agent workflows with explicit state, edges, cycles, and checkpoints.

AdvancedState Graph · Nodes/Edges3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

You draw the AI's workflow as boxes and arrows, with a shared notepad that every box can read and write, and the framework runs it step by step.

Think of it like…

A subway map for a task: stations are steps (nodes), lines are the allowed connections (edges), and the passenger carries a ticket with notes (state) that each station can stamp. Some lines loop back, some branch depending on the stamp, and a conductor can pause the train at a station and resume it later.

Where you’ve seen it

A support-triage workflow in LangGraph has nodes classify, retrieve_policy, draft_reply, check_policy, and human_review. After check_policy, a conditional edge routes to draft_reply again (cycle, max 2 times) if the draft violates policy, to human_review if the refund exceeds a threshold, or to send. A Postgres checkpointer stores state per thread_id, so when a reviewer approves two hours later the run resumes exactly where it stopped, and every step is visible in traces.

Words you’ll hear

State
A typed object (TypedDict or Pydantic model) holding the data passed between nodes.
Reducer
A rule for merging node updates into state, e.g. appending to a messages list.
Conditional edge
A routing function that picks the next node from the current state.
Checkpointer
A persistence layer that saves state after each step, keyed by thread id.

Visual diagram

Loading interactive diagram

Theory & deep dive

State, nodes and edges

Define state as a schema: class State(TypedDict): messages: Annotated[list, add_messages]; refund_amount: float; draft: str. The annotation tells LangGraph how to merge updates (the add_messages reducer appends rather than overwrites). A node is a function def draft_reply(state) -> dict returning only the fields it changes. Build with StateGraph(State), add_node, add_edge, add_conditional_edges("check_policy", route_fn) where route_fn(state) returns the next node's name, and compile(checkpointer=...). START and END mark the entry and exit.

Prebuilt helpers cover the common agent pattern: a model node, a tool node and a conditional edge that loops while the model emits tool calls (create_react_agent, which newer LangChain releases expose as create_agent; check your version). Custom graphs let you add validation, retries, parallel branches (fan-out and join), sub-graphs (a graph as a node) and multi-agent structures such as supervisors and handoffs. Because nodes are plain functions over state, you can unit test them without calling a model.

A conditional edge

def route(state): if state["violations"] and state["attempts"] < 2: return "draft_reply"; if state["refund_amount"] > 5000: return "human_review"; return "send" then graph.add_conditional_edges("check_policy", route).

Key takeaway: Typed state, small node functions, conditional edges and bounded cycles.

Persistence, human-in-the-loop and operating it

With a checkpointer (in-memory for development; SQLite or Postgres for production) LangGraph saves the state after each step under a thread_id you supply in the run config. That enables resuming after a crash, continuing a conversation across requests, inspecting or editing past state, and "time travel" (replaying from an earlier checkpoint). Interrupts pause the graph at a node (or when a node calls interrupt(...)) to wait for human input; the run resumes with the human's response, which can approve, reject or edit.

Operating notes: stream intermediate events and tokens to the UI; add recursion limits to stop runaway cycles; keep node side effects idempotent because retries and replays can re-run steps; version your state schema carefully when persisted threads exist; use LangSmith or another tracing tool to inspect runs; and consider whether you need a graph at all, since a simple loop or fixed workflow is easier when the flow is short and linear. Competing or alternative approaches include provider SDKs with built-in agent loops, workflow engines like Temporal for durable execution, and other graph frameworks.

Running with a thread id

app = graph.compile(checkpointer=PostgresSaver(...)); app.invoke({"messages": [...]}, config={"configurable": {"thread_id": "ticket-8841"}, "recursion_limit": 25}) and later app.invoke(Command(resume="approved"), config=...) continues the same thread after approval.

Key takeaway: Checkpoint by thread, interrupt for humans, limit recursion, keep nodes idempotent.

How it works, step by step

Step 1 of 4
Design

1. Sketch the workflow

List steps, decisions, loops and approval points, and decide the state each step needs.

classify → draft ⇄ check → review/send
Key numbers at this step
Draw
before coding

When to use it & trade-offs

What it is

LangGraph is a framework for building agent workflows as graphs. You define a state schema (the data flowing through the run), nodes (functions that read the state and return updates: call an LLM, run a tool, apply logic) and edges (which node runs next, including conditional edges that choose based on the state, and cycles for loops like "agent → tools → agent"). The graph is compiled into an app that can be run, streamed, checkpointed (state saved after each step), interrupted for human input and resumed. It gives explicit control over flow where a free-form agent loop would be unpredictable.

Why it matters: Real agents need more than a loop: branching on conditions, retries, parallel branches, approvals, persistence, resumption after failures and visibility into what happened. Expressing the flow as a graph with typed state makes it testable and debuggable, and checkpointing makes long-running or human-in-the-loop flows practical. LangGraph is one of the most widely used orchestration frameworks, and the ideas (state, nodes, edges, checkpoints) apply to other tools too.

When to reach for it

  • Approval-gated customer-support and operations flows
  • Multi-step agents needing retries and branches
  • Long-running jobs that must resume after failure

When to avoid or be careful

  • A graph for a three-step linear pipeline
  • Cycles with no counter or recursion limit
  • Non-idempotent side effects in nodes that may be replayed

Orchestration options

LangGraph (graph + checkpoints)
Best for: Branching, cyclic, resumable agent workflows

Strengths: Explicit control; persistence; human-in-the-loop; tracing.

Watch out: More concepts than a simple loop.

Simple loop or SDK agent
Best for: Straightforward tool-using agents

Strengths: Little code; easy to reason about.

Watch out: Less control over complex flows.

Durable workflow engine (Temporal, etc.)
Best for: Long-running, mission-critical processes

Strengths: Strong guarantees on retries and durability.

Watch out: Heavier infrastructure; not LLM-specific.

Interview signals & numbers to know

When this topic comes up

  • “How do we pause an agent for approval?”
  • “The agent needs to resume after a crash”
  • “What is LangGraph?”
  • State machines for LLM apps
  • Checkpoint and time travel

Benchmarks & rules of thumb

25 -
a common recursion limit setting
thread_id -
the key for persisted state
2 -
max draft iterations in the example

Common mistakes & follow-ups

Common interview mistakes

  • Overwriting the messages list in a node instead of appending with a reducer.
  • Sending an email inside a node that can be re-run on resume, without an idempotency key.
  • Using the in-memory checkpointer in production and losing state on restart.

Likely interviewer follow-ups

  • How does LangGraph differ from a plain agent loop?
  • How would you implement human approval in a LangGraph workflow?
  • What makes a node safe to replay?
Interview tip: Describe a concrete graph (classify, draft, check, review) and point to where the cycle bound and the checkpoint live. Concrete beats abstract.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply LangGraph with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Orchestrator-Worker Pattern
Next topic
OpenAI Agents SDK