Coding an Agent: DAG Workflow Backend (Assignment Walkthrough)
The assignment: mini workflow engine
Original assignment: build a mini workflow orchestration engine. A backend accepts workflows via HTTP. Steps run inside a leased Kubernetes runner pod.
- Step queue - decides execution order
- Result queue - sends results back to the backend asynchronously
- DAG resolver - respects dependencies between steps
- Pod manager - owns execution (acquire pod, exec command, release pod), not workflow state
- Backend - owns all state and writes every status; user can query steps any time
Step lifecycle in the backend:
Pending -> Queued (pushed to queue) -> Running (pod manager acquires pod) -> Completed or Failed
Invariant: a step is running if and only if its pod lease exists. Lease gone means the step is not running.
Simplified version used in class: drop Kubernetes and queues. Keep the HTTP endpoint, the DAG resolution and a run-agent function.
What a workflow looks like
DAG - directed (every edge goes from one node to another), acyclic (no loops), graph.
Example
Step A has no dependency. B and C depend on A. D depends on B and C. Order: A first, then B and C together, then D.
Each node is a natural-language prompt, e.g. 'What is the date right now?', 'What is 2+2?'. The agent may call tools (sleep, bash, datetime) to answer. A frontend could let users build this graph visually and submit it.
Step 1: Express endpoint with Zod validation
const stepSchema = z.object({
id: z.string(),
prompt: z.string(),
dependsOn: z.array(z.string()).optional(),
});
const createWorkflowSchema = z.object({
workflowId: z.string(),
steps: z.array(stepSchema),
});
app.use(express.json());
app.post('/workflow', async (req, res) => {
const { success, data, error } = createWorkflowSchema.safeParse(req.body.workflow);
if (!success) {
console.log(error);
return res.status(411).json({ message: 'Incorrect inputs' });
}
const results = await resolveGraph(data.steps);
res.json({ message: 'ok', results });
});- Missing express.json() -> req.body is undefined -> 500 error
- Wrong route -> 404
- Body was nested under 'workflow', so parse req.body.workflow, not req.body. Logging the Zod error exposed this.
Response schema: message plus results, an array of { id, result } for every step.
Step 2: Resolving the DAG recursively
Algorithm (recursive, Kahn-style layering):
- Find every node whose dependsOn is empty -> can run now
- Run them all with run agent via Promise.all (concurrent)
- For remaining nodes, filter the finished ids out of dependsOn
- Remove finished nodes from the graph
- Recurse on the smaller graph
- If graph is empty, return []
async function resolveGraph(graph: Step[]): Promise<{id:string,result:string}[]> {
if (!graph.length) return [];
const ready = graph.filter(n => !n.dependsOn?.length);
const outs = await Promise.all(ready.map(n => runAgent(n.prompt)));
const doneIds = ready.map(n => n.id);
const next = graph
.filter(n => !doneIds.includes(n.id))
.map(n => ({ ...n, dependsOn: (n.dependsOn ?? []).filter(d => !doneIds.includes(d)) }));
const rest = await resolveGraph(next);
return [...outs.map((r, i) => ({ id: ready[i].id, result: r })), ...rest];
}Test: logging each prompt showed A first, then B, C (and a third independent step E), then D. Order stayed correct even when the steps were listed in a different order.
A graph with a cycle would never get nodes with zero dependencies, so this recursion would not terminate usefully. Input must be acyclic.
Step 3: run agent without tools
runAgent is a black box: prompt in, final response string out. Without tools it is a single LLM call via the SDK (ai.models.generateContent, then read response text).
- Keep the API key in .env
- Delete or rotate keys that were shown on screen
- LLM calls are slow, so concurrent steps matter
Adding tools later turns this into the ReAct-style loop from earlier lectures. The harder engineering part would be streaming results to the frontend as each step finishes.
Remaining steps (homework)
- Step 1: boilerplate (done)
- Step 2: resolve the DAG and call runAgent (done)
- Step 3: runAgent with a plain LLM call (done)
- Step 4: runAgent with tools
- Step 5: stream results so the user sees each node fill in as it finishes
Libraries like LangGraph can live inside runAgent, not around the DAG resolver. Many agent tools are written in TypeScript (Claude Code, Cursor, Pi) and Codex in Rust; Python is common mainly because most engineers know it.
Glossary
- DAG
- Directed acyclic graph: edges have direction and there are no cycles.
- Workflow
- A set of steps with dependencies, each step being a prompt for an agent.
- Zod
- TypeScript library for defining and validating data schemas.
- Promise.all
- Runs several async tasks concurrently and waits for all.
- Pod lease
- Temporary claim on a Kubernetes pod while a step runs.