Designing a Long-Running Workflow Engine
A long-running workflow engine orchestrates complex, stateful processes that span minutes, hours, days, or even indefinitely. It must handle failures gracefully, persist state across restarts, and support human-in-the-loop interactions. Key features like timers , retries , cancellation , and compensation make it resilient for distributed systems (e.g., sagas in microservices).
I'll outline a high-level design, core components, implementation strategies, and a concrete example using modern patterns. This draws from systems like Temporal , Cadence , Camunda , or Netflix Conductor , but is framework-agnostic for custom builds.
Core Architecture
code Copy code
[Client API] --> [Workflow Scheduler] --> [Task Queue] --> [Worker Pool]
|
[State Store] (DB)
|
[Event Log] (for replay)
State Store : Durable DB (e.g., PostgreSQL, DynamoDB) for workflow instances, variables, history.
Task Queue : Message broker (Kafka, RabbitMQ, SQS) for dispatching tasks.
Event Log : Append-only log (Kafka or DB table) for deterministic replay (crucial for timers/retries).
Workers : Stateless processes executing tasks (e.g., Docker containers, Kubernetes jobs).
Scheduler : Heart of the engine; manages timers, retries, and state transitions.
Persistence Model : Every workflow is a state machine. Serialize state as JSON/BSON. Use optimistic concurrency (versioning) for updates.
Idempotency : Every task has a unique ID; check state before executing.
Feature Breakdown & Implementation
1. Timers (Delays, Timeouts, Heartbeats)
Purpose : Pause workflows (e.g., "wait 24h before escalating"), enforce SLAs, or poll periodically.
How :
Store timer events in the event log with absolute/relative timestamps.
Scheduler polls/crons expired timers, injecting "TimerFired" events.
Use cron-like syntax or ISO durations (e.g., P1D for 1 day).
Edge Cases : Clock skew (NTP), timezone handling, leap seconds (ignore or UTC).
Pseudocode (Workflow Definition):
python Copy code
def order_workflow(order_id):
approve = approve_order(order_id) # Activity (task)
timer = schedule_timer(duration="24h")
if timer.fired():
ship_order(order_id)
2. Retries (Failure Recovery)
Purpose : Transient failures (network blips, rate limits) without human intervention.
How :
Policy Description Example Config Fixed Retry N times, fixed interval retries=5, interval=30sExponential Backoff Interval *= multiplier (e.g., 1s → 2s → 4s) max_retries=10, base=1s, multiplier=2, jitter=0.1Custom Per-task policy (e.g., non-retriable: DB schema errors)
On failure, store next_attempt_at in state; scheduler re-queues.
Circuit breakers for downstream services.
Pseudocode (Activity Wrapper):
python Copy code
@retry_policy(max_retries=5, backoff="exponential")
def charge_card(amount):
# Throws if fails
pass
3. Cancellation (Graceful Shutdown)
Purpose : Abort workflows (e.g., user cancels order, timeout SLA).
How :
Expose API: cancel_workflow(instance_id, reason).
Inject "CancelRequested" signal/event; workflow handles via on_cancel handler.
Propagate to child workflows/tasks (fan-out).
Non-blocking: Mark as "Cancelling" state, await in-flight tasks.
Edge Cases : Partially completed work (triggers compensation).
Pseudocode :
python Copy code
def workflow():
try:
step1()
if signal.cancel_requested():
compensate_step1()
return "Cancelled"
step2()
finally:
cleanup()
4. Compensation (Saga Pattern for ACID-like Behavior)
Purpose : Rollback distributed transactions without 2PC (e.g., undo payment if shipping fails).
How :
Choreography : Each step defines a compensating action (forward + reverse).
Store compensating txns in a stack; on failure/cancel, pop and execute in reverse.
Idempotent compensators (e.g., "refund if not already refunded").
Saga State :
code Copy code
Steps: [ReserveInventory (compensate: ReleaseInventory),
ChargePayment (compensate: RefundPayment),
ShipOrder (compensate: N/A)]
On Ship fail: Refund -> Release
Pseudocode :
python Copy code
compensators = []
try:
inventory = reserve_inventory(order_id)
compensators.append(release_inventory)
payment = charge_payment(order_id)
compensators.append(refund_payment)
ship_order(order_id)
except Exception:
while compensators:
compensators.pop()() # Execute reverse
Scalability & Reliability
Horizontal Scaling : Shard by workflow ID (consistent hashing).
Fault Tolerance :
Failure Mitigation Worker crash Replay from event log (deterministic code). Scheduler down Distributed scheduler (e.g., via ZooKeeper leader election). DB outage Eventual consistency; dual-writes to cache.
Monitoring : Workflow DAG visualization (e.g., via GraphQL), metrics (latency, failure rate), alerts on stuck timers.
Visibility : Query API for state/history/search (e.g., "orders pending >24h").
Tech Stack Example (Go/Python/Java)
Language : Go (for perf, e.g., Temporal SDK) or Python (asyncio).
Storage : CockroachDB (distributed SQL), Redis (caching/queues).
Queue : Kafka (durable, partitioned).
Full Open-Source : Temporal (Go-based, batteries-included: timers=built-in, retries=SDK, cancel=signals, compensation=sagas).
Real-World Example: E-Commerce Order Workflow
code Copy code
Start(OrderCreated)
├── ReserveInventory (retry: exp, compensate: Release)
├── Timer(30min) // Wait for payment
├── ChargePayment (retry: 3x, compensate: Refund)
├── ScheduleDelivery (timer: 24h if stock low)
├── ShipOrder
└── NotifyCustomer
(Cancel: Triggers full compensation)
Workflow JSON State (simplified):
json Copy code
{
"id": "order-123",
"status": "Running",
"history": ["Reserve OK", "Timer Expired"],
"timers": [{"expires": "2023-10-01T12:00Z"}],
"compensators": ["RefundPayment"],
"retries": {"ChargePayment": {"attempts": 1, "next": "2023-10-01T11:30Z"}}
}
This design ensures at-least-once semantics with deduping. Start with a prototype using Temporal for rapid iteration—it's production-ready and handles all these out-of-the-box.
Questions? Want code samples in a specific language or deeper dive into any feature?