Designing a workflow engine
It seems like the user is asking about a long-running workflow engine, which is pretty broad. I should consider asking clarifying questions, but I can propose an architecture that includes durable workflows, state machines, event sourcing, message queues, and cancellation mechanisms. I’ll also mention existing engines like Temporal and AWS Step Functions, highlighting their pros and cons.
I’ll provide key concepts necessary for implementation and a structured overview that balances detail with clarity, ensuring I touch on timers, retry policies, and cancellation strategies.Discussing compensation in workflows
I need to define compensation in terms of reverse activities, ensuring they’re idempotent and that results are stored, especially for partial failures. I could illustrate this with pseudocode, like an order workflow involving charge cards, inventory reservation, and shipping, with a cancellation process. It’s also essential to address concerns like consistency, state persistence, and scalability, and perhaps ask the user if they are looking to build or choose an engine. My recommendation is to use Temporal or Zeebe, but if they’re building, they should focus on core components like persistence and task queues.
A long‑running workflow engine that supports durable timers, retries, cancellation, and compensation is essentially a durable state machine + event log + task dispatcher. You can either adopt an existing engine (recommended) or build one with a clear set of primitives and invariants.
1) Use an existing engine (often the right answer)
If you need “timers/retries/cancel/compensate” and correctness matters, engines that already solve the hard parts:
- Temporal (Cadence): strongest general-purpose choice; durable timers, retries, cancellation, signals, child workflows, history replay, good SDKs.
- Camunda 8 / Zeebe: BPMN-friendly, strong for orchestration; compensation patterns supported via modeling.
- AWS Step Functions: managed; good timers/retries; compensation via explicit steps; less flexible than Temporal for complex code logic.
- Azure Durable Functions: similar durable orchestration model.
If you tell me your stack (language/cloud/throughput/latency/SLA), I can narrow a recommendation.
2) If building: the minimal “correct” architecture
Core primitives
- Workflow instance
- Identified by
workflow_id.
- Has a current state (or derived from history).
- History / event log (append-only)
- Every meaningful change is an event:
Started, TaskScheduled, TaskCompleted, TimerFired, CancelRequested, etc.
- Lets you recover, debug, and (optionally) replay deterministically.
- Commands derived from state/history
- “Schedule activity A”, “start timer T”, “request cancellation”, etc.
- Activity/task execution
- Activities run in workers; engine is responsible for dispatch + durability + retries.
- Timers
- Durable “wake me up at time X” objects tied to a workflow instance.
- Signals / external events
- Messages that mutate workflow state (e.g., “payment confirmed”).
Storage model (practical)
workflow_instances(workflow_id, status, state_blob, version, updated_at, …)
workflow_history(workflow_id, event_id, event_type, payload, ts, …) (optional but very useful)
activity_tasks(task_id, workflow_id, activity_type, input, status, attempt, run_after, …)
timers(timer_id, workflow_id, fire_at, status, …)
- Index timers by
fire_at for efficient scanning.
Dispatcher model
- A scheduler loop finds due timers / runnable tasks and enqueues them to a queue (Kafka/SQS/Rabbit/etc) OR directly hands them to workers.
- Workers lease tasks (visibility timeout / heartbeat) to handle crashes.
3) Timers (durable and scalable)
Timers are deceptively hard because you need them to survive restarts and scale horizontally.
Common approaches:
-
DB-backed timer table + poller
- Query
WHERE fire_at <= now AND status='pending' LIMIT N FOR UPDATE SKIP LOCKED
- Mark as
fired / enqueue “TimerFired” event.
- Pros: simple, durable. Cons: DB polling load; needs tuning/sharding.
-
Delayed queue
- Put a message with delay (SQS delay, Rabbit delayed exchange).
- Pros: low DB load. Cons: max delay limits, provider quirks, needs reconciliation if messages lost.
Correctness notes:
- Timers should be idempotent: firing twice should not break semantics.
- Use at-least-once delivery and design workflow state transitions to tolerate duplicates.
4) Retries (policy + idempotency)
Retries should be engine-managed, not ad-hoc per worker, so they’re visible and consistent.
Key pieces:
- Retry policy per activity:
- max attempts
- backoff strategy: exponential with jitter
- max backoff
- retryable vs non-retryable error types
- Attempt state stored durably (
attempt, last_error, run_after).
Idempotency is mandatory
Because your system will almost certainly be at-least-once, activities must tolerate duplicates:
- Use idempotency keys (e.g.,
workflow_id + activity_name + logical_step_id).
- Store external side-effect results keyed by that idempotency key (payment provider idempotency, DB unique constraints, etc.).
5) Cancellation (cooperative + propagated)
Cancellation is also more than “set a flag”.
Cancellation model:
- Workflow-level:
CancelRequested(workflow_id)
- Activity-level: mark in DB and notify workers; workers should:
- poll for cancellation / heartbeat
- abort if safe
- report
Canceled vs Completed
Propagation rules:
- Cancel workflow ⇒ cancel outstanding activities/timers/child workflows.
- Some activities may be non-cancelable (already committed external side effects). In that case:
- let them complete
- workflow proceeds to compensation if needed
Important: cancellation is often “best effort” at the activity boundary; you need a clear semantic contract.
6) Compensation (Saga pattern)
Compensation is not “rollback”; it’s a forward recovery path.
How to model it
- Each step that makes an irreversible change has:
Do activity (e.g., ChargeCard)
- optional
Compensate activity (e.g., RefundCharge)
- The workflow records successful steps, then on failure/cancel it runs compensations in reverse order.
Rules for compensations:
- Must be idempotent (refund called twice should be safe).
- Must handle “partial” success (refund may fail; need retry policy and escalation).
- Should be durable: once you decide to compensate, that decision is recorded and continues after restarts.
7) The main correctness constraints (don’t skip these)
To make timers/retries/cancel/compensate reliable:
-
State transitions must be atomic
- When an activity completes, you atomically:
- append completion event / update workflow state
- schedule next commands (next activities, timers)
- Use DB transaction with optimistic concurrency (
version column) or a single-writer per workflow.
-
At-least-once everywhere
- Expect duplicate task deliveries, duplicate timer fires, and repeated signals.
- Design with idempotency + deterministic state transitions.
-
Leases + heartbeats
- If a worker dies mid-activity, the task becomes runnable again.
- Heartbeats allow cancellation and liveness detection.
-
Poison message / permanent failure handling
- After retries exhausted: mark activity as failed and let workflow decide (compensate, fail, or wait for human).
8) A concrete workflow sketch (example)
Order workflow:
- Reserve inventory (compensate: release inventory)
- Charge payment (compensate: refund)
- Create shipment (compensate: cancel shipment)
- If any step fails/cancel requested ⇒ run compensations in reverse.
Engine behavior:
- Each activity has retry policy.
- A “payment timeout” is a durable timer; if it fires before payment completes, the workflow cancels and compensates.
9) Questions that decide the right design
If you answer these, I can propose a more specific design (or pick an engine):
- Do you want to build this or choose an off-the-shelf engine?
- Language/runtime for workflow definitions (Java/Go/TS/Python/.NET)?
- Expected scale: workflows/day, max concurrent, typical duration (minutes vs months)?
- Need human-in-the-loop tasks?
- Multi-tenant? Cross-region DR?
- Do you require strict determinism/replay (Temporal-style) or is a DB state machine fine?
If you share your constraints, I can outline a concrete schema, state machine, and worker protocol (including timer scanning strategy and cancellation semantics).