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.
Join the conversation! Your thoughts help the community grow.