The user wants an overview or design of a "Long-running workflow engine" that supports timers, retries, cancellation, and compensation. This is a classic distributed systems problem, often solved by patterns like the Saga pattern or orchestration engines like Temporal, Camunda, or AWS Step Functions.
I need to structure the answer to cover:
Core Concepts: What is a long-running workflow? Why is it hard? (State persistence, handling failures, dealing with time).
Key Features Requested:
Timers: How to handle delays (e.g., "wait 3 days").
Retries: Handling transient failures.
Cancellation: Stopping an ongoing process cleanly.
Compensation: Rolling back completed steps if the workflow fails later (Saga pattern).
Architecture/Design: How to build one (or how existing ones work).
Event Sourcing / History.
Determinism.
The "Replay" concept.
Implementation Strategies: Code examples or pseudo-code using a hypothetical SDK (or referencing Temporal/Cadence style as the industry standard for this specific type of engine).
Self-Correction/Refinement during thought process:
Initial thought: Just list open source tools. Correction: The user likely wants to understand the mechanics of how these engines work, not just a list of tools. The prompt looks like a requirements list for a system design.
Focus: Make sure to distinguish between "Cancellation" (stopping what's happening now) and "Compensation" (undoing what happened in the past).
Timers: Explain that you can't just Thread.sleep() in a distributed workflow. You need durable timers.
Retries: Need exponential backoff and jitter.
Structure of the response:
Introduction: Definition of the problem.
The "Durable Function" Pattern: Explain how modern engines (Temporal, Cadence) handle code state.
Deep Dive into Requirements:
Timers: Durable timers vs. in-memory.
Retries: Policies, exponential backoff.
Cancellation: Signals, propagating cancellation to activities.
State: The workflow must be serializable. The engine stops, the process restarts, and it picks up where it left off. This implies "Replay".
Timers: Create a timer task in the database. If the worker dies, another picks it up. When time is up, an event triggers the workflow to resume.
Retries: Wrap the external call (Activity). If it throws an error, catch it, schedule a retry timer.
Cancellation: This is tricky. If an Activity is running, you need to send a signal to the worker running that Activity to kill it. If the workflow is just waiting, you just move to the next logic branch.
Compensation: If step A succeeded, and step B fails, run Compensate_A. This requires storing the history of successes.
Refining the "How to build" section:
Don't just say "use a database." Explain the Event Loop.
Load Workflow state.
Execute logic until a blocking point (Timer, Activity call).
Persist state + pending task.
Wait.
Event arrives (Timer done, Activity done).
Reload state, replay history (or just load snapshot).
Continue.
Let's stick to the "Temporal/Cadence" model as the mental framework because it's the most robust implementation of these specific requirements.
Check against constraints: The user provided a very short prompt. I should provide a comprehensive design guide.
Section 1: The Mental Model.
Workflow = State Machine + Business Logic.
Activity = The actual work (side effects).
Section 2: Addressing specific features.
Timers: "Sleep for 30 days" cannot be an in-memory thread sleep. It must be a durable timer stored in Redis/SQL.
Retries: "Activity failed? Retry 3 times with backoff."
Cancellation: "User clicked 'Cancel'". Send signal to workflow. If Activity is running, request cancellation on the Activity Worker.
Compensation: "Payment failed, unreserve inventory." This is explicit logic, usually chained.
Section 3: Example.
Pseudo-code representing a saga.
try { reserveInventory() } catch { ... }
Actually, explicit compensation steps are clearer.
workflow.executeActivity(reserveInventory).compensate(releaseInventory)
Let's write the response.
Designing a Long-Running Workflow Engine requires a shift from traditional request-response architecture to Stateful Orchestration. The system must be able to "pause" execution for days or months (durable timers), survive server crashes (persistence), and handle complex failure logic.
Below is a comprehensive guide to architecting an engine that supports Timers, Retries, Cancellation, and Compensation.
1. The Core Architecture: Event Sourcing & The "Replay" Loop
You cannot keep workflow state in memory for 30 days. The industry standard approach (used by Temporal, Camunda, and Azure Durable Functions) relies on Command Sourcing and Replay.
The Workflow State: The state of a workflow is determined by the history of events it has processed.
The Event Loop:
Execute: The engine runs the workflow code until it hits a blocking operation (e.g., "Wait for 3 days" or "Call API").
Command: Instead of performing the operation, the engine emits a Command (e.g., ScheduleTimer, ScheduleActivity).
Persist: The engine persists the current state and the command to a database.
Yield: The workflow process/thread yields or exits entirely to free up resources.
Wake Up: When the timer fires or the API call returns, an external event triggers the engine.
Replay: The engine reloads the workflow history (previous events) to rebuild the state in memory, processes the new event, and the loop continues.
2. Implementation: The Big 4 Features
A. Durable Timers
Standard setTimeout or sleep functions fail if the process restarts. You need Durable Timers.
Mechanism: When the workflow code requests a sleep (e.g., workflow.sleep(30 days)), the engine calculates the absolute wake-up time.
Storage: This timestamp is stored in a dedicated "Timers" table (or a Redis Sorted Set).
Service: A background "Timer Service" (or a delayed message queue like RabbitMQ/Kafka) watches the time. When the time arrives, it pushes a TimerFired event into the workflow's event queue.
Use Case: Handling SLAs (e.g., "If approval not received in 24 hours, escalate").
B. Retries (Resilience)
Network calls fail. The engine must automate the retry logic so the workflow developer doesn't have to write while loops.
Policy: Activities (external calls) should have a defined RetryPolicy (Max Attempts, Backoff Strategy, Exponential Coefficients).
Implementation:
If an Activity fails, the engine catches the error.
It calculates the next retry time based on the backoff policy.
It schedules an internal timer.
When the timer fires, the engine replays the workflow and re-executes the activity.
Non-Retryable Errors: Allow configuration to ignore retries for specific errors (e.g., "404 Not Found" or "Permission Denied").
C. Cancellation
Cancellation is a two-phase process: Request and Propagate.
Request: An external client or parent workflow sends a CancelRequest.
Handling In-Progress Tasks:
If the workflow is waiting on a Timer: The timer is cancelled/ignored.
If the workflow is waiting on an Activity: The engine must support CancellationToken or heartbeats. If the activity is running on a remote worker, the engine sends a Cancel signal to that worker.
Cleanup: The workflow does not just vanish; it transitions to a "Cancelled" state, allowing for logging or notifications.
D. Compensation (The Saga Pattern)
In distributed transactions, if Step 3 fails, you must undo Step 1 and Step 2.
Design: Every business action (e.g., DebitAccount) should have a corresponding compensation action (e.g., CreditAccount).
Strategy:
Wrap actions in a Compensatable scope.
The engine tracks completed steps.
If an error occurs in Step 3, the engine catches it and immediately begins executing compensation logic for Step 2, then Step 1, in reverse order.
Failure in Compensation: This is a critical failure ("Panic state"). Usually, this requires manual intervention (Human Task) or a dedicated alert.
3. System Design Diagram
mermaid
graph TD
Client[Client / Starter] --> API[Workflow API]
API --> Store[Event Store (DB)]
subgraph "Workflow Engine Cluster"
Matchmaker[Task Dispatcher]
Worker[Workflow Worker (Replay Logic)]
TimerSvc[Timer Service]
end
Store --> Matchmaker
Matchmaker --> Worker
%% Timer Logic
Worker -- 1. Schedule Timer --> Store
TimerSvc -- Watch Store --> Store
TimerSvc -- 2. Timer Fired --> Store
%% Activity Execution
Worker -- 3. Schedule Activity --> Store
ActivityWorker[Activity Worker (External Calls)] -- Poll --> Store
ActivityWorker -- 4. Return Result/Failure --> Store
%% Cancellation
Client -.->|Cancel Request| Store
Store -.->|Signal Cancel| Worker
Worker -.->|Cancel Signal| ActivityWorker
4. Data Model (Simplified)
You need a database that supports transactions (Postgres, MySQL, or a specialized store).
Table: Workflows
WorkflowID (PK)
Status (Running, Completed, Cancelled, Failed)
CurrentState (Serialized JSON/Blob of current variables)
Table: History_Events
EventID (PK)
WorkflowID (FK)
Type (WorkflowStarted, ActivityScheduled, ActivityCompleted, TimerStarted, TimerFired)
Timestamp
Payload (JSON)
Table: Timers
TimerID
WorkflowID
FireTime
Status (Pending, Fired)
5. Code Concept (Developer Experience)
How a developer would write this workflow using your engine's SDK.
python
@workflow.defn
class OrderWorkflow:
def __init__(self):
self.order_id = None
self.cancelled = False
@workflow.run
async def run(self, order_id: str):
self.order_id = order_id
# 1. Reserve Inventory (with Compensation)
# If this step succeeds, 'compensate_reserve' is registered for rollback.
try:
await workflow.execute_activity(
"reserve_inventory",
order_id,
retry_policy=RetryPolicy(max_attempts=3),
compensate="release_inventory"
)
except Exception:
return "Failed to reserve inventory"
# 2. Process Payment (Retries handled automatically)
try:
# Wait for payment OR cancellation
payment_task = workflow.execute_activity("charge_card", order_id)
# Handle Cancellation
# We wait for either the payment to finish or a cancellation signal
done, pending = await workflow.wait_any([payment_task, self.cancelled_event])
if self.cancelled:
# Trigger Compensation for step 1 automatically
raise CancelledError("User cancelled order")
await payment_task
except CancelledError:
# Engine automatically runs 'release_inventory' here
workflow.logger.info("Workflow cancelled, compensating...")
return "Cancelled"
# 3. Long Timer (Durable)
# Waits 30 days for shipping confirmation.
# Process can die and restart; timer survives.
await workflow.sleep(timedelta(days=30))
return "Completed"
@workflow.signal
def cancel_order(self):
self.cancelled = True
self.cancelled_event.set()
6. Key Technologies to Study
If you are building this from scratch, look at:
Persistence: PostgreSQL (for reliability) or Redis (for speed, but harder to handle crashes perfectly).
Queueing: You need a task queue to dispatch work to workers. NATS, RabbitMQ, or Kafka are common.
Existing Frameworks:
Temporal: The modern standard for this pattern (Code-first, highly scalable).
Camunda/Zeebe: Visual BPMN-based workflows, excellent for complex compensation logic.
AWS Step Functions: Managed service, state machine defined in JSON.
7. Common Pitfalls
Non-Determinism: In the "Replay" model, your workflow code must be deterministic. You cannot use local_time = datetime.now() or random_int = rand(). You must use workflow.now() and workflow.random(). If the replayed history doesn't match the execution path, the engine crashes.
Heartbeating: For long-running "Activities" (e.g., processing a video), the worker must send heartbeats back to the engine. If the worker dies (OOM), the engine detects the lack of heartbeat and retries the task on a different worker.