HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 41“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
LangGraph and Stateful Agent Workflows
TechLearningPro's refund desk asked for a workflow the lesson-reply chain cannot express.
Course progress0%
Focus
23 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
AI-Powered Full Stack Development · Lesson 41 · AI Agents, Workflow Automation and Integrations
Lesson Overview
TechLearningPro's refund desk asked for a workflow the lesson-reply chain cannot express. A specialist opens a ticket. The system drafts a finding from the ticket the specialist is allowed to see. A policy check either accepts the finding, asks for one revision, or stops. If the finding recommends a credit, the workflow pauses until a human approves. The first implementation was a recursive function and a handful of booleans. A deploy mid-draft lost the state. A second implementation imported a graph library — the family of packages people mean by LangGraph — into the route and stored the full prompt in a checkpoint row. The checkpoint table became a second copy of customer text, and a library upgrade renamed the builder the route called.
The fix is to treat the graph as an architecture you own. State is a typed object. Nodes are functions that return a partial update. Edges are fixed or conditional. Cycles exist and carry a step budget. A checkpoint stores the state you need to resume, not the prompt body. An interrupt sets the status to paused before any credit is written. LangGraph's published builders stay in an optional adapter. The route calls WorkflowRuntime.
The lab runtime is TypeScript. It does not import LangGraph.
Published graph libraries rename node builders, edge helpers, checkpointers, and interrupt helpers between versions. Verify those names against the docs for the version you pin. This lesson teaches the workflow shape, not a constructor.
The checkpoint store in tests is in-memory. Production uses PostgreSQL keyed by tenant_id and run_id.
The model is called at most twice in the happy revision path: draft, then one revise. A third model call is a bug.
No credit is posted. paused is the furthest a refund-shaped decision gets.
Prompt version is refund-finding-v1. Timeouts stay at 8 seconds, inherited from Lesson 23.
Learning Objectives
By the end of this lesson you will be able to:
Explain a stateful workflow as a graph over a typed state, not as an open-ended agent loop.
Distinguish a node (work) from an edge (which node runs next).
Implement a conditional edge that chooses revise, pause, complete, or fail.
Enforce a step budget so a cycle cannot run until the token cap melts.
Persist a checkpoint that is enough to resume, and omit prompt text and secrets.
Resume a paused run only for the same tenant, and only through an explicit resume call.
Show that a process restart can load the checkpoint and continue without a second draft when the status is already paused.
Keep ledger writes out of every node. The pause is the handoff to Lesson 45's approval flow.
Describe LangGraph's ideas — state, nodes, conditional edges, checkpoints, interrupts — and state that package method names must be copied from current docs.
Test a fake model that returns a revise decision once and a pause decision next.
Test a failure path: policy input missing returns failed and never calls the model.
Record node id, step count, and status in a trace.
Explain why a graph checkpoint is not conversation memory from Lesson 38.
Isolate a graph-library adapter so the route depends on WorkflowRuntime.
Prepare Lesson 42 to stream status events from a run without streaming an unapproved credit.
You can read a discriminated union and a Map. You do not need a LangGraph account or a provider key.
What is LangGraph and Stateful Agent Workflows?
LangGraph is a library family, associated with the LangChain ecosystem, for running model-driven workflows as graphs that can cycle, pause, and resume. Stateful agent workflows, in this course, means that same shape under your types: a refund-finding run whose state survives a restart and whose next node is a function of that state, not a hidden stack of the model.
The purpose is control. A chain from Lesson 40 is a straight line. The refund desk needs a line that can bend once back to "draft again," then stop, and that can wait overnight for a specialist. Graphs exist in workflow engines outside AI — queues, business process tools, bank payment state machines. LangGraph applied that idea to model nodes. TechLearningPro applies it to a ticket finding without adopting the library's types in the route.
You will read, in current docs, about compiling a graph, adding nodes, and installing a checkpointer. Those words describe the architecture. The method names that implement them change. The lab runtime below is the source of truth for the course. If you later wrap the published library, the adapter must round-trip the state in this lesson's interface and must pass the same tests.
Restart loses the draft, or a loop calls the model
until the budget is gone
|
v
A graph library in the route stores prompts
in a checkpoint and breaks on upgrade
|
v
WorkflowRuntime with a typed state, a step budget,
a content-free checkpoint, and a pause
Benefits:
A deploy does not forget that a ticket is waiting for approval.
The revise cycle is visible and capped.
Tests force each decision without a vendor.
Staff can explain the run from status and stepCount.
The ledger stays unwired until a later lesson adds an approval record.
Real World Example
A specialist at TechLearningPro opens ticket t_104 for tenant A. The runtime creates run_104, loads the ticket summary the specialist may see, and drafts a finding. The policy node classifies the finding as revise because the draft omitted the purchase date that was in the summary. The draft node runs once more. The policy node returns pause because the revised finding recommends a credit. The checkpoint stores paused. The UI says the finding is waiting. Nobody has posted a credit.
Banks run payment investigations with the same pause: a model or a rules engine may recommend, and a person releases the money. Amazon return workflows and Microsoft support macros separate recommendation from execution. Google's internal workflow systems and Netflix's content-ops pipelines checkpoint long jobs for the same reason a refund draft must survive a restart. The graph is not what makes the action safe. The pause, the authorization check, and the absence of a ledger call are what make it safe.
Internal Working
start authenticates the specialist and checks TicketPort for tenant, ticket, and role. A missing ticket returns failed with reason not_found and does not call the model.
The runtime builds the initial state: status: "running", stepCount: 0, empty finding, decision: "draft".
It saves a checkpoint, then enters the loop. The loop reads the conditional edge. draft runs the draft node. pause, completed, and failed stop the loop.
The draft node calls ModelPort once with the ticket summary in the user message and refund-finding-v1 in the system message. It increments stepCount.
The policy node is deterministic. It does not call a model. It looks at flags the draft parser produced: missingDate, recommendsCredit, ok.
If missingDate and stepCount is still under the budget, decision becomes revise and the edge returns to draft. If the budget is exhausted, decision becomes fail.
If recommendsCredit, decision becomes pause and status becomes paused. The runtime saves and returns. It does not call a payment port.
If ok and no credit is recommended, status becomes completed. The finding is explanatory only.
resume loads the checkpoint. It requires the same tenantId. If status is not paused, it returns the stored state and does not call the model. A human decision of reject completes the run with creditApproved: false. A human decision of approve completes the run with creditApproved: true in state only. Posting the credit is still not this lesson's write.
Architecture
flowchart TB
subgraph staff [Staff UI]
Desk[Refund desk]
end
subgraph runtime [Workflow runtime]
Start[start]
Draft[draft node]
Policy[policy node]
Pause[paused interrupt]
EndNode[completed or failed]
Store[Checkpoint store]
end
subgraph ports [Ports]
Tickets[TicketPort]
Model[ModelPort v1]
end
Desk --> Start
Start --> Tickets
Start --> Draft
Draft --> Model
Draft --> Policy
Policy -->|revise and budget remains| Draft
Policy -->|recommends credit| Pause
Policy -->|explain only| EndNode
Policy -->|budget exhausted| EndNode
Draft --> Store
Pause --> Store
EndNode --> Store
text
start(tenant, ticket)
|
v
checkpoint running
|
v
draft node -- ModelPort --> finding flags
|
v
policy node -- deterministic
|
+--> revise --> draft (while stepCount allows)
+--> pause --> save and return
+--> complete or fail --> save and return
|
resume(tenant, runId, humanDecision)
|
v
same checkpoint, no new model call
|
x ledger write is absent
The browser talks to your API. The checkpoint table is yours. The provider sees one completion at a time and does not store the graph.
Deep Dive
State versus conversation memory
Lesson 38 memory is what the product may quote back to a learner, under that learner's retention rules. A workflow checkpoint is an operational record: where a run stopped. Mixing them means a prompt log lives in an ops table, or a resume loads another user's chat. RefundState holds ids, a short finding string the specialist will review, flags, and status. It does not hold the system template. The template is a constant in code, as in Lesson 40.
Nodes return patches
A node returns the fields it changes. The runtime merges them into state. That merge is shallow and explicit so a node cannot drop tenantId. In the lab, the runtime assigns known keys only. A node that returns a provider payload is a leak. Map the model text to flags inside the node, then discard the raw text after the finding string is set.
Conditional edges and cycles
The edge function is total. Every decision maps to a node name or END. revise is the only edge that cycles, and only when stepCount < MAX_STEPS. MAX_STEPS is 4, which allows an initial draft and one revision with their policy checks. Raising it is a budget change reviewed with Lesson 19, not a prompt tweak.
Interrupts
An interrupt is a pause the runtime understands. Some graph libraries model it as a special exception or a reserved node. Those mechanisms differ by version. Verify them if you wrap a library. In this runtime, pause is a status value plus a saved checkpoint. There is no stack to unwind and no half-open tool call.
Checkpoints and idempotency
runId is created by the server. A second start with the same runId returns the existing checkpoint and does not draft again. That is the restart story and the double-click story. resume is also idempotent for a terminal state: a second resume returns the stored state.
Human decisions are data
approve and reject are a closed union from the staff API. They are not model output. The model may set recommendsCredit. Only the specialist's resume sets creditApproved. Even then the boolean is a record of intent on this run. It is not the pending review executeSupportTool inserts for open_refund_review, and it is not the approval ticket Lesson 45 will execute. This lesson stops at the boolean so the boundary stays testable.
Library adapter boundary
A future adapter may call a published graph runtime. It must: accept and return RefundState, honor MAX_STEPS, persist through CheckpointStore, and refuse to register a node that receives a payment client. The route file's imports stay on ./runtime.js. The adapter's header comment records the library version and the doc URL you verified that day.
const state =await deps.store.load(tenantId, runId);
if(!state)return{ ok:false, reason:"not_found"};
if(state.status !=="paused")return state;
const next: RefundState ={
...state,
status:"completed",
decision:"complete",
creditApproved: human ==="approve",
};
await deps.store.save(next);
return next;
},
};
}
FindingModel is the node boundary. A production adapter implements it with ModelPort and a parser. Tests implement it with a script of answers. The runtime never sees a vendor type.
A library adapter, if you add one, sits between FindingModel or the whole runtime and the pinned package. The checkpoint it writes still goes through CheckpointStore, so a second serializer cannot quietly store the prompt.
Real-Time Enterprise Example
Production checkpoints live in workflow_checkpoints (tenant_id, run_id, status, step_count, decision, finding, credit_approved, updated_at). finding is the specialist-facing paragraph, retained with the ticket's policy. The system prompt is not a column. Row-level security uses tenant_id from the session, matching Lesson 34's isolation habit.
The staff UI polls or subscribes to your API for status. It shows "Waiting for approval" when paused. The approve button calls resume. It is enabled only for a specialist role. Learners never see this route.
Long-running challenge: a draft that exceeds 8 seconds fails as unavailable through the model adapter's timeout mapping. The checkpoint keeps the previous finding if one was saved. The specialist may start a new runId. The runtime does not spin. High-traffic challenge: one in-flight run per ticket, enforced by a unique partial index on (tenant_id, ticket_id) where status is running or paused. A second click returns the existing run.
Provider-outage challenge: FindingModel returns unavailable and the run is failed with that reason. Because start is idempotent only for the same runId, the specialist's retry uses a new id and a new budget. It does not loop inside the node.
Performance Optimization
The loop is bounded by MAX_STEPS and by the statuses that break. Each model call is a full complete, not a stream, so the specialist waits for a finding they can read. Streaming a half-written credit recommendation is a Lesson 42 concern and is a poor fit here: the policy node needs the whole JSON.
Checkpoint writes happen after each node so a crash loses at most the in-flight model call, not the previous finding. That is one extra row write per step, which is cheap next to the model. Do not write a checkpoint per token.
Keep the ticket summary small. TicketPort returns the fields the prompt is allowed to see, already trimmed. The runtime does not load attachments. CPU for the policy function is irrelevant. Spend attention on the step budget and on not drafting again on resume.
If you wrap a graph library, measure its serializer. A checkpoint that base64-encodes the entire message list will dominate storage and will copy personal data into a table your ops role can read. Prefer this state object.
Authorization.TicketPort checks tenant and role. resume loads with the session tenant. Cross-tenant resume returns not_found.
Least privilege. The workflow role can read tickets and write checkpoints. It has no payment grant.
Validation. Human decisions are approve or reject. Model flags are booleans from your parser, not from the client.
Secrets.FindingModel implementations that call ModelPort keep secret handles inside the adapter. The state has no credential field.
Tenant isolation. Store keys and SQL predicates include tenant_id.
Injection. The ticket summary is user-visible data in the user message inside FindingModel. It cannot add a node or raise MAX_STEPS.
Audit.resume should later write an approval row. This lesson at least stores creditApproved with the run id. Do not treat the model finding as the audit record.
OWASP themes: broken access control (resume without tenant), insecure design (model posts a credit), and sensitive data exposure (prompt in the checkpoint). The controls are the tenant key, the missing payment port, and the slim state.
Common Mistakes
Putting the graph library in the route. Symptom: an upgrade breaks refund drafts. Cause: the builder API was called from the handler. Fix: call WorkflowRuntime. Confine any library to an adapter after you verify its docs.
Checkpointing the full prompt. Symptom: customer text is duplicated into an ops table. Cause: the library's default serializer saved messages. Fix: persist RefundState only.
No step budget. Symptom: revise cycles until the account is rate limited. Cause: missingDate always looped. Fix: MAX_STEPS and a budget failure.
Calling the model on resume. Symptom: the approved finding changes after the human clicked. Cause: resume ran the draft node. Fix: resume only flips creditApproved and status.
Posting the credit inside the pause node. Symptom: money moves before the specialist acts. Cause: a payment client was injected "so the graph could finish." Fix: no payment dependency. Lesson 45 owns the effect.
Using conversation memory as the checkpoint. Symptom: a learner's chat resume loads a staff finding, or the reverse. Cause: one table for two jobs. Fix: separate stores and keys.
Trusting the client for tenantId. Symptom: a forged body reads another tenant's run. Cause: the id came from JSON. Fix: session tenant only.
Double draft on retry. Symptom: two findings for one click. Cause: start always inserted. Fix: return the existing checkpoint for the same runId.
Model sets creditApproved. Symptom: a prompt injection approves a credit. Cause: that field was parsed from model JSON. Fix: the model may set recommendsCredit. Only resume sets creditApproved.
Abort leaves status running forever. Symptom: the unique index blocks a new run. Cause: the signal was ignored. Fix: on abort, save failed. A production system may instead save paused if a partial finding is worth keeping. Pick one and test it.
Logging the ticket summary in the runtime. Symptom: support notes in the app log. Cause: a debug dump of state. Fix: log runId, status, stepCount, and decision.
Copying an interrupt helper from a blog. Symptom: the pause never persists on the version you installed. Cause: the helper's name or semantics moved. Fix: status paused plus CheckpointStore, unless an adapter test proves the library matches this behavior.
Best Practices
Make state a reviewed type, not a free-form bag.
Keep tenant id immutable inside the runtime.
Merge node results by known fields.
Make the edge function total and unit-test it.
Cap cycles with MAX_STEPS.
Save a checkpoint after each node that called the model.
Make start idempotent on runId.
Make resume a no-op when the run is already terminal.
Load checkpoints with the session tenant.
Keep templates in code, not in the checkpoint.
Separate workflow state from conversation memory.
Let the model recommend. Let the human set creditApproved.
Do not inject a payment, email, or grade client.
Map provider failures to failed and stop.
Pass AbortSignal into the model node.
Test the no-ticket path, the revise-then-pause path, and the cross-tenant resume.
Log ids and statuses, not summaries.
If you pin a graph library, record the version and the doc URL, and rerun these tests through the adapter.
Enforce one active run per ticket in the database.
Leave ledger idempotency to the approval lesson.
Do not stream an unfinished finding into an approval button.
Review a new node the way you review a new write: list the ports it holds.
Interview Questions & Answers
Beginner
Why use a graph when Lesson 40 already has a chain?
A chain is a straight sequence. A refund finding may return to draft once and then wait for a person. A graph makes that branch and that pause explicit. The chain's model call can still sit inside the draft node.
What is a checkpoint?
A saved RefundState for a tenant and a run id. After a restart, start with the same id returns it. The checkpoint is not a copy of the prompt and not the learner's chat memory.
What does the model get to decide?
The finding text and the flags missingDate and recommendsCredit, after your parser accepts them. It does not decide creditApproved, and it does not call the ledger.
Intermediate
How do you stop a revise cycle? applyPolicy checks stepCount against MAX_STEPS. When the budget is exhausted and the date is still missing, the run fails with budget. The while-loop only continues while nextNode says draft.
Why is resume safe to call twice?
The first resume moves paused to completed and saves. The second load sees a terminal status and returns it without calling FindingModel. The test counts model calls and expects them to stay constant across resume.
What would you verify in LangGraph's docs before adopting it?
How a node is registered, how conditional edges are declared, what a checkpointer persists by default, and how a human interrupt is represented, for the exact version you pin. Then you prove your adapter still omits prompts from storage and still refuses a second model call on resume.
Senior
A crash happens after the model responds and before save. What is the user-visible outcome?
The previous checkpoint remains. A retry of the same runId returns that older state if you saved before the call, or re-enters the node if you only saved after success. This runtime saves after a successful policy merge and on failure. A crash during the call can repeat that call on a new start only if no checkpoint was written for that step. Document that duplicate draft risk and keep the payment out of the node so a repeat cannot double-charge.
How is this different from a queue of steps?
A queue can run a straight workflow. A conditional cycle plus a long pause is awkward as ad-hoc jobs. The graph keeps the decision in one state object. A queue is still useful to host the runtime off the request thread when drafts get slow. The state machine stays the source of truth either way.
Architect
How would you split this across services?
One service owns WorkflowRuntime and the checkpoint table. TicketPort and ModelPort are remote or in-process ports. The payment service is not called. Staff identity is validated at the edge. A second service that "helps" by reading checkpoints must use the same tenant predicate and must not be the model vendor.
When would you allow a graph library to own the checkpoint format?
Almost never for this product. If a platform team standardizes on one engine, the adapter may store the engine's blob only after a test proves it excludes message bodies, or you store RefundState yourself and use the engine as a runner. Owning the row shape keeps audits and row-level security in PostgreSQL.
How do you connect this to evaluation?
Sample paused findings. Score whether missingDate matched the summary, not whether the prose was pretty. Track step count and budget failures as cost signals. Do not send the specialist's later approval back into the model as an automatic reward loop in production without a reviewed dataset.
What should Lesson 42 and Lesson 45 add, and what must they leave alone?
Lesson 42 may stream status (running, paused) to a staff panel. It should not stream a credit posting. Lesson 45 may turn creditApproved: true into an audited, reversible ledger command with an idempotency key. It should not move that command into the draft node.
Knowledge Check
1. What problem does this capability solve?
It lets a refund finding revise a bounded number of times, pause for a human, and survive a restart, using the graph ideas associated with LangGraph, without storing prompts in a library checkpoint or posting a credit.
2. What alternatives exist, and when would you choose each?
A Lesson 40 chain fits a straight draft. This runtime fits a capped cycle plus a pause. A pinned graph library fits a team that will wrap it in an adapter and retest persistence. An unbounded agent loop fits none of the refund paths. A human-only form fits when you do not want a model draft at all.
3. Which data, identity, and trust boundaries matter?
Staff identity and session tenant gate start and resume. Ticket text is authorized by TicketPort. Model output is untrusted until parsed into flags. creditApproved is human data. Checkpoints are operational state, not chat memory.
4. What can fail, and how should the system respond?
Unknown tickets fail with no model call. Model failures mark the run failed. Budget exhaustion stops the cycle. Abort saves a failure. Cross-tenant resume returns not_found. The ledger does not move.
5. How would you test quality, security, performance, and cost?
Script the model: revise once, then pause, and count two calls. Repeat start and assert the count is unchanged. Resume as another tenant and expect not_found. Assert MAX_STEPS fails a run that always returns missingDate. Cost is the call count. Security is the absent payment port and the tenant key.
Key Takeaways
A stateful workflow is a typed state plus nodes and edges.
LangGraph names this shape in the library ecosystem. Your route depends on WorkflowRuntime.
Verify library method names in the docs for the version you pin.
The only cycle is revise, and MAX_STEPS ends it.
Pause is a status, not a ledger write.
Checkpoints store RefundState, not prompts or secrets.
start is idempotent on tenant and run id.
resume does not call the model.
The model may recommend a credit. A human sets creditApproved.
Conversation memory and checkpoints are different stores.
Tenant id comes from the session and is part of the store key.
Policy is deterministic and unit-testable.
Provider failures stop the run.
One active run per ticket belongs in the database.
Streaming status and posting credits are later lessons.
Summary
Lesson 41 gives the refund desk a graph it can resume. Draft and policy alternate only while the step budget allows. A credit recommendation pauses the run and writes a checkpoint the specialist can approve later. The model port stays behind FindingModel. A graph library, if adopted, has to prove it preserves those rules. The workflow is now explicit enough for a staff UI to show status as a stream, which is the next lesson, and explicit enough that a later approval step can post a reversible credit without teaching the draft node how money moves.
Next Lesson Preview
AI SDKs and Streaming UI Integration connects a run like this one, and the tutor stream from Lesson 16, to a panel. You will map server events to UI state, keep tool proposals from looking like finished actions, and place any vendor UI SDK behind an adapter whose hook names you have checked in current docs.
Deliverable and Rubric
Submit the state diagram, the runtime tests, a checkpoint field list that excludes prompts and secrets, and a note on what resume is allowed to change. If you evaluated a graph library, include the version and the doc URL you read.
The current LangGraph documentation for the language you use. Copy builder and checkpointer names from that page, pin the version, and keep them inside an adapter.