Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Orchestrations are long-running stateful workflows that you can start, query, suspend, resume, and end using built-in management APIs. In Durable Functions, the orchestration client binding exposes these APIs. In the Durable Task SDKs, these operations are available through the DurableTaskClient class. This article covers all supported instance management operations for both platforms.
Tip
The Azure Durable Task Scheduler is the recommended backend for both Durable Functions and the Durable Task SDKs, providing a fully managed, serverless experience for running durable workflows at scale.
Start instances
The start-new (or schedule-new) method on the orchestration client starts a new orchestration instance. Internally, this method writes a message to the configured backend (such as the Durable Task Scheduler or Azure Storage) and then returns. This message asynchronously triggers the start of an orchestration with the specified name.
Here are the parameters for starting a new orchestration instance:
- Name: The name of the orchestrator function to schedule.
- Input: Any JSON-serializable data that should be passed as the input to the orchestrator function.
- InstanceId: (Optional) The unique ID of the instance. If you don't specify this parameter, the method uses a random ID.
Tip
Use a random identifier for the instance ID whenever possible. Random instance IDs help ensure an equal load distribution when you scale orchestrator functions across multiple VMs. The proper time to use nonrandom instance IDs is when the ID comes from an external source or when you're implementing the singleton orchestrator pattern.
- Name: The name of the orchestration to schedule.
- Input: Any JSON-serializable data that should be passed as input to the orchestration.
- InstanceId: (Optional) The unique ID of the instance. If you don't specify this parameter, the method uses a random ID.
Tip
Use a random identifier for the instance ID whenever possible. Random instance IDs help ensure an equal load distribution when you scale orchestrations across multiple VMs. The proper time to use nonrandom instance IDs is when the ID comes from an external source or when you're implementing the singleton orchestrator pattern.
The following example function starts a new orchestration instance:
[FunctionName("HelloWorldQueueTrigger")]
public static async Task Run(
[QueueTrigger("start-queue")] string input,
[DurableClient] IDurableOrchestrationClient starter,
ILogger log)
{
string instanceId = await starter.StartNewAsync("HelloWorld", input);
log.LogInformation($"Started orchestration with ID = '{instanceId}'.");
}
Note
The previous C# code is for Durable Functions 2.x. For Durable Functions 1.x, use the OrchestrationClient attribute instead of the DurableClient attribute, and use the DurableOrchestrationClient parameter type instead of IDurableOrchestrationClient. For more information about the differences between versions, see Durable Functions versions.
Important
Currently, the PowerShell Durable Task SDK isn't available.
The following code shows how to start a new orchestration instance by using the Durable Task SDKs:
using Microsoft.DurableTask.Client;
// Schedule a new orchestration instance
string instanceId = await client.ScheduleNewOrchestrationInstanceAsync("HelloWorld", input);
Console.WriteLine($"Started orchestration with ID = '{instanceId}'.");
// Optionally, wait for the orchestration to start
OrchestrationMetadata metadata = await client.WaitForInstanceStartAsync(instanceId, timeout: TimeSpan.FromSeconds(30));
Query instances
After you start new orchestration instances, you most likely need to query their runtime status to learn whether they're running, complete, or failed.
The get-status method on the orchestration client returns the status of an orchestration instance.
It takes an instanceId (required), showHistory (optional), showHistoryOutput (optional), and showInput (optional) as parameters.
showHistory: If set totrue, the response contains the execution history.showHistoryOutput: If set totrue, the execution history contains activity outputs.showInput: If set tofalse, the response doesn't contain the input of the function. The default value istrue.
The method returns an object with the following properties:
- Name: The name of the orchestrator function.
- InstanceId: The instance ID of the orchestration (should be the same as the
instanceIdinput). - CreatedTime: The time at which the orchestrator function starts running.
- LastUpdatedTime: The time at which the orchestration last checkpoints.
- Input: The input of the function as a JSON value. This field isn't populated if
showInputisfalse. - CustomStatus: Custom orchestration status in JSON format.
- Output: The output of the function as a JSON value (if the function completes). If the orchestrator function fails, this property includes the failure details. If the orchestrator function is suspended or terminated, this property includes the reason for the suspension or termination (if any).
- RuntimeStatus: One of the following values:
- Pending: The instance is scheduled but hasn't yet started running.
- Running: The instance is running.
- Completed: The instance completed normally.
- ContinuedAsNew: The instance restarted itself with a new history. This state is a transient state.
- Failed: The instance failed with an error.
- Terminated: The instance stopped abruptly.
- Suspended: The instance is suspended and can be resumed at a later point in time.
- History: The execution history of the orchestration. This field is only populated if
showHistoryis set totrue.
showHistory: If set totrue, the response contains the execution history.showHistoryOutput: If set totrue, the execution history contains activity outputs.showInput: If set tofalse, the response doesn't contain the input of the orchestration. The default value istrue.
The method returns an object with the following properties:
- Name: The name of the orchestration.
- InstanceId: The instance ID of the orchestration (should be the same as the
instanceIdinput). - CreatedTime: The time at which the orchestration starts running.
- LastUpdatedTime: The time at which the orchestration last checkpoints.
- Input: The input of the orchestration as a JSON value. This field isn't populated if
showInputisfalse. - CustomStatus: Custom orchestration status in JSON format.
- Output: The output of the orchestration as a JSON value (if the orchestration completes). If the orchestration fails, this property includes the failure details. If the orchestration is suspended or terminated, this property includes the reason for the suspension or termination (if any).
- RuntimeStatus: One of the following values:
- Pending: The instance is scheduled but hasn't yet started running.
- Running: The instance is running.
- Completed: The instance completed normally.
- ContinuedAsNew: The instance restarted itself with a new history. This state is a transient state.
- Failed: The instance failed with an error.
- Terminated: The instance stopped abruptly.
- Suspended: The instance is suspended and can be resumed at a later point in time.
- History: The execution history of the orchestration. This field is only populated if
showHistoryis set totrue.
Note
An orchestrator isn't marked as Completed until all of its scheduled tasks finish and the orchestrator returns. In other words, it isn't sufficient for an orchestrator to reach its return statement for it to be marked as Completed. This is particularly relevant for cases where WhenAny is used; those orchestrators often return before all the scheduled tasks execute.
This method returns null (.NET and Java), undefined (JavaScript), or None (Python) if the instance doesn't exist.
[FunctionName("GetStatus")]
public static async Task Run(
[DurableClient] IDurableOrchestrationClient client,
[QueueTrigger("check-status-queue")] string instanceId)
{
DurableOrchestrationStatus status = await client.GetStatusAsync(instanceId);
// do something based on the current status.
}
Note
The previous C# code is for Durable Functions 2.x. For Durable Functions 1.x, use the OrchestrationClient attribute instead of the DurableClient attribute, and use the DurableOrchestrationClient parameter type instead of IDurableOrchestrationClient. For more information about the differences between versions, see the Durable Functions versions article.
using Microsoft.DurableTask.Client;
// Get the status of an orchestration instance
OrchestrationMetadata? metadata = await client.GetInstanceAsync(instanceId, getInputsAndOutputs: true);
if (metadata != null)
{
OrchestrationRuntimeStatus status = metadata.RuntimeStatus;
// do something based on the current status
}
Query all instances
You can use APIs in your language SDK to query the statuses of all orchestration instances in your task hub. This "list-instances" or "get-status" API returns a list of objects that represent the orchestration instances matching the query parameters.
[FunctionName("GetAllStatus")]
public static async Task Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestMessage req,
[DurableClient] IDurableOrchestrationClient client,
ILogger log)
{
var noFilter = new OrchestrationStatusQueryCondition();
OrchestrationStatusQueryResult result = await client.ListInstancesAsync(
noFilter,
CancellationToken.None);
foreach (DurableOrchestrationStatus instance in result.DurableOrchestrationState)
{
log.LogInformation(JsonConvert.SerializeObject(instance));
}
// Note: ListInstancesAsync only returns the first page of results.
// To request additional pages provide the result.ContinuationToken
// to the OrchestrationStatusQueryCondition's ContinuationToken property.
}
Note
The previous C# code is for Durable Functions 2.x. For Durable Functions 1.x, you must use OrchestrationClient attribute instead of the DurableClient attribute, and you must use the DurableOrchestrationClient parameter type instead of IDurableOrchestrationClient. For more information about the differences between versions, see the Durable Functions versions article.
using Microsoft.DurableTask.Client;
// Query all orchestration instances
AsyncPageable<OrchestrationMetadata> instances = client.GetAllInstancesAsync(new OrchestrationQuery());
await foreach (OrchestrationMetadata instance in instances)
{
Console.WriteLine(instance.InstanceId);
}
Query instances with filters
What if you don't need all the information that a standard instance query provides? For example, what if you're just looking for the orchestration creation time or the orchestration runtime status? Narrow your query by applying filters.
[FunctionName("QueryStatus")]
public static async Task Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestMessage req,
[DurableClient] IDurableOrchestrationClient client,
ILogger log)
{
// Get the first 100 running or pending instances that were created between 7 and 1 days ago
var queryFilter = new OrchestrationStatusQueryCondition
{
RuntimeStatus = new[]
{
OrchestrationRuntimeStatus.Pending,
OrchestrationRuntimeStatus.Running,
},
CreatedTimeFrom = DateTime.UtcNow.Subtract(TimeSpan.FromDays(7)),
CreatedTimeTo = DateTime.UtcNow.Subtract(TimeSpan.FromDays(1)),
PageSize = 100,
};
OrchestrationStatusQueryResult result = await client.ListInstancesAsync(
queryFilter,
CancellationToken.None);
foreach (DurableOrchestrationStatus instance in result.DurableOrchestrationState)
{
log.LogInformation(JsonConvert.SerializeObject(instance));
}
}
Note
The previous C# code is for Durable Functions 2.x. For Durable Functions 1.x, you must use OrchestrationClient attribute instead of the DurableClient attribute, and you must use the DurableOrchestrationClient parameter type instead of IDurableOrchestrationClient. For more information about the differences between versions, see the Durable Functions versions article.
using Microsoft.DurableTask.Client;
// Get running or pending instances created in the last 7 days
var query = new OrchestrationQuery
{
Statuses = new[] { OrchestrationRuntimeStatus.Running, OrchestrationRuntimeStatus.Pending },
CreatedFrom = DateTime.UtcNow.AddDays(-7),
CreatedTo = DateTime.UtcNow.AddDays(-1),
PageSize = 100
};
AsyncPageable<OrchestrationMetadata> instances = client.GetAllInstancesAsync(query);
await foreach (OrchestrationMetadata instance in instances)
{
Console.WriteLine($"{instance.InstanceId}: {instance.RuntimeStatus}");
}
Terminate instances
If you have an orchestration instance that's taking too long to run, or you need to stop it before it completes for any reason, you can end it.
The two parameters for the terminate API are an instance ID and a reason string, which write to logs and to the instance status.
[FunctionName("TerminateInstance")]
public static Task Run(
[DurableClient] IDurableOrchestrationClient client,
[QueueTrigger("terminate-queue")] string instanceId)
{
string reason = "Found a bug";
return client.TerminateAsync(instanceId, reason);
}
Note
The previous C# code is for Durable Functions 2.x. For Durable Functions 1.x, you must use OrchestrationClient attribute instead of the DurableClient attribute, and you must use the DurableOrchestrationClient parameter type instead of IDurableOrchestrationClient. For more information about the differences between versions, see the Durable Functions versions article.
using Microsoft.DurableTask.Client;
string reason = "Found a bug";
await client.TerminateInstanceAsync(instanceId, reason);
A terminated instance eventually transitions into the Terminated state. But this transition doesn't happen immediately. Rather, the terminate operation is queued in the task hub along with other operations for that instance. You can use the instance query APIs to know when a terminated instance has actually reached the Terminated state.
Note
Instance termination doesn't currently propagate. Activity functions and sub-orchestrations run to completion, regardless of whether you end the orchestration instance that called them.
Suspend and resume instances
Suspending an orchestration lets you stop a running orchestration. Unlike ending an orchestration, you can resume a suspended orchestrator later.
The two parameters for the suspend API are an instance ID and a reason string, which are written to logs and to the instance status.
[FunctionName("SuspendResumeInstance")]
public static async Task Run(
[DurableClient] IDurableOrchestrationClient client,
[QueueTrigger("suspend-resume-queue")] string instanceId)
{
// To suspend an orchestration
string suspendReason = "Need to pause workflow";
await client.SuspendAsync(instanceId, suspendReason);
// To resume an orchestration
string resumeReason = "Continue workflow";
await client.ResumeAsync(instanceId, resumeReason);
}
using Microsoft.DurableTask.Client;
// To suspend an orchestration
string suspendReason = "Need to pause workflow";
await client.SuspendInstanceAsync(instanceId, suspendReason);
// To resume an orchestration
string resumeReason = "Continue workflow";
await client.ResumeInstanceAsync(instanceId, resumeReason);
A suspended instance eventually transitions to the Suspended state. However, this transition doesn't happen immediately. Rather, the suspend operation is queued in the task hub along with other operations for that instance. Use the instance query APIs to know when a running instance has actually reached the Suspended state.
When a suspended orchestrator is resumed, its status changes back to Running.
Send events to instances
In some scenarios, orchestrator functions need to wait and listen for external events. Examples where this approach is useful include the monitoring and human interaction scenarios.
In some scenarios, orchestrations need to wait and listen for external events. Examples where this approach is useful include the monitoring and human interaction scenarios.
You can send event notifications to running instances by using the raise event API of the orchestration client. Orchestrations can listen and respond to these events using the wait for external event orchestrator API.
The parameters for raise event are:
- Instance ID: The unique ID of the instance.
- Event name: The name of the event to send.
- Event data: A JSON-serializable payload to send to the instance.
[FunctionName("RaiseEvent")]
public static Task Run(
[DurableClient] IDurableOrchestrationClient client,
[QueueTrigger("event-queue")] string instanceId)
{
int[] eventData = new int[] { 1, 2, 3 };
return client.RaiseEventAsync(instanceId, "MyEvent", eventData);
}
Note
The previous C# code is for Durable Functions 2.x. For Durable Functions 1.x, you must use OrchestrationClient attribute instead of the DurableClient attribute, and you must use the DurableOrchestrationClient parameter type instead of IDurableOrchestrationClient. For more information about the differences between versions, see the Durable Functions versions article.
using Microsoft.DurableTask.Client;
int[] eventData = new int[] { 1, 2, 3 };
await client.RaiseEventAsync(instanceId, "MyEvent", eventData);
Note
If there's no orchestration instance with the specified instance ID, the event message is discarded. If an instance exists but it isn't yet waiting for the event, the event is stored in the instance state until it's ready to be received and processed.
Wait for orchestration completion
In long-running orchestrations, you might want to wait and get the results of an orchestration. In these cases, it's also useful to define a timeout period on the orchestration. If the timeout is exceeded, the state of the orchestration is returned instead of the results.
Use the "wait for completion or create check status response" API to get the actual output from an orchestration instance synchronously. By default, this method has a timeout of ten seconds and a polling interval of one second.
Here's an example HTTP-trigger function that demonstrates how to use this API:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
namespace VSSample
{
public static class HttpSyncStart
{
private const string Timeout = "timeout";
private const string RetryInterval = "retryInterval";
[FunctionName("HttpSyncStart")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, methods: "post", Route = "orchestrators/{functionName}/wait")]
HttpRequestMessage req,
[DurableClient] IDurableOrchestrationClient starter,
string functionName,
ILogger log)
{
// Function input comes from the request content.
object eventData = await req.Content.ReadAsAsync<object>();
string instanceId = await starter.StartNewAsync(functionName, eventData);
log.LogInformation($"Started orchestration with ID = '{instanceId}'.");
TimeSpan timeout = GetTimeSpan(req, Timeout) ?? TimeSpan.FromSeconds(30);
TimeSpan retryInterval = GetTimeSpan(req, RetryInterval) ?? TimeSpan.FromSeconds(1);
return await starter.WaitForCompletionOrCreateCheckStatusResponseAsync(
req,
instanceId,
timeout,
retryInterval);
}
private static TimeSpan? GetTimeSpan(HttpRequestMessage request, string queryParameterName)
{
string queryParameterStringValue = request.RequestUri.ParseQueryString()[queryParameterName];
if (string.IsNullOrEmpty(queryParameterStringValue))
{
return null;
}
return TimeSpan.FromSeconds(double.Parse(queryParameterStringValue));
}
}
}
The Durable Task SDKs provide a method to wait for an orchestration to finish synchronously.
using Microsoft.DurableTask.Client;
// Wait for orchestration to complete with a timeout
OrchestrationMetadata metadata = await client.WaitForInstanceCompletionAsync(
instanceId,
timeout: TimeSpan.FromSeconds(30),
getInputsAndOutputs: true);
if (metadata.RuntimeStatus == OrchestrationRuntimeStatus.Completed)
{
Console.WriteLine($"Output: {metadata.SerializedOutput}");
}
Call the function with the following line. Use two seconds for the timeout and 0.5 seconds for the retry interval:
curl -X POST "http://localhost:7071/orchestrators/E1_HelloSequence/wait?timeout=2&retryInterval=0.5"
Note
The above cURL command assumes you have an orchestrator function named E1_HelloSequence in your project. Because of how the HTTP trigger function is written, you can replace it with the name of any orchestrator function in your project.
Depending on the time required to get the response from the orchestration instance, two cases exist:
- The orchestration instances finish within the defined timeout (in this case two seconds), and the response is the actual orchestration instance output, delivered synchronously:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Thu, 14 Dec 2021 06:14:29 GMT
Transfer-Encoding: chunked
[
"Hello Tokyo!",
"Hello Seattle!",
"Hello London!"
]
- The orchestration instances can't finish within the defined timeout, and the response is the default one described in HTTP API URL discovery:
HTTP/1.1 202 Accepted
Content-Type: application/json; charset=utf-8
Date: Thu, 14 Dec 2021 06:13:51 GMT
Location: http://localhost:7071/runtime/webhooks/durabletask/instances/d3b72dddefce4e758d92f4d411567177?taskHub={taskHub}&connection={connection}&code={systemKey}
Retry-After: 10
Transfer-Encoding: chunked
{
"id": "d3b72dddefce4e758d92f4d411567177",
"sendEventPostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d3b72dddefce4e758d92f4d411567177/raiseEvent/{eventName}?taskHub={taskHub}&connection={connection}&code={systemKey}",
"statusQueryGetUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d3b72dddefce4e758d92f4d411567177?taskHub={taskHub}&connection={connection}&code={systemKey}",
"terminatePostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d3b72dddefce4e758d92f4d411567177/terminate?reason={text}&taskHub={taskHub}&connection={connection}&code={systemKey}",
"suspendPostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d3b72dddefce4e758d92f4d411567177/suspend?reason={text}&taskHub={taskHub}&connection={connection}&code={systemKey}",
"resumePostUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/d3b72dddefce4e758d92f4d411567177/resume?reason={text}&taskHub={taskHub}&connection={connection}&code={systemKey}"
}
Note
The format of the webhook URLs might differ, depending on which version of the Azure Functions host you run. The preceding example is for the Azure Functions 3.0 host.
Retrieve HTTP management webhook URLs
Use an external system to monitor or raise events to an orchestration. External systems communicate with Durable Functions through the webhook URLs that are part of the default response described in HTTP API URL discovery. The webhook URLs are alternatively accessible programmatically using the orchestration client binding. Specifically, the create HTTP management payload API gets a serializable object that contains these webhook URLs.
The create HTTP management payload API has one parameter:
- Instance ID: The unique ID of the instance.
The methods return an object with the following string properties:
- Id: The instance ID of the orchestration (should be the same as the
InstanceIdinput). - StatusQueryGetUri: The status URL of the orchestration instance.
- SendEventPostUri: The "raise event" URL of the orchestration instance.
- TerminatePostUri: The "terminate" URL of the orchestration instance.
- PurgeHistoryDeleteUri: The "purge history" URL of the orchestration instance.
- SuspendPostUri: The "suspend" URL of the orchestration instance.
- ResumePostUri: The "resume" URL of the orchestration instance.
Functions send instances of these objects to external systems to monitor or raise events on the corresponding orchestrations, as shown in the following examples.
[FunctionName("SendInstanceInfo")]
public static void SendInstanceInfo(
[ActivityTrigger] IDurableActivityContext ctx,
[DurableClient] IDurableOrchestrationClient client,
[CosmosDB(
databaseName: "MonitorDB",
containerName: "HttpManagementPayloads",
Connection = "CosmosDBConnectionSetting")]out dynamic document)
{
HttpManagementPayload payload = client.CreateHttpManagementPayload(ctx.InstanceId);
// send the payload to Azure Cosmos DB
document = new { Payload = payload, id = ctx.InstanceId };
}
Note
The previous C# code is for Durable Functions 2.x. For Durable Functions 1.x, use DurableActivityContext instead of IDurableActivityContext, use the OrchestrationClient attribute instead of the DurableClient attribute, and use the DurableOrchestrationClient parameter type instead of IDurableOrchestrationClient. For more information about the differences between versions, see the Durable Functions versions article.
Rewind instances
If you have an orchestration failure for an unexpected reason, rewind the instance to a previously healthy state by using an API built for that purpose.
Note
This API isn't intended to be a replacement for proper error handling and retry policies. Rather, it's intended to be used only in cases where orchestration instances fail for unexpected reasons. Orchestrations in states other than Failed (for example, Running, Pending, Terminated, or Completed) can't be "rewound". For more information about error handling and retry policies, see the Error handling article.
Use the RewindAsync (.NET) or rewind (JavaScript) method of the orchestration client binding to put the orchestration back into the Running state. This method also reruns the activity or suborchestration execution failures that caused the orchestration failure.
For example, say you have a workflow involving a series of human approvals. Suppose a series of activity functions notify someone that their approval is needed and wait out the real-time response. After all the approval activities receive responses or time out, suppose another activity fails because of an application misconfiguration, like an invalid database connection string. The result is an orchestration failure deep into the workflow. With the RewindAsync (.NET) or rewind (JavaScript) API, an application admin can fix the configuration error and rewind the failed orchestration back to the state immediately before the failure. None of the human-interaction steps need to be re-approved, and the orchestration can now complete successfully.
Note
The rewind feature doesn't support rewinding orchestration instances that use durable timers.
[FunctionName("RewindInstance")]
public static Task Run(
[DurableClient] IDurableOrchestrationClient client,
[QueueTrigger("rewind-queue")] string instanceId)
{
string reason = "Orchestrator failed and needs to be revived.";
return client.RewindAsync(instanceId, reason);
}
Note
The previous C# code is for Durable Functions 2.x. For Durable Functions 1.x, you must use OrchestrationClient attribute instead of the DurableClient attribute, and you must use the DurableOrchestrationClient parameter type instead of IDurableOrchestrationClient. For more information about the differences between versions, see the Durable Functions versions article.
using Microsoft.DurableTask.Client;
string reason = "Orchestrator failed and needs to be revived.";
await client.RewindInstanceAsync(instanceId, reason);
Restart instances
Restarting an orchestration creates a new instance using the history of a previously run instance. This feature is useful when you want to rerun an orchestration with the same input and instance ID pattern, creating a fresh run based on the original.
[FunctionName("RestartInstance")]
public static Task Run(
[DurableClient] IDurableOrchestrationClient client,
[QueueTrigger("restart-queue")] string instanceId)
{
return client.RestartAsync(instanceId, restartWithNewInstanceId: true);
}
Note
The previous C# code is for Durable Functions 2.x. For Durable Functions 1.x, you must use OrchestrationClient attribute instead of the DurableClient attribute, and you must use the DurableOrchestrationClient parameter type instead of IDurableOrchestrationClient. For more information about the differences between versions, see the Durable Functions versions article.
using Microsoft.DurableTask.Client;
// Restart an orchestration with a new instance ID
string newInstanceId = await client.RestartInstanceAsync(instanceId, restartWithNewInstanceId: true);
Console.WriteLine($"Restarted as new instance: {newInstanceId}");
// Restart an orchestration keeping the same instance ID
await client.RestartInstanceAsync(instanceId, restartWithNewInstanceId: false);
Purge instance history
To remove all the data associated with an orchestration, purge the instance history. For example, delete any storage resources associated with a completed instance. Use the purge instance API defined by the orchestration client.
The following example shows how to purge a single orchestration instance.
[FunctionName("PurgeInstanceHistory")]
public static Task Run(
[DurableClient] IDurableOrchestrationClient client,
[QueueTrigger("purge-queue")] string instanceId)
{
return client.PurgeInstanceHistoryAsync(instanceId);
}
using Microsoft.DurableTask.Client;
// Purge a single orchestration instance
PurgeResult result = await client.PurgeInstanceAsync(instanceId);
Console.WriteLine($"Purged {result.PurgedInstanceCount} instance(s).");
The following example shows a timer-triggered function that purges the history for all orchestration instances that completed after the specified time interval. In this case, it removes data for all instances completed 30 or more days ago. This example function is scheduled to run once per day, at 12:00 PM UTC:
[FunctionName("PurgeInstanceHistory")]
public static Task Run(
[DurableClient] IDurableOrchestrationClient client,
[TimerTrigger("0 0 12 * * *")] TimerInfo myTimer)
{
return client.PurgeInstanceHistoryAsync(
DateTime.MinValue,
DateTime.UtcNow.AddDays(-30),
new List<OrchestrationStatus>
{
OrchestrationStatus.Completed
});
}
Note
The previous C# code is for Durable Functions 2.x. For Durable Functions 1.x, you must use OrchestrationClient attribute instead of the DurableClient attribute, and you must use the DurableOrchestrationClient parameter type instead of IDurableOrchestrationClient. For more information about the differences between versions, see the Durable Functions versions article.
using Microsoft.DurableTask.Client;
// Purge completed instances older than 30 days
var filter = new PurgeInstancesFilter(
CreatedFrom: DateTime.MinValue,
CreatedTo: DateTime.UtcNow.AddDays(-30),
Statuses: new[] { OrchestrationRuntimeStatus.Completed });
PurgeResult result = await client.PurgeAllInstancesAsync(filter);
Console.WriteLine($"Purged {result.PurgedInstanceCount} instance(s).");
Note
For the purge history operation to succeed, the runtime status of the target instance must be Completed, Terminated, or Failed.