AI agents are moving from simple chat interfaces into applications that perform actual work. An agent may receive a request, call an API, query a database, execute a tool, wait for another system, and then continue the workflow. Once an application works this way, keeping the agent's state only in memory becomes a reliability problem.
A simple ASP.NET Core endpoint can process a request from beginning to end without storing much state. An AI agent workflow is different. The workflow may take several seconds or several minutes, depend on external services, encounter transient failures, or require human approval before continuing.
Durable state gives the application a way to remember where the workflow is, what has already happened, which tools were called, and what information is still required.
This article explains how to design an AI agent workflow in ASP.NET Core using durable state, how to separate workflow state from conversational history, and how to make retries and recovery safer in production.
Why AI Agent Workflows Need Durable State
Consider an AI support agent that receives this request:
Investigate order 48291, check its payment status, contact the shipping service,
and create a support ticket if the shipment is delayed.The agent may perform several operations:
Read the order.
Check payment status.
Call the shipping API.
Determine whether the shipment is delayed.
Create a support ticket.
Return the result to the user.
If everything happens inside one HTTP request, the design appears simple.
HTTP Request
|
v
AI Agent
|
+--> Order API
|
+--> Payment API
|
+--> Shipping API
|
+--> Ticket API
|
v
HTTP ResponseThe problem appears when something fails halfway through the process.
Suppose the shipping API succeeds, but the ticket API times out. The application now needs to know whether the shipping operation already completed. Otherwise, a retry could call the shipping API again and create an unexpected duplicate operation.
This is where durable state becomes important.
Instead of treating the workflow as one long request, store the workflow state as it progresses.
Request
|
v
Create Workflow
|
v
Persist State
|
v
Execute Step
|
v
Persist Result
|
v
Execute Next Step
|
v
Persist ResultIf the process stops, the application can resume from the last safe state instead of starting everything again.
Durable State and Conversation History Are Different
One common design mistake is treating chat history as workflow state.
They are related, but they serve different purposes.
Conversation history answers questions such as:
What did the user ask?
What did the agent say?
What information did the user provide?Workflow state answers questions such as:
Which step has completed?
Which tool was called?
What was the result?
What step should execute next?
Was an external operation already performed?
Does the workflow require approval?A production system may therefore have both.
Conversation
|
+--> User messages
+--> Assistant messages
+--> Tool messages
Workflow
|
+--> Current state
+--> Completed steps
+--> Tool results
+--> Retry information
+--> Approval statusKeeping these concepts separate makes the system easier to reason about.
Define the Workflow State Explicitly
The first step is creating a state model.
For example:
public enum WorkflowStatus
{
Created,
Running,
WaitingForApproval,
Completed,
Failed
}
public sealed class AgentWorkflowState
{
public Guid WorkflowId { get; init; }
public string UserRequest { get; init; } = string.Empty;
public WorkflowStatus Status { get; set; }
public int CurrentStep { get; set; }
public bool OrderChecked { get; set; }
public bool PaymentChecked { get; set; }
public bool ShippingChecked { get; set; }
public bool TicketCreated { get; set; }
public string? OrderStatus { get; set; }
public string? PaymentStatus { get; set; }
public string? ShippingStatus { get; set; }
public string? ErrorMessage { get; set; }
}The exact properties will vary by application. The important part is that the workflow state represents business progress rather than internal implementation details.
For example, storing:
ShippingChecked = trueis more useful than storing:
LastMethodExecuted = "ExecuteToolHandler42"The first represents business state. The second is tightly coupled to the implementation.
Store State in a Durable Repository
ASP.NET Core applications can use a database-backed repository for workflow state.
A simple abstraction keeps the agent logic independent of the storage technology.
public interface IWorkflowStateStore
{
Task<AgentWorkflowState?> GetAsync(
Guid workflowId,
CancellationToken cancellationToken);
Task SaveAsync(
AgentWorkflowState state,
CancellationToken cancellationToken);
}A PostgreSQL, SQL Server, or another transactional database can implement this interface.
The agent does not need to know where the state is stored.
AI Workflow
|
v
IWorkflowStateStore
|
+--> PostgreSQL
|
+--> SQL Server
|
+--> Other durable storeThis separation also makes testing easier.
Create the Workflow From an ASP.NET Core Endpoint
The API endpoint should generally create the workflow rather than execute a long-running agent process synchronously.
For example:
app.MapPost("/api/agent/workflows",
async (
CreateWorkflowRequest request,
IWorkflowStateStore store,
CancellationToken cancellationToken) =>
{
var workflowId = Guid.NewGuid();
var state = new AgentWorkflowState
{
WorkflowId = workflowId,
UserRequest = request.Message,
Status = WorkflowStatus.Created,
CurrentStep = 0
};
await store.SaveAsync(state, cancellationToken);
return Results.Accepted(
$"/api/agent/workflows/{workflowId}",
new
{
workflowId,
status = state.Status
});
});The important behavior here is that the API returns quickly.
The client receives a workflow identifier and can later retrieve the status.
POST /api/agent/workflows
|
v
Workflow ID
|
v
Background processing
|
v
GET /api/agent/workflows/{id}This approach prevents long-running AI operations from being unnecessarily tied to an HTTP request.
Execute Each Agent Step Independently
An agent workflow should be divided into small steps.
For example:
Step 1: Understand request
Step 2: Load order
Step 3: Check payment
Step 4: Check shipping
Step 5: Create support ticket
Step 6: Generate responseEach step should have a clear input and output.
A simple service could look like this:
public interface IAgentStep
{
Task ExecuteAsync(
AgentWorkflowState state,
CancellationToken cancellationToken);
}An order step could then update the durable state after successful completion.
public sealed class OrderCheckStep : IAgentStep
{
private readonly IOrderService _orderService;
public OrderCheckStep(IOrderService orderService)
{
_orderService = orderService;
}
public async Task ExecuteAsync(
AgentWorkflowState state,
CancellationToken cancellationToken)
{
var order = await _orderService.GetAsync(
state.UserRequest,
cancellationToken);
state.OrderChecked = true;
state.OrderStatus = order.Status;
state.CurrentStep++;
}
}The workflow engine can persist the updated state after the step completes.
Execute Step
|
v
Update State
|
v
Save State
|
v
Next StepThis gives the system a recovery point after each important operation.
Do Not Store Only the Final AI Response
Another common mistake is storing only the final response generated by the model.
For example:
WorkflowId
FinalResponse
Status = CompletedThis is not enough for troubleshooting.
A production workflow should normally preserve useful execution information such as:
Workflow ID
Current state
Current step
Completed steps
Tool execution status
External operation identifiers
Retry count
Failure information
Timestamps
Approval stateThe exact amount of information depends on the application's security and compliance requirements.
Sensitive data should not be stored simply because it might be useful for debugging.
Make External Tool Calls Idempotent
Durable state does not automatically prevent duplicate operations.
Consider this sequence:
Create Ticket
|
v
Ticket API succeeds
|
v
Application crashes before saving stateAfter recovery, the application may believe the ticket was never created.
It could call the ticket API again.
This is why external operations should support idempotency whenever possible.
For example:
Workflow ID: 6f8...
Operation: CreateSupportTicket
Idempotency Key: 6f8...-ticketThe external service can use that key to identify repeated requests.
A retry then becomes safer:
Attempt 1
|
+--> External API succeeds
|
+--> Application fails before persisting state
Attempt 2
|
+--> Same idempotency key
|
+--> Existing result returnedThis pattern is especially important for operations such as payments, orders, ticket creation, provisioning, and notifications.
Use Optimistic Concurrency for Workflow State
Multiple workers may accidentally process the same workflow at the same time.
For example:
Worker A --> Workflow 123
Worker B --> Workflow 123Both workers could load the same state and make conflicting changes.
A version column can help detect this.
WorkflowId | Status | Version
-----------|---------|--------
123 | Running | 7Worker A reads version 7 and updates it to version 8.
Worker B also tries to update version 7.
The database rejects the second update because the version is no longer current.
This prevents silent state corruption.
In a relational database, the update can conceptually look like:
UPDATE agent_workflows
SET status = @status,
current_step = @step,
version = version + 1
WHERE workflow_id = @workflowId
AND version = @expectedVersion;If zero rows are updated, the application knows that another worker changed the state.
Handle Retries Carefully
AI workflows usually depend on external systems, so retries are expected.
However, retrying every failure is dangerous.
A useful classification is:
Failure | Retry |
|---|---|
Temporary network timeout | Usually |
HTTP 429 | Usually with backoff |
HTTP 503 | Usually |
Invalid API request | No |
Authentication failure | Usually no |
Validation error | No |
Business rule rejection | No |
Model output validation failure | Controlled retry |
Retries should also use backoff.
Attempt 1 -> immediate
Attempt 2 -> short delay
Attempt 3 -> longer delay
Attempt 4 -> longer delayWithout backoff, a large number of failed workflows can create another traffic spike against an already unhealthy dependency.
Protect Against Partial Completion
A workflow can fail after completing some operations.
For example:
Order lookup -> Completed
Payment check -> Completed
Shipping check -> Completed
Ticket creation -> FailedThe recovery system should not restart the workflow from the beginning.
Instead, it should resume from the last safe point.
Order lookup -> Skip
Payment check -> Skip
Shipping check -> Skip
Ticket creation -> RetryThis is one of the biggest benefits of durable workflow state.
Add Human Approval When the Agent Can Cause Side Effects
Not every agent action should happen automatically.
For sensitive operations, the workflow can enter an approval state.
Agent
|
v
Prepare Action
|
v
WaitingForApproval
|
v
Human Approval
|
+---- Reject --> Cancelled
|
+---- Approve --> ContinueThe persisted state might contain:
Status = WaitingForApproval
CurrentStep = 4
ApprovalRequired = trueThe workflow can remain in this state for minutes or hours without losing its place.
This is much safer than keeping an HTTP request open while waiting for a human decision.
Secure the Workflow State
Workflow state can contain sensitive information, including user requests, tool results, internal identifiers, and business data.
Apply normal application security controls.
Use authentication and authorization when reading workflow state.
GET /api/agent/workflows/{id}should not automatically allow any authenticated user to view any workflow.
The application should verify that the requesting user is allowed to access the workflow.
Also avoid storing secrets in workflow state.
Do not store:
API keys
Access tokens
Passwords
Database connection strings
Private credentialsStore references to secrets instead and retrieve them through the appropriate secret-management mechanism when required.
Monitor Workflow Progress
Traditional API monitoring is not enough for long-running agent workflows.
Track workflow-level metrics such as:
Workflows started
Workflows completed
Workflows failed
Average workflow duration
Step failure rate
Retry count
Approval wait time
External tool latencyStructured logs should include the workflow identifier.
logger.LogInformation(
"Executing workflow {WorkflowId}, step {Step}",
state.WorkflowId,
state.CurrentStep);This allows operators to follow one workflow across multiple services and background workers.
Common Mistakes
Keeping the Entire Agent in HTTP Memory
Long-running agent execution should not depend on one HTTP request remaining alive.
Use an asynchronous workflow model when execution can take significant time.
Saving Only the Chat History
Conversation history does not tell you which business operation has already completed.
Persist workflow state separately.
Retrying Side Effects Without Idempotency
Repeatedly creating orders, tickets, payments, or notifications can cause real business problems.
Use idempotency keys or another deduplication mechanism.
Allowing Multiple Workers to Process the Same Workflow
Use leases, queues, optimistic concurrency, or another coordination mechanism.
Storing Secrets in Workflow Data
Durable storage increases the lifetime of the data. Secrets should not be copied into it unnecessarily.
Making the Workflow State Too Detailed
The state should represent durable business progress, not every internal implementation detail.
If changing a class name requires migrating thousands of workflow records, the state model is probably too tightly coupled to the code.
Best Practices
Define workflow state explicitly.
Separate conversation history from workflow state.
Persist state after meaningful workflow steps.
Use idempotency for external side effects.
Use optimistic concurrency or another locking strategy.
Retry only transient failures.
Resume from the last completed step.
Add human approval for sensitive operations.
Protect workflow data with normal authorization controls.
Add workflow-level logging and metrics.
Keep durable state independent from agent implementation details.
Test recovery scenarios, not only successful execution.
Advantages and Disadvantages
Approach | Advantages | Disadvantages |
|---|---|---|
In-memory agent state | Simple and fast | Lost after restart |
HTTP request based workflow | Easy to implement | Poor fit for long-running operations |
Database-backed state | Durable and easy to inspect | Requires persistence and concurrency handling |
Queue-based workflow | Good reliability and scaling | More infrastructure |
Durable workflow engine | Strong recovery capabilities | Additional architecture and operational complexity |
For small experiments, in-memory state can be acceptable.
For production workflows that perform important business operations, durable state is usually a better foundation.
Troubleshooting Checklist
When an AI workflow behaves incorrectly in production, check the following:
Is the workflow state persisted after each important operation?
Can the workflow be resumed after an application restart?
Can two workers process the same workflow simultaneously?
Are external operations idempotent?
Are retryable and non-retryable failures separated?
Can operators identify a workflow from logs?
Is the workflow state protected by authorization?
Are secrets excluded from durable state?
Can a workflow remain in an approval state safely?
Can failed workflows be inspected and replayed without repeating unsafe operations?
A Practical Production Architecture
A reliable ASP.NET Core AI agent application can be structured like this:
Client
|
v
ASP.NET Core API
|
+----> Workflow Store
|
+----> Queue
|
v
Agent Worker
|
+----> AI Model
|
+----> Tool APIs
|
+----> Database
|
v
Persist Workflow StateThe API handles requests and status queries.
The worker executes the long-running workflow.
The workflow store records durable progress.
The AI model makes reasoning decisions, while application code remains responsible for business rules, authorization, validation, and safe execution of side effects.
This separation is important. The AI model should not become the system of record for workflow progress.
Summary
AI agents become much harder to operate reliably once they move beyond simple request-and-response interactions. A production agent may call several services, wait for external events, retry failed operations, or require human approval before continuing.
Durable state gives the application a reliable record of where the workflow is and what has already happened. ASP.NET Core can provide the API layer, while a database, queue, or durable workflow system can handle long-running execution and recovery.
The most important design principle is to treat the agent as a workflow rather than as one large HTTP request. Persist meaningful state, make external side effects idempotent, protect against concurrent workers, and design every important step so that the workflow can recover after failure.
With these practices, an AI agent can remain useful even when services restart, networks fail, requests time out, or individual workflow steps need to be retried.

Join the conversation! Your thoughts help the community grow.