Building a Durable Workflow Orchestrator Across Microservices
System DesignModel answerLast updated
Design a fault-tolerant engine that runs multi-step service workflows with ordering, retries, compensation, and exactly-once side effects.
Context
You are designing a workflow orchestration engine that coordinates long-running business processes spanning several independent services. Typical processes include fulfilling a purchase, onboarding a seller, and issuing driver payouts. Each process is a chain of steps that touch different downstream services (payments, inventory, dispatch, notifications), and steps may branch, run in parallel, and depend on each other.
The engine must keep these processes moving correctly even when engine hosts crash, networks partition, or workers die mid-step. The downstream services include non-idempotent real-world actions (charging a card, sending a notification), so duplicate execution is not acceptable.
Requirements
Functional
- Define workflows as DAGs or state machines with branching, parallelism, dependencies, and typed inputs/outputs.
- Dispatch individual steps to separate worker services over queues or RPC.
- Per-step retry policy with exponential backoff, timeouts, and optional compensation (rollback) steps that run when a workflow hits a terminal failure.
- Guarantee that critical side effects are never duplicated.
- Provide APIs to inspect a workflow's progress, per-step history, and to pause, resume, cancel, or replay a run.
Non-functional
- Durability: no committed state is lost when an engine node or worker crashes.
- Scale: ~50,000 concurrent workflow runs, peak ~10,000 state transitions per second.
- Latency: handoff between dependent steps under 100ms at p99.
- Language-agnostic workers: any service can register for a task type.
What to Cover
- Overall component architecture and their interactions.
- Data model and how execution state is persisted.
- How workers are dispatched to, monitored, and how unrecoverable steps are handled.
- Recovery procedure for orchestrator crashes and worker crashes.
- The idempotency and leasing scheme that makes side effects safe.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Sizing and semantics first
Convert the numbers before designing. 50K concurrent runs is not 50K busy threads: most runs are parked waiting on a downstream call or timer, so the engine is a write-heavy state machine.
- At 10K transitions/s, each transition appends roughly 2–3 events (complete the task, schedule the next). That's ~30K event inserts/s at ~1 KB each, about 30 MB/s and ~250M events/day at average load. Keep 7–30 days hot, archive the rest to object storage.
- The 100ms p99 handoff rules out timer-based DB polling. Dispatch must be event-driven with long-poll or push delivery.
- Pin down the delivery contract with the interviewer: at-least-once execution with exactly-once effects via idempotency; ordering only guaranteed within a run; compensation is best-effort and itself retryable.
2. API sketch
StartWorkflow(type, version, input, idempotency_key) -> run_id
Signal(run_id, name, payload) # e.g. "merchant_approved"
Pause / Resume / Cancel / Replay(run_id, from_event_id?)
DescribeWorkflow(run_id) -> status, per-step states, history
# Worker-facing, gRPC/REST so any language works
PollTask(queue, worker_id) -> {task_token, run_id, step, attempt, input} # long-poll
Heartbeat(task_token, progress) -> {cancel_requested}
CompleteTask(task_token, result)
FailTask(task_token, error, retryable)
The task_token encodes (shard, run_id, step, attempt, lease_epoch). That epoch is the fencing token that protects against zombie workers.
3. Architecture
Six components:
- Stateless API gateway that hashes
run_idto one of ~4,096 logical shards and forwards. - History/engine service. Each shard is owned by exactly one node at a time, ownership governed by a lease in etcd/ZK with a monotonically increasing shard epoch. The owner evaluates the DAG, appends events, and writes outgoing tasks to a per-shard outbox in the same transaction.
- Matching service — partitioned in-memory queues keyed by task type, fed from the outbox. Workers long-poll; a waiting worker receives a task in a few milliseconds, which is what satisfies the p99 target. Queue depth per type is the autoscaling and rate-limiting signal.
- Timer service — per-shard time-ordered queue for backoff, timeouts, and heartbeat deadlines.
- Persistence — sharded store with conditional writes (Cassandra LWT, or sharded Postgres) for events, mutable state, outbox, timers, and dedup keys.
- Visibility store — Elasticsearch, updated asynchronously, for search and operator inspection.
Choose pull over push: workers self-throttle, the engine doesn't track worker addresses or liveness, and a poll loop is trivial in any language.
4. Data model
Write both an event log and a snapshot in a single conditional transaction per shard:
| Table | Key | Purpose |
|---|---|---|
workflow_defs | (type, version) | DAG spec, per-step retry/compensation config |
history_events | (shard, run_id, event_id) | append-only: Started, TaskScheduled, TaskStarted, Completed/Failed/TimedOut, CompensationScheduled, Signal |
mutable_state | (shard, run_id) | status, next_event_id, per-step {state, attempt, lease_epoch, heartbeat_deadline} |
transfer_tasks / timer_tasks | (shard, id / fire_ts) | outbox and timers |
start_dedup | idempotency_key | run_id for idempotent starts |
The event log gives audit and the answer to "why was this refunded?" The snapshot gives O(1) decisions without replaying history on the hot path. The condition next_event_id == expected provides optimistic concurrency so two writers can never fork a run's history.
5. Worker lifecycle
- Engine commits
TaskScheduled; the outbox processor pushes to Matching. - Worker polls and receives the task; the engine records
TaskStartedwithlease_epoch++and arms a heartbeat deadline of 10–30s. - Long tasks heartbeat, extending the deadline; the heartbeat response can carry a cancellation.
- On deadline expiry or start-to-close timeout, record
TaskTimedOutand reschedule withmin(base·2^attempt, cap)plus jitter. - On retries exhausted or a non-retryable error: if the step has a compensation, start a Saga unwind — run compensating steps of already-completed steps in reverse topological order (refund payment, release inventory). Compensations are normal tasks with their own retries and idempotency keys. If not, park the run in
NEEDS_ATTENTION, which doubles as the dead-letter queue; an operator fixes data and calls Replay/Resume.
6. Failure recovery
Engine node crash. The shard lease expires within seconds; another node acquires it with a higher shard epoch. The new owner lazily loads mutable state and replays transfer_tasks / timer_tasks from the last acknowledged watermark, re-dispatching anything pending — duplicate dispatches are acceptable. Every write is conditioned on the shard epoch, so if the old node comes back it is fenced off and its writes fail. Nothing acknowledged was ever uncommitted, so no state is lost.
Worker crash mid-task. Heartbeats stop, the deadline fires, the task is rescheduled with a new attempt and a fresh lease_epoch. When the zombie worker eventually calls CompleteTask with the stale token, the engine sees the mismatch and discards it. If the original step had already performed its side effect before dying, the side effect's idempotency key (deterministic from run_id + step + attempt-independent seed, e.g. run_id:step) makes the retry a no-op downstream.
Idempotency strategy. Two layers: (a) StartWorkflow dedup keys map to an existing run_id so retried client calls don't spawn duplicate runs; (b) each task carries a deterministic idempotency key that the downstream service honors — a charge attempt with the same key returns the original result instead of charging twice. Lease epochs are the fencing mechanism that stops stale writers; idempotency keys are the effect deduplication mechanism. You need both, because fencing alone doesn't protect the moment between "side effect performed" and "completion recorded."
7. Common mistakes and trade-offs
- Polling a DB for due timers → misses the p99 target; use a timer wheel/queue.
- Single global ordering or a single shard → the throughput ceiling; shard by run and accept per-run-only ordering.
- Relying on "exactly-once delivery" from the queue instead of idempotency keys → duplicate charges the first time a broker redelivers.
- Encoding only
run_idin the task token → zombies corrupt state; encode the epoch. - Forgetting to make compensation idempotent → unwind retries double-refund.
- Storing state only as an event log and replaying on every decision → 100ms p99 becomes seconds at scale; keep the snapshot.
Trade-off worth stating: event sourcing gives audit and replay but costs storage and a snapshot-maintenance burden; a pure mutable-state machine is lighter but loses the "why" trail. The hybrid above keeps both at roughly one extra write per transition, which at 30 MB/s is a comfortable margin.