Azure Durable Functions: what happens to state when code changes mid-execution
An orchestrator function in Durable Functions does not store its state the way a regular object would. There is no snapshot of local variables that gets serialized and loaded back. What gets persisted is an event history -which activities were called, what they returned, which timers were created, which external signals arrived- and every time the orchestration needs to continue, the runtime does not "resume" the function: it re-executes it from the top, on the same logical thread, replaying that history so that calls which already resolved instantly return the value they already had, without re-running the actual activity.
This mechanism is called replay, and it is what lets an orchestration survive a host restart, a scale-out event, or days of waiting on a durable timer. It is also what turns a mid-flight code deploy into a concrete problem, not a theoretical one.
Why replay requires deterministic code
For replay to work, the orchestrator code has to produce exactly the same sequence of activity calls, in the same order, every time it runs from the top with the same input history. This is Durable Functions' determinism constraint: no DateTime.Now, no directly generated GUID, no reading an environment variable that can change between runs, no iterating a Dictionary without a guaranteed order, inside orchestrator code. Anything non-deterministic has to be delegated to an activity, which can do whatever it wants because its result gets persisted in the history, and on replay that stored result is used instead of re-running the activity.
[FunctionName("ProcessOrderOrchestrator")]
public static async Task Run(
[OrchestrationTrigger] IDurableOrchestrationContext context)
{
var order = context.GetInput<Order>();
var inStock = await context.CallActivityAsync<bool>("CheckStock", order);
if (!inStock)
{
await context.CallActivityAsync("NotifyOutOfStock", order);
return;
}
var payment = await context.CallActivityAsync<PaymentResult>("ProcessPayment", order);
await context.CallActivityAsync("ConfirmShipment", payment);
}
This code is deterministic in the way that matters: every time it replays against the same history, it reaches the same await context.CallActivityAsync lines in the same order, and the runtime can match those calls against the events already recorded in the history.
The problem shows up when code changes between two replays of the same instance
An orchestration instance can live for a long time: an approval flow waiting days for someone to respond, a fan-out/fan-in process with hundreds of activities, a week-long durable timer. While that instance is "in flight" -not finished, its history still growing- it is entirely possible for the team to ship a deploy that changes the orchestrator's code.
The concrete risk: if the new code changes the order of activity calls, adds a new call before one that already existed, or removes one that already ran, the next replay of that instance is going to try to match the new code against a history that was recorded by the old code. If the instance already has CheckStock's result in history position 0, and the new code puts CallActivityAsync("LogAudit", ...) in that position instead, the runtime has no way to know this is an intentional change: it simply finds a history event that does not correspond to what the code at that position is asking for, and the orchestration fails with a non-determinism exception -or, in some cases, worse: it continues with an incorrect pairing between a persisted result and the current call, handing the new activity a result that actually belonged to something else.
This is not a rare case. It happens every time:
- A new step is added mid-flow while instances are still running the previous version.
- Logic gets reordered -for example moving a validation before a call that used to come first.
- A sub-orchestration's shape changes, or an activity gets renamed that an old instance is still going to call on its next step.
- A new conditional branch is introduced that changes which activities get called based on data an old instance already locked in differently.
The instance does not fail at deploy time. It fails the next time that specific orchestrator needs to replay -which can be seconds later, if it is mid-await, or days later, if it is waiting on a long timer- and by then the deploy that caused it is long gone from anyone's list of suspects.
Orchestrator versioning: the mitigation that actually works
Durable Functions has no automatic mechanism that blocks a deploy incompatible with in-flight instances. Not breaking replay is the team's responsibility, and the strategy we use is to explicitly version the orchestrator whenever a change alters the call sequence, instead of editing the existing function in place.
[FunctionName("ProcessOrderOrchestrator_V2")]
public static async Task RunV2(
[OrchestrationTrigger] IDurableOrchestrationContext context)
{
var order = context.GetInput<Order>();
await context.CallActivityAsync("LogAudit", order);
var inStock = await context.CallActivityAsync<bool>("CheckStock", order);
// rest of the new flow
}
The old function (ProcessOrderOrchestrator) stays deployed, body untouched, until no in-flight instance is using it anymore. New instances start against ProcessOrderOrchestrator_V2. This requires the code that starts orchestrations (StartNewAsync) to know which version to target, which in practice means centralizing that decision -for instance, in a single entry point that reads which function name to use from configuration- instead of hardcoding the orchestrator name across half a dozen different triggers.
To know when it is safe to delete the old version, we query the actual state of active instances before any cleanup:
var instancesStillRunning = await client.ListInstancesAsync(
new OrchestrationStatusQueryCondition
{
RuntimeStatus = new[] { OrchestrationRuntimeStatus.Running, OrchestrationRuntimeStatus.Pending },
InstanceIdPrefix = "ProcessOrderOrchestrator-"
},
CancellationToken.None);
Only once that query returns an empty list for the old version do we retire the function. There is no fixed date for this -it depends on how long a real instance of that flow can live- so we treat it as a condition to verify, not a deadline to schedule.
What did not work on the first try
Before adopting explicit function versioning, the first thing we tried was feature flags inside the orchestrator itself: an input parameter saying "use the new flow" or "use the old flow", resolved with an if at the top of the function.
if (order.UseNewFlow)
{
await context.CallActivityAsync("LogAudit", order);
}
var inStock = await context.CallActivityAsync<bool>("CheckStock", order);
This looks reasonable, but it has the same problem it is trying to avoid: the value of UseNewFlow comes from the instance's original input, fixed at start time, so in theory each instance always takes the same branch on every replay. The real problem showed up when someone, months later, touched the code inside the false branch thinking it was dead code since no one was starting new instances with that flag off anymore. It was not dead code: there were still old instances in flight, weeks old, that were going to replay against that branch. Touching "dead code" that was actually still the replay path for real instances broke those instances exactly as if we had edited the function without versioning it. The flag inside the same function did not solve the underlying problem, it just hid it one level down, because it was still a single function whose entire body had to stay stable across every branch for as long as any instance of any branch was in flight.
What worked was moving the distinction out of the data layer and into the deployed-code layer: two functions with different names, each with its own deployment lifecycle, where deleting the old one is an explicit decision backed by a query against the real state of instances, not an assumption about which branch of an if no longer matters.
What we check before changing an existing orchestrator
Before changing the body of an orchestrator function that already has instances deployed in production, we first confirm whether the change alters the sequence, order, or parameters of activity and sub-orchestration calls; if it does, we do not edit the existing function, we create a new version under a different name. We check that the code starting new instances can point at the right version without touching half a dozen different places. And before deleting an old version, we query the real state of active instances for that version instead of assuming, based on time elapsed since the deploy, that none are left in flight.