Workflow Engine with DAG Execution and Timeout-Based Refunds
System DesignModel answerLast updated
Build a workflow engine that executes order tasks as a directed acyclic graph, finalizes successful orders, and triggers refunds when timeouts occur.
You are building a workflow engine for an e-commerce platform. Orders flow through multiple stages—inventory check, payment capture, fulfillment preparation, and shipping—organized as a directed acyclic graph where each task may depend on one or more prior tasks completing successfully.
Your system must handle:
- Submission: Accept a new order with a defined workflow graph and a global timeout
- Execution: Run tasks only after their dependencies finish; each task may call an external service
- Terminal states: If all tasks complete before the timeout, mark the order finalized. If the timeout elapses first, trigger a refund workflow instead
- Status queries: Return the current state of an order and which tasks have completed
- Recovery: After a crash, resume in-progress orders without duplicating side effects
Requirements
- DAG validation: Reject cycles and undefined dependencies at submission time
- Prerequisite scheduling: A task runs only when every upstream task has succeeded
- Atomic terminal decision: Completion and timeout are mutually exclusive; once one path is taken, the other cannot occur
- Idempotency: Restarting a task or refund operation that already ran must not double-charge or double-refund
- Durable state: Persist enough information to recover after a process restart
- Correct status: Queries must reflect the true state even during concurrent task execution
What to Cover
Describe your high-level architecture, data model, and coordination mechanism. Explain how you prevent race conditions between completion and timeout, how you ensure idempotency, and how recovery works after a failure. Provide a sketch of the core APIs and outline common failure scenarios with your mitigation strategy.
Hints
Hint 1
Think about where the timeout clock lives and who is responsible for checking it—centralized or per-order?
Hint 2
Use versioning or unique execution identifiers to make external calls idempotent, so retries are safe.
Hint 3
Consider separating task state persistence from the actual decision to finalize or refund, using a compare-and-swap or lock to enforce atomicity.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture
The workflow engine consists of three main components:
Workflow Coordinator: Accepts order submissions, validates the DAG, persists initial state, and spawns an executor for each order.
Task Executor: Polls the dependency graph, runs tasks whose prerequisites are met, records outcomes, and checks for terminal conditions after every task completion.
Timeout Monitor: Tracks each order's deadline and attempts to transition timed-out orders into the refund path.
State is persisted in a durable store (PostgreSQL, DynamoDB, or similar) with strong consistency guarantees for the terminal-state transition.
Data Model
Order record:
order_id, workflow_dag, deadline, status [pending|finalizing|finalized|refunding|refunded], terminal_version
Task execution log:
order_id, task_id, status [pending|running|succeeded|failed], idempotency_key, started_at, completed_at
The terminal_version field acts as a concurrency token: only one writer can successfully increment it from null to 1, claiming the right to execute the terminal path (finalization or refund).
Core Workflow
1. Submission and Validation
- Topologically sort the DAG; reject if a cycle is detected or a dependency references a nonexistent task.
- Assign a unique
order_idanddeadline = now() + timeout. - Insert the order record with
status = pendingand all tasks withstatus = pending. - Return the
order_idto the caller.
2. Task Execution
A background executor (or distributed workers pulling from a queue) repeatedly:
- Scans for orders in
pendingorfinalizingstate wheredeadline > now(). - For each order, finds tasks in
pendingstate whose dependencies have all reachedsucceeded. - Marks the task
running, generates anidempotency_key = hash(order_id, task_id, attempt_number), and calls the external service with that key. - On success, updates the task to
succeeded; on retriable failure, resets topendingfor retry; on permanent failure, the order may transition to a failure state or trigger compensation depending on policy.
After every task completion, check if all tasks are succeeded. If so, attempt to claim finalization.
3. Atomic Terminal Decision
When all tasks succeed:
UPDATE orders
SET status = 'finalizing', terminal_version = 1
WHERE order_id = ? AND terminal_version IS NULL;
If the update affects one row, this process owns finalization. Execute the finalize logic (mark inventory committed, send confirmation email) using a new idempotency key finalize-{order_id}. Then set status = finalized.
If the update affects zero rows, another process (timeout monitor or concurrent executor) already claimed the terminal state; abort.
The timeout monitor runs:
UPDATE orders
SET status = 'refunding', terminal_version = 1
WHERE order_id = ? AND deadline <= now() AND terminal_version IS NULL;
If successful, trigger the refund workflow (release inventory, reverse payment) with idempotency key refund-{order_id}. Then set status = refunded.
Idempotency
Every external call (task execution, payment capture, refund API) includes an idempotency token derived from order_id, task_id, and attempt or operation type. The receiving service deduplicates using this token. If the workflow engine retries a task after a crash, the external service returns the cached result, preventing double-execution.
Recovery After Failure
On restart:
- Load all orders in
pending,finalizing, orrefundingstate. - For
pendingorders, resume task execution from the current dependency graph state. - For
finalizingorrefunding, re-execute the terminal operation (finalize or refund) with the same idempotency key; the external system will return success if already completed. - Check
deadlinefor anypendingorder and allow the timeout monitor to claim refund if elapsed.
No in-memory coordinator state is required beyond caching task progress for efficiency.
Status Queries
GET /orders/{order_id}/status
Returns:
{
"order_id": "...",
"status": "pending",
"tasks": [
{"task_id": "inventory_check", "status": "succeeded"},
{"task_id": "payment_capture", "status": "running"},
{"task_id": "fulfill_prep", "status": "pending"}
],
"deadline": "2026-11-03T10:30:00Z"
}
Read directly from the database; no stale cache issues if reads hit the primary replica.
Common Failure Scenarios
| Scenario | Mitigation |
|---|---|
| Task completes just as timeout fires | Compare-and-swap on terminal_version ensures only one path wins |
| Executor crashes mid-task | Task remains running; a reaper marks stale tasks pending after a grace period; retry with same idempotency key |
| Refund API called twice | Idempotency key refund-{order_id} deduplicates |
| Network partition delays task | Timeout monitor will claim refund; late task completion fails the terminal-state CAS |
| DAG has thousands of nodes | Partition task execution across multiple workers using a queue; coordinator only tracks high-level order state |
Scalability and Extensions
- Distributed execution: Use a message queue (Kafka, SQS) with one message per runnable task; workers pull and execute.
- Saga pattern: For complex multi-service transactions, store compensating actions alongside each task and replay them on timeout or failure.
- Observability: Emit events (task started, task completed, order finalized, order refunded) to a stream for monitoring and analytics.
- Priority and SLA tiers: Add a priority field; high-priority orders get shorter poll intervals and dedicated worker capacity.
This design provides durable, race-free order processing with clear terminal semantics and straightforward recovery, suitable for production e-commerce workloads.