We are going to design a long-running workflow engine that supports timers, retries, cancellation, and compensation.
The engine will be built with the following considerations:
- Workflows are composed of activities (steps) that may fail and require retries.
- Timers can be set for delays or specific timeouts.
- Cancellation can be requested for a running workflow, and we need to handle cleanup (compensation) for steps that have completed.
- Compensation (also known as sagas) allows undoing the effects of completed steps in case of a failure or cancellation.
We'll design the engine with the following components:
- Workflow: a sequence of activities (or parallel activities) with possible error handling and compensation.
- Activity: a unit of work that can be retried and has a compensation action.
- Timer: a way to wait for a certain duration or until a specific time.
- Workflow Engine: manages the state of workflows, schedules activities and timers, handles retries, and triggers compensation.
We'll use a state machine approach for each workflow instance. The state will include:
- Current step(s)
- History of completed steps (for compensation)
- Timers set
- Retry counts for each step
We'll assume we have a persistence layer to store workflow state so that the engine can be restarted.
Steps:
-
Define the workflow definition (static) and workflow instance (runtime state).
-
The engine will advance the workflow by executing activities and timers.
-
If an activity fails, it may be retried (according to a retry policy) or the workflow may fail (and then compensation may be triggered).
-
Timers can be used to wait for a condition (like a message from an external system) or just a delay.
-
Cancellation can be requested at any time. When cancelled, the engine will:
a. Cancel any pending timers and activities.
b. Run compensation for the steps that have been completed (in reverse order).
-
Compensation is defined per activity (or step) and is executed when the workflow is cancelled or fails after some steps have completed.
Let's sketch the classes and interfaces:
WorkflowDefinition:
- List steps (could be sequential or parallel, but for simplicity let's assume sequential with possible branches)
Step (abstract):
- Could be ActivityStep, TimerStep, ParallelStep, etc.
ActivityStep:
- activity: Activity (with execute and compensate methods)
- retryPolicy: how many retries, backoff, etc.
TimerStep:
WorkflowInstance:
- id: string
- definitionId: string
- currentStepIndex: int
- state: enum (Running, Completed, Failed, Cancelled, Compensating)
- history: list of completed steps (with their results and compensation status)
- timers: list of active timers (with their scheduled time and id)
- retryCounts: map from step index to current retry count
Activity:
- execute(): returns result or throws exception
- compensate(): undo the activity (if possible)
Engine:
- schedule(workflowInstance): starts or resumes a workflow instance.
- cancel(workflowInstanceId): requests cancellation.
The engine will have a main loop (or be event-driven) that:
- Checks for timers that have fired.
- Picks up workflow instances that are ready to execute the next step (no pending timers, not in error, etc.)
- Executes activities (possibly in a separate thread pool) and then updates the state.
We need to handle:
- Persistence: save the state of each workflow instance after each step (or timer) so we can recover.
- Concurrency: multiple workflow instances running, and multiple steps in parallel? We'll start with sequential for simplicity.
Let's outline the process for a workflow instance:
-
Load the workflow instance from storage (or create new).
-
If the state is:
- Running: check current step.
- If current step is a timer and the timer hasn't fired, wait.
- If timer fired, mark timer as done and move to next step.
- If current step is an activity and there's no ongoing execution, start the activity (with retry if needed).
- If the activity fails and retries are left, schedule a retry (with backoff) and keep the state as Running.
- If activity fails and no retries left, mark the workflow as Failed and start compensation (if any).
- If activity succeeds, record the result, save the step in history, and move to next step.
-
If there are no more steps, mark as Completed.
-
If cancellation is requested:
- Change state to Cancelling (or Cancelled) and then start compensation from the last completed step backwards.
-
Compensation:
- For each step in reverse order of completion, if it has a compensation action, execute it.
- If compensation fails, we might need to retry? (But note: compensation might be best-effort, or we might have a compensation retry policy.)
- After all compensations are done (or failed), mark the workflow as Cancelled.
Implementation considerations:
- We need a durable store for workflow instances. We'll assume we have a repository that can save and load by id.
- We need a way to store timers so that we can fire them even if the engine restarts. This could be a separate timer service or using the same storage with a query for due timers.
Let's assume we have:
class WorkflowRepository {
WorkflowInstance load(string id);
void save(WorkflowInstance instance);
}
class TimerService {
void scheduleTimer(Timer timer); // timer has a fire time and a callback (or we can poll)
// Alternatively, we can have a table of timers and a background process that checks for due timers.
}
However, for simplicity, we can have the engine periodically check for due timers by querying the repository for instances with timers that are due.
But note: we might have many instances, so we need an index on the timer fire time.
Alternatively, we can use a dedicated timer queue (like a priority queue) that survives restarts. But that's complex.
Let's assume we have a way to get the next due timer from the repository.
Steps for the engine loop:
while (true) {
// 1. Check for timers that are due.
List instancesWithDueTimers = repository.getInstancesWithDueTimers(now);
for each instance in instancesWithDueTimers:
// Load the instance (if not already in memory), process the timer, save.
// 2. Check for workflows that are ready to run the next step (no pending timers, not in error, etc.)
List<WorkflowInstance> runnableInstances = repository.getRunnableInstances();
for each instance in runnableInstances:
// Load, execute next step (if it's an activity, we might run it asynchronously and then update state when done)
// But note: if we run asynchronously, we need to store the fact that the activity is in progress.
// 3. Check for cancellations? (We can have a separate queue for cancellation requests.)
// Sleep for a bit to avoid busy wait.
}
However, this is a simplified version. In reality, we might use an event-driven approach with a message queue for events (like timer fired, activity completed, cancellation requested).
Given the complexity, let's design a more event-driven system:
Events:
- TimerFiredEvent(workflowInstanceId, timerId)
- ActivityCompletedEvent(workflowInstanceId, stepIndex, result)
- ActivityFailedEvent(workflowInstanceId, stepIndex, error)
- CancellationRequestedEvent(workflowInstanceId)
The engine would subscribe to these events and update the workflow state accordingly.
But then we need a way to generate these events. For timers, we can have a timer service that publishes TimerFiredEvent when a timer expires.
For activities, we have activity workers that publish the completion or failure.
However, for the sake of this design, let's stick to a simpler polling model for the engine, but note that in production we might use events.
Let's define the state transitions for a workflow instance:
New -> Running (when scheduled)
Running -> Completed (last step succeeded)
Running -> Failed (last step failed and no retry)
Running -> Cancelling (when cancellation requested)
Cancelling -> Cancelled (after compensation done)
Running -> Compensating (when an activity fails and we have compensation for previous steps? Actually, compensation is only on cancellation or failure? We said failure leads to compensation. So we might have:
Actually, let's clarify:
In a saga pattern, when a step fails, we compensate the previous steps. So we might have:
Running -> Compensating (when an activity fails and we decide to compensate the already completed steps)
But note: we might also have a compensation on cancellation. So:
- On failure of an activity (with no retry left) we trigger compensation for the completed steps (in reverse order) and then mark as Failed.
- On cancellation request, we trigger compensation for the completed steps and then mark as Cancelled.
So we have two ways to enter Compensating: failure or cancellation.
Let's define:
enum WorkflowState {
New,
Running,
Completed,
Failed,
Cancelled,
Compensating
}
And we have:
- When in Running and an activity fails (and no retry) -> change to Compensating and start compensating from the last completed step.
- When in Running and cancellation requested -> change to Compensating and start compensating from the last completed step.
Then, during compensation, we execute the compensation actions for each step (in reverse order). If all compensations succeed, then:
if we were in Compensating due to failure -> mark as Failed.
if due to cancellation -> mark as Cancelled.
If a compensation fails, we might retry? Or mark as CompensationFailed? Let's assume we have a retry policy for compensation too.
Now, let's design the step:
abstract class Step {
// maybe a method to execute (for activity) or wait (for timer)
// and a method to compensate (for activity that supports compensation)
}
But note: a timer step doesn't have compensation? Or does it? Maybe if we set a timer and then we cancel, we might want to cancel the timer? That's not compensation per se, but we cancel the timer.
Actually, compensation is about undoing the effects of a completed step. A timer step that has completed (i.e., the wait is over) might not have any effect to undo. So only activity steps have compensation.
So:
class ActivityStep : Step {
Activity activity;
RetryPolicy retryPolicy;
Result execute() { ... }
void compensate() { activity.compensate(); }
}
class TimerStep : Step {
Duration duration; // or until a specific time
// No compensation, but if the workflow is cancelled while the timer is waiting, we cancel the timer.
}
Now, the workflow instance must track:
- For each step, whether it has been completed (and for activity steps, the compensation may be needed).
- For the current step, if it's an activity, we might be in the middle of a retry? Or if it's a timer, we have scheduled it.
Let's design the WorkflowInstance:
class WorkflowInstance {
string id;
string definitionId;
WorkflowState state;
int currentStepIndex; // index of the step we are currently on (if running, this is the step we are trying to execute, or if it's a timer, then it's the timer step and we are waiting)
List history; // for completed steps, we store the result and the step index, and also whether compensation has been done for that step?
List activeTimers; // timers that are set and not yet fired (for timer steps that are pending)
// We might also store retry counts per step? Or in the StepResult for the current step if it's an activity and we are retrying?
// Actually, we can store the current retry count for the current step in the instance, because if we are in the middle of retries, we need to know how many we've done.
int currentRetryCount; // for the current step (if it's an activity and we are retrying)
}
StepResult:
int stepIndex;
Step step; // or just the activity if we need to compensate? We need to know which step to compensate.
object result; // for activity, the result of execute. For timer, maybe the time it fired?
bool compensated; // whether we have run compensation for this step.
Timer:
string timerId;
DateTime fireTime;
int stepIndex; // which timer step this is for? Actually, each timer step might have a timer. But what if the same timer step is retried? Then we might have multiple timers?
// Actually, a timer step is just one step. If the timer fires, we move on. So we only need one timer per timer step.
But note: what if the workflow is cancelled while a timer is waiting? We need to cancel that timer.
So in the workflow instance, when we start a timer step, we schedule a timer and store the timerId. Then when the timer fires, we remove it from activeTimers and move on.
Now, the engine:
We have a loop that:
-
Check for due timers:
For each workflow instance that has active timers that are due (fireTime <= now):
- Load the instance.
- Find the timer that is due (by timerId or by stepIndex? Actually, we might have multiple timers? But in a sequential workflow, only one timer at a time? Not necessarily, if we have parallel steps, we might have multiple timers. But let's assume sequential for now.)
- Remove the timer from activeTimers.
- Mark the current step (which should be a TimerStep) as completed? Actually, the timer step is completed when the timer fires. So we treat it as a successful completion of the timer step.
- Then we move to the next step.
-
Check for runnable instances:
An instance is runnable if:
- state is Running
- current step is not a timer that has an active timer (i.e., if it's a timer step and we haven't scheduled a timer, we need to schedule one and then wait, so it's not runnable until the timer fires? Actually, when we first encounter a timer step, we schedule the timer and then the instance becomes waiting. So runnable instances are those that are not waiting for a timer and not in the middle of an activity execution? But what about activity retries? We might have scheduled a retry with a delay, which is like a timer. So we might treat retry delays as timers too.
Actually, we can unify: every time we need to wait (for a timer or for an activity retry delay), we set a timer.
So:
- When we start an activity and it fails, we schedule a retry after a delay (if retries left). So we set a timer for the retry delay and then the instance becomes waiting.
Therefore, an instance is runnable only when:
- It is in state Running
- There is no active timer (i.e., we are not waiting for a timer to fire) and there is no ongoing activity execution.
But how do we track ongoing activity execution? We might have started an activity and are waiting for it to complete (which is asynchronous). So we need to mark that the current step is in progress.
Let's change:
In WorkflowInstance, we have:
Step currentStep; // the step we are currently working on
bool currentStepInProgress; // if we have started executing the current step (activity) and are waiting for it to complete.
Then, an instance is runnable if:
state == Running and
(currentStep is null? Actually, we might have just started and currentStep is the first step)
and not currentStepInProgress and
no active timers.
But wait, if currentStep is a timer step and we haven't scheduled a timer, then we are runnable? Actually, when we first encounter a timer step, we schedule a timer and then set activeTimers, so then we are not runnable until the timer fires.
So:
When we process a runnable instance:
if currentStep is ActivityStep and not currentStepInProgress:
start the activity (set currentStepInProgress = true) and then we will wait for the activity to complete (which will generate an event).
if currentStep is TimerStep and we haven't scheduled a timer for it:
schedule a timer for the duration (or until the specific time) and store the timerId in activeTimers, and then set currentStepInProgress? Actually, we don't need to set in progress for timer because the timer is scheduled and we are waiting. But we can mark that the timer step is in progress? Actually, the timer step is not completed until the timer fires. So we can set currentStepInProgress = true and then when the timer fires, we complete the step.
But note: when the timer fires, we will get an event and then we complete the step and move to next.
However, if we are using events, then:
- When we start an activity, we call activity.execute() (or submit to a worker) and then we don't do anything until we get an event.
So the engine, when it finds a runnable instance, will start the activity and then save the instance with currentStepInProgress=true. Then when the activity completes (or fails), we get an event and update the instance.
Similarly, for a timer step, when we first encounter it, we schedule a timer and then save the instance with the timerId and currentStepInProgress=true? But then the timer step is in progress until the timer fires.
Actually, for a timer step, we don't have an asynchronous operation other than the timer itself. So we can schedule the timer and then set currentStepInProgress=true and then when the timer fires, we complete the step.
But note: if the workflow is cancelled while the timer is waiting, we cancel the timer and then we don't complete the step? Actually, we are cancelling the whole workflow, so we don't care about completing the step. We go to compensation.
So let's adjust:
When we start a timer step:
- schedule the timer, store the timerId in activeTimers.
- set currentStepInProgress = true.
- save.
Then, when the timer fires:
- we load the instance, check that the timerId matches (and that the current step is still a TimerStep and in progress) and then:
- remove the timer from activeTimers.
- mark the step as completed (add to history, set currentStepInProgress=false, move to next step).
But what if the workflow was cancelled while the timer was waiting? Then when the timer fires, we should ignore it? Or we cancel the timer when we cancel the workflow.
So in the cancellation process, we cancel all active timers for the instance.
Now, let's write the pseudo-code for the engine loop (with events):
We have:
onTimerFired(workflowInstanceId, timerId):
instance = repository.load(workflowInstanceId)
if instance.state != Running or instance.currentStepInProgress == false or instance.currentStep is not a TimerStep or the timerId doesn't match the one we have for the current step? Actually, we store the timerId in activeTimers. So we check if the timerId is in activeTimers.
then ignore (maybe log an error)
else:
remove the timer from activeTimers.
complete the current step (add to history, set currentStepInProgress=false, increment currentStepIndex)
save instance.
Then, if there are more steps, we might want to schedule the next step? Actually, the next step might be an activity or timer. We can try to run the next step immediately? But we are in an event, so we can call scheduleNextStep(instance) which will check if the next step is runnable and start it if it's an activity, or schedule a timer if it's a timer.
onActivityCompleted(workflowInstanceId, stepIndex, result):
instance = repository.load(workflowInstanceId)
// Check that the stepIndex matches the current step and that currentStepInProgress is true.
if valid:
set currentStepInProgress = false
add to history (with result and compensated=false)
increment currentStepIndex
save instance
scheduleNextStep(instance)
onActivityFailed(workflowInstanceId, stepIndex, error):
instance = repository.load(workflowInstanceId)
if valid:
currentRetryCount++
if currentRetryCount <= retryPolicy.maxRetries:
// schedule a retry after delay
scheduleRetry(instance, retryPolicy.delay)
else:
// no more retries, trigger compensation
startCompensation(instance)
onCancellationRequested(workflowInstanceId):
instance = repository.load(workflowInstanceId)
if instance.state == Running:
instance.state = Compensating
save instance
startCompensation(instance)
startCompensation(instance):
// We are in state Compensating.
// We need to compensate the steps in reverse order that have been completed and not yet compensated.
// We might have to do this step by step, because each compensation might take time and might fail.
// Find the last step in history that is not compensated.
// Then, for each step (from last to first) that is not compensated:
// if the step has compensation (i.e., it's an ActivityStep with a compensate method), then:
// run the compensation (asynchronously? we can do it synchronously for simplicity, but note that compensation might take time and we might want to retry)
// if compensation fails, we might need to retry? Or mark as compensation failed and stop? Let's assume we have a compensation retry policy.
// But note: compensation might be defined only for some steps.
// We can do:
// while there are uncompensated steps:
// step = get next step to compensate (last uncompensated)
// try {
// step.compensate()
// mark step as compensated
// } catch (Exception e) {
// // retry? or fail the compensation?
// // We might have a compensation retry policy. Let's assume we try a fixed number of times.
// // If we run out of retries, then we mark the workflow as CompensationFailed? Or we log and continue?
// // This is a design decision. In some systems, if compensation fails, we might need manual intervention.
// }
// After all compensations are done (or if we decide to stop because of failure), we set the state:
// if we were compensating due to failure -> Failed
// if due to cancellation -> Cancelled
// But note: we might be compensating multiple steps and one fails. We might still want to mark as Failed (or Cancelled) but note that the workflow is already in a bad state.
// Alternatively, we can have a state for CompensationFailed.
// Let's do:
// instance.state = Compensating
// for each step in reverse order of history:
// if step has compensation and not compensated:
// try {
// step.compensate()
// step.compensated = true
// } catch (Exception e) {
// // log and maybe retry? But for simplicity, we break and mark as CompensationFailed?
// instance.state = CompensationFailed
// break
// }
// if instance.state != CompensationFailed:
// if we were compensating due to failure -> instance.state = Failed
// else -> instance.state = Cancelled
// But note: we might have been in Compensating due to failure, but then we might have a step that fails compensation. Then we are in a state where we tried to compensate but failed. So we mark as CompensationFailed.
However, we are doing compensation in a loop and then updating the state. But what if the engine crashes during compensation? We need to store the state after each compensation step? Or we can do:
- When we start compensation, we mark the instance as Compensating and save.
- Then we compensate one step at a time, and after each step we save the instance (with that step marked as compensated).
- If the engine crashes, we can resume compensation from the last uncompensated step.
So we need to track which steps have been compensated.
In the StepResult, we have a 'compensated' flag.
So in startCompensation:
instance.state = Compensating
save(instance)
// Then we have a loop that picks the next uncompensated step (from the end of history) and compensates it.
// But note: we might be doing this in one go, but if there are many steps, we might want to do one step per event? Or we can do all in one transaction?
// Since we are persisting after each step, we can do:
while (true) {
stepResult = getNextUncompensatedStep(instance)
if stepResult == null: break
try {
stepResult.step.compensate()
stepResult.compensated = true
save(instance)
} catch (Exception e) {
// log and break, and set state to CompensationFailed?
instance.state = CompensationFailed
save(instance)
break
}
}
// After the loop, if we have compensated all steps and state is still Compensating, then set to Failed or Cancelled.
if (instance.state == Compensating) {
if (compensationTrigger == Failure) {
instance.state = Failed
} else {
instance.state = Cancelled
}
save(instance)
}
But how do we know the compensationTrigger? We can store it in the instance: maybe a field 'cancellationReason' or 'failureReason'. Or we can have two different methods: compensateDueToFailure() and compensateDueToCancellation().
Alternatively, we can have:
onActivityFailed: set instance.failureReason = error, then startCompensation(instance, dueToFailure=true)
onCancellationRequested: set instance.cancellationReason = reason, then startCompensation(instance, dueToFailure=false)
Then in startCompensation, we know the trigger.
Now, let's think about the scheduleNextStep:
After a step is completed (or after compensation of a step? Actually, compensation doesn't move the current step index, it just marks steps as compensated and then we eventually set the state to Failed or Cancelled. So we don't schedule next step after compensation.
So scheduleNextStep is only called when a step completes successfully.
In scheduleNextStep(instance):
instance.currentStepIndex++
if instance.currentStepIndex >= definition.steps.size():
instance.state = Completed
save(instance)
return
nextStep = definition.steps[instance.currentStepIndex]
if nextStep is ActivityStep:
// Check if we need to retry? Actually, if we are coming from a retry, we might have a currentRetryCount? But note: when we complete an activity, we reset the retry count for the next activity? Or we keep per step?
// We are moving to a new step, so we reset the currentRetryCount to 0? But what if we are retrying the same step? Actually, when an activity fails and we schedule a retry, we don't move the currentStepIndex. So the current step remains the same and we increment the retry count.
// So in the case of a new step, we set currentRetryCount = 0.
instance.currentRetryCount = 0
// Then we start the activity. But note: the activity might have a retry policy. We will handle retries in the onActivityFailed.
// Start the activity:
try {
result = nextStep.activity.execute()
// We are in the engine loop, but we don't want to block. So we should run the activity asynchronously and then post an event when done.
// But for simplicity, let's assume we run it synchronously in the engine thread? That would block the engine. So we need an activity executor.
// We submit the activity to an executor and then set currentStepInProgress=true and return. The executor will post the event when done.
} catch (Exception e) {
// This is a synchronous failure? We can treat it as an activity failure and then schedule a retry.
onActivityFailed(instance.id, instance.currentStepIndex, e)
}
if nextStep is TimerStep:
// Schedule a timer for the duration (or until time) and set currentStepInProgress = true? Actually, we don't set in progress for timer because the timer is the step. We schedule the timer and then wait for it to fire.
timerId = timerService.scheduleTimer(nextStep.duration, instance.id, nextStep.stepIndex? or just the instance id and then we look up by step index? We can store the step index in the timer.
instance.activeTimers.add(new Timer { timerId = timerId, stepIndex = instance.currentStepIndex })
instance.currentStepInProgress = true? Actually, we don't have a currentStepInProgress for timer? We can use the same field. But note: when the timer fires, we complete the step and set currentStepInProgress=false.
// So we set currentStepInProgress = true.
instance.currentStepInProgress = true
save(instance)
But note: we are in the scheduleNextStep, and we are about to schedule a timer. We don't wait for the timer to fire. The timer will fire later and we'll handle the event.
However, what if the timer step is the first step? Then we are in the same situation.
Now, what about parallel steps? We haven't considered them. For simplicity, let's stick to sequential.
But note: if we have parallel steps, we need to wait for all of them to complete. That would require a different structure. We might have a parallel step that contains multiple sub-steps. Then we need to track the status of each sub-step and only when all are done, we move on.
Given the complexity, we'll leave parallel steps for future.
Now, let's summarize the engine components:
- WorkflowRepository: saves and loads WorkflowInstance.
- TimerService: schedules timers and cancels them. It might be implemented with a priority queue and a background thread that checks for due timers and publishes events.
- ActivityExecutor: runs activities (maybe in a thread pool) and posts events when done.
The engine itself is event-driven:
onEvent(Event e) {
switch (e.type) {
case TimerFired: handleTimerFired(e); break;
case ActivityCompleted: handleActivityCompleted(e); break;
case ActivityFailed: handleActivityFailed(e); break;
case CancellationRequested: handleCancellationRequested(e); break;
}
}
And each handler loads the instance, updates the state, and saves.
But note: we must be careful about concurrency. Two events for the same instance might be processed concurrently? We should lock the instance by id.
So in each event handler, we load the instance, lock it (by instance id), and then process and save.
Alternatively, we can have a single thread per workflow instance? That would avoid locking but might not scale. Or we can use optimistic locking with version numbers.
Let's assume we use a lock per instance id (or a database lock) to ensure only one thread updates an instance at a time.
Now, let's write the code structure:
class WorkflowEngine {
WorkflowRepository repository;
TimerService timerService;
ActivityExecutor activityExecutor;
void start() {
// start listening to events from timerService and activityExecutor
timerService.onTimerFired(this::onTimerFired);
activityExecutor.onActivityCompleted(this::onActivityCompleted);
activityExecutor.onActivityFailed(this::onActivityFailed);
cancellationRequestQueue.onCancellationRequested(this::onCancellationRequested);
}
void onTimerFired(TimerFiredEvent e) {
lock(e.workflowInstanceId) {
WorkflowInstance instance = repository.load(e.workflowInstanceId);
// check if the timer is in activeTimers and matches the current step?
Timer timer = instance.activeTimers.find(t => t.timerId == e.timerId);
if (timer == null) {
// maybe it was cancelled? ignore.
return;
}
// Remove the timer
instance.activeTimers.remove(timer);
// Complete the current step (which is a TimerStep) and move to next
completeCurrentStep(instance, result: null); // for timer, result is just that it fired? We don't have a result.
}
}
void onActivityCompleted(ActivityCompletedEvent e) {
lock(e.workflowInstanceId) {
WorkflowInstance instance = repository.load(e.workflowInstanceId);
// Check that the current step index matches and that currentStepInProgress is true.
if (instance.currentStepIndex != e.stepIndex || !instance.currentStepInProgress) {
// maybe this is an old event? ignore.
return;
}
completeCurrentStep(instance, e.result);
}
}
void onActivityFailed(ActivityFailedEvent e) {
lock(e.workflowInstanceId) {
WorkflowInstance instance = repository.load(e.workflowInstanceId);
if (instance.currentStepIndex != e.stepIndex || !instance.currentStepInProgress) {
return;
}
// Reset currentStepInProgress because the activity is done (failed)
instance.currentStepInProgress = false;
instance.currentRetryCount++;
if (instance.currentRetryCount <= instance.currentStep.retryPolicy.maxRetries) {
// schedule a retry
scheduleRetry(instance, instance.currentStep.retryPolicy.delay);
} else {
// no more retries, trigger compensation
startCompensation(instance, dueToFailure=true, failureReason=e.error);
}
repository.save(instance);
}
}
void onCancellationRequested(CancellationRequestedEvent e) {
lock(e.workflowInstanceId) {
WorkflowInstance instance = repository.load(e.workflowInstanceId);
if (instance.state == WorkflowState.Running) {
instance.state = WorkflowState.Compensating;
instance.cancellationReason = e.reason;
repository.save(instance);
startCompensation(instance, dueToFailure=false);
}
}
}
void completeCurrentStep(WorkflowInstance instance, object result) {
// This is called when a step (activity or timer) completes successfully.
// Add to history
StepResult stepResult = new StepResult {
stepIndex = instance.currentStepIndex,
step = instance.currentStep, // we need to store the step definition? Actually, we have the definition in the workflow definition. But we need to know which step to compensate, so we might store the step type and the activity?
// Alternatively, we can store the step index and then look up the step from the definition when we need to compensate? But the definition might change? We should store the step definition at the time of execution? Or we can store the step index and then when compensating, we use the current definition? That might be dangerous if the definition changed.
// Let's store the step type and the activity (if it's an activity) and the compensation action? Actually, we need to run compensation for that step. So we need to have the compensation action.
// We can store in StepResult:
// stepIndex
// stepType (Activity or Timer)
// activityId (if activity) and the compensation activity? But the compensation might be a separate activity? Or the activity itself has a compensate method.
// Since we have the Activity object in the ActivityStep, and the Activity has a compensate method, we can store the Activity? But what if the Activity is not serializable? We might store the activityId and then look up the activity from a registry? This is getting complex.
// For simplicity, let's assume that the step definition (the ActivityStep) is stored in the workflow definition and we don't change it. Then we can store only the step index and when compensating, we look up the step from the definition by index.
// But note: if we change the workflow definition, then old instances will use the new definition? That might be wrong. So we should store the step definition at the time of execution? Or we can store the step as a serialized object?
// Given the complexity, let's assume we don't change the workflow definition for a running instance. So we can store the step index and then use the current definition. But if we do change the definition, we must be careful.
// Alternatively, we can store the step type and the activity name and parameters? Then we can reconstruct the activity? But the compensation might be different.
// Let's change: in the StepResult, we store:
// stepIndex
// stepType (enum)
// if Activity: activityName and activityParameters? and compensationActivityName? But that's too much.
// Given the time, let's assume we have a way to get the step from the definition by index and that the definition doesn't change for a running instance.
result = result,
compensated = false
};
instance.history.add(stepResult);
instance.currentStepInProgress = false;
instance.currentStepIndex++;
if (instance.currentStepIndex >= instance.definition.steps.size()) {
instance.state = WorkflowState.Completed;
} else {
// Try to schedule the next step immediately? But we are in an event handler, and we might want to avoid recursion. So we can schedule the next step by calling scheduleNextStep(instance) which might start an activity or schedule a timer.
// But note: we are already in the event handler and we are holding the lock. We can do:
scheduleNextStep(instance);
}
repository.save(instance);
}
void scheduleNextStep(WorkflowInstance instance) {
// Precondition: instance.state == Running, currentStepIndex is set to the next step, and no currentStepInProgress and no active timers.
if (instance.currentStepIndex >= instance.definition.steps.size()) {
instance.state = WorkflowState.Completed;
repository.save(instance);
return;
}
Step nextStep = instance.definition.steps[instance.currentStepIndex];
if (nextStep is ActivityStep) {
instance.currentStepInProgress = true;
// We don't reset currentRetryCount because this is a new step. But note: the currentRetryCount is for the current step. Since we moved to a new step, we should reset it.
instance.currentRetryCount = 0;
repository.save(instance);
// Now, run the activity asynchronously? We submit to activityExecutor.
activityExecutor.execute(instance.id, instance.currentStepIndex, ((ActivityStep)nextStep).activity);
} else if (nextStep is TimerStep) {
TimerStep timerStep = (TimerStep)nextStep;
// Schedule a timer
string timerId = timerService.scheduleTimer(timerStep.duration, instance.id, instance.currentStepIndex);
instance.activeTimers.add(new Timer { timerId = timerId, stepIndex = instance.currentStepIndex });
instance.currentStepInProgress = true;
repository.save(instance);
}
}
void scheduleRetry(WorkflowInstance instance, Duration delay) {
// We schedule a timer for the retry delay, and when it fires, we will retry the current activity.
// But note: we don't want to create a new step? We just want to retry the same step.
// So we schedule a timer that will fire after delay, and when it fires, we will treat it as a retry attempt? Actually, we don't have a step for retry. We just want to execute the same activity again.
// We can have a special event: RetryTimerFired(workflowInstanceId, stepIndex)
// Alternatively, we can schedule a timer and when it fires, we start the activity again? But note: the current step is still the same and we are already in progress? Actually, when the activity failed, we set currentStepInProgress=false. So when the retry timer fires, we are not in progress.
// So in the timer fired event for a retry, we check: if the instance is in Running and the current step is the same step and not in progress, then we start the activity again (with currentRetryCount already incremented? Actually, we incremented when the activity failed).
// So we need to know that this timer is for retry? We can store in the Timer object a field: isRetryTimer.
// Alternatively, we can have two types of timers: step timers (for TimerStep) and retry timers.
// Let's do:
// When scheduling a retry, we set a timer and store in the instance's activeTimers a timer with stepIndex = currentStepIndex and isRetry = true.
// Then in onTimerFired, we check:
// if the timer is for a step (i.e., the stepIndex is the current step and currentStepInProgress is true) then it's a timer step that fired? Actually, for a timer step, we set currentStepInProgress=true when we schedule the timer. So when the timer fires, we complete the step.
// if the timer is for a retry (isRetry=true) then we check: currentStepInProgress is false and currentStepIndex is the same? Then we start the activity again.
// So we need to extend the Timer class to have a flag isRetry.
// But note: we also have the stepIndex in the timer. So:
// In scheduleRetry:
string timerId = timerService.scheduleTimer(delay, instance.id, instance.currentStepIndex);
instance.activeTimers.add(new Timer { timerId = timerId, stepIndex = instance.currentStepIndex, isRetry = true });
repository.save(instance);
// Then in onTimerFired:
Timer timer = instance.activeTimers.find(...);
if (timer.isRetry) {
// This is a retry timer.
instance.activeTimers.remove(timer);
// Now, we are going to retry the current activity.
// We don't change the step index, we just set currentStepInProgress=true and run the activity again.
instance.currentStepInProgress = true;
repository.save(instance);
activityExecutor.execute(instance.id, instance.currentStepIndex, ((ActivityStep)instance.currentStep).activity);
} else {
// It's a timer step that fired.
// ... as before
}
}
void startCompensation(WorkflowInstance instance, bool dueToFailure, Exception failureReason=null) {
instance.state = WorkflowState.Compensating;
if (dueToFailure) {
instance.failureReason = failureReason;
} else {
instance.cancellationReason = ...; // we might have set this in onCancellationRequested.
}
repository.save(instance);
// Now, we need to compensate steps in reverse order.
// We can do it in a loop, but we might want to do one step at a time? Because compensation might take time and we don't want to block the engine.
// Let's do: we find the next step to compensate (the last one that is not compensated) and then compensate it. We can schedule the compensation as an activity? Or we can run it directly?
// Since compensation is part of the workflow, we might have a separate compensation activity? Or we can run it in the engine thread? But compensation might be long-running and might fail.
// We can treat compensation as an activity? Then we can use the same activity executor? But note: compensation is not defined as an activity in the workflow. It's defined per step.
// Alternatively, we can have a compensation executor that runs the compensation methods. But note: the compensation method might be a simple method or it might be an activity that requires retries?
// Given the complexity, let's assume that the compensation is a method that we call and if it fails, we retry (with a fixed policy) and if it still fails, we mark the workflow as CompensationFailed.
// We can do:
while (true) {
StepResult stepToCompensate = instance.history.findLast(s => !s.compensated);
if (stepToCompensate == null) {
// all compensated
break;
}
// Check if the step has compensation? Only activity steps have compensation.
if (stepToCompensate.step is ActivityStep) {
try {
stepToCompensate.step.compensate();
stepToCompensate.compensated = true;
repository.save(instance);
} catch (Exception e) {
// Compensation failed. We might retry? But for simplicity, we break and mark as CompensationFailed.
instance.state = WorkflowState.CompensationFailed;
repository.save(instance);
return;
}
} else {
// Timer steps don't have compensation, but we might have already cancelled the timer? Actually, when we cancelled the workflow, we cancelled all timers. So we just mark as compensated?
stepToCompensate.compensated = true;
repository.save(instance);
}
}
// After compensating all steps:
if (dueToFailure) {
instance.state = WorkflowState.Failed;
} else {
instance.state = WorkflowState.Cancelled;
}
repository.save(instance);
}
This is a simplified version. We have not considered:
- Parallel steps.
- Compensation might be asynchronous and require retries.
- The engine might be distributed, so we need to handle multiple engine instances and distributed locking.
- The timer service and activity executor might be distributed as well.
But this gives a basic design.
Let's summarize the main components:
- WorkflowDefinition: a list of steps (ActivityStep, TimerStep, etc.)
- WorkflowInstance: runtime state.
- WorkflowEngine: event handlers that update the state.
- TimerService: schedules timers and fires events.
- ActivityExecutor: runs activities and posts events.
We assume that the workflow definition is immutable and that we don't change it for running instances.
This design is similar to the AWS Step Functions or Apache Camel's Saga pattern.
Note: This is a simplified design for educational purposes. A production system would require more features and robustness.
Let me know if you have any questions or if you want to extend any part.
I'll design a comprehensive long-running workflow engine with core features: timers, retries, cancellation, and compensation (saga pattern). This is inspired by systems like AWS Step Functions, Temporal, and Camunda.
Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ Workflow Engine │
├─────────────┬─────────────┬─────────────┬───────────────┤
│ Timer │ Retry │ Cancellation│ Compensation │
│ Manager │ Manager │ Handler │ (Saga) │
└─────────────┴─────────────┴─────────────┴───────────────┘
│ │ │ │
└──────────────┼──────────────┼────────────────┘
│ │
┌──────▼──────┐ ┌────▼──────┐
│State Machine│ │Persistency│
│ (WF Inst) │ │ Store │
└─────────────┘ └───────────┘
Core Components
1. Workflow Definition DSL
class WorkflowDefinition:
steps: List[Step] # Sequential or parallel
variables: Dict[str, Any]
compensation_strategy: SagaStrategy
class Step:
type: StepType # ACTIVITY, TIMER, PARALLEL, CHOICE
name: str
activity_ref: str # Reference to activity implementation
retry_policy: RetryPolicy
compensation_ref: str # Compensation activity
timeout: Optional[timedelta]
class RetryPolicy:
max_attempts: int
backoff_multiplier: float
initial_interval: timedelta
max_interval: timedelta
retry_on: List[ExceptionType]
2. Workflow Instance (State Machine)
class WorkflowInstance:
id: UUID
definition_id: str
status: WorkflowStatus # RUNNING, COMPLETED, FAILED, CANCELLING, CANCELLED
# Current execution state
current_step_index: int
executed_steps: List[ExecutedStep] # History with results
pending_compensations: List[CompensationTask] # LIFO stack
# Runtime context
variables: Dict[str, Any]
started_at: datetime
last_updated: datetime
retry_states: Dict[str, RetryState] # Per-step retry tracking
class ExecutedStep:
step_name: str
step_index: int
status: StepStatus # SUCCESS, FAILED, COMPENSATED
result: Any
executed_at: datetime
compensated_at: Optional[datetime]
3. Timer Manager
class TimerManager:
def schedule_timer(timer_id: str,
fire_time: datetime,
workflow_id: UUID,
step_index: int,
callback: Callable):
"""Schedule a persistent timer"""
# Uses durable storage + scheduler (e.g., Quartz, RabbitMQ delayed messages)
pass
def cancel_timer(timer_id: str):
"""Cancel pending timer"""
pass
def on_timer_fired(timer_id: str):
"""Handler when timer fires"""
pass
4. Retry Manager
class RetryManager:
def should_retry(step_name: str,
attempt: int,
error: Exception) -> bool:
policy = get_retry_policy(step_name)
if attempt >= policy.max_attempts:
return False
if type(error) not in policy.retry_on:
return False
return True
def calculate_delay(attempt: int, policy: RetryPolicy) -> timedelta:
"""Exponential backoff with jitter"""
base = policy.initial_interval.total_seconds()
max_delay = policy.max_interval.total_seconds()
delay = min(
base * (policy.backoff_multiplier ** (attempt - 1)),
max_delay
)
jitter = random.uniform(0, delay * 0.1) # 10% jitter
return timedelta(seconds=delay + jitter)
5. Cancellation Handler
class CancellationHandler:
def cancel_workflow(workflow_id: UUID,
reason: str,
graceful_timeout: Optional[timedelta] = None):
"""
1. Mark workflow as CANCELLING
2. Cancel pending timers
3. Stop new activity executions
4. Trigger compensation (saga)
5. Wait for graceful shutdown (optional)
"""
instance = store.load(workflow_id)
instance.status = WorkflowStatus.CANCELLING
# Cancel all timers
for timer in instance.active_timers:
timer_manager.cancel_timer(timer.id)
# Trigger compensation for completed steps (in reverse order)
compensation_manager.execute_compensation(instance)
6. Compensation Manager (Saga Pattern)
class CompensationManager:
def execute_compensation(instance: WorkflowInstance):
"""
Execute compensations in reverse order (LIFO):
1. Iterate through executed_steps in reverse
2. For each step with compensation:
- Execute compensation activity
- Handle failures (retry or fail workflow)
3. Mark workflow as CANCELLED when done
"""
for step in reversed(instance.executed_steps):
if step.status == StepStatus.SUCCESS and step.compensation_ref:
try:
compensation_activity = get_activity(step.compensation_ref)
result = compensation_activity.execute(
step.result,
instance.variables
)
step.compensated_at = datetime.utcnow()
store.save(instance)
except Exception as e:
# Compensation failed - decide strategy
if config.strict_compensation:
raise CompensationFailedError(step.name, e)
else:
log.error(f"Compensation failed for {step.name}: {e}")
# Continue with next compensation or mark as PARTIAL_COMPENSATED
instance.status = WorkflowStatus.CANCELLED
store.save(instance)
7. Persistent State Store
class WorkflowStore:
def save(instance: WorkflowInstance):
"""ACID transaction:
1. Update workflow instance
2. Update timer records
3. Update activity executions
4. Update compensation state
"""
with transaction():
db.save_workflow(instance)
db.save_timers(instance.active_timers)
db.save_executions(instance.executed_steps)
def load(workflow_id: UUID) -> WorkflowInstance:
"""Load with optimistic locking"""
pass
def find_runnable_workflows() -> List[WorkflowInstance]:
"""Find workflows ready for next step (timers fired, retries ready)"""
pass
Execution Flow Examples
Basic Workflow with Retry & Timer
1. Start → Step A (with retry: 3 attempts, exponential backoff)
2. Step A succeeds → Step B (timer: wait 5 minutes)
3. Timer fires → Step C (no retry)
4. Step C fails → Trigger compensation for Step B, then Step A
Cancellation Flow
User cancels at Step 3:
1. Status → CANCELLING
2. Cancel Step 3 timer (if pending)
3. Compensate Step 2 → Step 1 (reverse order)
4. Status → CANCELLED
Key Design Patterns
1. State Machine Pattern
class WorkflowStateMachine:
transitions = {
WorkflowStatus.RUNNING: [WorkflowStatus.COMPLETED,
WorkflowStatus.FAILED,
WorkflowStatus.CANCELLING],
WorkflowStatus.CANCELLING: [WorkflowStatus.CANCELLED],
# ... other transitions
}
def can_transition(current: Status, target: Status) -> bool:
return target in transitions.get(current, [])
2. Idempotency Design
- All activities must be idempotent or track execution IDs
- Use deduplication keys for external calls
- Compensation must also be idempotent
3. Exactly-Once Processing
def execute_activity(workflow_id, step_name, activity_input):
execution_id = f"{workflow_id}:{step_name}:{activity_hash}"
if store.is_already_executed(execution_id):
return store.get_result(execution_id) # Idempotent read
with store.lock(execution_id):
result = activity.execute(activity_input)
store.record_execution(execution_id, result)
return result
Scalability Considerations
Sharding Strategy
# Hash workflow_id to shard
shard_id = hash(workflow_id) % NUM_SHARDS
# Each shard processes its workflows sequentially
# But multiple shards process in parallel
Event Sourcing Alternative
class WorkflowEvent:
type: EventType # STEP_STARTED, STEP_COMPLETED, TIMER_SCHEDULED, etc.
workflow_id: UUID
data: Dict
timestamp: datetime
version: int
# Rebuild state by replaying events
def rebuild_workflow(workflow_id):
events = store.get_events(workflow_id)
return apply_events(events)
Error Handling Strategies
class ErrorHandlingPolicy:
# Per-step or global
retryable_errors: Set[ExceptionType] # {TimeoutError, ServiceUnavailable}
non_retryable_errors: Set[ExceptionType] # {ValidationError}
def handle_error(step_name: str, error: Exception) -> ErrorAction:
if type(error) in retryable_errors:
return ErrorAction.RETRY
elif type(error) in non_retryable_errors:
return ErrorAction.FAIL_WORKFLOW
else:
return ErrorAction.COMPENSATE_AND_FAIL
Monitoring & Observability
class WorkflowMetrics:
- Active workflows count
- Step duration percentiles
- Retry rate per step
- Compensation rate
- Timer accuracy (scheduled vs fired)
- Queue depths (pending activities/timers)
Implementation Choices
| Aspect | Option 1 (Simple) | Option 2 (Scalable) |
|---|
| Storage | Single DB with locking | Event store + projections |
| Timers | DB polling + sleep | Dedicated timer service (e.g., Quartz) |
| Activities | Synchronous execution | Async worker queue (RabbitMQ/Kafka) |
| State | CRUD updates | Event sourcing |
| Locking | DB row locks | Optimistic concurrency (version) |
Example: HTTP API Request with Compensation
workflow:
steps:
- name: "reserve_inventory"
activity: "InventoryService.reserve"
compensation: "InventoryService.release"
retry:
max_attempts: 3
backoff: "exponential"
- name: "process_payment"
activity: "PaymentService.charge"
compensation: "PaymentService.refund"
timeout: "30s"
- name: "send_confirmation"
activity: "EmailService.send"
- name: "wait_for_delivery"
timer: "P7D" # Wait 7 days
compensation: "DeliveryService.cancel"
Execution:
- Reserve inventory → succeeds (persisted)
- Process payment → fails after 3 retries
- Compensation triggered:
- Cancel delivery (if timer not fired)
- Refund payment (if charged)
- Release inventory
Trade-offs
| Feature | Pros | Cons |
|---|
| Synchronous timers | Simple | Blocks thread |
| Async timers | Scalable | Complex, needs durable timer store |
| Eager compensation | Quick cleanup | May over-compensate |
| Lazy compensation | Minimal compensation | Leaves resources allocated longer |
| Event sourcing | Full audit trail, rebuild | Complex, storage growth |
| CRUD state | Simple, familiar | Harder to audit, race conditions |
Recommended Stack
- Temporal - Production-ready, supports all features
- Camunda Zeebe - Native Kafka, scalable
- AWS Step Functions - Managed, integrates with AWS
- Custom (this design) - Full control, simpler needs
Common Pitfalls to Avoid
- Non-idempotent activities → Duplicate executions on retries
- Missing compensation → Orphaned resources
- Long-running transactions → Database locks
- Timer drift → System clock changes affect timers
- No dead-letter queue → Failed compensations get lost
This design provides a robust foundation for long-running workflows. Start with the simple CRUD approach, add event sourcing if you need full audit trails, and always make activities/compensations idempotent.