Build a Workflow Engine with an AI Coding Assistant
System DesignModel answerLast updated
Design, implement, and verify a two-endpoint workflow service—create and execute—in 45 minutes while demonstrating a disciplined plan-then-code loop with an AI assistant.
The Task
You have 45 minutes and access to an AI coding assistant. Use it to build a small backend service that manages and runs workflows. The service needs exactly two endpoints:
- POST /workflows — accept a workflow definition, validate it, persist it, and return a unique identifier.
- POST /workflows/:id/run — load a stored workflow, execute it against a provided input, and return a per-step summary of what happened.
The interviewer is watching how you collaborate with the assistant, not counting lines of code. The goal is to show a deliberate plan-before-code habit, critical review of whatever the assistant produces, and a working tested slice by the end of the session.
What is a Workflow?
The prompt leaves this open on purpose. A reasonable starting definition:
- A workflow has a name and an ordered-or-unordered set of steps.
- Each step has a unique ID, names one action from a fixed server-side registry, carries its own static parameters, and may declare dependencies on other step IDs.
- When a workflow runs, each step receives its static parameters plus the outputs of whatever steps it depends on.
- The run returns a result object that records the final status and output of every step.
You may simplify or extend this — but whatever you choose, state it explicitly before touching any code.
Clarifying Questions to Settle Before Coding
Think through (and ask the interviewer about) these before writing a plan:
- Are dependencies a flat list or a full DAG? Can independent steps run in parallel, or is serial topological order fine for this session?
- What actions can a step call — only a hard-coded in-process registry, or arbitrary HTTP endpoints?
- Does
POST /workflows/:id/runblock until the run finishes, or does it return a run ID for the client to poll? - When a step fails, does the entire run abort, or do steps that don't depend on the failed step still execute?
- Does state need to survive a process restart, or is in-memory storage acceptable?
- Can a stored workflow be updated after creation? If so, which version does an in-flight run use?
What Each Part Should Demonstrate
Part 1 — Plan with the assistant
Produce a short written plan before generating any code. It should cover:
- The assumptions you chose and any scope you deliberately cut to fit the time box.
- A concrete JSON schema for a workflow definition and for both request/response bodies, including what error responses look like.
- A list of tests you intend to write, named before implementation begins.
- Evidence that you steered the assistant rather than accepted its first output wholesale.
Part 2 — Implement the two endpoints
Build POST /workflows and POST /workflows/:id/run. Requirements:
- Creation-time validation: reject definitions that reference unknown actions, contain duplicate step IDs, point to non-existent dependency steps, or contain a dependency cycle.
- Execution: run steps in an order that satisfies all dependencies; pass each step the outputs of its declared predecessors; catch step-level errors without crashing the service.
- HTTP layer: return appropriate status codes (201, 400, 404, 500); keep routing code thin and separate from core logic.
Part 3 — Verify correctness
Demonstrate that the service behaves correctly by:
- Running tests that cover the happy path, out-of-order step definitions, each category of invalid definition, and a step that throws at runtime.
- Diagnosing any test failures rather than commenting them out or patching without understanding.
- Reviewing the assistant's generated code for hallucinated library calls, silently swallowed errors, and branches that have no test coverage.
Hints
Hint 1
Start by writing your test list before asking the assistant for any code. Naming the tests first forces you to pin down the exact behavior you want — cycle detection, failure propagation, out-of-order deps — and gives you a checklist to drive the implementation conversation instead of reacting to whatever the assistant generates first.
Hint 2
Separate the problem into three layers before coding: (1) a pure validator that checks the workflow definition in isolation, (2) a pure executor that takes a validated workflow and an input map and returns a result map, and (3) a thin HTTP shell that wires them together. Ask the assistant to implement each layer independently so you can test the hard logic without spinning up a server.
Hint 3
After the assistant writes the dependency-ordering logic, ask it to walk you through the algorithm on a concrete example: three steps where C depends on B and B depends on A, all defined in reverse order. If it can't narrate the traversal correctly, the code probably has a bug you should find before running tests.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
What a Strong Answer Looks Like
A strong candidate treats this as a demonstration of engineering judgment, not a speed-coding contest. The interview has three distinct phases; each one has failure modes worth knowing.
Phase 1 — Planning (roughly the first 10 minutes)
Before typing a single line of code, use the assistant to produce a written plan. This is the most important signal: candidates who skip straight to code generation almost always run out of time or produce something untestable.
Scope decisions to state out loud:
- In-memory storage only — no database.
- Synchronous execution —
POST /runblocks and returns the full result. - Serial topological order — no parallel step execution.
- On step failure: mark the step as failed, skip all downstream dependents, continue everything else.
- Actions come from a small hard-coded registry (e.g.,
add,multiply,concat).
Workflow schema (example):
{
"name": "compute-discount",
"steps": [
{ "id": "base", "action": "multiply", "params": { "b": 10 }, "depends_on": [] },
{ "id": "final", "action": "add", "params": { "b": 5 }, "depends_on": ["base"] }
]
}
Test list written before any code:
- Create a valid two-step workflow — expect 201 and a returned ID.
- Create a workflow with a duplicate step ID — expect 400.
- Create a workflow with an unknown action — expect 400.
- Create a workflow with a dependency on a non-existent step — expect 400.
- Create a workflow with a cycle (A → B → A) — expect 400.
- Execute a workflow with steps defined out of dependency order — all steps complete successfully.
- Execute a workflow where one step fails — that step is
failed, its dependents areskipped, independent steps stillcompleted. - Execute with a workflow ID that doesn't exist — expect 404.
Writing this list first accomplishes two things: it confirms your understanding of the spec with the interviewer, and it prevents you from accepting assistant-generated code that doesn't handle these cases.
Phase 2 — Implementation (roughly 20–25 minutes)
Structure the code in three layers and ask the assistant to build them separately.
Layer 1 — Validator (validate_workflow)
Runs at creation time. Four checks, in order:
- Duplicate step IDs — collect all IDs into a set; if
len(set) != len(steps), reject. - Unknown actions — check each step's action against the registry.
- Missing dependency references — for each step's
depends_on, confirm the referenced ID exists somewhere in the step list. - Cycles — run DFS with a
visiting/visitedstate set. If DFS ever re-enters avisitingnode, a cycle exists.
Return a list of error messages so the 400 response can describe every problem, not just the first one found.
Layer 2 — Executor (execute_workflow)
def topological_sort(steps):
# Kahn's algorithm or recursive DFS post-order
# Returns steps in an order where each step's deps appear earlier
...
def execute_workflow(workflow, input_data, registry):
outputs = {"__input__": input_data}
results = {}
for step in topological_sort(workflow.steps):
if any(results[dep]["status"] != "completed" for dep in step.depends_on):
results[step.id] = {"status": "skipped", "output": None}
continue
dep_outputs = {dep: results[dep]["output"] for dep in step.depends_on}
try:
output = registry[step.action](**step.params, **dep_outputs)
results[step.id] = {"status": "completed", "output": output}
except Exception as e:
results[step.id] = {"status": "failed", "error": str(e), "output": None}
return results
The key insight: a step is skipped if any of its declared dependencies did not complete — it doesn't matter whether they failed or were themselves skipped. This propagates failure down the dependency chain without extra bookkeeping.
Layer 3 — HTTP shell
Keep this as thin as possible. Each route calls the validator or executor and maps the return value to a status code. Nothing else belongs here. Mixing validation logic into route handlers is a common mistake that makes the core logic impossible to test without HTTP infrastructure.
Common mistakes the assistant tends to make:
- Hallucinating library calls (e.g., a cycle-detection function that doesn't exist in the standard library).
- Building topological sort correctly but forgetting to handle the case where
depends_oncontains IDs that aren't resolved to step objects yet. - Swallowing exceptions with a bare
except: passinstead of recording the error. - Returning a 200 for a partially failed run when the spec says only individual steps fail, not the run itself.
Ask the assistant to narrate its topological sort on a concrete three-node example. If the explanation is wrong, the code is almost certainly wrong too.
Phase 3 — Verification (remaining ~10 minutes)
Run the test list from Phase 1. For each failure:
- Read the actual vs expected output before changing anything.
- Hypothesize a cause, then confirm it in the code before patching.
Review the executor code for:
- Silently swallowed errors: any
exceptblock that doesn't record the error string. - Untested branches: the
skippedpath is the most commonly unexercised — make sure test 7 from your list covers it. - Off-by-one in topological order: the sort is correct only if it handles steps that are defined in reverse dependency order (test 6).
At the end of 45 minutes, a strong candidate has: a working create + execute cycle, all eight tests passing, and a clear verbal account of one or two things the assistant got wrong and how they were caught.
Trade-offs to mention if asked about production readiness
| Concern | Current state | What you'd add |
|---|---|---|
| Persistence | In-memory, lost on restart | Append-only event log or a document store |
| Parallelism | Serial topological order | Async task queue; run steps whose deps are all satisfied |
| Long-running steps | Blocking response | Async run with a polling endpoint and run-status resource |
| Action isolation | In-process function call | Sandboxed subprocess or container per step |
| Observability | None | Structured log per step with duration, input hash, output hash |