Crash-Safe Refund Pipeline as a Resumable Task Graph
System DesignModel answerLast updated
Design a fault-tolerant orchestration service that runs a refund as a dependency graph of steps, survives worker crashes, avoids double refunds, and handles failure and versioning.
Crash-Safe Refund Pipeline as a Resumable Task Graph
Your team is building the backend that processes customer refunds. A single refund is made of five steps: ValidateOrder, CheckInventory, ProcessPayment, UpdateDatabase and NotifyCustomer. The steps depend on one another and form a directed acyclic graph (DAG). You are asked to design the orchestration engine that runs these graphs reliably.
What the engine must guarantee
- Persistent progress. Execution state is stored durably. If a worker dies mid-run, the refund continues from the last step that finished instead of starting over.
- Dependency ordering. A step starts only after every one of its upstream steps has completed successfully.
- Safe retries. Each step can be run more than once without repeating its side effects. A customer must never be refunded twice because a step was retried after a partial failure.
- Terminal failure policy. When a step fails for good, the system either runs compensating actions (rollback) or parks the refund in a
Manual Reviewstate. - Concrete data model. Define the structures for a
WorkflowDefinition(nodes and edges) and aWorkflowExecution(current state and event log).
Questions to address in your answer
- How do you get effectively-once results for side effects that are not naturally idempotent?
- How do you detect that a long-running step has stalled, using heartbeats or timeouts?
- What happens to refunds already in flight when a new version of the workflow definition is deployed?
What is expected
Walk through requirements and rough scale, the data model, the architecture, the key state transitions, the failure and compensation strategy, and the trade-offs you considered. Code or pseudo-code for the core structures and transitions is welcome.
Hints
Hint 1
Start by naming what matters most here: correctness over throughput. Estimate load (for example, about 1M refunds a day) to show that one relational database is enough, then spend your time on state transitions.
Hint 2
Make 'mark task done', 'decrement children's pending-parent counts' and 'record dispatch intent' a single database transaction (outbox pattern). Add a fencing check (status plus attempt number) so stale workers cannot overwrite newer results.
Hint 3
Derive the idempotency key from stable identifiers (refund and node), never from the attempt number. Then choose a technique per downstream: pass the key through, dedupe in the same transaction, or query-before-act for non-idempotent systems, and route ambiguous cases to manual review.
Hint 4
Pin each execution to the definition version it started with, and make published definitions immutable. Only new executions pick up the new version.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
This is a correctness-first problem. Volume is modest (assume about 1M refunds a day, peaking around 50/s, with five steps each, so roughly 250 task transitions per second). One relational database such as Postgres handles that comfortably. The real risk is a bug that refunds a customer twice or loses a refund, so the design effort goes into state transitions, idempotency and failure semantics rather than sharding.
Delivery is at-least-once; correctness of effects comes from idempotency, giving effectively-once results.
The graph
ValidateOrder -> CheckInventory -> UpdateDatabase -> NotifyCustomer
\> ProcessPayment -/
Inventory and payment run in parallel after validation. UpdateDatabase is a join and waits for both.
Data model
class TaskStatus(Enum):
PENDING, READY, RUNNING, SUCCEEDED, RETRY_WAIT, FAILED, COMPENSATED
class WorkflowStatus(Enum):
RUNNING, SUCCEEDED, COMPENSATING, COMPENSATED, MANUAL_REVIEW
@dataclass(frozen=True)
class NodeDef:
node_id: str
task_type: str # selects the worker queue
max_attempts: int
backoff_initial_s: float
backoff_max_s: float
non_retryable_errors: tuple
start_to_close_timeout_s: int
heartbeat_timeout_s: int | None
compensation_task: str | None # None = cannot be undone
@dataclass(frozen=True)
class WorkflowDefinition: # immutable once published
name: str
version: int
nodes: dict[str, NodeDef]
edges: list[tuple[str, str]] # validated acyclic at publish
@dataclass
class TaskExecution:
node_id: str
status: TaskStatus
attempt: int # also the fencing token
idempotency_key: str # hash(refund_id, node_id)
pending_parents: int
lease_owner: str | None
lease_expires_at: float | None
output: dict | None
last_error: str | None
@dataclass
class WorkflowExecution:
execution_id: str
definition_name: str
definition_version: int # pinned at start
refund_id: str
order_id: str
status: WorkflowStatus
tasks: dict[str, TaskExecution]
history: list[dict] # append-only event log
Tables: workflow_definitions (name, version), workflow_executions, task_executions (execution_id, node_id), history_events (append-only) and outbox.
Architecture
A centralized orchestrator over a durable store, in the style of Temporal or Cadence:
- Orchestrator: stateless and horizontally scaled, owns every state transition, reads and writes Postgres.
- Outbox relay: publishes
READYtasks to per-task-type queues (SQS or Kafka). - Workers: pull tasks, call the downstream service, and report
complete,failorheartbeat. - Timer/reaper: fires retry backoffs and reclaims expired leases.
A choreographed design (services reacting to each other's events) scales further, but DAG state becomes scattered, joins are awkward, and answering "where is refund X stuck?" is painful. At this volume the orchestrator's visibility wins.
Atomic completion transition
When a worker reports success, one transaction does the following:
- Fenced update:
UPDATE task_executions SET status='SUCCEEDED', output=? WHERE execution_id=? AND node_id=? AND status='RUNNING' AND attempt=?. Zero rows updated means a stale worker, so discard the report. - Append a
TaskSucceededhistory event. - Decrement
pending_parentsfor each child. Any child reaching zero becomesREADYand gets an outbox row. - If all nodes succeeded, mark the workflow
SUCCEEDED. - Commit.
Because the state change and the dispatch intent commit together, a crash cannot lose a task. After a crash the relay resumes publishing and the reaper requeues dead leases. Duplicate queue deliveries are harmless because of the fenced update and idempotent tasks.
Idempotency and effectively-once side effects
Key: hash(refund_id, node_id). It must be identical on every retry, so the attempt number is excluded. Using refund_id instead of order_id still allows a legitimate second partial refund on the same order.
By downstream type:
- Supports idempotency keys (a payment gateway): pass the key through; a retry returns the original result.
- Our own database: insert the key into
processed_keysin the same transaction as the business write. A duplicate-key error means it was already done, so return success. - Not idempotent: write an
INITIATEDintent row first; on retry, query the downstream by our external reference and act only if it has no record. If it cannot be queried, the step is unsafe to retry automatically, so ambiguous outcomes (timeouts) go to manual review. - Notifications: dedupe by key where possible and accept rare duplicates otherwise, since a duplicate email is tolerable.
Heartbeats and timeouts
A worker claims a task by setting RUNNING, lease_owner and lease_expires_at = now + heartbeat_timeout. Long steps call heartbeat() to extend the lease (and optionally save progress). The reaper finds expired leases, increments attempt (which invalidates the old worker through fencing), and re-queues the task, or fails it if attempts are exhausted. Separate timeouts apply: a start-to-close timeout bounds one attempt, a heartbeat timeout detects stalls quickly, and an overall workflow deadline bounds the whole refund.
Failure handling
- Transient errors: retry with exponential backoff plus jitter, up to
max_attempts, viaRETRY_WAIT. - Non-retryable errors (for example, order not refundable): fail immediately.
- Terminal failure: if completed steps have a
compensation_task, move the workflow toCOMPENSATINGand run compensations in reverse dependency order (saga pattern), each idempotent and retried like any other task. If a step has no compensation, or compensation itself fails, setMANUAL_REVIEWwith the full history attached for an operator. - Payment is the dangerous step: prefer ordering so that irreversible actions happen late, and treat unknown payment outcomes as manual review rather than blind retry.
Versioning
Definitions are immutable and keyed by (name, version). Each execution pins its version at start and the orchestrator always interprets it against that version. New refunds use the latest version; in-flight ones finish on the old one. Keep old versions until no executions reference them. For urgent fixes, offer an explicit migration tool that maps old nodes to new ones for specific executions, rather than changing graphs implicitly.
Trade-offs and common mistakes
- Including the attempt number in the idempotency key defeats idempotency and causes double refunds.
- Publishing to the queue outside the DB transaction creates lost or phantom tasks; use the outbox.
- Skipping fencing lets a slow, presumed-dead worker overwrite newer state.
- Retrying ambiguous payment timeouts blindly is how duplicate refunds happen.
- Mutating a published definition under running executions breaks resumption.
- Over-engineering for scale (sharding, choreography) at 250 transitions/s adds risk without benefit.
Operationally, add metrics for stuck tasks per node, retry rates, and the size of the manual-review queue, plus an audit trail built from the history table.