AI agents are often designed to perform multiple operations before completing a task. An agent might retrieve information from a database, call an LLM, process the response, interact with external APIs, and finally save the result. These operations are usually connected, meaning the output of one step becomes the input for another.
The challenge begins when something fails during execution.
A network timeout, application restart, database connection failure, or unavailable external service can interrupt the workflow. If the application does not track its progress, the agent may need to start the entire process again.
This is inefficient, especially when earlier operations involve expensive LLM calls or external services that have already completed their work.
A better approach is to build resumable agent workflows. Instead of restarting every operation, the application saves its progress and continues from the last successfully completed step.
In this article, we will explore how to design resumable AI agent workflows using C# and .NET, implement checkpoint-based execution, handle failures, and prevent completed operations from running again.
Understanding the Problem With Multi Step Agent Workflows
Consider an AI-powered document processing agent.
The agent performs the following operations:
- Download a document from storage.
- Extract text from the document.
- Send the extracted text to an LLM for analysis.
- Generate a structured summary.
- Save the summary to a database.
- Send a notification to the user.
Now imagine that the first four operations complete successfully, but the database becomes unavailable during the fifth operation.
If the workflow runs entirely in memory, restarting the application may cause the agent to repeat every operation.
The document gets downloaded again, text extraction runs again, and the LLM receives another request.
Apart from wasting resources, repeated execution can introduce inconsistencies when an external operation has already produced a result.
A resumable workflow avoids this problem by recording which operations have completed and which operation should run next.
What Makes an Agent Workflow Resumable?
A resumable workflow maintains enough information to reconstruct its execution after an interruption.
This generally requires three capabilities.
Persistent Workflow State
The application stores workflow information in a durable database rather than relying only on memory.
The state identifies the workflow, its current status, and the data needed for the next operation.
Execution Checkpoints
A checkpoint records progress after an important operation completes.
For example, after successfully extracting document text, the application saves that result and marks the extraction step as completed.
Idempotent Operations
An idempotent operation can be repeated without producing unintended additional effects.
This is especially important when workflows interact with payment systems, databases, email services, or external APIs.
Together, these capabilities allow the application to recover from failures without unnecessarily repeating completed work.
Designing a Resumable Workflow Architecture
A simple resumable workflow can use the following architecture.
Workflow Request
|
v
Workflow Manager
|
v
Load Workflow State
|
v
Find Next Pending Step
|
v
Execute Operation
|
+------+------+
| |
v v
Success Failure
| |
v v
Save Result Record Error
| |
v v
Save Checkpoint Schedule Retry
|
v
Next Operation
|
v
Workflow CompletedThe workflow manager coordinates execution, while a persistent state repository stores the results.
A background worker or durable queue can handle execution independently of the original HTTP request.
This separation is useful because long-running agent jobs should not depend on an active client connection.
Creating a Workflow State Model in C#
Start by defining a model that represents the execution state of an agent workflow.
public class AgentWorkflow
{
public Guid WorkflowId { get; set; }
public string Status { get; set; } = "Pending";
public int CurrentStep { get; set; }
public int RetryCount { get; set; }
public string? LastError { get; set; }
public DateTime UpdatedAt { get; set; }
public List<WorkflowStep> Steps { get; set; } = new();
}
public class WorkflowStep
{
public int StepNumber { get; set; }
public string Name { get; set; } = string.Empty;
public string Status { get; set; } = "Pending";
public string? Result { get; set; }
}The CurrentStep property identifies the next operation to execute.
Each workflow step maintains its own status and result.
For example, if document extraction completes successfully, its status becomes Completed, and the extracted text can be stored as the step result.
In production applications, large results should generally be stored separately in a database or object storage. The workflow record can maintain references to those results.
Persisting Workflow State With Entity Framework Core
The next step is to save workflow information in a database.
Entity Framework Core provides a convenient way to manage workflow records.
For a simple implementation, the workflow state can be stored as a JSON document.
public class WorkflowRecord
{
public Guid Id { get; set; }
public string StateJson { get; set; } = string.Empty;
public DateTime UpdatedAt { get; set; }
}Configure the database context:
public class WorkflowDbContext : DbContext
{
public WorkflowDbContext(
DbContextOptions<WorkflowDbContext> options)
: base(options)
{
}
public DbSet<WorkflowRecord> Workflows =>
Set<WorkflowRecord>();
}A repository can serialize the workflow state before saving it.
public async Task SaveAsync(
AgentWorkflow workflow,
CancellationToken cancellationToken)
{
var json = JsonSerializer.Serialize(workflow);
var record = await _context.Workflows
.FindAsync(
new object[] { workflow.WorkflowId },
cancellationToken);
if (record == null)
{
record = new WorkflowRecord
{
Id = workflow.WorkflowId
};
_context.Workflows.Add(record);
}
record.StateJson = json;
record.UpdatedAt = DateTime.UtcNow;
await _context.SaveChangesAsync(cancellationToken);
}The application should also provide a corresponding method to retrieve and deserialize the saved state.
For production workloads, use optimistic concurrency control or a workflow lease to prevent multiple workers from overwriting the same record.
Executing Only Pending Workflow Steps
The central idea behind resumable execution is to identify the next incomplete step.
Instead of executing the entire workflow again, the application checks the saved state before running each operation.
public async Task ExecuteWorkflowAsync(
AgentWorkflow workflow,
CancellationToken cancellationToken)
{
foreach (var step in workflow.Steps
.OrderBy(x => x.StepNumber))
{
if (step.Status == "Completed")
{
continue;
}
workflow.CurrentStep = step.StepNumber;
workflow.Status = "Running";
await _repository.SaveAsync(
workflow, cancellationToken);
try
{
step.Status = "Running";
step.Result = await ExecuteStepAsync(
step, workflow, cancellationToken);
step.Status = "Completed";
await _repository.SaveAsync(
workflow, cancellationToken);
}
catch (Exception ex)
{
step.Status = "Failed";
workflow.Status = "Failed";
workflow.LastError = ex.Message;
await _repository.SaveAsync(
workflow, CancellationToken.None);
throw;
}
}
workflow.Status = "Completed";
await _repository.SaveAsync(
workflow, cancellationToken);
}This implementation skips steps already marked as completed.
If the workflow fails during the database-saving step, the application can reload the workflow state and continue from that operation.
However, there is an important limitation.
An external operation may complete successfully before the application saves its checkpoint. If the worker crashes during that interval, the application cannot know from the checkpoint alone whether the operation succeeded.
For this reason, checkpointing should be combined with idempotency keys, operation identifiers, and external status verification.
Resuming a Workflow After an Application Restart
When the application restarts, it should identify workflows that were interrupted.
A recovery service can retrieve workflows with statuses such as Running, Failed, or RetryScheduled.
The service then loads the saved state and continues execution.
public async Task ResumeWorkflowAsync(
Guid workflowId,
CancellationToken cancellationToken)
{
var workflow = await _repository.GetAsync(
workflowId, cancellationToken);
if (workflow == null)
{
throw new InvalidOperationException(
"Workflow was not found.");
}
if (workflow.Status == "Completed")
{
return;
}
await ExecuteWorkflowAsync(
workflow, cancellationToken);
}The repository's GetAsync method should retrieve the persisted JSON state and deserialize it into an AgentWorkflow instance.
In a distributed environment, recovery workers should acquire a lease before executing a workflow. Otherwise, two workers may resume the same job simultaneously.
The lease should have an expiration time and support renewal while the worker remains active.
Handling LLM Calls During Workflow Recovery
LLM operations require special attention because they can be expensive and may return different responses when repeated.
Suppose the agent successfully generates a document summary but crashes before saving the result.
After restarting, the application may send the same request to the LLM again.
This can increase costs and produce a different summary.
A safer design records each LLM operation separately.
| Operation state | Recovery action |
|---|---|
| Pending | Submit the request |
| Running | Check whether the previous attempt has a known outcome |
| Completed | Reuse the saved response |
| Failed | Evaluate whether retrying is appropriate |
| Unknown | Reconcile the original request before retrying |
Store a unique operation ID, request metadata, response reference, and provider request identifier when available.
If the provider supports idempotency or request-status retrieval, use those capabilities to reduce duplicate execution.
Otherwise, the application must accept that some interrupted requests may have an unknown outcome.
Using Retry Policies for Temporary Failures
Not every workflow failure requires manual intervention.
Temporary network errors, service unavailability, and rate limiting may be resolved by retrying the affected operation.
A retry policy should use bounded attempts and increasing delays.
For example:
public async Task<T> RetryAsync<T>(
Func<CancellationToken, Task<T>> operation,
CancellationToken cancellationToken)
{
const int maxAttempts = 3;
for (int attempt = 1; attempt <= maxAttempts; attempt++)
{
try
{
return await operation(cancellationToken);
}
catch (HttpRequestException)
when (attempt < maxAttempts)
{
var delay = TimeSpan.FromSeconds(
Math.Pow(2, attempt));
await Task.Delay(delay, cancellationToken);
}
}
throw new InvalidOperationException(
"Operation could not be completed.");
}This example handles temporary HTTP request failures.
Production applications should also respect provider-specific retry guidance, rate-limit responses, and cancellation requests.
For long-running workflows, schedule retries through durable storage or a message queue rather than keeping a worker occupied during extended delays.
Comparing Workflow Recovery Approaches
Different applications require different recovery strategies.
| Approach | Advantages | Limitations |
|---|---|---|
| Restart entire workflow | Simple implementation | Repeats completed work |
| In-memory checkpoints | Fast access | State disappears after process failure |
| Database checkpoints | Durable and flexible | Requires persistence management |
| Queue-based execution | Supports asynchronous processing | Requires message handling and idempotency |
| Durable workflow engine | Provides orchestration and recovery features | Adds infrastructure and learning complexity |
For a small application, database checkpoints may provide sufficient reliability.
For workflows involving many services, parallel tasks, human approvals, or long waiting periods, a durable workflow engine can reduce the amount of custom orchestration code.
Best Practices for Production Agent Workflows
Save Checkpoints After Important Operations
Create checkpoints after completing meaningful steps such as data retrieval, LLM generation, external API execution, and result persistence.
Avoid unnecessary database writes after every small internal operation.
Make External Operations Idempotent
Use unique operation identifiers when creating records, sending notifications, or calling external services.
Before retrying an operation, check whether its intended effect already exists.
Separate Workflow State From Large Results
Keep workflow metadata small and store large documents, model responses, and generated files separately.
This makes state updates more efficient and simplifies recovery.
Protect Concurrent Execution
Use workflow leases, optimistic concurrency, or another distributed coordination mechanism.
A workflow should not be processed by multiple workers unless its execution model explicitly supports parallelism.
Monitor Stuck Workflows
Track workflows that remain in the Running state longer than expected.
Use lease expiration, heartbeat timestamps, and recovery checks to identify abandoned executions.
Version Workflow Definitions
A workflow may be resumed after the application has been deployed with new code.
Maintain workflow definition versions so previously saved jobs can continue using compatible execution logic.
Common Mistakes and Troubleshooting
| Problem | Possible cause | Recommended solution |
|---|---|---|
| Workflow restarts from the first step | Checkpoint was not saved | Verify persistence after each completed step |
| Same API runs twice | Crash occurred before checkpoint persistence | Use idempotency and operation reconciliation |
| Workflow remains in Running state | Worker stopped unexpectedly | Use leases and stale-workflow detection |
| Two workers process one job | Missing concurrency protection | Implement distributed coordination |
| Saved workflow cannot load | State schema changed | Introduce versioning and migration logic |
| Retry continues indefinitely | Missing retry limits | Configure maximum attempts and failure handling |
Advantages and Disadvantages of Resumable Agent Workflows
Resumable workflows provide several important advantages.
Advantages:
- Reduce unnecessary repeated LLM calls.
- Preserve completed work after application failures.
- Support long-running background processing.
- Improve workflow reliability and visibility.
- Make troubleshooting easier through execution history.
- Allow controlled recovery after infrastructure interruptions.
Disadvantages:
- Require additional database storage.
- Introduce workflow state management complexity.
- Need careful concurrency handling.
- Require idempotency for operations with side effects.
- Add maintenance requirements for workflow versioning and recovery logic.
The additional complexity is usually justified when an agent performs expensive operations or interacts with important business systems.
Summary
Resuming a multi step agent job without starting from the beginning is an important capability for reliable AI applications. A workflow should not lose all its progress simply because an LLM request fails, a worker restarts, or an external service becomes temporarily unavailable.
Using C# and .NET, developers can implement resumable workflows by maintaining persistent execution state, saving checkpoints after completed operations, and executing only the remaining steps.
However, checkpointing alone is not enough. Production systems must also handle unknown operation outcomes, duplicate execution, concurrent workers, retry policies, and workflow version changes.
By combining durable storage, checkpoint-based execution, idempotent operations, and controlled recovery, developers can build AI agents that continue their work reliably even when individual operations or application workers fail.

Join the conversation! Your thoughts help the community grow.