Skip to main content

How to Resume a Microsoft Agent Framework Workflow from a Checkpoint After a Restart in C#

· 19 min read
Jagdish Kumawat
Founder @ Dewiride

A Microsoft Agent Framework workflow that waits for a person doesn't need your program to keep running until the answer comes. Save the run's checkpoints to files, end the program, and on a later start resume the run from its latest checkpoint: the waiting question comes back, and the answer finishes the run. This guide builds a refund approval that asks on one start of a program and gets its answer on the next.

Syntax​

Syntax
using var <store> = new FileSystemJsonCheckpointStore(new DirectoryInfo("<folder>"));
CheckpointManager <checkpointManager> = CheckpointManager.CreateJson(<store>);

// The first start: run with checkpoints, under a session ID.
await using Run <run> = await InProcessExecution.RunAsync(<workflow>, <input>, <checkpointManager>, "<sessionId>");

// A later start: find the session's latest checkpoint and resume the run from it.
CheckpointInfo? <latest> = await <checkpointManager>.GetLatestCheckpointAsync("<sessionId>");
await using Run <resumed> = await InProcessExecution.ResumeAsync(<workflow>, <latest>, <checkpointManager>);
PartWhat it is
FileSystemJsonCheckpointStoreProvides a file system-based implementation of a JSON checkpoint store that persists checkpoint data and index information to disk using JSON files.
"<folder>"The folder the files go to. The store creates it when it doesn't exist.
using varDisposes of the store at the end. Its documentation: callers should ensure Dispose is called to release file handles and system resources when the store is no longer needed.
CheckpointManager.CreateJson(<store>)Creates a new instance of the CheckpointManager that uses JSON serialization for checkpoint data.
<checkpointManager> in RunAsyncTurns checkpoints on for the run. Microsoft's checkpoints guide: To enable checkpointing, a CheckpointManager needs to be provided when running the workflow.
"<sessionId>"The session the run's checkpoints belong to: An optional unique identifier for the session. If not provided, a new identifier will be generated.
GetLatestCheckpointAsyncRetrieves the most recently committed checkpoint for the specified session, or null when the session has no checkpoints.
InProcessExecution.ResumeAsyncResumes a non-streaming execution of the workflow from a checkpoint.
<workflow>The same workflow on every start. The same guide: A rehydrated workflow must preserve the topology and executor identities of the workflow that created the checkpoint.

The guide also says when the checkpoints are saved: Checkpoints are created at the end of each superstep, after all executors in that superstep have completed their execution. A superstep is one round of the workflow: the executors that have messages waiting run, and the messages they send wait for the next round. Each checkpoint holds the executors' state, the messages for the next superstep, the pending requests and responses, and the shared state.

The Example​

A console app called RefundApproval asks a supervisor to approve a refund of 25 USD. Its workflow has three steps: DescribeRefund writes the question, the request port AskSupervisor waits for a yes or a no, and RecordAnswer turns the answer into Refund approved. or Refund rejected.. The first start, dotnet run, runs the workflow until it asks, and the program ends. A later start, dotnet run -- y, resumes the run from its checkpoint and answers yes. The checkpoints go to a checkpoints folder in the project, under the session ID refund-1042. There's no AI model in it, so you don't need an Azure account.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0; this guide used 10.0.404.

Step 1: Create a Console App​

In a terminal, in the folder where you keep your projects, create a console app, move into it and add Agent Framework's workflows package:

Terminal
dotnet new console -o RefundApproval
cd RefundApproval
dotnet add package Microsoft.Agents.AI.Workflows --version 1.28.0
  • dotnet new console -o RefundApproval creates a console app in a new RefundApproval folder, and cd moves into it.
  • dotnet add package adds Microsoft.Agents.AI.Workflows, which has the workflow types, the checkpoint manager and the file store. --version keeps you on the version this guide used.
Output (shortened)
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/RefundApproval/RefundApproval.csproj:
Restore succeeded.
…
info : PackageReference for package 'Microsoft.Agents.AI.Workflows' version '1.28.0' added to file '/Users/you/source/RefundApproval/RefundApproval.csproj'.
info : Generating MSBuild file /Users/you/source/RefundApproval/obj/RefundApproval.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/RefundApproval/obj/project.assets.json
log : Restored /Users/you/source/RefundApproval/RefundApproval.csproj (in 829 ms).

The project file now has the package:

RefundApproval.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Agents.AI.Workflows" Version="1.28.0" />
</ItemGroup>

</Project>

Step 2: Store the Checkpoints in Files​

Replace everything in Program.cs with:

Program.cs
using Microsoft.Agents.AI.Workflows;
using Microsoft.Agents.AI.Workflows.Checkpointing;

const string SessionId = "refund-1042";

// Checkpoints go to JSON files in the checkpoints folder, so they outlive this process.
using var store = new FileSystemJsonCheckpointStore(new DirectoryInfo("checkpoints"));
CheckpointManager checkpointManager = CheckpointManager.CreateJson(store);
  • The second using line brings in the Microsoft.Agents.AI.Workflows.Checkpointing namespace, where FileSystemJsonCheckpointStore lives.
  • SessionId is the session the refund's checkpoints are saved under. Every start of the program uses the same one, so a later start finds them. In an app that handles many requests, each request gets its own session ID.
  • new FileSystemJsonCheckpointStore(new DirectoryInfo("checkpoints")) keeps the checkpoints in a folder called checkpoints. The path is relative, so it starts from the current folder: the project folder, when you start the app there with dotnet run. The store creates the folder the first time. using var disposes of the store when the program ends.
  • CheckpointManager.CreateJson(store) creates the checkpoint manager, the object the run gives its checkpoints to. It turns each checkpoint into JSON and hands it to the store.

Step 3: Build the Same Workflow on Every Start​

Add this below the checkpoint manager:

Program.cs (below the checkpoint manager)
// Build the same workflow on every start: a checkpoint only fits the workflow that saved it.
Workflow workflow = BuildWorkflow();

And add the method that builds it at the end of the file:

Program.cs (at the end of the file)
static Workflow BuildWorkflow()
{
RequestPort askSupervisor = RequestPort.Create<string, bool>("AskSupervisor");

Func<int, string> describe = amount => $"Refund {amount} USD to the customer?";
Func<bool, string> record = approved => approved ? "Refund approved." : "Refund rejected.";

ExecutorBinding describeRefund = describe.BindAsExecutor("DescribeRefund");
ExecutorBinding recordAnswer = record.BindAsExecutor("RecordAnswer");

return new WorkflowBuilder(describeRefund)
.AddEdge(describeRefund, askSupervisor)
.AddEdge(askSupervisor, recordAnswer)
.WithOutputFrom(recordAnswer)
.Build();
}
  • RequestPort.Create<string, bool>("AskSupervisor") is the request port: the workflow sends it a question as a string and waits for a bool answer. The guide to pausing a workflow until a person answers explains request ports step by step.
  • describe turns the amount into the question, and record turns the answer into the result.
  • BindAsExecutor turns each function into a step with a fixed ID, and the edges connect DescribeRefund to the port and the port to RecordAnswer.

The workflow is built in one method because the checkpoint has to fit it on every start. A checkpoint names the executors by their IDs, so a later start has to build the same steps with the same IDs, connected in the same way. Calling one method on every start builds it the same way each time.

Step 4: Run Until the Question on the First Start​

Add this below Workflow workflow = BuildWorkflow();:

Program.cs (below the workflow)
if (args.Length == 0)
{
// First start: run until the workflow asks its question, then end the program.
await using Run run = await InProcessExecution.RunAsync(workflow, 25, checkpointManager, SessionId);
Console.WriteLine($"Status: {await run.GetStatusAsync()}");
Console.WriteLine($"Checkpoints saved: {run.Checkpoints.Count}");
Console.WriteLine("The program ends here. Answer later with: dotnet run -- y");
return;
}
  • args holds the program's command-line arguments. Without any, this is a first start.
  • InProcessExecution.RunAsync(workflow, 25, checkpointManager, SessionId) runs the workflow with 25, the refund amount, as its input. Passing the checkpoint manager turns checkpoints on, and SessionId names the session they're saved under. The run goes on until its first halt, which is the question.
  • run.Checkpoints is documented as Gets a read-only list of checkpoint information associated with the current context. The program prints how many checkpoints the run saved.
  • return ends the program. The run still waits for its answer, but only in the checkpoint files now.

Step 5: Resume from the Latest Checkpoint on a Later Start​

Add this below the first start's block:

Program.cs (below the first start)
// A later start: find the session's latest checkpoint and continue the run from it.
CheckpointInfo? latest = await checkpointManager.GetLatestCheckpointAsync(SessionId);
if (latest is null)
{
Console.WriteLine($"No checkpoints for {SessionId}. Start the request first with: dotnet run");
return;
}

await using Run resumed = await InProcessExecution.ResumeAsync(workflow, latest, checkpointManager);
Console.WriteLine($"Resumed from checkpoint {latest.CheckpointId}");
Console.WriteLine($"Status: {await resumed.GetStatusAsync()}");
  • GetLatestCheckpointAsync(SessionId) asks the checkpoint manager for the session's most recent checkpoint. It returns a CheckpointInfo, the key of a checkpoint: its session ID and its own ID. It returns null when the session has no checkpoints, and then the program says so and ends.
  • InProcessExecution.ResumeAsync(workflow, latest, checkpointManager) loads that checkpoint into the workflow and continues the run. Like RunAsync, it runs the workflow until its first halt and then returns the run.
  • The two Console.WriteLine lines print the checkpoint's ID and the status of the resumed run.

Step 6: Answer the Question That Comes Back​

Add this below the resume:

Program.cs (below the resume)
// The question the first start asked comes back as a RequestInfoEvent.
RequestInfoEvent question = resumed.OutgoingEvents.OfType<RequestInfoEvent>().Single();
question.Request.TryGetDataAs(out string? text);
Console.WriteLine($"Waiting question: {text}");

bool approved = args[0] == "y";
await resumed.ResumeAsync([question.Request.CreateResponse(approved)]);

foreach (WorkflowOutputEvent output in resumed.NewEvents.OfType<WorkflowOutputEvent>())
{
Console.WriteLine($"Output: {output.Data}");
}

Console.WriteLine($"Status: {await resumed.GetStatusAsync()}");
  • The question comes back by itself. Microsoft's human-in-the-loop guide: When you restore from a checkpoint, any pending requests will be re-emitted as RequestInfoEvent objects, allowing you to capture and respond to them. So the resumed run has a RequestInfoEvent, and TryGetDataAs takes the question text out of it.
  • args[0] == "y" turns the first argument into the answer: true for y, false for anything else.
  • CreateResponse(approved) wraps the answer for the request it answers, and ResumeAsync sends it into the run, which continues to RecordAnswer.
  • NewEvents gives the events the run hasn't handed out yet. The loop prints the output among them, and the last line prints the status.

Step 7: Start the Request​

Terminal
dotnet run
Output
Status: PendingRequests
Checkpoints saved: 2
The program ends here. Answer later with: dotnet run -- y

macOS-style terminal window titled Terminal — RefundApproval showing dotnet run printing Status: PendingRequests, Checkpoints saved: 2, and The program ends here. Answer later with: dotnet run -- y

The run stopped at the question with the status PendingRequests, and the program ended. Before it halted, the run went through two supersteps, DescribeRefund and then the port taking the question, and saved a checkpoint at the end of each. Those two files are all that's left of the run.

Step 8: Answer on a Later Start​

Start the program again, this time with the answer:

Terminal
dotnet run -- y

-- separates the arguments of dotnet run from the app's own: everything after it goes to the program, so y reaches it as args[0].

Output
Resumed from checkpoint 7dfdd3fbe9d645dda5907c6f7c1fdbc1
Status: PendingRequests
Waiting question: Refund 25 USD to the customer?
Output: Refund approved.
Status: Idle

macOS-style terminal window titled Terminal — RefundApproval showing dotnet run -- y printing Resumed from checkpoint 7dfdd3fbe9d645dda5907c6f7c1fdbc1, Status: PendingRequests, Waiting question: Refund 25 USD to the customer?, Output: Refund approved., and Status: Idle

Line by line:

  1. Resumed from checkpoint 7dfdd3fb… — the latest checkpoint of the session, the one the first start saved last.
  2. Status: PendingRequests — the resumed run is where the first start left it: halted at the question.
  3. Waiting question: Refund 25 USD to the customer? — the question the first start asked, back as a RequestInfoEvent.
  4. Output: Refund approved. — the answer went to RecordAnswer, and its result is the workflow's output.
  5. Status: Idle — the run finished, with nothing outstanding.

:::warning Answer only once Once the run has finished, the session's latest checkpoint is the one saved at its end, and ResumeAsync from that checkpoint doesn't return: a third dotnet run -- y prints nothing until you stop it. Fixed: InProcessExecution.ResumeAsync Never Returns When a Microsoft Agent Framework Workflow Has Already Finished shows the hang and how to avoid it, and How to Resume a Microsoft Agent Framework Workflow from the Checkpoint Where It Waits for an Answer in C# shows how to keep that checkpoint and answer from it. :::

Step 9: Look at the Checkpoint Files​

The store created a checkpoints folder in the project folder. After the two starts it holds an index and four checkpoint files:

checkpoints
index.jsonl
refund-1042_09a68775c7d14c2c947ff03d88846aac%2Ejson
refund-1042_25db25d87cdd46e58070db299f66ac86%2Ejson
refund-1042_2a9c61f004624dad89e84ed87d8c187b%2Ejson
refund-1042_7dfdd3fbe9d645dda5907c6f7c1fdbc1%2Ejson

Two checkpoints come from the first start, and two from the second: the resumed run went on saving checkpoints in the same session. Each file is named after the session ID and the checkpoint ID, and inside, it refers to the workflow's steps by their IDs. The %2E before json is an escaped dot. Agent Framework's FileSystemJsonCheckpointStore.cs builds the name like this:

FileSystemJsonCheckpointStore.cs (GetFileNameForCheckpoint)
string protoPath = $"{sessionId}_{key.CheckpointId}.json";

// Escape the protoPath to ensure it is a valid file name, especially if sessionId or CheckpointId contain path separators, etc.
return Uri.EscapeDataString(protoPath) // This takes care of most of the invalid path characters
.Replace(".", "%2E"); // This takes care of escaping the root folder, since EscapeDataString does not escape dots

Uri.EscapeDataString escapes most characters a path can't have, and Replace escapes the dots, which EscapeDataString leaves alone, so the dot before json becomes %2E too. The files are ordinary JSON all the same.

index.jsonl has one line for each checkpoint, in the order they were saved:

checkpoints/index.jsonl
{"checkpointInfo":{"sessionId":"refund-1042","checkpointId":"2a9c61f004624dad89e84ed87d8c187b"},"fileName":"refund-1042_2a9c61f004624dad89e84ed87d8c187b%2Ejson","hasParentMetadata":true}
{"checkpointInfo":{"sessionId":"refund-1042","checkpointId":"7dfdd3fbe9d645dda5907c6f7c1fdbc1"},"fileName":"refund-1042_7dfdd3fbe9d645dda5907c6f7c1fdbc1%2Ejson","parentCheckpointId":"2a9c61f004624dad89e84ed87d8c187b","hasParentMetadata":true}
{"checkpointInfo":{"sessionId":"refund-1042","checkpointId":"25db25d87cdd46e58070db299f66ac86"},"fileName":"refund-1042_25db25d87cdd46e58070db299f66ac86%2Ejson","parentCheckpointId":"7dfdd3fbe9d645dda5907c6f7c1fdbc1","hasParentMetadata":true}
{"checkpointInfo":{"sessionId":"refund-1042","checkpointId":"09a68775c7d14c2c947ff03d88846aac"},"fileName":"refund-1042_09a68775c7d14c2c947ff03d88846aac%2Ejson","parentCheckpointId":"25db25d87cdd46e58070db299f66ac86","hasParentMetadata":true}

Each checkpoint after the first names its parent, the checkpoint the run went on from. The answer resumed from 7dfdd3fb…, so the first checkpoint the answer saved has it as its parent. The last line is the latest checkpoint: the one GetLatestCheckpointAsync returns now, saved at the end of the run's last superstep.

:::warning Treat checkpoint files as trusted data Microsoft's checkpoints guide: Checkpoint storage is a trust boundary. Whether you use the built-in storage implementations or a custom one, the storage backend must be treated as trusted, private infrastructure. It adds, in bold: Never load checkpoints from untrusted or potentially tampered sources. Keep the folder where only your app can read and write it. :::

The Complete File​

Program.cs
using Microsoft.Agents.AI.Workflows;
using Microsoft.Agents.AI.Workflows.Checkpointing;

const string SessionId = "refund-1042";

// Checkpoints go to JSON files in the checkpoints folder, so they outlive this process.
using var store = new FileSystemJsonCheckpointStore(new DirectoryInfo("checkpoints"));
CheckpointManager checkpointManager = CheckpointManager.CreateJson(store);

// Build the same workflow on every start: a checkpoint only fits the workflow that saved it.
Workflow workflow = BuildWorkflow();

if (args.Length == 0)
{
// First start: run until the workflow asks its question, then end the program.
await using Run run = await InProcessExecution.RunAsync(workflow, 25, checkpointManager, SessionId);
Console.WriteLine($"Status: {await run.GetStatusAsync()}");
Console.WriteLine($"Checkpoints saved: {run.Checkpoints.Count}");
Console.WriteLine("The program ends here. Answer later with: dotnet run -- y");
return;
}

// A later start: find the session's latest checkpoint and continue the run from it.
CheckpointInfo? latest = await checkpointManager.GetLatestCheckpointAsync(SessionId);
if (latest is null)
{
Console.WriteLine($"No checkpoints for {SessionId}. Start the request first with: dotnet run");
return;
}

await using Run resumed = await InProcessExecution.ResumeAsync(workflow, latest, checkpointManager);
Console.WriteLine($"Resumed from checkpoint {latest.CheckpointId}");
Console.WriteLine($"Status: {await resumed.GetStatusAsync()}");

// The question the first start asked comes back as a RequestInfoEvent.
RequestInfoEvent question = resumed.OutgoingEvents.OfType<RequestInfoEvent>().Single();
question.Request.TryGetDataAs(out string? text);
Console.WriteLine($"Waiting question: {text}");

bool approved = args[0] == "y";
await resumed.ResumeAsync([question.Request.CreateResponse(approved)]);

foreach (WorkflowOutputEvent output in resumed.NewEvents.OfType<WorkflowOutputEvent>())
{
Console.WriteLine($"Output: {output.Data}");
}

Console.WriteLine($"Status: {await resumed.GetStatusAsync()}");

static Workflow BuildWorkflow()
{
RequestPort askSupervisor = RequestPort.Create<string, bool>("AskSupervisor");

Func<int, string> describe = amount => $"Refund {amount} USD to the customer?";
Func<bool, string> record = approved => approved ? "Refund approved." : "Refund rejected.";

ExecutorBinding describeRefund = describe.BindAsExecutor("DescribeRefund");
ExecutorBinding recordAnswer = record.BindAsExecutor("RecordAnswer");

return new WorkflowBuilder(describeRefund)
.AddEdge(describeRefund, askSupervisor)
.AddEdge(askSupervisor, recordAnswer)
.WithOutputFrom(recordAnswer)
.Build();
}

macOS-style code window titled Program.cs — RefundApproval showing a FileSystemJsonCheckpointStore on a checkpoints folder with CheckpointManager.CreateJson, a first start that runs the workflow with the checkpoint manager and the session ID refund-1042, a later start that gets the latest checkpoint with GetLatestCheckpointAsync and resumes with InProcessExecution.ResumeAsync, answers the re-emitted RequestInfoEvent with CreateResponse, and a BuildWorkflow method with the request port AskSupervisor between two steps

Common Mistakes​

MistakeWhat happensDo this instead
Building a different workflow on the later startThe checkpoint no longer fits it: Microsoft's guide requires the same topology and executor identitiesBuild the workflow in one method and call it on every start
Leaving out using on the storeThe store isn't disposed of, though its documentation asks callers to dispose of itWrite using var store = ...
Opening the same folder from two running programsThe store is meant for one process: it locks index.jsonl, and the second program's store throws an InvalidOperationException saying the store is already in use by another processGive each process its own folder, or write your own store
Starting the answer again after the run has finishedResumeAsync doesn't returnResume from the checkpoint where the run waits
Using CheckpointManager.CreateInMemory() for a restartThe checkpoints live in the program's memory and end with itUse a store that writes them somewhere lasting, such as files

FAQ​

Where else can checkpoints go?​

Into any store you write yourself. How to Write a Custom Checkpoint Store for Microsoft Agent Framework Workflows in C# builds one and shows when the framework calls it.

Can a checkpoint hold my own types?​

Yes. The documentation of CreateJson's second parameter, the custom JSON options, says they Must be provided if using custom types in messages or state. How to Save Your Own Types in Microsoft Agent Framework Workflow Checkpoints in C# shows when an app needs them and how to pass them.

Is there another way to turn checkpoints on?​

Yes. InProcessExecution.Default and InProcessExecution.Concurrent are execution environments, and each has a WithCheckpointing method, documented as Configure a new execution environment, inheriting configuration for the current one with the specified CheckpointManager for use in checkpointing. The environment it returns runs and resumes workflows with that checkpoint manager, so its RunAsync and ResumeAsync don't take one. This guide passes the manager to InProcessExecution.RunAsync and ResumeAsync instead.

What changes when the workflow has agents?​

An agent's ID, and its name when it has one, become part of its step's identity, so they have to stay the same on every start. Microsoft's checkpoints guide: If the workflow contains local ChatClientAgent instances that are reconstructed across requests, dependency injection scopes, processes, or deployments, assign each agent a stable ChatClientAgentOptions.Id. It adds: If an agent also sets a Name, keep that Name unchanged as well.

Conclusion​

To let a workflow wait across restarts, give the run a checkpoint manager on a store that lasts, such as FileSystemJsonCheckpointStore, and a session ID. On a later start, build the same workflow, get the session's latest checkpoint with GetLatestCheckpointAsync, and resume it with InProcessExecution.ResumeAsync: the waiting question comes back as a RequestInfoEvent, ready for its answer. In the example, the first start saved 2 checkpoints and ended, and dotnet run -- y resumed the run, answered it, and finished it with Refund approved..

Additional Resources​