AI agents often perform multiple operations before producing a final response. An agent might collect information, call an external API, analyze the returned data, generate a summary, and then save the result. Each operation depends on the previous one, making the workflow more complicated than a normal request-response application.
One common problem occurs when an LLM call fails halfway through execution. The application might experience a network timeout, a provider error, a rate limit, or an unexpected worker interruption. If the application does not preserve its progress, it may need to repeat the entire workflow.
This creates unnecessary API calls, increases processing costs, and can even repeat operations that have already changed external systems.
A reliable AI application should save its state before and after important operations. This allows the application to identify completed work, recover unfinished operations, and continue execution without losing previously collected information.
In this article, we will explore how to preserve AI agent state in a .NET application, implement checkpoints, handle failed LLM requests, and build a recovery mechanism suitable for production environments.
Why Saving Agent State Is Important
Consider an AI-powered customer support agent that processes a refund request.
The workflow might contain the following operations:
- Read the customer's refund request.
- Retrieve the customer's order details.
- Ask the LLM to analyze the refund eligibility.
- Call the payment service if the refund is approved.
- Generate a response for the customer.
- Save the final result.
Now imagine that the application successfully completes the first three operations, but the LLM request times out while generating the response.
If the application stores everything only in memory, restarting the worker can result in losing the previous execution context.
The agent may retrieve the order details again, repeat the analysis, and potentially execute operations that have already been completed.
This problem becomes more serious when an AI workflow involves several external services.
Saving agent state helps solve these problems by maintaining a record of execution progress.
The application should know:
- Which workflow steps have completed.
- Which operation is currently running.
- What input was provided to the LLM.
- Whether a response was received.
- Which external tool operations were completed.
- Whether an operation can safely be retried.
- Where the workflow should resume.
The important point is that an agent's conversation history alone is not sufficient. The application also needs execution metadata and reliable storage.
Understanding Agent State and Checkpoints
Agent state represents the information required to continue an AI workflow.
It generally includes conversation messages, intermediate results, tool execution details, workflow status, and the current execution step.
A checkpoint is a saved snapshot of this information at a particular point in the workflow.
For example, an application can create a checkpoint after retrieving customer information and another after receiving a successful LLM response.
If the next operation fails, the application can load the latest checkpoint instead of starting from the beginning.
What Should Be Saved?
A production-oriented agent workflow should maintain separate information for different responsibilities.
| State information | Purpose |
| Workflow ID | Identifies a particular execution |
| Conversation history | Maintains previous messages |
| Current step | Identifies the active workflow operation |
| Completed steps | Prevents unnecessary repetition |
| LLM request details | Helps identify the original model request |
| LLM response | Preserves successfully generated output |
| Tool execution results | Records completed external operations |
| Retry count | Tracks repeated failures |
| Workflow status | Indicates running, failed, or completed execution |
It is also important to avoid storing API keys, access tokens, or unnecessary personal information inside agent state.
Designing a State Management Model in .NET
Before implementing recovery logic, create a structured model that represents the current execution state.
The following C# model provides a simple starting point.
public class AgentWorkflowState
{
public Guid WorkflowId { get; set; }
public string CurrentStep { get; set; } = "Started";
public string Status { get; set; } = "Running";
public int RetryCount { get; set; }
public List<string> CompletedSteps { get; set; } = new();
public string? CustomerData { get; set; }
public string? LlmResponse { get; set; }
public string? LastError { get; set; }
public DateTime UpdatedAt { get; set; }
}
This model tracks the workflow's current position and previously completed operations.
For example, if the CustomerData property already contains the retrieved order information, the application does not need to call the customer service again.
Similarly, if LlmResponse contains a successfully generated response, the application can continue with the next operation.
For a production system, conversation history and large tool outputs should generally be stored separately or in appropriately sized structured records. This keeps checkpoint updates manageable.
Implementing an Agent State Repository
The next step is to introduce a repository responsible for saving and retrieving workflow state.
Keeping persistence logic separate from agent execution makes the application easier to maintain and test.
Define an interface:
public interface IAgentStateRepository
{
Task SaveAsync(
AgentWorkflowState state,
CancellationToken cancellationToken);
Task<AgentWorkflowState?> GetAsync(
Guid workflowId,
CancellationToken cancellationToken);
}
An implementation can use Entity Framework Core with SQL Server or PostgreSQL.
For example:
public class AgentStateRepository : IAgentStateRepository
{
private readonly AppDbContext _context;
public AgentStateRepository(AppDbContext context)
{
_context = context;
}
public async Task SaveAsync(
AgentWorkflowState state,
CancellationToken cancellationToken)
{
state.UpdatedAt = DateTime.UtcNow;
var existing = await _context.AgentStates
.FirstOrDefaultAsync(
x => x.WorkflowId == state.WorkflowId,
cancellationToken);
if (existing == null)
{
_context.AgentStates.Add(state);
}
else
{
_context.Entry(existing).CurrentValues
.SetValues(state);
}
await _context.SaveChangesAsync(cancellationToken);
}
public Task<AgentWorkflowState?> GetAsync(
Guid workflowId,
CancellationToken cancellationToken)
{
return _context.AgentStates
.AsNoTracking()
.FirstOrDefaultAsync(
x => x.WorkflowId == workflowId,
cancellationToken);
}
}
The repository updates an existing workflow record or creates a new one.
In a real application, configure the workflow ID as a unique database key and use concurrency control, such as a row version, to prevent multiple workers from overwriting each other's updates.
Saving State Before and After an LLM Call
One of the most important design decisions is when to save the workflow state.
A common mistake is saving state only after the complete LLM operation finishes.
If the request fails before the response is returned, the application has no durable record of the operation that was in progress.
A better approach is to save the execution state before sending the request and again after receiving the response.
Consider the following service:
public class AgentService
{
private readonly IAgentStateRepository _repository;
private readonly IChatCompletionService _llm;
public AgentService(
IAgentStateRepository repository,
IChatCompletionService llm)
{
_repository = repository;
_llm = llm;
}
public async Task ProcessAsync(
AgentWorkflowState state,
CancellationToken cancellationToken)
{
try
{
state.CurrentStep = "LLMProcessing";
state.Status = "Running";
await _repository.SaveAsync(
state, cancellationToken);
var response = await _llm.GenerateAsync(
state.CustomerData!,
cancellationToken);
state.LlmResponse = response;
state.CompletedSteps.Add("LLMProcessing");
state.CurrentStep = "ResponseReady";
await _repository.SaveAsync(
state, cancellationToken);
}
catch (Exception ex)
{
state.Status = "Failed";
state.LastError = ex.Message;
await _repository.SaveAsync(
state, CancellationToken.None);
throw;
}
}
}
Here, the application saves the workflow before calling the LLM.
After receiving a successful response, it saves the generated output and updates the completed step.
If the request fails, the exception handler records the failure information.
However, there is an important detail to understand.
A timeout does not always mean that the LLM provider failed to process the request. The provider might have completed the operation while the response was lost during network communication.
Therefore, an application should not automatically assume that an interrupted request can safely be repeated.
For this reason, production implementations should maintain a separate LLM operation record with a unique operation ID and a status such as Pending, InProgress, Succeeded, Failed, or Unknown.
Recovering an Agent Workflow After Failure
Once the application stores workflow state, it can implement a recovery mechanism.
The recovery process should first retrieve the saved state and determine which operations are already complete.
For example:
public async Task ResumeAsync(
Guid workflowId,
CancellationToken cancellationToken)
{
var state = await _repository.GetAsync(
workflowId,
cancellationToken);
if (state == null)
{
throw new InvalidOperationException(
"Workflow state was not found.");
}
if (state.CompletedSteps.Contains("LLMProcessing"))
{
await ContinueNextStepAsync(
state, cancellationToken);
return;
}
await ProcessAsync(state, cancellationToken);
}
This example demonstrates the basic recovery idea.
If the LLM operation has completed, the application moves to the next step. Otherwise, it processes the pending operation.
A complete implementation must also distinguish between an operation that was never submitted and one whose outcome is unknown.
For an unknown outcome, the application should reconcile the request using provider-supported request identifiers, idempotency mechanisms, or application-level operation records before issuing another request.
This prevents unnecessary duplicate calls and unexpected side effects.
Handling Retries Without Repeating Completed Operations
Retry mechanisms are useful when an LLM provider temporarily becomes unavailable.
However, retrying an entire workflow is not always the correct approach.
Suppose an agent has already retrieved customer information and completed its initial analysis. Only the final LLM request has failed.
Repeating every operation wastes resources.
Instead, retry only the failed operation when its outcome is known and retrying is safe.
A simple exponential backoff strategy can help manage temporary failures.
public static async Task<T> ExecuteWithRetryAsync<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 failed after multiple attempts.");
}
This example demonstrates retrying transient HTTP failures.
Production applications should additionally consider provider-specific rate-limit responses, retry-after headers, request timeouts, cancellation, and permanent errors.
Do not retry every exception. Invalid requests, authentication failures, and unsupported model configurations generally require corrective action rather than another identical request.
Best Practices for Production AI Workflows
Saving state is only one part of building reliable AI applications. The following practices help make recovery more predictable.
Save Checkpoints at Meaningful Boundaries
Do not save the entire conversation after every minor operation.
Instead, create checkpoints after important workflow transitions, such as completing data retrieval, receiving an LLM response, finishing tool execution, and generating the final result.
This provides useful recovery points without unnecessary database writes.
Use Idempotency for External Operations
An agent may call payment services, send emails, create support tickets, or update customer records.
If a worker fails after an external operation succeeds but before saving its completion status, the operation might execute again during recovery.
Use unique idempotency keys and verify the external operation's status before retrying it.
Keep Agent State Separate From Application Logic
Avoid placing all workflow information inside a single conversation object.
Maintain separate records for workflow metadata, conversation history, LLM requests, tool execution results, and generated artifacts.
This improves data management and makes troubleshooting easier.
Add State Versioning
AI applications evolve over time. New versions may introduce additional fields or change the structure of saved conversation data.
Include a state schema version so older workflow records can be migrated or handled safely.
Monitor Failed and Stuck Workflows
Track workflow duration, retry counts, provider errors, checkpoint failures, and workflows that remain in progress for too long.
These metrics help identify problems before they affect a large number of users.
Common Mistakes to Avoid
| Mistake | Why it causes problems | Better approach |
| Saving state only at completion | Intermediate progress is lost | Save checkpoints at important boundaries |
| Keeping state in memory | Worker restarts remove application state | Use durable storage |
| Retrying the entire workflow | Completed operations run again | Retry individual safe operations |
| Ignoring unknown request outcomes | Duplicate LLM or tool operations may occur | Reconcile the original operation |
| Storing everything in one record | Large updates become difficult to manage | Separate metadata and execution results |
| Allowing multiple workers to update freely | State can become inconsistent | Use concurrency control and leases |
Advantages and Disadvantages of Checkpoint-Based State Management
Checkpoint-based state management provides several benefits for AI applications.
Advantages:
- Preserves completed workflow progress.
- Reduces unnecessary repeated operations.
- Supports recovery after worker restarts.
- Improves troubleshooting and execution visibility.
- Helps manage long-running AI workflows.
- Provides a foundation for workflow auditing.
Disadvantages:
- Requires additional database storage.
- Introduces persistence and synchronization complexity.
- Requires careful handling of concurrent workers.
- State migrations become necessary as application models evolve.
- Checkpointing does not guarantee that external operations execute exactly once.
For small AI applications, a simple database-backed state repository may be sufficient. More complex applications involving multiple agents, parallel execution, and long-running operations may benefit from a durable workflow engine.
Troubleshooting Common State Recovery Problems
Workflow Starts Again From the Beginning
Check whether the application successfully saved its latest checkpoint before the failure.
Also verify that the recovery service loads the existing workflow record instead of creating a new workflow ID.
Duplicate LLM Requests Appear in Logs
Check whether the application distinguishes between a failed request and a request with an unknown outcome.
Use operation identifiers and provider-supported idempotency or reconciliation mechanisms wherever available.
Two Workers Update the Same Workflow
This usually indicates that multiple workers are processing the same workflow simultaneously.
Introduce distributed locking, worker leases, or optimistic concurrency checks to ensure that only an authorized worker can update the active workflow state.
Saved State Cannot Be Loaded
Check the serialized state structure, schema version, database constraints, and compatibility between the current application version and previously saved records.
Keep migration logic available when changing the state model.
Summary
Saving agent state when an LLM call fails halfway through is an important part of building reliable AI applications. Without persistent execution state, a worker interruption can force an application to repeat previously completed operations, increase processing costs, and create inconsistent results.
A practical .NET implementation should maintain a structured workflow state, save checkpoints before and after important operations, record LLM request outcomes, and resume execution from the latest valid checkpoint.
Retry mechanisms should be designed around individual operations rather than entire workflows. Applications should also account for unknown request outcomes, duplicate tool execution, concurrent workers, and state versioning.
For production AI systems, combining durable state storage, meaningful checkpoints, idempotent operations, and controlled retries provides a stronger foundation for building AI agents that can recover from failures without unnecessarily repeating their work.
Join the conversation! Your thoughts help the community grow.