<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Durable Functions on Jeppe Spanggaard - Software Developer | .NET, Azure &amp; Microsoft 365</title><link>https://jeppe-spanggaard.dk/tags/durable-functions/</link><description>Recent content in Durable Functions on Jeppe Spanggaard - Software Developer | .NET, Azure &amp; Microsoft 365</description><generator>Hugo</generator><language>en-US</language><lastBuildDate>Tue, 15 Sep 2026 00:00:00 +0000</lastBuildDate><atom:link href="https://jeppe-spanggaard.dk/tags/durable-functions/index.xml" rel="self" type="application/rss+xml"/><item><title>Break Graph on Purpose: Testing Durable Functions Provisioning with Dev Proxy</title><link>https://jeppe-spanggaard.dk/blogs/testing-durable-functions-provisioning-dev-proxy/</link><pubDate>Tue, 15 Sep 2026 00:00:00 +0000</pubDate><guid>https://jeppe-spanggaard.dk/blogs/testing-durable-functions-provisioning-dev-proxy/</guid><description>Learn how to test Durable Functions retry logic, idempotency and failure handling locally by injecting Graph and SharePoint errors with Dev Proxy.</description><content:encoded><![CDATA[<p>I&rsquo;ve written a small series about making SharePoint provisioning with Durable Functions resilient: <a href="https://jeppe-spanggaard.dk/blogs/durable-functions-provisioning-checkpoints/">checkpointing so runs resume instead of restart</a>, <a href="https://jeppe-spanggaard.dk/blogs/durable-functions-idempotent-activities/">idempotent activities that survive reruns</a>, <a href="https://jeppe-spanggaard.dk/blogs/durable-functions-permanent-vs-transient-failures/">failing fast on permanent errors</a>, <a href="https://jeppe-spanggaard.dk/blogs/durable-functions-deterministic-instance-ids/">deterministic instance IDs against duplicate starts</a>, and <a href="https://jeppe-spanggaard.dk/blogs/sharepoint-graph-eventual-consistency-404/">waiting out Graph&rsquo;s eventual consistency</a>.</p>
<p>Here&rsquo;s the uncomfortable part. All of that is code that only runs when Microsoft&rsquo;s servers have a bad day.</p>
<p>I had tested the happy path a hundred times. The unhappy path: zero. You can&rsquo;t ask Graph to please throw a 429 at step four. So the retry ladder, the idempotency guards, the fail-fast logic - a good chunk of it had never executed outside my imagination.</p>
<p>The fix is Dev Proxy: a free command-line API simulator from Microsoft that sits between your app and the real APIs and injects failures into real traffic. No code changes, no mock frameworks, no test doubles that quietly drift from reality. Your provisioning engine makes its actual Graph and SharePoint calls; the proxy just makes some of them fail.</p>
<h2 id="point-the-engine-through-the-proxy">Point the Engine Through the Proxy</h2>
<p>Dev Proxy works as a regular HTTPS proxy, so the setup is a config file and an environment variable. The config says which URLs to intercept and what to do with them:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-json" data-lang="json"><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">&#34;plugins&#34;</span>: [
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>      <span style="color:#f92672">&#34;name&#34;</span>: <span style="color:#e6db74">&#34;RetryAfterPlugin&#34;</span>,
</span></span><span style="display:flex;"><span>      <span style="color:#f92672">&#34;enabled&#34;</span>: <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>      <span style="color:#f92672">&#34;pluginPath&#34;</span>: <span style="color:#e6db74">&#34;~appFolder/plugins/DevProxy.Plugins.dll&#34;</span>
</span></span><span style="display:flex;"><span>    },
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>      <span style="color:#f92672">&#34;name&#34;</span>: <span style="color:#e6db74">&#34;GraphRandomErrorPlugin&#34;</span>,
</span></span><span style="display:flex;"><span>      <span style="color:#f92672">&#34;enabled&#34;</span>: <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>      <span style="color:#f92672">&#34;pluginPath&#34;</span>: <span style="color:#e6db74">&#34;~appFolder/plugins/DevProxy.Plugins.dll&#34;</span>,
</span></span><span style="display:flex;"><span>      <span style="color:#f92672">&#34;configSection&#34;</span>: <span style="color:#e6db74">&#34;graphRandomErrorPlugin&#34;</span>
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>  ],
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">&#34;urlsToWatch&#34;</span>: [
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://graph.microsoft.com/*&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://contoso.sharepoint.com/*&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://contoso-admin.sharepoint.com/*&#34;</span>
</span></span><span style="display:flex;"><span>  ],
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">&#34;graphRandomErrorPlugin&#34;</span>: {
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&#34;allowedErrors&#34;</span>: [ <span style="color:#ae81ff">429</span>, <span style="color:#ae81ff">500</span>, <span style="color:#ae81ff">503</span> ],
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&#34;rate&#34;</span>: <span style="color:#ae81ff">50</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&#34;retryAfterInSeconds&#34;</span>: <span style="color:#ae81ff">5</span>
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Then start the Functions host with its outbound traffic routed through the proxy:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-bash" data-lang="bash"><span style="display:flex;"><span>devproxy --config-file devproxyrc.json    <span style="color:#75715e"># terminal 1</span>
</span></span><span style="display:flex;"><span>HTTPS_PROXY<span style="color:#f92672">=</span>http://127.0.0.1:8000 func start    <span style="color:#75715e"># terminal 2</span>
</span></span></code></pre></div><p><strong>What&rsquo;s happening here?</strong></p>
<ol>
<li><code>urlsToWatch</code> scopes the blast radius: Graph and my tenant&rsquo;s SharePoint hosts. Everything else (storage, Azurite, the Durable task hub) passes through untouched - you want chaos in the APIs you&rsquo;re hardening against, not in your own plumbing.</li>
<li><code>GraphRandomErrorPlugin</code> fails 50% of matching requests, randomly picking from the errors I allow. Each 429 carries a real <code>Retry-After</code> header, just like Graph&rsquo;s.</li>
<li><code>RetryAfterPlugin</code> is the referee. It remembers every <code>Retry-After</code> it hands out, and if my app calls the same URL again too early, it logs a warning and throttles the request - exactly what Graph would do, except this referee tells you about it.</li>
<li>Order matters: <code>RetryAfterPlugin</code> must come <em>before</em> the error plugin in the list, or the request is already failed before the referee sees it.</li>
<li>On first run Dev Proxy installs a root certificate for you to trust, so it can intercept HTTPS. The Functions host picks it up from the machine store; a .NET app needs no code changes.</li>
</ol>
<h2 id="one-storm-three-claims-tested">One Storm, Three Claims Tested</h2>
<p>What I like about this setup is that a single chaotic run exercises most of the series at once.</p>
<p><strong>The retry ladder gets rungs pulled out.</strong> With 429/500/503 flying at 50%, every layer runs for real: the SDK handlers eat the 429s, the in-activity loops eat the semantic failures, and the orchestrator reruns whole activities when those give up. Watch the logs; every message you wrote for these paths prints for the first time.</p>
<p><strong>Idempotency stops being theoretical.</strong> <a href="https://jeppe-spanggaard.dk/blogs/durable-functions-idempotent-activities/">Every activity will run twice</a> was the claim; now they actually do. After the run completes, audit the tenant: one site, one of each list, no duplicated navigation nodes, no double-applied template artifacts. A rerun that creates a second anything is a bug you can now reproduce at will.</p>
<p><strong>Back-off gets policed.</strong> The one thing your own logs can&rsquo;t tell you is whether you retried <em>too eagerly</em>. That&rsquo;s the <code>RetryAfterPlugin</code> line to grep for:</p>
<pre tabindex="0"><code>Calling https://graph.microsoft.com/v1.0/sites/... again before waiting
for the Retry-After period. Request will be throttled
</code></pre><p>If that shows up, some code path ignores <code>Retry-After</code> - in my experience usually a hand-rolled retry around a call the SDK was already retrying.</p>
<h2 id="failing-deterministically">Failing Deterministically</h2>
<p>Random chaos proves the transient path. The permanent path needs the opposite: a specific endpoint that always fails. That&rsquo;s <code>GenericRandomErrorPlugin</code> with a rate of 100 and an errors file:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-json" data-lang="json"><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">&#34;errors&#34;</span>: [
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>      <span style="color:#f92672">&#34;request&#34;</span>: { <span style="color:#f92672">&#34;url&#34;</span>: <span style="color:#e6db74">&#34;https://contoso-admin.sharepoint.com/*&#34;</span> },
</span></span><span style="display:flex;"><span>      <span style="color:#f92672">&#34;responses&#34;</span>: [
</span></span><span style="display:flex;"><span>        { <span style="color:#f92672">&#34;statusCode&#34;</span>: <span style="color:#ae81ff">403</span> }
</span></span><span style="display:flex;"><span>      ]
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>  ]
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Now every call to the admin endpoint is a 403, and the <a href="https://jeppe-spanggaard.dk/blogs/durable-functions-permanent-vs-transient-failures/">permanent-vs-transient</a> claim is testable: the orchestration should fail in minutes with a clear error, not grind through the full retry ladder for half an hour bouncing off a wall. If you sit there watching attempt 7 of 10 against a guaranteed 403, you know which post to reread.</p>
<p>Dial the same technique the other way: <code>rate: 100</code> on a single endpoint with a 503 reproduces &ldquo;step four keeps dying&rdquo; as often as you need while debugging, something production will never do for you on demand.</p>
<h2 id="what-about-just-unit-testing-the-orchestrator">What About Just Unit Testing the Orchestrator?</h2>
<p>Fair question, and it&rsquo;s where I started. I don&rsquo;t, and the reason isn&rsquo;t laziness.</p>
<p>Unit testing a Durable orchestration in the isolated model means standing in for <code>TaskOrchestrationContext</code>, and that type is not built to be stood in for. You end up writing a mock that reimplements the runtime&rsquo;s scheduling semantics, and then you&rsquo;re mostly testing your mock. Every hour on that harness buys confidence about something you wrote, not about the thing Azure runs.</p>
<p>The question I actually care about is narrower: when Graph returns 429 six times in a row, does the run still end with exactly one site? That needs the real SDK, the real retry handlers, the real replay. A mock can&rsquo;t answer it, because the behaviour under test lives in precisely the parts you&rsquo;d be mocking out.</p>
<p>So the harness is the proxy, and the assertions are on the outcome rather than the call sequence. If you want unit tests here, put them on the activity bodies. Those are ordinary methods with ordinary inputs, and that&rsquo;s where the logic worth unit testing lives.</p>
<h2 id="gotchas">Gotchas</h2>
<ul>
<li><strong>Plugin order is load-bearing.</strong> <code>RetryAfterPlugin</code> before the error plugins, or it never sees a request and validates nothing. The docs flag this; it&rsquo;s still easy to miss.</li>
<li><strong>Batches fail like Graph batches.</strong> When Dev Proxy fails a sub-request inside a <code>$batch</code>, the batch returns <code>424 Failed Dependency</code>, matching real Graph behavior - so your batch response mapping gets tested too, not just single calls.</li>
<li><strong>A distrusted cert looks like a broken tenant.</strong> If the Dev Proxy root certificate isn&rsquo;t trusted, every intercepted call dies with TLS errors and your app looks catastrophically down. If literally everything fails instantly, check the cert before your code.</li>
<li><strong>Scope <code>urlsToWatch</code> tightly.</strong> Let the proxy fail token endpoints or your storage account and you&rsquo;re testing scenarios that don&rsquo;t exist. Chaos belongs on the APIs you claim to be resilient against.</li>
<li><strong>This is failure testing, not load testing.</strong> Surviving a 50% error rate says nothing about surviving a thousand concurrent provisionings. Different question, different tools.</li>
</ul>
<h2 id="wrapping-up">Wrapping Up</h2>
<p>Resilience code you&rsquo;ve never watched run is a hypothesis, not a feature. Dev Proxy turns &ldquo;Graph had a bad day&rdquo; into a repeatable local scenario: point the provisioning engine through it, inject 429s and 500s at a rate, and check that the run still lands with exactly one of everything. The series told you how the engine should behave; this is how you catch it lying.</p>
<p>That series starts with <a href="https://jeppe-spanggaard.dk/blogs/what-are-durable-functions/">Durable Functions: A Function That Sleeps for a Week</a> if you want the behaviour before the test harness.</p>
]]></content:encoded></item><item><title>Durable Functions Concurrency: Gate the Queue, Not the Host</title><link>https://jeppe-spanggaard.dk/blogs/durable-functions-concurrency-gate/</link><pubDate>Thu, 10 Sep 2026 00:00:00 +0000</pubDate><guid>https://jeppe-spanggaard.dk/blogs/durable-functions-concurrency-gate/</guid><description>Learn why host.json concurrency limits don't cap running Durable Functions orchestrations, and how a queue-level gate with deferred Service Bus messages does.</description><content:encoded><![CDATA[<p>A batch of customers landed on the queue at once. Every message got picked up, every message started an orchestration, and every orchestration began building a SharePoint site.</p>
<p>Then I watched them all crawl forward together. Site 1 finished step three. Site 2 finished step three. Site 40 finished step three. Nothing was stuck, nothing failed, and nothing <em>finished</em> either. The Durable runtime was faithfully round-robining between dozens of instances, one activity at a time, and the wall-clock distance from &ldquo;message arrives&rdquo; to &ldquo;customer has a site&rdquo; stretched out to something I&rsquo;d be embarrassed to put in a status mail.</p>
<p>The fix I reached for first was the obvious one. It&rsquo;s also the one that doesn&rsquo;t work.</p>
<h2 id="hostjson-limits-are-not-a-concurrency-limit">host.json Limits Are Not a Concurrency Limit</h2>
<p>My <code>host.json</code> already had this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-json" data-lang="json"><span style="display:flex;"><span><span style="color:#e6db74">&#34;extensions&#34;</span><span style="color:#960050;background-color:#1e0010">:</span> {
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">&#34;durableTask&#34;</span>: {
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&#34;maxConcurrentActivityFunctions&#34;</span>: <span style="color:#ae81ff">3</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&#34;maxConcurrentOrchestratorFunctions&#34;</span>: <span style="color:#ae81ff">5</span>
</span></span><span style="display:flex;"><span>  }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Five orchestrators. So at most five sites at a time, right?</p>
<p>Wrong. Those settings cap how many orchestrator and activity functions a worker holds <em>in memory</em> at once. An orchestration only occupies a slot while it&rsquo;s actually processing an event. The moment it awaits an activity, it unloads and stops counting. Microsoft&rsquo;s own performance guidance says it in one sentence: an orchestration that&rsquo;s waiting for an activity to finish doesn&rsquo;t count toward the throttle, and even millions of instances in <code>Running</code> state can sit there while only the ones in memory count.</p>
<p>My orchestrations spend nearly all their time awaiting activities that call SharePoint. So the effective limit on simultaneous site builds was: however many messages arrive. The throttle throttles episodes, not work.</p>
<p>The second half of the same doc page is worth having tattooed somewhere: concurrency throttles apply per worker and don&rsquo;t limit total system throughput. Even if the numbers did what I thought, they&rsquo;d only do it one instance at a time.</p>
<h2 id="the-throttling-you-dont-see">The Throttling You Don&rsquo;t See</h2>
<p>Here&rsquo;s the part that made this more than an impatience problem. Every one of those parallel site builds hits SharePoint as the same app registration, and SharePoint&rsquo;s application limits are counted per app per tenant across Graph, CSOM and REST together. Forty sites building at once is forty times the request rate against one bucket.</p>
<p>And I never saw a single 429. Not one. CSOM&rsquo;s retry helpers and the Graph client&rsquo;s retry handler both catch throttling responses, honour <code>Retry-After</code>, sleep, and try again. From the outside, that isn&rsquo;t an error, it&rsquo;s just slow. What I actually observed was retries climbing and durations stretching, which reads like &ldquo;SharePoint is having a bad day&rdquo; rather than &ldquo;I am the bad day&rdquo;.</p>
<p>That&rsquo;s the trap: the SDKs are good enough at absorbing throttling that you can be deep into it without a single failed request to point at. Microsoft&rsquo;s own first line of advice for avoiding it is &ldquo;reduce the number of concurrent requests&rdquo;, which is exactly the knob I thought <code>host.json</code> was giving me.</p>
<h2 id="the-durable-functions-concurrency-gate">The Durable Functions Concurrency Gate</h2>
<p>So the limit has to live where the work is <em>started</em>, not where it runs. The Service Bus subscriber asks a gate for permission before scheduling anything:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">internal</span> <span style="color:#66d9ef">async</span> Task&lt;<span style="color:#66d9ef">bool</span>&gt; HasCapacityAsync(DurableTaskClient client, CancellationToken cancellationToken = <span style="color:#66d9ef">default</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> query = <span style="color:#66d9ef">new</span> OrchestrationQuery {
</span></span><span style="display:flex;"><span>        Statuses = [OrchestrationRuntimeStatus.Running, OrchestrationRuntimeStatus.Pending],
</span></span><span style="display:flex;"><span>        InstanceIdPrefix = InstanceIdPrefix,
</span></span><span style="display:flex;"><span>        CreatedFrom = DateTimeOffset.UtcNow - LookbackWindow,
</span></span><span style="display:flex;"><span>        FetchInputsAndOutputs = <span style="color:#66d9ef">false</span>
</span></span><span style="display:flex;"><span>    };
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> cap = _settings.MaxConcurrentOrchestrations;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> active = <span style="color:#ae81ff">0</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Stop counting at the cap; never enumerate the full instance history.</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> <span style="color:#66d9ef">foreach</span> (<span style="color:#66d9ef">var</span> _ <span style="color:#66d9ef">in</span> client.GetAllInstancesAsync(query).WithCancellation(cancellationToken)) {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (++active &gt;= cap) {
</span></span><span style="display:flex;"><span>            logger.LogInformation(<span style="color:#e6db74">&#34;Provisioning at capacity ({Active}/{Cap} orchestrations active).&#34;</span>, active, cap);
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">false</span>;
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">true</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><strong>What&rsquo;s happening here?</strong></p>
<ol>
<li>The query counts instances that are actually occupying the system: <code>Running</code> and <code>Pending</code>. Completed, failed and terminated instances are irrelevant to capacity.</li>
<li><code>InstanceIdPrefix</code> is why the <a href="https://jeppe-spanggaard.dk/blogs/durable-functions-deterministic-instance-ids/">deterministic instance IDs</a> from the dedupe design pay off twice. Because every provisioning instance is named <code>provision-customer-{id}</code>, the prefix is a free filter that separates provisioning from every other orchestration in the task hub.</li>
<li><code>CreatedFrom</code> bounds the scan to the last seven days. The Azure Storage backend doesn&rsquo;t index instances by ID prefix, so without a time bound the count walks more history every week the app lives.</li>
<li>The loop returns the moment it reaches the cap. It&rsquo;s a &ldquo;do we have room&rdquo; question, not a &ldquo;how many are there&rdquo; question, and the cheap version of that answer is the one that stops counting early.</li>
<li><code>FetchInputsAndOutputs = false</code> keeps the payloads out of it. Nothing here needs to know what the orchestrations are doing.</li>
</ol>
<p>My cap is <strong>2</strong>, in config rather than in code, and two sites in parallel finish in about three minutes. That&rsquo;s the number that made the difference: two runs that <em>complete</em> beat forty that all progress.</p>
<h2 id="deferral-is-not-abandonment">Deferral Is Not Abandonment</h2>
<p>Being at capacity doesn&rsquo;t mean rejecting the message. It means putting it back with a delay:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">readonly</span> TimeSpan[] DeferDelays = [
</span></span><span style="display:flex;"><span>    TimeSpan.FromMinutes(<span style="color:#ae81ff">1</span>),
</span></span><span style="display:flex;"><span>    TimeSpan.FromMinutes(<span style="color:#ae81ff">2</span>),
</span></span><span style="display:flex;"><span>    TimeSpan.FromMinutes(<span style="color:#ae81ff">5</span>),
</span></span><span style="display:flex;"><span>    TimeSpan.FromMinutes(<span style="color:#ae81ff">10</span>)
</span></span><span style="display:flex;"><span>];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Publish-then-complete: caller must schedule the clone BEFORE completing the original.</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// A crash between the two leaves a harmless duplicate rather than a lost message.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">internal</span> <span style="color:#66d9ef">async</span> Task DeferAsync(ServiceBusReceivedMessage original, <span style="color:#66d9ef">int</span> deferCount, CancellationToken cancellationToken = <span style="color:#66d9ef">default</span>) {
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> delay = DeferDelays[Math.Min(deferCount, DeferDelays.Length - <span style="color:#ae81ff">1</span>)];
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> jitter = TimeSpan.FromSeconds(Random.Shared.Next(_settings.DeferJitterSeconds + <span style="color:#ae81ff">1</span>));
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> scheduledTime = DateTimeOffset.UtcNow.Add(delay).Add(jitter);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> clone = <span style="color:#66d9ef">new</span> ServiceBusMessage(original.Body) {
</span></span><span style="display:flex;"><span>        ContentType = original.ContentType,
</span></span><span style="display:flex;"><span>        Subject = original.Subject,
</span></span><span style="display:flex;"><span>        ScheduledEnqueueTime = scheduledTime
</span></span><span style="display:flex;"><span>    };
</span></span><span style="display:flex;"><span>    clone.ApplicationProperties[DeferCountProperty] = deferCount + <span style="color:#ae81ff">1</span>;
</span></span><span style="display:flex;"><span>    clone.ApplicationProperties[FirstSeenUtcProperty] = GetFirstSeenUtc(original).ToString(<span style="color:#e6db74">&#34;o&#34;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> _sender.ScheduleMessageAsync(clone, scheduledTime, cancellationToken);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Why a scheduled clone instead of abandoning the message? Because abandoning gives you Service Bus&rsquo;s redelivery schedule, which is seconds, and counts toward <code>MaxDeliveryCount</code>. A message that waits an hour for a slot would dead-letter itself on the broker&rsquo;s timetable rather than mine. Scheduling a fresh copy with <code>ScheduledEnqueueTime</code> means the wait is mine to define, and the delivery count never moves.</p>
<p>The delays escalate 1, 2, 5, 10 minutes and then hold at 10, with up to 30 seconds of jitter on top. The jitter is not decoration: without it, every message deferred in the same second wakes in the same second and stampedes the gate together, which is the same burst I was trying to prevent, just on a timer.</p>
<p>Two application properties ride along. <code>DeferCount</code> picks the next delay. <code>FirstSeenUtc</code> is copied across every bounce so the log line can say how long this customer has genuinely been waiting, not how long since the last hop.</p>
<p>And the ordering is deliberate: schedule the clone, <em>then</em> complete the original. Crash in between and you get a duplicate message, which the dedupe checks make a no-op. Do it the other way and a crash loses a customer&rsquo;s site request entirely.</p>
<h2 id="gotchas">Gotchas</h2>
<ul>
<li><strong>The cap is soft.</strong> The instances query is eventually consistent, so two workers can both pass the gate at the same moment. Occasional N+1 is fine and expected. If you need an exact count, a Durable entity acting as a semaphore is the tool, and it costs you a lot more moving parts.</li>
<li><strong>Gate last, after the dedupe checks.</strong> A redelivered message for a customer that already has a site should short-circuit, not queue up for a slot it will never need.</li>
<li><strong>There is no deadline, on purpose.</strong> A message with no free slot waits indefinitely. Any age limit would eventually dead-letter customers whose only crime was arriving late in a backlog, and a large bulk run legitimately takes days at a cap of two.</li>
<li><strong>A wedged instance eats a slot forever.</strong> One orchestration stuck in <code>Running</code> permanently reduces the cap, and with no deadline the queue behind it just waits. Alert on deferral volume and on the oldest <code>FirstSeenUtc</code>, because nothing else will surface it - the same <a href="https://jeppe-spanggaard.dk/blogs/durable-functions-failed-orchestration-alert/">log search alert</a> that catches failed orchestrations is where those queries belong.</li>
<li><strong>FIFO is gone.</strong> A deferred message is completed and republished, so it gets a new sequence number and loses its place in line. Harmless when customers are independent of each other. Not harmless if something downstream assumes order.</li>
</ul>
<h2 id="wrapping-up">Wrapping Up</h2>
<p><code>maxConcurrentOrchestratorFunctions</code> sounds like a concurrency cap and isn&rsquo;t one: it limits orchestrator episodes in memory per worker, and an orchestration waiting on an activity doesn&rsquo;t count. If you need &ldquo;only N of these at a time&rdquo;, the only place to enforce it is before the orchestration is scheduled. Count the non-terminal instances by prefix, and when you&rsquo;re full, hand the message back to the queue with a future delivery time and some jitter. Rule of thumb: throttle where work is admitted, not where it runs.</p>
]]></content:encoded></item><item><title>The Site Exists, Graph Says 404: Eventual Consistency in Provisioning</title><link>https://jeppe-spanggaard.dk/blogs/sharepoint-graph-eventual-consistency-404/</link><pubDate>Sat, 05 Sep 2026 00:00:00 +0000</pubDate><guid>https://jeppe-spanggaard.dk/blogs/sharepoint-graph-eventual-consistency-404/</guid><description>Learn how to handle Microsoft Graph 404s on freshly created SharePoint sites with layered retries instead of one giant retry hammer.</description><content:encoded><![CDATA[<p>My provisioning engine had just created a SharePoint site. I could open it in the browser. Title rendered, default library in place, everything fine.</p>
<p>The very next line of code asked Microsoft Graph for that site&rsquo;s ID.</p>
<ol start="404">
<li>Not found.</li>
</ol>
<p>I created you <em>two seconds ago</em>. I&rsquo;m looking at you. And Graph, with a straight face: no such site.</p>
<p>Welcome to eventual consistency between SharePoint and Graph. The site creation goes through CSOM against SharePoint directly; the ID lookup goes through Graph, which has its own view of the world that updates on its own schedule. For a freshly created site, that schedule can lag from seconds to a couple of minutes. Your code sits exactly in that gap.</p>
<h2 id="the-loop">The Loop</h2>
<p>This runs at the end of my site creation activity, after the site exists in SharePoint:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">private</span> <span style="color:#66d9ef">async</span> Task&lt;<span style="color:#66d9ef">string</span>&gt; ResolveGraphSiteIdWithRetryAsync(<span style="color:#66d9ef">string</span> siteUrl)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> uri = <span style="color:#66d9ef">new</span> Uri(siteUrl);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> serverRelativePath = uri.AbsolutePath.TrimStart(<span style="color:#e6db74">&#39;/&#39;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> siteIdentifier = <span style="color:#e6db74">$&#34;{uri.Host}:/{serverRelativePath}&#34;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">const</span> <span style="color:#66d9ef">int</span> maxAttempts = <span style="color:#ae81ff">8</span>;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> delay = TimeSpan.FromSeconds(<span style="color:#ae81ff">10</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">for</span> (<span style="color:#66d9ef">int</span> attempt = <span style="color:#ae81ff">1</span>; attempt &lt;= maxAttempts; attempt++)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">try</span>
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">var</span> site = <span style="color:#66d9ef">await</span> graphClient.Sites[siteIdentifier].GetAsync();
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> site?.Id
</span></span><span style="display:flex;"><span>                ?? <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> InvalidOperationException(<span style="color:#e6db74">$&#34;Graph returned null site ID for {siteUrl}&#34;</span>);
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">catch</span> (ODataError ex) when (ex.ResponseStatusCode == <span style="color:#ae81ff">404</span> &amp;&amp; attempt &lt; maxAttempts)
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// Site not yet indexed in Graph - wait and retry</span>
</span></span><span style="display:flex;"><span>            logger.LogInformation(
</span></span><span style="display:flex;"><span>                <span style="color:#e6db74">&#34;Graph site not found yet (attempt {Attempt}/{Max}), retrying in {Delay}s...&#34;</span>,
</span></span><span style="display:flex;"><span>                attempt, maxAttempts, delay.TotalSeconds);
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">await</span> Task.Delay(delay);
</span></span><span style="display:flex;"><span>            delay = TimeSpan.FromSeconds(Math.Min(delay.TotalSeconds * <span style="color:#ae81ff">1.5</span>, <span style="color:#ae81ff">60</span>));
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> InvalidOperationException(<span style="color:#e6db74">$&#34;Could not resolve Graph site ID for {siteUrl} after {maxAttempts} attempts.&#34;</span>);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><strong>What&rsquo;s happening here?</strong></p>
<ol>
<li>The site is addressed as <code>{hostname}:/sites/{alias}</code> - Graph&rsquo;s path-based site addressing, so no ID is needed to ask for the ID. The thing it hands back is the composite <code>{hostname},{siteCollectionId},{webId}</code> form, three parts comma-joined, which is why you can&rsquo;t just build one yourself: two of the three are GUIDs with no relationship to the URL.</li>
<li>The <code>catch</code> filter is deliberately narrow: <code>ODataError</code> <em>and</em> status 404 <em>and</em> attempts remaining. A 403 means permissions and should fail now. A 401 means auth and should fail now. Only &ldquo;not found&rdquo; means &ldquo;not found <em>yet</em>&rdquo;.</li>
<li>Backoff starts at 10 seconds and multiplies by 1.5 with a 60-second cap: 10, 15, 22, 34, 51, 60, 60. Eight attempts covers about four minutes, which in practice covers the Graph indexing lag with room to spare.</li>
<li>When the loop gives up, it throws an ordinary exception, and something interesting happens one level up. More on that next.</li>
</ol>
<h2 id="three-layers-of-retry-three-different-jobs">Three Layers of Retry, Three Different Jobs</h2>
<p>This loop lives inside a Durable Functions activity that already has retries around and below it. It took me a while to see these as separate tools rather than redundant paranoia, so here&rsquo;s the layer map:</p>
<p><strong>Layer 1: the HTTP pipeline.</strong> The Graph SDK&rsquo;s Kiota handlers honor <code>Retry-After</code> on 429s; my CSOM calls go through PnP&rsquo;s <code>ExecuteQueryRetry</code>, which does the same for SharePoint throttling. This layer retries <em>individual requests</em> over seconds. It handles &ldquo;you&rsquo;re going too fast&rdquo;.</p>
<p><strong>Layer 2: in-activity loops like the one above.</strong> This layer knows the <em>semantics</em> of the operation. No HTTP handler can know that a 404 right after site creation means &ldquo;wait&rdquo;, while a 404 anywhere else means &ldquo;broken&rdquo;. Only code that knows a create just happened can decide that. Seconds to minutes, single operation.</p>
<p><strong>Layer 3: the orchestrator&rsquo;s retry policy.</strong> Every activity call gets 10 attempts with exponential backoff from 5 seconds to 5 minutes. This layer retries <em>whole activities</em>, which is why the loop&rsquo;s final throw is a plain <code>InvalidOperationException</code>: if four minutes of polite waiting wasn&rsquo;t enough, the orchestrator reruns the entire activity. The rerun finds the site already exists, skips creation, and effectively buys the resolution another eight attempts, minutes later. The layers compose.</p>
<p>The failure mode to avoid is collapsing these into one: cranking the orchestrator policy to 30 attempts because &ldquo;Graph is flaky&rdquo;. Then every genuine failure, including permanent config errors, grinds through half an hour of retries, and you still haven&rsquo;t expressed the one thing you actually knew - that a 404 after a create is expected.</p>
<p>Each layer catches what it can <em>name</em>. The HTTP layer names status codes. The activity names operations. The orchestrator names steps.</p>
<h2 id="naming-things-reading-a-graph-sdk-exception">Naming Things: Reading a Graph SDK Exception</h2>
<p>All of that depends on the middle layer being able to tell a 404 from a 403, so it&rsquo;s worth spelling out where <code>ex.ResponseStatusCode</code> in that catch filter comes from. Most of the advice you&rsquo;ll find online is written against a type that no longer exists: SDK v5 replaced <code>ServiceException</code> with <code>ODataError</code>.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">catch</span> (ODataError ex)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> status = ex.ResponseStatusCode;   <span style="color:#75715e">// 404, 403, 401...</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> code   = ex.Error?.Code;          <span style="color:#75715e">// &#34;itemNotFound&#34;, &#34;accessDenied&#34;</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> msg    = ex.Error?.Message;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> inner  = ex.Error?.InnerError;    <span style="color:#75715e">// request-id and date, for support tickets</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Status code for control flow, <code>Error?.Code</code> when two failures share a status and you need to tell them apart, and <code>InnerError</code> for the request ID that support will ask for.</p>
<h2 id="its-not-just-site-ids">It&rsquo;s Not Just Site IDs</h2>
<p>The same lag shows up one step later in my pipeline, wearing a different costume. After the site exists, an activity pulls content types from the content type hub. On a fresh site, that pull can fail with a transient HTTP 400, or report success while the content types take their time actually appearing - and a missing content type breaks the PnP template apply that comes after, because child content types have no parent to inherit from.</p>
<p>The pattern there is verify-then-escalate: after requesting the pull, the activity polls for each content type&rsquo;s presence with a short bounded backoff. Genuinely present: done. Still missing after the window: throw a transient error so the orchestrator retries the <em>whole pull</em>, since a content type that never got pulled won&rsquo;t appear no matter how long you stare at it.</p>
<p>There&rsquo;s a 503-shaped sibling worth recognising too:</p>
<pre tabindex="0"><code>Microsoft.Graph.Models.ODataErrors.ODataError: The underlying service is
experiencing a high load and is unable to fulfill your request. Please retry
after a brief backoff period.
</code></pre><p>Same treatment as the 404: transient, retry it. The catch is that this one asks you to back off without telling you how long - there&rsquo;s no <code>Retry-After</code> header to honour, so the Kiota retry handlers have nothing to work with and the delay has to come from your own code. Layer 2&rsquo;s job again.</p>
<p>Same philosophy as the 404 loop, different escalation point. Wait briefly for the thing that&rsquo;s probably coming; retry the operation that produces it if it demonstrably isn&rsquo;t. What you never get to do is assume that &ldquo;the API returned success&rdquo; and &ldquo;the resource is usable&rdquo; happen at the same time. In Microsoft 365 provisioning, they&rsquo;re separated by an index, a cache, or a queue you can&rsquo;t see.</p>
<h2 id="gotchas">Gotchas</h2>
<ul>
<li><strong>Bound every wait.</strong> Every retry loop in the engine has a max attempt count and a delay cap, and the activity level has the orchestrator&rsquo;s policy above it as a final bound. An unbounded &ldquo;wait until it appears&rdquo; loop is an outage with extra steps.</li>
<li><strong><code>Task.Delay</code> is fine here, in an activity.</strong> In an <em>orchestrator</em> function it would be a determinism violation - there you&rsquo;d use <code>context.CreateTimer</code>. Activities are plain code; orchestrators replay. Know which kind of function you&rsquo;re standing in before you sleep.</li>
<li><strong>Log the attempt number and the delay.</strong> &ldquo;Graph site not found yet (attempt 3/8), retrying in 22s&rdquo; in the logs turns a scary multi-minute silence into a visible, healthy process. My first version logged nothing and I spent an evening convinced the function was hung.</li>
<li><strong>Don&rsquo;t cache your way around it.</strong> My first instinct was to compute the Graph site ID from the URL format and skip the lookup. Tempting, but the composite ID contains GUIDs you can&rsquo;t derive, and half-guessed IDs fail later in worse places. Wait for the real one.</li>
<li><strong>The lag varies wildly.</strong> Dev tenant: usually under 15 seconds. Production tenant under load: I&rsquo;ve seen over two minutes. Tune <code>maxAttempts</code> for the worst tenant you serve, not the one on your laptop.</li>
</ul>
<h2 id="wrapping-up">Wrapping Up</h2>
<p>A 404 immediately after a create isn&rsquo;t an error, it&rsquo;s a timestamp - proof you&rsquo;re faster than the index. Catch exactly that case in a narrow, bounded, backing-off loop inside the activity, and leave throttling to the HTTP layer and rerun-the-step to the orchestrator. Retry layers work when each one handles only what it can name.</p>
<p>The &ldquo;rerun the step&rdquo; half of that sentence is the orchestrator&rsquo;s job, and <a href="https://jeppe-spanggaard.dk/blogs/what-are-durable-functions/">Durable Functions: A Function That Sleeps for a Week</a> explains why it can be trusted with it.</p>
]]></content:encoded></item><item><title>Failed Durable Functions Runs: One KQL Alert, No Code</title><link>https://jeppe-spanggaard.dk/blogs/durable-functions-failed-orchestration-alert/</link><pubDate>Sun, 30 Aug 2026 00:00:00 +0000</pubDate><guid>https://jeppe-spanggaard.dk/blogs/durable-functions-failed-orchestration-alert/</guid><description>Learn how to get notified about failed Durable Functions orchestrations with a KQL log search alert in Application Insights, instead of writing watchdog code.</description><content:encoded><![CDATA[<p>I&rsquo;m in the middle of a bulk provisioning run: a queue message per new customer, one Durable Functions orchestration per site, more than 10,000 sites to create. Three of them have failed.</p>
<p>I know that because I&rsquo;ve been opening the portal several times a day and looking. There&rsquo;s a customer deadline on this run, and if the failures turn out to be a pattern rather than three unlucky sites, I want to stop the whole thing before it creates 9,000 more. So I check. Manually. Like a night watchman without a bell.</p>
<p>Three failures out of ten thousand is a rounding error until it&rsquo;s the three sites belonging to the customer who calls.</p>
<h2 id="a-failed-orchestration-tells-nobody">A Failed Orchestration Tells Nobody</h2>
<p>Here&rsquo;s the thing that makes this harder than it sounds: nothing surfaces a failed orchestration on its own.</p>
<p>My orchestrator wraps the whole run so a failure gets written to the status list before it propagates:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">private</span> <span style="color:#66d9ef">async</span> Task&lt;ProvisioningContext&gt; ExecuteProvisioning(Func&lt;Task&lt;ProvisioningContext&gt;&gt; action)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span>
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">await</span> action();
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">catch</span> (Exception ex)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        _logger.LogError(ex, <span style="color:#e6db74">&#34;Provisioning failed.&#34;</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Try to update status, but never let a status-update failure mask the original error.</span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">try</span>
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">await</span> TryUpdateStatus(errorMessage: ex.Message);
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">catch</span> (Exception statusEx)
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            _logger.LogWarning(statusEx, <span style="color:#e6db74">&#34;Failed to update status after provisioning error.&#34;</span>);
</span></span><span style="display:flex;"><span>        }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">throw</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>That bare <code>throw;</code> is the load-bearing line. Because the exception isn&rsquo;t swallowed, the instance ends in runtime status <code>Failed</code> instead of quietly finishing as <code>Completed</code> with half a site behind it. Good. But <code>Failed</code> is a row in a storage table and a red badge in a tool nobody has open at 21:00.</p>
<p>And getting there takes a while. Every activity call runs under a retry policy of 10 attempts with exponential backoff from 5 seconds up to 5 minutes, so an activity that can&rsquo;t succeed spends roughly 25 minutes failing before the orchestration is allowed to give up. The hub association step is the reigning champion: <code>JoinHubSite</code> can return 200 and silently do nothing on a freshly created site, so the activity reads the association back and throws a plain <code>InvalidOperationException</code> when it didn&rsquo;t stick. Plain, on purpose, because that one usually <em>is</em> transient. It gets all ten attempts before the orchestration dies. If you want the other half of that story, <a href="https://jeppe-spanggaard.dk/blogs/durable-functions-permanent-vs-transient-failures/">permanent versus transient failures</a> is about which exceptions deserve the full ten.</p>
<p>So the failure is real, it&rsquo;s slow, and it&rsquo;s silent. I needed the bell.</p>
<h2 id="three-ways-to-get-told-and-why-i-picked-the-boring-one">Three Ways to Get Told, and Why I Picked the Boring One</h2>
<p>I had three options on the table.</p>
<p><strong>Publish an Event Grid event when the orchestration fails.</strong> I already run Event Grid in this solution, so the plumbing exists. But it means code in the failure path, a new event type, a subscriber, and a deployment. And every time I want the notification to say something slightly different, that&rsquo;s another deployment.</p>
<p><strong>A timer-triggered watchdog.</strong> A function that wakes up every N minutes, queries the instance table for anything in <code>Failed</code>, and shouts. Also code, also a deployment, plus its own state to remember what it already shouted about. Now I have two things to monitor: the pipeline and the thing watching the pipeline.</p>
<p><strong>A log search alert in Application Insights.</strong> No code at all. The Durable Functions extension already writes lifecycle events for every orchestration, and I already have an action group wired up for this customer&rsquo;s other alerts. Write a KQL query, point an alert rule at it, done.</p>
<p>I picked the third one, and the deciding argument wasn&rsquo;t elegance. It was that I bill by the hour. The alert costs about $1.50 a month; writing and deploying either of the other two costs more than that in the first fifteen minutes, and then keeps costing every time it needs a tweak. The KQL, by contrast, I can widen tomorrow, from the portal, without touching the function app.</p>
<p>The two code options are better if you need the failure to <em>do</em> something automatically. Mine only needs to reach a human.</p>
<h2 id="durable-functions-already-logs-every-failure">Durable Functions Already Logs Every Failure</h2>
<p>The reason no code is needed: the Durable extension emits tracking events to Application Insights for every lifecycle transition, under the log category <code>Host.Triggers.DurableTask</code>. They land in the <code>traces</code> table, and everything useful is hiding in <code>customDimensions</code> behind a <code>prop__</code> prefix.</p>
<p>This is the query behind the alert:</p>
<pre tabindex="0"><code class="language-kusto" data-lang="kusto">traces
| where customDimensions.Category == &#34;Host.Triggers.DurableTask&#34;
| extend functionName = tostring(customDimensions[&#34;prop__functionName&#34;])
| extend functionType = tostring(customDimensions[&#34;prop__functionType&#34;])
| extend instanceId   = tostring(customDimensions[&#34;prop__instanceId&#34;])
| extend state        = tostring(customDimensions[&#34;prop__state&#34;])
| extend reason       = tostring(customDimensions[&#34;prop__reason&#34;])
| extend isReplay     = tobool(tolower(customDimensions[&#34;prop__isReplay&#34;]))
| where isReplay != true
| where functionType == &#34;Orchestrator&#34; and state == &#34;Failed&#34;
| project timestamp, functionName, instanceId, reason, appName = cloud_RoleName
</code></pre><p><strong>What&rsquo;s happening here?</strong></p>
<ol>
<li>The category filter is the whole trick. <code>Host.Triggers.DurableTask</code> is the extension&rsquo;s own channel, separate from anything my code logs, so the query keeps working no matter how I change my own logging.</li>
<li>The <code>extend</code> block lifts the tracking fields out of the dynamic <code>customDimensions</code> bag and casts them to strings. Without <code>tostring</code>, comparisons against dynamic values get weird in ways that cost you an afternoon.</li>
<li><code>isReplay != true</code> drops replayed history. Orchestrators replay their execution constantly, so without this filter a single failure can produce the same tracking event more than once, and your alert email count stops meaning anything. I wrote it in defensively from the start rather than learning it the fun way.</li>
<li><code>functionType == &quot;Orchestrator&quot;</code> is the difference between &ldquo;a run failed&rdquo; and &ldquo;an attempt failed&rdquo;. Activities emit <code>Failed</code> events too, and with a 10-attempt retry policy a perfectly healthy orchestration produces a pile of them on the way to succeeding. Filter to the orchestrator and you get one row per genuinely dead run.</li>
<li><code>reason</code> carries the error details, so the alert email arrives with the instance ID and the actual message. That&rsquo;s the difference between &ldquo;go look&rdquo; and &ldquo;here&rsquo;s what broke&rdquo;.</li>
</ol>
<h2 id="the-alert-rule-setting-by-setting">The Alert Rule, Setting by Setting</h2>
<p>Nothing exotic, and that&rsquo;s the point:</p>
<ul>
<li><strong>Signal name:</strong> Custom log search</li>
<li><strong>Query type:</strong> Aggregated logs</li>
<li><strong>Measure:</strong> Table rows, <strong>Aggregation type:</strong> Count, <strong>Aggregation granularity:</strong> 5 minutes</li>
<li><strong>Threshold type:</strong> Static, <strong>Operator:</strong> Greater than, <strong>Threshold value:</strong> 0</li>
<li><strong>Frequency of evaluation:</strong> 5 minutes</li>
</ul>
<p>Static threshold, not dynamic. Dynamic thresholds learn a baseline and alert on deviation, which is the right tool for something with a natural rhythm. The natural rhythm of failed provisioning runs is zero. Any row is an incident, not an anomaly.</p>
<p>Threshold <code>0</code> on row count with a 5-minute window means &ldquo;tell me about the first one&rdquo;, which is exactly what I want during a bulk run. Three failures out of ten thousand is fine. Three failures in ten minutes means the hub is down and I should stop the queue.</p>
<p>The action group sends mail to me and to the customer&rsquo;s IT department. That second recipient changed how I write the alert description: it has to make sense to someone who has never seen a task hub. The description says what failed, where the instance ID can be looked up, and who does what next.</p>
<h2 id="why-would-the-alert-miss-a-failure-sampling">Why Would the Alert Miss a Failure? Sampling.</h2>
<p>Application Insights samples telemetry under load, and <code>traces</code> is sampled by default. A high-volume run producing thousands of lifecycle events per minute is exactly the situation where sampling starts dropping rows - including, possibly, the one you&rsquo;re alerting on.</p>
<p>This is also the answer to the more general complaint that Azure Functions invocation logs go missing sometimes, or that App Insights alerts miss exceptions that definitely happened. The telemetry isn&rsquo;t lost because something broke; it was sampled out, and sampling gets more aggressive precisely when things are busiest. Which is when you need it.</p>
<p>If your run is that noisy, look at <code>samplingSettings</code> in <code>host.json</code> before you trust the alert. Raising <code>maxTelemetryItemsPerSecond</code> or excluding types from sampling is a one-line change, and the Azure Functions monitoring docs spell out the trade-off. The uncomfortable part is that an alert built on sampled data fails silently: you don&rsquo;t get a wrong answer, you get no answer, which looks identical to nothing having gone wrong.</p>
<h2 id="gotchas">Gotchas</h2>
<ul>
<li><strong>Failed is not the only bad ending.</strong> An orchestration stuck in <code>Running</code> never emits a <code>Failed</code> event, so this alert says nothing about it. With retries nested inside HTTP-level retries, a single activity can hold a run open for a long time and look perfectly healthy. If that&rsquo;s a risk for you, a second alert on orchestration duration is the companion piece.</li>
<li><strong>Alert on the orchestrator, not the activity.</strong> I cannot stress this one enough. Drop the <code>functionType</code> filter and your retry policy becomes a mailing list. Every attempt under <code>CallActivityWithRetryAsync</code> (or <code>CallActivityAsync</code> with retry options) logs its own <code>Failed</code> event, so one healthy orchestration that recovers on attempt four has already emitted three of them.</li>
<li><strong><code>isReplay</code> is not optional.</strong> Replay is normal behaviour, not a fault, and the same lifecycle event can show up more than once without that filter.</li>
<li><strong>A threshold of zero only works if failures are rare.</strong> Mine are. If yours are routine, raise the threshold and treat the alert as a rate detector instead, or you&rsquo;ll train yourself to archive the mail unread.</li>
<li><strong>The alert is detection, not remediation.</strong> Getting the mail is step one. Knowing what to do with a <code>Failed</code> instance, and whether a rerun is safe, is a separate problem that <a href="https://jeppe-spanggaard.dk/blogs/durable-functions-idempotent-activities/">idempotent activities</a> exist to make answerable.</li>
</ul>
<h2 id="wrapping-up">Wrapping Up</h2>
<p>A failed Durable Functions orchestration is loud in the storage table and silent everywhere a human looks. The Durable extension already logs every lifecycle transition to Application Insights, so the cheapest possible monitor is a KQL query over <code>traces</code> filtered to non-replay orchestrator events in state <code>Failed</code>, wired to an action group you already own. Rule of thumb: before you write a watchdog, check whether the thing you want to watch is already logging it. Mine was, and the difference between knowing and not knowing cost me $1.50 a month.</p>
<p>New to this corner of Azure? <a href="https://jeppe-spanggaard.dk/blogs/what-are-durable-functions/">Durable Functions: A Function That Sleeps for a Week</a> is where the rest of this series starts.</p>
]]></content:encoded></item><item><title>Stop Retrying the Unretryable: Permanent Failures in Durable Functions</title><link>https://jeppe-spanggaard.dk/blogs/durable-functions-permanent-vs-transient-failures/</link><pubDate>Tue, 25 Aug 2026 00:00:00 +0000</pubDate><guid>https://jeppe-spanggaard.dk/blogs/durable-functions-permanent-vs-transient-failures/</guid><description>Learn how to build a Durable Functions retry policy based on exception type, so permanent errors short-circuit instead of burning every retry attempt.</description><content:encoded><![CDATA[<p>I watched my provisioning orchestration retry an activity ten times over roughly 25 minutes.</p>
<p>The error? An invalid site type string in the provisioning schema. A config mistake. Attempt one failed with &ldquo;unknown site type&rdquo;. So did attempt two, five seconds later. And attempt three, ten seconds after that. Exponential backoff dutifully stretched the intervals to five minutes while the outcome stayed exactly as impossible as it was at second zero.</p>
<p>Retrying a throttled request is smart. Retrying a typo is just failing slowly.</p>
<h2 id="retry-policies-dont-read-exceptions">Retry Policies Don&rsquo;t Read Exceptions</h2>
<p>My orchestrator calls every activity with the same retry options: 10 attempts, exponential backoff from 5 seconds up to 5 minutes. That&rsquo;s the right shape for what the policy is there for - SharePoint throttling, Graph hiccups, the occasional 503. Transient stuff.</p>
<p>But <code>RetryPolicy</code> is blunt. Timeout? Retry. HTTP 429? Retry. &ldquo;The site type &lsquo;TeamSiet&rsquo; does not exist&rdquo;? Retry, obviously, maybe the spelling will heal.</p>
<p>The fix has two halves: activities that <em>know</em> when they&rsquo;ve hit a wall, and an orchestrator that listens.</p>
<h2 id="half-one-activities-declare-permanence">Half One: Activities Declare Permanence</h2>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#75715e">/// &lt;summary&gt;</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">/// Thrown by activities to signal a non-transient failure that should NOT be retried.</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">/// Examples: invalid configuration, illegal site name, missing required fields.</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">/// The orchestrator inspects this to short-circuit the retry policy.</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">/// &lt;/summary&gt;</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">PermanentProvisioningException</span> : Exception
</span></span></code></pre></div><p>Activities throw it exactly where a retry can&rsquo;t help: an unknown site type in the schema, a hub site ID that isn&rsquo;t a valid GUID, a PnP template file that doesn&rsquo;t exist at the configured path. These are all &ldquo;fix the config and start over&rdquo; failures. No amount of waiting turns a missing file into a present one.</p>
<p>Everything else - network faults, throttling, SharePoint having a moment - throws ordinary exceptions and rides the retry policy as designed.</p>
<h2 id="half-two-the-orchestrator-listens">Half Two: The Orchestrator Listens</h2>
<p>Every activity call goes through a wrapper instead of calling <code>CallActivityAsync</code> raw:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#75715e">/// &lt;summary&gt;</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">/// Calls an activity with retry options, but short-circuits immediately for permanent failures.</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">/// Durable Functions&#39; built-in RetryPolicy retries ALL exceptions; this wrapper inspects the</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">/// inner exception and re-throws immediately if it&#39;s a PermanentProvisioningException.</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">/// &lt;/summary&gt;</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">private</span> <span style="color:#66d9ef">async</span> Task CallActivitySafeAsync(<span style="color:#66d9ef">string</span> activityName, <span style="color:#66d9ef">object</span> input)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">try</span>
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">await</span> context.CallActivityAsync(activityName, input, ActivityRetryOptions);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">catch</span> (TaskFailedException ex) when (IsPermanentFailure(ex))
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> PermanentProvisioningException(
</span></span><span style="display:flex;"><span>            <span style="color:#e6db74">$&#34;Activity &#39;{activityName}&#39; failed with a non-retryable error: {ex.InnerException?.Message ?? ex.Message}&#34;</span>,
</span></span><span style="display:flex;"><span>            ex);
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>And the detection, which is where the real lesson lives:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">bool</span> IsPermanentFailure(TaskFailedException ex)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Check if the activity explicitly signaled a permanent failure</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (ex.InnerException <span style="color:#66d9ef">is</span> PermanentProvisioningException)
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">true</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Also check the failure details for the exception type name, since</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Durable Functions may serialize/deserialize across process boundaries.</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> details = ex.FailureDetails;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (details?.ErrorType?.Contains(nameof(PermanentProvisioningException), StringComparison.Ordinal) == <span style="color:#66d9ef">true</span>)
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">true</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">false</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><strong>What&rsquo;s happening here?</strong></p>
<ol>
<li>Activity failures surface in the orchestrator as <code>TaskFailedException</code>, with the original error wrapped inside.</li>
<li>The first check is the obvious one: is the inner exception our permanent type?</li>
<li>The second check is the one you&rsquo;d never write until it bites you. In the isolated worker model, the activity&rsquo;s exception is serialized when it crosses from the worker process back to the host and into orchestration history. What you get back is not necessarily your exception instance - sometimes all that survives is <code>FailureDetails</code> with the type name as a string. So the check falls back to matching <code>ErrorType</code> textually. If you see <code>Failed to deserialize exception from TaskActivity</code> in the logs, that&rsquo;s the same boundary telling you out loud what it usually does quietly. In the in-process model the shape is the same with different names: the wrapper is <code>FunctionFailedException</code>, and its <code>InnerException</code> arrives as a plain <code>System.Exception</code> rather than your type, which is why <code>catch (MyException)</code> never fires there either.</li>
<li>When either check hits, the wrapper rethrows as a fresh <code>PermanentProvisioningException</code> and the orchestration fails right now, with a message naming the activity, instead of 25 minutes from now.</li>
</ol>
<p>If you only take one thing from this post: <strong>an exception that crosses the Durable Functions process boundary is not guaranteed to arrive as its original type.</strong> Any design that relies on <code>catch (MySpecificException)</code> around <code>CallActivityAsync</code> needs the string-based fallback, or it will silently degrade into retry-everything.</p>
<p>Wait, doesn&rsquo;t <code>RetryPolicy</code> have a handle-callback for this? The in-process model had <code>RetryOptions.Handle</code>; in the isolated model the equivalent is a retry handler reading <code>RetryContext.LastFailure</code>, where <code>IsCausedBy&lt;T&gt;()</code> does the type test for you. That shape has been shakier across versions, and even where the callback exists you&rsquo;re inspecting the same serialized <code>FailureDetails</code> anyway. I went with the explicit wrapper: it&rsquo;s boring, it&rsquo;s visible in the call path, and it works the same on every version I&rsquo;ve touched.</p>
<p>Worth naming the in-process spelling too, since most samples you&rsquo;ll find use it: <code>CallActivityWithRetryAsync</code> is the same call as <code>CallActivityAsync(name, input, retryOptions)</code> here. If your retry policy appears to do nothing at all, this section is usually why - the policy is running fine, your <code>catch</code> just never matches, so every attempt burns.</p>
<h2 id="the-inverse-trick-throwing-to-request-a-retry">The Inverse Trick: Throwing to Request a Retry</h2>
<p>Once permanent and transient failures are distinct, activities can use exceptions the other way around: throw a deliberately <em>transient</em> exception to ask for a rerun.</p>
<p>My property bag activity writes values to a fresh site, then reads them back, because SharePoint occasionally accepts the write and forgets it. When verification fails:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> InvalidOperationException(
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">$&#34;Property bag verification failed on {siteUrl}. &#34;</span> +
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;Values did not persist to the server; retrying the activity.&#34;</span>);
</span></span></code></pre></div><p>Plain <code>InvalidOperationException</code>, on purpose. It doesn&rsquo;t match the permanent check, so the retry policy picks it up and reruns the activity, which rewrites and reverifies. The exception type has become a control channel: permanent means &ldquo;stop, a human needs to fix input&rdquo;, everything else means &ldquo;run me again&rdquo;.</p>
<p>That&rsquo;s the whole taxonomy. Two kinds of failure, one bit of information, and the activity is the only place with enough context to set that bit. The orchestrator can&rsquo;t know whether a 500 from SharePoint is a fluke or a doomed request - but the activity that built the request usually can.</p>
<h2 id="gotchas">Gotchas</h2>
<ul>
<li><strong>Fail fast still means fail loudly.</strong> When the wrapper short-circuits, my orchestrator writes the error message to the provisioning status list before rethrowing, so the person who typo&rsquo;d the schema sees &ldquo;unknown site type&rdquo; next to the customer row instead of finding a generic failed instance in the portal a day later.</li>
<li><strong>Be stingy with permanence.</strong> Marking a failure permanent when it&rsquo;s actually transient is worse than the reverse: the reverse wastes 25 minutes, but a wrong permanent verdict kills runs that would have succeeded. When in doubt, let it retry.</li>
<li><strong><code>ErrorType</code> matching should use the exception&rsquo;s name, via <code>nameof</code>.</strong> Hardcoding the string invites drift when the class gets renamed; <code>nameof(PermanentProvisioningException)</code> keeps the match and the type in lockstep.</li>
<li><strong><code>maxNumberOfAttempts</code> counts the first call.</strong> Ten attempts means the original plus nine retries, not ten retries. Set it to 1 and you have disabled retries entirely - which is a perfectly good way to convince yourself the final retry &ldquo;never executes&rdquo;.</li>
<li><strong>Don&rsquo;t forget the sub-orchestration case.</strong> If you split into sub-orchestrations later, the same wrapping applies to <code>CallSubOrchestratorAsync</code> - permanent failures need to propagate up through every layer that has a retry policy, or one layer&rsquo;s policy will happily retry another layer&rsquo;s typo.</li>
</ul>
<h2 id="wrapping-up">Wrapping Up</h2>
<p>A retry policy without a permanent-failure escape hatch turns config errors into slow-motion failures. Give activities an exception type that means &ldquo;never retry this&rdquo;, short-circuit it in the orchestrator, and match on the serialized type name, not just the .NET type, because the process boundary eats exception identity. Retries are for the weather, not for typos.</p>
<p>This one assumes you already have a retry policy worth escaping. <a href="https://jeppe-spanggaard.dk/blogs/what-are-durable-functions/">Durable Functions: A Function That Sleeps for a Week</a> is the starting point for the rest of this series.</p>
]]></content:encoded></item><item><title>One Message, One Site: Deterministic Instance IDs in Durable Functions</title><link>https://jeppe-spanggaard.dk/blogs/durable-functions-deterministic-instance-ids/</link><pubDate>Sat, 15 Aug 2026 00:00:00 +0000</pubDate><guid>https://jeppe-spanggaard.dk/blogs/durable-functions-deterministic-instance-ids/</guid><description>Learn how deterministic orchestration instance IDs stop Service Bus redelivery from starting the same Durable Functions provisioning twice.</description><content:encoded><![CDATA[<p>My provisioning flow starts with a Service Bus message: a customer was created in the business system, a message lands on the <code>provisioning</code> queue, a Functions trigger picks it up and schedules a Durable Functions orchestration that builds the customer&rsquo;s SharePoint site.</p>
<p>Now walk through the failure case with me. The trigger receives the message. It schedules the orchestration. And then, before it can complete the queue message, the process dies. Deployment restart, scale-in, hardware burp, doesn&rsquo;t matter.</p>
<p>Service Bus does exactly what it promises: the message lock expires and the message comes back. A fresh trigger invocation receives it and schedules the orchestration.</p>
<p>Again.</p>
<p>Two orchestrations, one customer, and a race to see which one creates the site first. The other one gets to fail in interesting ways for the next ten minutes.</p>
<h2 id="the-trigger-guard-by-guard">The Trigger, Guard by Guard</h2>
<p>Here&rsquo;s the subscriber, trimmed to the part that matters:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#75715e">// Deterministic instance ID: if the process dies after scheduling but before completing the</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// message, Service Bus redelivery hits the already-existing instance instead of provisioning twice.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> instanceId = <span style="color:#e6db74">$&#34;provision-{message.MessageId}&#34;</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> existing = <span style="color:#66d9ef">await</span> client.GetInstanceAsync(instanceId, cancellation: cancellationToken);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">if</span> (existing <span style="color:#66d9ef">is</span> not <span style="color:#66d9ef">null</span>)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    logger.LogWarning(
</span></span><span style="display:flex;"><span>        <span style="color:#e6db74">&#34;Orchestration {InstanceId} already exists (status {Status}); completing redelivered message without rescheduling.&#34;</span>,
</span></span><span style="display:flex;"><span>        instanceId, existing.RuntimeStatus);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> messageActions.CompleteMessageAsync(message, cancellationToken);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span>;
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">await</span> client.ScheduleNewOrchestrationInstanceAsync(
</span></span><span style="display:flex;"><span>    nameof(ProvisioningOrchestrator),
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">new</span> OrchestratorInput(schema, ListItemId: listItemId, CustomSteps: CustomProvisioningSteps.Build()),
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">new</span> StartOrchestrationOptions { InstanceId = instanceId },
</span></span><span style="display:flex;"><span>    cancellationToken);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">await</span> messageActions.CompleteMessageAsync(message, cancellationToken);
</span></span></code></pre></div><p><strong>What&rsquo;s happening here?</strong></p>
<ol>
<li>The instance ID is computed from <code>message.MessageId</code>, so the same message always maps to the same orchestration instance. No randomness anywhere in the path from message to instance.</li>
<li><code>GetInstanceAsync</code> asks the task hub whether that instance already exists. On first delivery it doesn&rsquo;t; on redelivery it does, in whatever state the first attempt left it - <code>Running</code>, <code>Completed</code>, even <code>Failed</code>.</li>
<li>If it exists, the trigger completes the message and does nothing else. The redelivery was a symptom of the earlier crash, not a request for another site.</li>
<li>Only when the instance is genuinely new does the trigger schedule it, passing the deterministic ID through <code>StartOrchestrationOptions</code>.</li>
<li>The message is completed <em>after</em> scheduling. That ordering is the whole point, and it&rsquo;s worth dwelling on.</li>
</ol>
<h2 id="the-order-of-operations-is-the-design">The Order of Operations Is the Design</h2>
<p>There are only two possible orderings, and both can crash in the middle:</p>
<p><strong>Complete first, then schedule.</strong> A crash between the two loses the message forever - Service Bus considers it done, but no orchestration exists. A customer quietly never gets a site. Nobody notices until they complain.</p>
<p><strong>Schedule first, then complete.</strong> A crash between the two causes a redelivery of a message whose orchestration already exists. Without the dedupe check, that&rsquo;s a duplicate provisioning. With it, the redelivery is a no-op.</p>
<p>So you pick the second ordering, accept that duplicates are now <em>possible</em>, and make them <em>harmless</em> with the deterministic ID. This is the standard shape of at-least-once messaging: you can&rsquo;t prevent redelivery, you can only make redelivery boring.</p>
<p>One prerequisite hiding in the function attributes: <code>AutoCompleteMessages = false</code> on the Service Bus trigger. With auto-complete on, the runtime settles the message on its own schedule and the careful ordering above is fiction. Explicit completion also means explicit dead-lettering - my trigger dead-letters messages with an unknown event type or a customer that doesn&rsquo;t exist, instead of letting them retry into oblivion.</p>
<h2 id="choosing-the-key-delivery-identity-vs-business-identity">Choosing the Key: Delivery Identity vs Business Identity</h2>
<p><code>provision-{message.MessageId}</code> dedupes <em>deliveries of one message</em>. Same message redelivered: blocked. But if the upstream system sends two distinct messages for the same customer (double-click on &ldquo;create&rdquo;, integration replay, someone reruns a job), each has a fresh <code>MessageId</code> and both provision.</p>
<p>My local dev trigger, an HTTP endpoint for testing, actually uses a different scheme: <code>provision-{listItemId}</code>, keyed on the customer&rsquo;s row in the intake list. That&rsquo;s a <em>business</em> key. It dedupes at the customer level, no matter how many messages or HTTP calls ask for it.</p>
<p>So which is right? Depends on what &ldquo;again&rdquo; should mean:</p>
<ul>
<li><strong>Delivery key</strong> (<code>MessageId</code>): re-sending a message later <em>does</em> provision again. Right when upstream legitimately re-requests provisioning, such as a retry after a fixed config.</li>
<li><strong>Business key</strong> (customer ID): one provisioning per customer, ever, until the old instance is purged. Right when duplicates upstream are common and re-provisioning is the rare, deliberate case.</li>
</ul>
<p>I run the delivery key in production because my retry story goes through an explicit resume flow rather than &ldquo;send the message again&rdquo;, and the business system already guards against duplicate customer events. But I&rsquo;d flip to a business key in a heartbeat if the upstream were flakier. The point is that the instance ID is not a cosmetic label - it&rsquo;s the dedupe boundary, and you should choose it on purpose.</p>
<p>Whatever you pick, keep it deterministic and keep it readable. <code>provision-4711</code> in the portal tells you which customer at a glance; a random GUID tells you nothing.</p>
<h2 id="telling-the-caller-what-happened">Telling the Caller What Happened</h2>
<p>Because the instance ID is predictable, everything downstream gets simpler. The dev trigger returns the standard management payload:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> AcceptedResult(location: <span style="color:#66d9ef">null</span>, <span style="color:#66d9ef">value</span>: client.CreateHttpManagementPayload(instanceId));
</span></span></code></pre></div><p>That&rsquo;s a 202 with ready-made URLs for polling status, raising events, and terminating the instance. And since my orchestrator publishes its progress as custom status after every step, polling that URL shows exactly which provisioning step is running. Support can check on &ldquo;the provisioning for customer 4711&rdquo; without knowing anything about task hubs, because the instance ID is guessable from the customer.</p>
<h2 id="gotchas">Gotchas</h2>
<ul>
<li><strong>A <code>Failed</code> instance also blocks its ID.</strong> <code>GetInstanceAsync</code> returns failed and terminated instances too, and scheduling over an existing instance ID doesn&rsquo;t reliably give you a clean second run. If &ldquo;retry the failed provisioning&rdquo; is a flow you need (it is), make it explicit: purge the old instance or start a new instance ID that carries a resume checkpoint. Deciding this <em>after</em> the first production failure is the wrong time. Ask me how I know.</li>
<li><strong>The check-then-schedule pair isn&rsquo;t atomic.</strong> Two redeliveries processed concurrently could both pass the <code>GetInstanceAsync</code> check. In practice my queue runs with <code>maxConcurrentCalls: 1</code> so this doesn&rsquo;t occur, but if you crank concurrency, know that the guard is best-effort and the deterministic ID is what actually prevents two <em>distinct</em> instances - the second schedule call targets the same ID rather than minting a new orchestration.</li>
<li><strong>Keep dev and prod schemes consciously different, or consciously the same.</strong> Mine differ (delivery key in prod, business key in dev), which is fine because I know why. Discovering by accident that your environments dedupe differently is less fine.</li>
<li><strong>Instance IDs live until purged.</strong> With a business key, &ldquo;one per customer, ever&rdquo; includes instances from last year. Build purging into your lifecycle (mine purges on cancellation) or old completed instances will block legitimate re-provisioning.</li>
</ul>
<h2 id="wrapping-up">Wrapping Up</h2>
<p>With at-least-once delivery, the question is never whether you&rsquo;ll see a duplicate, only what it costs you. Derive the instance ID from the message, check for the existing instance before scheduling, and complete the message last. Then the answer is: one log line.</p>
<p>Instance IDs only make sense once orchestrations do. If this is your first stop, start with <a href="https://jeppe-spanggaard.dk/blogs/what-are-durable-functions/">Durable Functions: A Function That Sleeps for a Week</a>.</p>
]]></content:encoded></item><item><title>Every Activity Will Run Twice: Idempotency in Durable Functions</title><link>https://jeppe-spanggaard.dk/blogs/durable-functions-idempotent-activities/</link><pubDate>Wed, 05 Aug 2026 00:00:00 +0000</pubDate><guid>https://jeppe-spanggaard.dk/blogs/durable-functions-idempotent-activities/</guid><description>Learn how to make every Durable Functions activity idempotent so retry policies can safely rerun SharePoint and Graph provisioning steps.</description><content:encoded><![CDATA[<p>My provisioning engine creates SharePoint team sites through a Durable Functions orchestration: create the site, activate features, pull content types, apply templates, seed folders. Every activity call in that orchestrator goes through one shared retry policy:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#75715e">// Outer safety net: retry any activity that throws a transient error (e.g. throttling</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// that slips past HTTP-level retry). Exponential backoff: 5s, 10s, 20s, ... up to 5min,</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// 10 attempts total. All activities are idempotent, so retrying the full activity is safe.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">readonly</span> TaskOptions ActivityRetryOptions = <span style="color:#66d9ef">new</span>(
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">new</span> RetryPolicy(
</span></span><span style="display:flex;"><span>        maxNumberOfAttempts: <span style="color:#ae81ff">10</span>,
</span></span><span style="display:flex;"><span>        firstRetryInterval: TimeSpan.FromSeconds(<span style="color:#ae81ff">5</span>),
</span></span><span style="display:flex;"><span>        backoffCoefficient: <span style="color:#ae81ff">2.0</span>,
</span></span><span style="display:flex;"><span>        maxRetryInterval: TimeSpan.FromMinutes(<span style="color:#ae81ff">5</span>)));
</span></span></code></pre></div><p>Read that comment again: &ldquo;All activities are idempotent, so retrying the full activity is safe.&rdquo;</p>
<p>That sentence is either the best thing about the whole engine or a lie that duplicates customer sites at 2am. There&rsquo;s no middle ground. The retry policy reruns the <em>entire activity</em>, not the line that failed. If your activity created a site and then died resolving its ID, the retry creates the site again - unless the activity was written to survive being run twice.</p>
<p>So this post is a catalog of how I actually make that sentence true. Five patterns, all from real provisioning code.</p>
<h2 id="pattern-1-check-before-create">Pattern 1: Check Before Create</h2>
<p>The site creation activity is the highest-stakes one. If a previous attempt created the site but failed a moment later (say, while resolving the Graph site ID), the retry must not create it again. So it probes first:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#75715e">// Idempotency: if the site already exists (e.g. previous attempt created it but</span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// failed during Graph ID resolution), skip creation and go straight to Graph lookup.</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">if</span> (<span style="color:#66d9ef">await</span> SiteExistsAsync(newSiteUrl))
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    logger.LogInformation(<span style="color:#e6db74">&#34;Site already exists at {SiteUrl}, skipping creation.&#34;</span>, newSiteUrl);
</span></span><span style="display:flex;"><span>}
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">else</span>
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> CreateSiteAsync(parsedType, site, siteAlias, newSiteUrl);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Note what makes the probe possible in the first place: the site URL is deterministic, built from a prefix and alias in the schema. No timestamps, no random suffixes. If the URL contained <code>Guid.NewGuid()</code>, attempt two would probe a different URL, find nothing, and create a second site. Deterministic naming is the quiet prerequisite for check-before-create.</p>
<h2 id="pattern-2-already-exists-is-success">Pattern 2: &ldquo;Already Exists&rdquo; Is Success</h2>
<p>Sometimes you can&rsquo;t probe cheaply, so you attempt the operation and translate the failure. Activating a site feature that&rsquo;s already active comes back from SharePoint as an error - but it means the activity already did its job on a previous run:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">catch</span> (InvalidOperationException ex) when (
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// &#34;Feature already activated&#34; comes back as HTTP 500 with odata.error.code</span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// &#34;System.Data.DuplicateNameException&#34; - locale-independent, unlike the human message.</span>
</span></span><span style="display:flex;"><span>    ex.Message.Contains(<span style="color:#e6db74">&#34;System.Data.DuplicateNameException&#34;</span>, StringComparison.OrdinalIgnoreCase))
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    logger.LogInformation(<span style="color:#e6db74">&#34;{Feature} feature is already active, skipping.&#34;</span>, displayName);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>The comment is a scar. My first version matched on the English error text, which works great until the code runs against a tenant in another language. Match on error <em>codes</em>, not error <em>messages</em>. The OData error code survives localization; &ldquo;Feature &hellip; is already activated&rdquo; does not.</p>
<p>Graph makes this pattern cleaner because it gives you a real status code. Copying folder structures into the new site:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">catch</span> (ODataError ex) when (ex.ResponseStatusCode == <span style="color:#ae81ff">409</span>)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Item already exists in target - idempotent on retry</span>
</span></span><span style="display:flex;"><span>    logger.LogInformation(<span style="color:#e6db74">&#34;Item &#39;{ItemName}&#39; already exists in target, skipping copy.&#34;</span>, itemName);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>409 Conflict on a create is not a failure. It&rsquo;s a receipt from your previous attempt.</p>
<h2 id="pattern-3-upsert-by-nature">Pattern 3: Upsert by Nature</h2>
<p>The best idempotency is the kind you get for free by choosing the right API. The registration activity writes the new site&rsquo;s URL and ID back to an inventory list, and it does so with SharePoint&rsquo;s <code>ValidateUpdateListItem</code> against a known item ID. Setting the same fields on the same item to the same values twice is indistinguishable from doing it once. There&rsquo;s nothing to guard because the operation has no failure mode for repetition.</p>
<p>When you&rsquo;re designing an activity and you get to pick between &ldquo;add a row&rdquo; and &ldquo;set fields on item X&rdquo;, pick the second. Every <code>Add</code> needs a guard; a keyed <code>Set</code> guards itself.</p>
<h2 id="pattern-4-verify-after-write">Pattern 4: Verify After Write</h2>
<p>The dark twin of idempotency: some SharePoint writes report success and then don&rsquo;t stick. Property bag values on a freshly created site are notorious for this. The activity&rsquo;s answer is to re-read everything it just wrote and throw if reality disagrees:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">if</span> (mismatches.Count &gt; <span style="color:#ae81ff">0</span>)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">throw</span> <span style="color:#66d9ef">new</span> InvalidOperationException(
</span></span><span style="display:flex;"><span>        <span style="color:#e6db74">$&#34;Property bag verification failed on {siteUrl}: {string.Join(&#34;</span>; <span style="color:#e6db74">&#34;, mismatches)}. &#34;</span> +
</span></span><span style="display:flex;"><span>        <span style="color:#e6db74">&#34;Values did not persist to the server; retrying the activity.&#34;</span>);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><strong>What&rsquo;s happening here?</strong></p>
<ol>
<li>After writing the property bag values, the activity loads <code>Web.AllProperties</code> fresh from the server.</li>
<li>Each expected key/value is compared against what actually persisted.</li>
<li>Any mismatch throws a plain transient exception, which hands the problem to the orchestrator&rsquo;s retry policy.</li>
<li>The rerun is safe precisely because setting a property bag key is an upsert - pattern 3 again. Verification and idempotency are two halves of the same loop: writes are repeatable, so failed verification can simply demand a repeat.</li>
</ol>
<p>This inverts the usual relationship with retries. Instead of retries being something inflicted on the activity, the activity uses a throw to <em>request</em> one.</p>
<h2 id="pattern-5-idempotent-deletes-too">Pattern 5: Idempotent Deletes Too</h2>
<p>Removal flows have the same problem in the other direction. Removing a user from a site&rsquo;s members group when they&rsquo;re already gone throws a <code>ServerException</code>, and treating that as failure would wedge every cleanup retry:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">catch</span> (ServerException ex)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    logger.LogWarning(ex, <span style="color:#e6db74">&#34;Could not remove {LoginName} from {SiteUrl} ({ErrorType}); treating as already removed.&#34;</span>,
</span></span><span style="display:flex;"><span>        loginName, siteUrl, ex.ServerErrorTypeName);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Desired state: user is not in the group. User is not in the group. Done. Idempotency is about converging on a state, not performing an action.</p>
<h2 id="gotchas">Gotchas</h2>
<ul>
<li><strong>One non-idempotent activity poisons the whole pipeline.</strong> I had a security activity that created SharePoint groups without checking for existing ones. Every retry of that step risked duplicate groups, which meant retries weren&rsquo;t safe, which meant the retry policy comment was a lie for the whole orchestration. It&rsquo;s disabled until it earns its way back in. Idempotency is all-or-nothing per pipeline.</li>
<li><strong>The failure window is between success and checkpoint.</strong> The orchestrator records completed steps, but a crash can land after the activity finished and before the record was written. The completed-steps list narrows how often reruns happen; idempotency is what makes the remaining reruns harmless. You need both.</li>
<li><strong><code>catch</code> the narrowest thing you can.</strong> The 409 handler above catches <code>ODataError</code> with status 409, nothing else. A broad <code>catch { return; }</code> also &ldquo;makes retries pass&rdquo;, by swallowing real failures. Idempotency guards should be precise enough that a genuinely broken call still throws.</li>
<li><strong>Test by running it twice, literally.</strong> My smoke test for a new activity is: run the provisioning, then immediately queue the exact same provisioning again. Zero errors and zero duplicates or it doesn&rsquo;t ship.</li>
</ul>
<h2 id="wrapping-up">Wrapping Up</h2>
<p>A Durable Functions retry policy is a contract: it promises to rerun your activities, and your activities promise not to care. Check before create, read &ldquo;already exists&rdquo; as success, prefer upserts, verify writes that lie. Write every activity as if it will run twice, because on a long enough timeline, it will.</p>
<p>If retry policies and replay are new to you, <a href="https://jeppe-spanggaard.dk/blogs/what-are-durable-functions/">Durable Functions: A Function That Sleeps for a Week</a> covers what an orchestration actually is, and why &ldquo;it will run twice&rdquo; is a feature rather than a bug.</p>
]]></content:encoded></item><item><title>Provision Forward, Never Backward: Checkpointing Durable Functions</title><link>https://jeppe-spanggaard.dk/blogs/durable-functions-provisioning-checkpoints/</link><pubDate>Thu, 16 Jul 2026 00:00:00 +0000</pubDate><guid>https://jeppe-spanggaard.dk/blogs/durable-functions-provisioning-checkpoints/</guid><description>Learn how to checkpoint a Durable Functions orchestration so a failed SharePoint provisioning run resumes where it stopped instead of starting over.</description><content:encoded><![CDATA[<p>I built a provisioning engine that creates a SharePoint team site for every new customer. Create the site, activate features, apply a template, seed a folder structure, add groups, register the site in an inventory list. Roughly ten steps, several minutes end to end, talking to SharePoint and Microsoft Graph the whole way.</p>
<p>The first time step seven failed, I got to watch my engine try to create a site that already existed.</p>
<p>That run taught me the rule this post is about: in a long provisioning flow, you don&rsquo;t roll back when something fails. You checkpoint, and you resume forward.</p>
<p>If Durable Functions are new to you, start with my intro to <a href="https://jeppe-spanggaard.dk/blogs/what-are-durable-functions/">what they are and what they can do</a> - this post builds on it.</p>
<h2 id="why-rollback-is-the-wrong-instinct">Why Rollback Is the Wrong Instinct</h2>
<p>When provisioning fails at step seven, you have a half-built site. The textbook answer is a compensation saga: undo steps six through one in reverse order. Delete the folders, detach the template, deactivate the features, delete the site, then recreate everything from scratch on the next attempt.</p>
<p>I started sketching that and stopped halfway through the list, because every line was either dangerous or absurd. Deleting a site collection to work around a failed navigation tweak is using a crane to hang a picture. And some steps don&rsquo;t even have an undo - you can&rsquo;t meaningfully &ldquo;unapply&rdquo; a provisioning template that merged fields into existing lists.</p>
<p>Here&rsquo;s the thing rollback ignores: the six completed steps aren&rsquo;t damage. They&rsquo;re progress. The site is fine; what&rsquo;s missing is the steps that haven&rsquo;t run yet. So the only recovery that makes sense is forward: figure out where the run stopped, and continue from there.</p>
<p>That reframes the problem completely. I don&rsquo;t need compensation logic. I need to know, reliably, which steps finished.</p>
<h2 id="carry-the-progress-in-the-state">Carry the Progress in the State</h2>
<p>Durable Functions makes this natural, because an orchestrator already passes state to each activity and gets state back. The trick is to make &ldquo;what&rsquo;s done&rdquo; part of that state. My orchestration state looks something like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">sealed</span> <span style="color:#66d9ef">record</span> <span style="color:#a6e22e">SiteSetupState</span>(
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">string</span> CustomerId,
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">string</span> SiteUrl,
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">string</span>[] CompletedSteps
</span></span><span style="display:flex;"><span>);
</span></span></code></pre></div><p>And the orchestrator walks its steps like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">var</span> state = context.GetInput&lt;SiteSetupState&gt;() ?? <span style="color:#66d9ef">await</span> CreateSite(context, customerId);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">string</span>[] pipeline =
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">[
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">    nameof(ActivateFeatures),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">    nameof(ApplyTemplate),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">    nameof(SeedFolders),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">    nameof(AddMemberGroups),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">    nameof(RegisterSite),
</span></span></span><span style="display:flex;"><span><span style="color:#a6e22e">]</span>;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">foreach</span> (<span style="color:#66d9ef">var</span> step <span style="color:#66d9ef">in</span> pipeline)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (state.CompletedSteps.Contains(step))
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        logger.LogInformation(<span style="color:#e6db74">&#34;{Step} already completed, skipping.&#34;</span>, step);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">continue</span>;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> context.CallActivityAsync(step, state, retryOptions);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    state = state with { CompletedSteps = [.. state.CompletedSteps, step] };
</span></span><span style="display:flex;"><span>    context.SetCustomStatus(state);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><strong>What&rsquo;s happening here?</strong></p>
<ol>
<li>The pipeline is just an ordered list of activity names. Nothing clever, and that&rsquo;s the point - the interesting machinery is around the calls, not in them.</li>
<li>Before each step, the orchestrator checks whether this step already ran. On a fresh run the array is empty and nothing is skipped. On a resumed run, this check is what fast-forwards past the finished work.</li>
<li>After each successful step, the state is copied with the step name appended. An immutable <code>with</code> copy, so nothing mutates in place, which keeps replays honest.</li>
<li><code>SetCustomStatus</code> publishes the updated state on the orchestration instance. This is the checkpoint. It costs one line.</li>
</ol>
<p>That last line is doing more work than it looks like. Custom status is readable from <em>outside</em> the orchestration - through the management API, without touching the orchestration history. So the same call gives you two things: anyone polling the instance sees live progress (&ldquo;three of six steps done&rdquo;), and if the run fails, the last published state is sitting right there, telling you exactly where it stopped.</p>
<h2 id="resume-is-just-input">Resume Is Just Input</h2>
<p>Because the checkpoint is a plain serializable record, resuming a failed run doesn&rsquo;t need any special framework support. You read the failed instance&rsquo;s custom status, and you start a <em>new</em> orchestration with that state as input:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">var</span> failed = <span style="color:#66d9ef">await</span> client.GetInstanceAsync(failedInstanceId, getInputsAndOutputs: <span style="color:#66d9ef">true</span>);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> checkpoint = failed.ReadCustomStatusAs&lt;SiteSetupState&gt;();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">await</span> client.ScheduleNewOrchestrationInstanceAsync(
</span></span><span style="display:flex;"><span>    nameof(SiteSetupOrchestrator),
</span></span><span style="display:flex;"><span>    checkpoint);
</span></span></code></pre></div><p>The new run enters the same loop, finds five steps in <code>CompletedSteps</code>, skips them in about a millisecond, and picks up at step six. No site deletion, no re-creation, no duplicate template apply. The half-built site becomes a five-sixths-built site, then a finished one.</p>
<p>I like how little there is to this. The &ldquo;resume feature&rdquo; is the skip-check in the loop plus the fact that the input type and the checkpoint type are the same type. That&rsquo;s it.</p>
<h2 id="the-gap-that-idempotency-covers">The Gap That Idempotency Covers</h2>
<p>One honest caveat. The checkpoint is written <em>after</em> the activity succeeds, so there&rsquo;s a window: the activity finishes, the process dies before the checkpoint lands. On resume, that step&rsquo;s name isn&rsquo;t in <code>CompletedSteps</code>, and it runs again.</p>
<p>You can&rsquo;t close that window - it&rsquo;s inherent to doing the work and recording the work as two operations. What you do instead is make every activity safe to run twice: check before create, treat &ldquo;already exists&rdquo; as success, write with upserts. That&rsquo;s a full topic on its own, but the division of labor is worth stating plainly: <strong>the checkpoint decides how often steps rerun, idempotency decides whether reruns hurt.</strong> You need both. The checkpoint alone has a crash window; idempotency alone means re-executing ten minutes of finished work on every hiccup.</p>
<p>And never checkpoint <em>before</em> the call to close the window from the other side - then a crashed step gets skipped on resume, which is far worse. A step that runs twice is a wasted minute; a step that runs zero times is a broken site that says &ldquo;Completed&rdquo;. Ask me how I know.</p>
<h2 id="gotchas">Gotchas</h2>
<ul>
<li><strong>Use the replay-safe logger.</strong> Orchestrator code replays from history every time the instance wakes up. <code>context.CreateReplaySafeLogger(...)</code> keeps your logs from repeating every completed step on each replay. A regular <code>ILogger</code> in an orchestrator will gaslight you.</li>
<li><strong>No clocks, no GUIDs in the orchestrator.</strong> <code>DateTime.UtcNow</code>, <code>Guid.NewGuid()</code>, and <code>Random</code> produce different values on replay and corrupt the history. Anything nondeterministic belongs inside an activity, including generated names and timestamps you want in the state.</li>
<li><strong>Custom status has a size limit</strong> (16 KB of JSON). A record with a customer ID, a URL, and an array of step names fits hundreds of times over, but don&rsquo;t stuff a whole template or file manifest in there. Checkpoint the <em>position</em>, not the <em>payload</em>.</li>
<li><strong>Step names are a contract.</strong> The moment <code>CompletedSteps</code> is persisted anywhere - a failed instance you might resume next week - renaming an activity breaks the match and the step silently reruns (fine, if idempotent) or the resume misbehaves (not fine). Rename with the same care you&rsquo;d give a database column.</li>
<li><strong>Report progress somewhere humans look.</strong> Custom status is great for machines; my engine also writes the current step name to a status column in the site inventory list, inside a try/catch that logs and swallows. A cosmetic status write must never kill a provisioning run.</li>
</ul>
<h2 id="wrapping-up">Wrapping Up</h2>
<p>Long provisioning flows fail in the middle, so design for resuming instead of undoing: carry a list of completed steps in the orchestration state, publish it as custom status after every step, skip completed steps on rerun, and feed the saved state back in to resume. Rollback is for databases. Provisioning goes forward.</p>
]]></content:encoded></item><item><title>Durable Functions: A Function That Sleeps for a Week</title><link>https://jeppe-spanggaard.dk/blogs/what-are-durable-functions/</link><pubDate>Wed, 15 Jul 2026 00:00:00 +0000</pubDate><guid>https://jeppe-spanggaard.dk/blogs/what-are-durable-functions/</guid><description>Learn what Azure Durable Functions are and what they can do, using a SharePoint site provisioning workflow as a real-world example.</description><content:encoded><![CDATA[<p>I had to build a provisioning engine. Every time a new customer lands in the business system, it creates a SharePoint team site for them: create the site, activate features, apply a template, seed a folder structure, add member groups, register the site in an inventory list. Roughly ten steps, several minutes end to end, and every single step talks to an API that can throttle, hiccup, or time out.</p>
<p>My first instinct was a plain Azure Function. One trigger, one method, ten steps in a row.</p>
<p>That instinct survived about a day. A plain function has a timeout measured in minutes. It holds its state in local variables, so when the process restarts mid-run (deployments, scale-in, Azure having a Tuesday), everything it knew is gone. Step six fails and your options are &ldquo;run all ten steps again&rdquo; or &ldquo;reconstruct what happened from logs like a crime scene&rdquo;.</p>
<p>And it&rsquo;s not like the step-sequencing part was new to me. I&rsquo;d already built <a href="https://github.com/Pinksky-ApS/provisioning-pipeline-dotnet">ProvisioningPipeline</a>, an open-source .NET library for composing provisioning workflows from middleware-style steps, with hooks and parallel execution. It solves the &ldquo;run these steps in order, cleanly&rdquo; problem well. What no in-process pipeline can solve is the other half: a pipeline in memory still dies with the process, and all its progress dies with it.</p>
<p>What I actually needed was a function that can run for a long time, remember how far it got, and pick up where it left off. That&rsquo;s not a pattern you bolt onto a normal function. It&rsquo;s a different tool, and Azure ships it: Durable Functions.</p>
<h2 id="three-functions-one-flow">Three Functions, One Flow</h2>
<p>A durable workflow is made of three kinds of functions, and the separation is the whole idea.</p>
<p>The <strong>client</strong> is a normal function with a normal trigger - HTTP, queue, timer, whatever starts your process. Its only durable job is to schedule an orchestration and get out of the way:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#a6e22e">[Function(nameof(StartProvisioning))]</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> Task Run(
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">    [ServiceBusTrigger(&#34;provisioning&#34;)]</span> ProvisioningMessage message,
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">    [DurableClient]</span> DurableTaskClient client)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> client.ScheduleNewOrchestrationInstanceAsync(
</span></span><span style="display:flex;"><span>        nameof(SiteSetupOrchestrator),
</span></span><span style="display:flex;"><span>        message.ToSetupRequest());
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>The <strong>orchestrator</strong> is the recipe. It calls the steps in order and holds the workflow logic, but does no real work itself:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#a6e22e">[Function(nameof(SiteSetupOrchestrator))]</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">async</span> Task RunOrchestrator(
</span></span><span style="display:flex;"><span><span style="color:#a6e22e">    [OrchestrationTrigger]</span> TaskOrchestrationContext context)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> request = context.GetInput&lt;SiteSetupRequest&gt;();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> site = <span style="color:#66d9ef">await</span> context.CallActivityAsync&lt;SiteInfo&gt;(nameof(CreateSite), request);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> context.CallActivityAsync(nameof(ActivateFeatures), site);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> context.CallActivityAsync(nameof(ApplyTemplate), site);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> context.CallActivityAsync(nameof(SeedFolders), site);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> context.CallActivityAsync(nameof(AddMemberGroups), site);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">await</span> context.CallActivityAsync(nameof(RegisterSite), site);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>The <strong>activities</strong> are where the actual SharePoint and Graph calls live. Each one is a small, self-contained function: <code>CreateSite</code> creates a site, <code>ApplyTemplate</code> applies a template, and so on.</p>
<p><strong>What&rsquo;s happening here?</strong></p>
<ol>
<li>The client schedules an orchestration instance and returns immediately. Nothing waits around; the run now has a life of its own, with an instance ID you can use to check on it later.</li>
<li>The orchestrator reads like a script: six awaited steps, top to bottom. This is the part that would be a state machine diagram in Logic Apps or a pile of queues in a hand-rolled solution. Here it&rsquo;s just code, with loops and try/catch available when you need them.</li>
<li>Every <code>CallActivityAsync</code> is a checkpoint boundary. The runtime records that the step completed, and what it returned, before moving on.</li>
<li>Activities take input, do I/O, return output. They don&rsquo;t know they&rsquo;re part of a workflow, which keeps them easy to write and easy to test.</li>
</ol>
<h2 id="the-durable-part-is-a-history-table">The &ldquo;Durable&rdquo; Part Is a History Table</h2>
<p>Here&rsquo;s what separates this from a normal async method: the orchestrator&rsquo;s progress doesn&rsquo;t live in memory. Every scheduled activity and every result gets written to a history table in storage as an event.</p>
<p>When the process dies mid-run - and over a multi-minute workflow across enough customers, it will - the runtime picks the orchestration up on another instance and <em>replays</em> it. The orchestrator code runs again from the top, but every activity that already completed doesn&rsquo;t re-execute; its recorded result comes straight back from history. The replay fast-forwards through the finished steps in milliseconds and resumes real work at the first step without a recorded result.</p>
<p>It&rsquo;s a save file in a video game. The console losing power doesn&rsquo;t send you back to level one; you reload and continue from the last save point. The orchestrator saves after every activity, and it never plays a level twice.</p>
<p>That same mechanism is why an orchestration can wait for days without costing you anything. Awaiting a durable timer or an external event just means &ldquo;write the wait to history and unload from memory&rdquo;. No process is alive, no compute is billed, and when the timer fires next week, replay reconstructs the state and continues. A function that sleeps for a week, literally.</p>
<h2 id="what-else-is-in-the-box">What Else Is in the Box</h2>
<p>Sequential steps are the basics. A few more capabilities, through the provisioning lens:</p>
<p><strong>Per-step retries.</strong> Every activity call can carry a retry policy, and this is the built-in retry logic worth knowing about. Mine looks like this:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-csharp" data-lang="csharp"><span style="display:flex;"><span><span style="color:#66d9ef">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">readonly</span> TaskOptions ActivityRetryOptions = <span style="color:#66d9ef">new</span>(
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">new</span> RetryPolicy(
</span></span><span style="display:flex;"><span>        maxNumberOfAttempts: <span style="color:#ae81ff">10</span>,
</span></span><span style="display:flex;"><span>        firstRetryInterval: TimeSpan.FromSeconds(<span style="color:#ae81ff">5</span>),
</span></span><span style="display:flex;"><span>        backoffCoefficient: <span style="color:#ae81ff">2.0</span>,
</span></span><span style="display:flex;"><span>        maxRetryInterval: TimeSpan.FromMinutes(<span style="color:#ae81ff">5</span>)));
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">await</span> context.CallActivityAsync(nameof(ApplyTemplate), site, ActivityRetryOptions);
</span></span></code></pre></div><p>If <code>ApplyTemplate</code> throws because SharePoint returned a 429, the runtime waits 5 seconds and reruns the activity. Then 10, then 20, backing off exponentially up to 5 minutes, for up to 10 attempts. The orchestration just sits there durably waiting between attempts. For workflows built on APIs that throttle, this one feature pays for the whole ticket.</p>
<p><strong>Fan-out/fan-in.</strong> Steps that don&rsquo;t depend on each other can run as parallel activities and be awaited together with <code>Task.WhenAll</code>. Seeding twelve folders one by one is a for-loop; seeding them as twelve parallel activities is the same loop without the awaits until the end.</p>
<p><strong>Durable timers.</strong> <code>context.CreateTimer(...)</code> gives you delays and polling loops that survive restarts. Waiting 30 seconds for SharePoint to finish creating a site is a timer, not a <code>Task.Delay</code> and a prayer.</p>
<p><strong>External events.</strong> An orchestration can pause until something outside signals it - <code>WaitForExternalEvent</code> is how you build &ldquo;wait for an admin to approve, then continue&rdquo;, even if the admin takes four days.</p>
<p><strong>Status from the outside.</strong> Every instance can be queried by ID: is it running, what step is it on, did it fail and why. My provisioning engine exposes this so the business system can show &ldquo;site is being created&rdquo; instead of a shrug.</p>
<h2 id="what-it-doesnt-do-for-you">What It Doesn&rsquo;t Do for You</h2>
<p>An honest intro should include the bill.</p>
<p><strong>Retries are per step, not per run.</strong> The retry policy reruns a failing <em>activity</em>. If an activity exhausts all ten attempts, the orchestration fails, and a failed run stays failed - nothing in the box restarts it from where it stopped. Resuming a dead run is a pattern you build yourself on top of these primitives.</p>
<p><strong>Retried activities rerun whole.</strong> When attempt two starts, it starts from the activity&rsquo;s first line, not from where attempt one died. An activity that created a site and then failed will try to create the site again. Every activity has to be written to survive running twice, and that&rsquo;s on you.</p>
<p><strong>Orchestrator code lives under house rules.</strong> Because the orchestrator replays, it must be deterministic: same history in, same decisions out. No <code>DateTime.UtcNow</code>, no <code>Guid.NewGuid()</code>, no HTTP calls, no reading config that might change between replays. Anything nondeterministic belongs in an activity. The rules are simple but unforgiving, and the failure mode is a corrupted run, not a compile error.</p>
<p>None of these are dealbreakers. They&rsquo;re the shape of the tool: the runtime guarantees your progress is never lost, and in exchange you write steps that tolerate being repeated.</p>
<h2 id="gotchas">Gotchas</h2>
<ul>
<li><strong>Use the replay-safe logger in orchestrators.</strong> <code>context.CreateReplaySafeLogger(...)</code> suppresses log lines during replay. A regular <code>ILogger</code> logs every completed step again on every replay, and the duplicated log stream will have you debugging problems you don&rsquo;t have.</li>
<li><strong>Keep activities small and single-purpose.</strong> One activity per step means one checkpoint per step. A mega-activity that does five things gives you one checkpoint for five steps, and a failure at thing four reruns things one through three.</li>
<li><strong>The retry policy can&rsquo;t tell a 429 from a typo.</strong> It retries every exception the same way, including the ones that will never succeed, like a broken config value. Distinguishing &ldquo;try again&rdquo; from &ldquo;stop, a human needs to fix this&rdquo; takes extra work.</li>
<li><strong>Don&rsquo;t sneak I/O into the orchestrator.</strong> It compiles, it works on the happy path, and it breaks determinism the first time a replay gets a different answer. If it touches the network or the clock, it&rsquo;s an activity.</li>
</ul>
<h2 id="wrapping-up">Wrapping Up</h2>
<p>A Durable Function is a workflow that remembers where it was: an orchestrator sequences the steps, activities do the work, and the runtime checkpoints every step so crashes, restarts, and week-long waits don&rsquo;t lose progress. If your process has numbered steps, talks to flaky APIs, and takes longer than a request, it&rsquo;s a fit - provisioning was mine.</p>
]]></content:encoded></item></channel></rss>