<?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>Throttling and Rate Limits on Jeppe Spanggaard - Software Developer | .NET, Azure &amp; Microsoft 365</title><link>https://jeppe-spanggaard.dk/tags/throttling/</link><description>Recent content in Throttling and Rate Limits on Jeppe Spanggaard - Software Developer | .NET, Azure &amp; Microsoft 365</description><generator>Hugo</generator><language>en-US</language><lastBuildDate>Sun, 26 Jul 2026 00:00:00 +0000</lastBuildDate><atom:link href="https://jeppe-spanggaard.dk/tags/throttling/index.xml" rel="self" type="application/rss+xml"/><item><title>SharePoint CSOM: Prevent Unnecessary Updates and API Calls</title><link>https://jeppe-spanggaard.dk/blogs/sharepoint-csom-prevent-unnecessary-updates/</link><pubDate>Wed, 05 Nov 2025 10:00:00 +0100</pubDate><author>Jeppe Spanggaard</author><guid>https://jeppe-spanggaard.dk/blogs/sharepoint-csom-prevent-unnecessary-updates/</guid><description>The SharePoint API call that wasted resources is now optimized with smart change detection, reducing unnecessary updates and costs.</description><content:encoded><![CDATA[<h2 id="the-moment-everything-clicked">The Moment Everything Clicked</h2>
<p>So there I was, building what I thought was a pretty straightforward API endpoint. Users fill out a form, click save, and boom—SharePoint list item gets updated. Simple, right?</p>
<p>Wrong.</p>
<p>It was during one of those routine maintenance windows when I decided to review some API logs that I noticed something odd. The numbers just didn&rsquo;t add up. We were making way more SharePoint API calls than seemed necessary for the amount of actual data changes happening in the system.</p>
<p><strong>Every operation was hitting SharePoint. Even when nothing had actually changed.</strong></p>
<p>That&rsquo;s when it hit me. Our application was treating every potential update as an actual update, regardless of whether the data was different from what SharePoint already had. Users could open a form, change nothing, click save, and we&rsquo;d still fire off an API call to &ldquo;update&rdquo; the item with identical values.</p>
<p>But SharePoint doesn&rsquo;t care if you&rsquo;re setting a field to the exact same value it already has. It still counts that as an API call. It still hits your throttling limits. And if you&rsquo;re paying for &ldquo;Service Prioritization in SharePoint&rdquo;? It still costs you money.</p>
<h2 id="the-why-did-i-even-build-this-moment">The &ldquo;Why Did I Even Build This?&rdquo; Moment</h2>
<p>I spent some time digging deeper into the patterns, and the numbers were&hellip; enlightening.</p>
<p>This wasn&rsquo;t just a user behavior issue. It was happening everywhere:</p>
<ul>
<li>Users frequently save forms without making actual changes</li>
<li>Automated processes periodically &ldquo;sync&rdquo; data that&rsquo;s already current</li>
<li>Applications send complete object states rather than just changed fields</li>
<li>Integration systems perform routine updates as part of larger workflows</li>
</ul>
<p>When I looked at a typical day&rsquo;s worth of operations, I found that <strong>roughly 70% of our SharePoint update calls weren&rsquo;t actually changing anything</strong>. We were essentially paying SharePoint to accept identical data and politely say &ldquo;thanks for the update!&rdquo;</p>
<p>The more I thought about it, the more I realized this pattern was probably happening in systems everywhere. How many developers have built the same &ldquo;just update everything&rdquo; approach without stopping to ask whether anything actually changed?</p>
<h2 id="sharepoints-sure-ill-take-your-money-attitude">SharePoint&rsquo;s &ldquo;Sure, I&rsquo;ll Take Your Money&rdquo; Attitude</h2>
<p>Here&rsquo;s the thing about SharePoint&rsquo;s CSOM that nobody really talks about: it doesn&rsquo;t care if you&rsquo;re being wasteful. You want to set a field to the exact same value it already has? &ldquo;No problem!&rdquo; says SharePoint. &ldquo;That&rsquo;ll be one API call, please.&rdquo;</p>
<p>And if you&rsquo;re using Service Prioritization in SharePoint? That&rsquo;s real money walking out the door.</p>
<p>Let me show you what I mean with some concrete numbers from a client I worked with recently:</p>
<h3 id="the-head-scratching-cases">The Head-Scratching Cases</h3>
<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">// These should be considered equal, but .NET says &#34;nope&#34;</span>
</span></span><span style="display:flex;"><span>currentValue: <span style="color:#e6db74">&#34;John Doe&#34;</span>
</span></span><span style="display:flex;"><span>newValue: <span style="color:#e6db74">&#34;John Doe&#34;</span>  <span style="color:#75715e">// Easy case, no problem here</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>currentValue: <span style="color:#66d9ef">null</span>
</span></span><span style="display:flex;"><span>newValue: <span style="color:#e6db74">&#34;&#34;</span>  <span style="color:#75715e">// Is empty string the same as null? Your call!</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>currentValue: <span style="color:#ae81ff">42</span>
</span></span><span style="display:flex;"><span>newValue: <span style="color:#e6db74">&#34;42&#34;</span>  <span style="color:#75715e">// Different types, same value. Fun times.</span>
</span></span></code></pre></div><h3 id="the-sharepoint-special-cases">The SharePoint Special Cases</h3>
<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">// User fields (oh boy...)</span>
</span></span><span style="display:flex;"><span>currentValue: FieldUserValue { LookupId = <span style="color:#ae81ff">15</span>, LookupValue = <span style="color:#e6db74">&#34;John Doe&#34;</span> }
</span></span><span style="display:flex;"><span>newValue: FieldUserValue { LookupId = <span style="color:#ae81ff">15</span>, LookupValue = <span style="color:#e6db74">&#34;John Doe&#34;</span> }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Multi-choice fields that hate you</span>
</span></span><span style="display:flex;"><span>currentValue: [<span style="color:#e6db74">&#34;Option A&#34;</span>, <span style="color:#e6db74">&#34;Option C&#34;</span>, <span style="color:#e6db74">&#34;Option B&#34;</span>]
</span></span><span style="display:flex;"><span>newValue: [<span style="color:#e6db74">&#34;Option B&#34;</span>, <span style="color:#e6db74">&#34;Option A&#34;</span>, <span style="color:#e6db74">&#34;Option C&#34;</span>]  <span style="color:#75715e">// Same options, different order</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Taxonomy fields (because why not make it complicated?)</span>
</span></span><span style="display:flex;"><span>currentValue: TaxonomyFieldValue { TermGuid = <span style="color:#e6db74">&#34;abc-123&#34;</span>, Label = <span style="color:#e6db74">&#34;Technology&#34;</span> }
</span></span><span style="display:flex;"><span>newValue: TaxonomyFieldValue { TermGuid = <span style="color:#e6db74">&#34;abc-123&#34;</span>, Label = <span style="color:#e6db74">&#34;Technology&#34;</span> }
</span></span></code></pre></div><p>After an hour of testing different scenarios, I realized I needed something more sophisticated than <code>oldValue == newValue</code>.</p>
<h2 id="building-the-actually-smart-comparison-engine">Building the &ldquo;Actually Smart&rdquo; Comparison Engine</h2>
<p>Alright, time to get serious. I needed a comparison function that could handle all of SharePoint&rsquo;s quirky field types and still be fast enough to not slow down my API.</p>
<p>Here&rsquo;s what I ended up building (and yes, it&rsquo;s a bit of a beast):</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">static</span> List&lt;(<span style="color:#66d9ef">string</span> InternalName, <span style="color:#66d9ef">object?</span> NewValue)&gt; GetDifferences(
</span></span><span style="display:flex;"><span>    ListItem item,
</span></span><span style="display:flex;"><span>    IDictionary&lt;<span style="color:#66d9ef">string</span>, <span style="color:#66d9ef">object?</span>&gt; newValues,
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">bool</span> treatEmptyStringAsNull)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> diffs = <span style="color:#66d9ef">new</span> List&lt;(<span style="color:#66d9ef">string</span>, <span style="color:#66d9ef">object?</span>)&gt;();
</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> kvp <span style="color:#66d9ef">in</span> newValues)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> name = kvp.Key;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> newVal = kvp.Value;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">object?</span> currentVal = <span style="color:#66d9ef">null</span>;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (item.FieldValues != <span style="color:#66d9ef">null</span> &amp;&amp; item.FieldValues.TryGetValue(name, <span style="color:#66d9ef">out</span> <span style="color:#66d9ef">var</span> cv))
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            currentVal = cv;
</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">if</span> (!ValuesEqual(currentVal, newVal, treatEmptyStringAsNull))
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            diffs.Add((name, newVal));
</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> diffs;
</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">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">bool</span> ValuesEqual(<span style="color:#66d9ef">object?</span> a, <span style="color:#66d9ef">object?</span> b, <span style="color:#66d9ef">bool</span> treatEmptyStringAsNull)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (ReferenceEquals(a, b))
</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><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (a <span style="color:#66d9ef">is</span> <span style="color:#66d9ef">null</span> || b <span style="color:#66d9ef">is</span> <span style="color:#66d9ef">null</span>)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (treatEmptyStringAsNull)
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">if</span> ((a <span style="color:#66d9ef">is</span> <span style="color:#66d9ef">null</span> &amp;&amp; IsEmptyStringLike(b)) || (b <span style="color:#66d9ef">is</span> <span style="color:#66d9ef">null</span> &amp;&amp; IsEmptyStringLike(a)))
</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><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><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    a = Normalize(a, treatEmptyStringAsNull);
</span></span><span style="display:flex;"><span>    b = Normalize(b, treatEmptyStringAsNull);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (a <span style="color:#66d9ef">is</span> IStructuralEquatable seA &amp;&amp; b <span style="color:#66d9ef">is</span> IStructuralEquatable seB)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> StructuralComparisons.StructuralEqualityComparer.Equals(seA, seB);
</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> Equals(a, b);
</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">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">bool</span> IsEmptyStringLike(<span style="color:#66d9ef">object?</span> x)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> x <span style="color:#66d9ef">is</span> <span style="color:#66d9ef">string</span> s &amp;&amp; <span style="color:#66d9ef">string</span>.IsNullOrWhiteSpace(s);
</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">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">object?</span> Normalize(<span style="color:#66d9ef">object?</span> v, <span style="color:#66d9ef">bool</span> treatEmptyStringAsNull)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (v == <span style="color:#66d9ef">null</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">null</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">switch</span> (v)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">case</span> <span style="color:#66d9ef">string</span> s:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> (treatEmptyStringAsNull &amp;&amp; <span style="color:#66d9ef">string</span>.IsNullOrWhiteSpace(s)) ? <span style="color:#66d9ef">null</span> : s;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">case</span> <span style="color:#66d9ef">bool</span> b:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> b;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">case</span> <span style="color:#66d9ef">byte</span> or <span style="color:#66d9ef">sbyte</span> or <span style="color:#66d9ef">short</span> or <span style="color:#66d9ef">ushort</span> or <span style="color:#66d9ef">int</span> or <span style="color:#66d9ef">uint</span> or <span style="color:#66d9ef">long</span> or <span style="color:#66d9ef">ulong</span> or <span style="color:#66d9ef">float</span> or <span style="color:#66d9ef">double</span> or <span style="color:#66d9ef">decimal</span>:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> Convert.ToDecimal(v, CultureInfo.InvariantCulture);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">case</span> DateTime dt:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">var</span> utc = (dt.Kind == DateTimeKind.Utc ? dt : DateTime.SpecifyKind(dt, DateTimeKind.Unspecified)).ToUniversalTime();
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> DateTime(utc.Year, utc.Month, utc.Day, utc.Hour, utc.Minute, utc.Second, DateTimeKind.Utc);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">case</span> FieldUserValue u:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> u.LookupId;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">case</span> FieldLookupValue l:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> l.LookupId;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">case</span> IEnumerable&lt;FieldLookupValue&gt; multiLookup:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> multiLookup.Select(x =&gt; x?.LookupId ?? <span style="color:#ae81ff">0</span>).OrderBy(x =&gt; x).ToArray();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">case</span> TaxonomyFieldValue tx:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> tx.TermGuid?.Trim().ToLowerInvariant();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">case</span> TaxonomyFieldValueCollection txc:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> txc
</span></span><span style="display:flex;"><span>                .Where(x =&gt; x != <span style="color:#66d9ef">null</span> &amp;&amp; !<span style="color:#66d9ef">string</span>.IsNullOrEmpty(x.TermGuid))
</span></span><span style="display:flex;"><span>                .Select(x =&gt; x.TermGuid.Trim().ToLowerInvariant())
</span></span><span style="display:flex;"><span>                .OrderBy(g =&gt; g)
</span></span><span style="display:flex;"><span>                .ToArray();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">case</span> FieldGeolocationValue geo:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">new</span> ValueTuple&lt;<span style="color:#66d9ef">double</span>, <span style="color:#66d9ef">double</span>, <span style="color:#66d9ef">double</span>, <span style="color:#66d9ef">double</span>&gt;(
</span></span><span style="display:flex;"><span>                Math.Round(geo.Latitude, <span style="color:#ae81ff">6</span>),
</span></span><span style="display:flex;"><span>                Math.Round(geo.Longitude, <span style="color:#ae81ff">6</span>),
</span></span><span style="display:flex;"><span>                Math.Round(geo.Altitude, <span style="color:#ae81ff">2</span>),
</span></span><span style="display:flex;"><span>                Math.Round(geo.Measure, <span style="color:#ae81ff">2</span>));
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">case</span> <span style="color:#66d9ef">string</span>[] ss:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> ss
</span></span><span style="display:flex;"><span>                .Select(x =&gt; treatEmptyStringAsNull &amp;&amp; <span style="color:#66d9ef">string</span>.IsNullOrWhiteSpace(x) ? <span style="color:#66d9ef">null</span> : x)
</span></span><span style="display:flex;"><span>                .OrderBy(x =&gt; x, StringComparer.Ordinal)
</span></span><span style="display:flex;"><span>                .ToArray();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">case</span> IEnumerable enumerable when v <span style="color:#66d9ef">is</span> not <span style="color:#66d9ef">string</span>:
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">var</span> list = <span style="color:#66d9ef">new</span> List&lt;<span style="color:#66d9ef">object?</span>&gt;();
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">foreach</span> (<span style="color:#66d9ef">var</span> e <span style="color:#66d9ef">in</span> enumerable)
</span></span><span style="display:flex;"><span>            {
</span></span><span style="display:flex;"><span>                list.Add(Normalize(e, treatEmptyStringAsNull));
</span></span><span style="display:flex;"><span>            }
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> list.ToArray();
</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">default</span>:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> v;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h2 id="the-magic-behind-the-scenes">The Magic Behind the Scenes</h2>
<h3 id="1-the-normalization-dance">1. <strong>The Normalization Dance</strong></h3>
<p>The <code>Normalize</code> method is where the real magic happens. It takes SharePoint&rsquo;s various field types and converts them into something we can actually compare:</p>
<ul>
<li><strong>Numbers</strong>: Everything becomes a <code>decimal</code> because SharePoint loves to mix integers and strings</li>
<li><strong>DateTime</strong>: Converted to UTC and truncated to seconds (because who needs millisecond precision for list items?)</li>
<li><strong>User/Lookup Fields</strong>: We only care about the <code>LookupId</code>, not the display text that might change</li>
<li><strong>Collections</strong>: Sorted alphabetically because SharePoint doesn&rsquo;t guarantee order</li>
<li><strong>Strings</strong>: Can optionally treat empty/whitespace as null (trust me, you want this)</li>
</ul>
<h3 id="2-the">2. <strong>The &ldquo;It&rsquo;s Not You, It&rsquo;s SharePoint&rdquo; Handling</strong></h3>
<p>For arrays and complex objects, I use <code>IStructuralEquatable</code> to do deep comparisons. Because yes, SharePoint will absolutely give you arrays that contain the same items but in different orders.</p>
<h3 id="3-the-business-logic-escape-hatch">3. <strong>The Business Logic Escape Hatch</strong></h3>
<p>The <code>treatEmptyStringAsNull</code> parameter saved my sanity. Different parts of your application might handle empty values differently, and this lets you define your own rules for what counts as &ldquo;unchanged.&rdquo;</p>
<h2 id="but-wait-why-not-just-use-json-comparison">But Wait, Why Not Just Use JSON Comparison?</h2>
<p>Before you ask (because I know you&rsquo;re thinking it): &ldquo;Why build this elaborate comparison engine when you could just serialize both objects to JSON and compare the strings?&rdquo;</p>
<p>Great question. I actually thought the same thing initially. How hard could it be, right? Just <code>JsonSerializer.Serialize()</code> both the old and new values, compare the resulting strings, and call it a day.</p>
<p>Here&rsquo;s what the &ldquo;simple&rdquo; JSON approach looks like:</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">static</span> List&lt;(<span style="color:#66d9ef">string</span> InternalName, <span style="color:#66d9ef">object?</span> NewValue)&gt; GetDifferencesJson(
</span></span><span style="display:flex;"><span>    IDictionary&lt;<span style="color:#66d9ef">string</span>, <span style="color:#66d9ef">object?</span>&gt; oldValues,
</span></span><span style="display:flex;"><span>    IDictionary&lt;<span style="color:#66d9ef">string</span>, <span style="color:#66d9ef">object?</span>&gt; newValues,
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">bool</span> treatEmptyStringAsNull)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> diffs = <span style="color:#66d9ef">new</span> List&lt;(<span style="color:#66d9ef">string</span>, <span style="color:#66d9ef">object?</span>)&gt;();
</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> kvp <span style="color:#66d9ef">in</span> newValues)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> name = kvp.Key;
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> newVal = kvp.Value;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">object?</span> currentVal = <span style="color:#66d9ef">null</span>;
</span></span><span style="display:flex;"><span>        oldValues?.TryGetValue(name, <span style="color:#66d9ef">out</span> currentVal);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> newJson = JsonSerializer.Serialize(newVal);
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> oldJson = JsonSerializer.Serialize(currentVal);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (newJson != oldJson)
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            diffs.Add((name, newVal));
</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> diffs;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p>Looks clean and simple, right? That&rsquo;s what I thought too. So I built both approaches and put them head-to-head with BenchmarkDotNet. The results were&hellip; eye-opening.</p>
<h3 id="the-performance-reality-check">The Performance Reality Check</h3>
<p>Here&rsquo;s what I found when comparing the performance of my custom approach versus JSON string comparison:</p>
<p><strong>Single List Item Comparison:</strong></p>
<ul>
<li><strong>Custom Dictionary Approach</strong>: 749,625 operations/second (1.334 μs per operation)</li>
<li><strong>JSON String Approach</strong>: 201,109 operations/second (4.972 μs per operation)</li>
<li><strong>Performance difference</strong>: 3.7x faster with the custom approach</li>
</ul>
<p><strong>Batch Operations (300 items):</strong></p>
<ul>
<li><strong>Custom Dictionary Approach</strong>: 3,705 operations/second (269.91 μs per batch)</li>
<li><strong>JSON String Approach</strong>: 712 operations/second (1,404.06 μs per batch)</li>
<li><strong>Performance difference</strong>: 5.2x faster with the custom approach</li>
</ul>
<h3 id="why-json-comparison-falls-short">Why JSON Comparison Falls Short</h3>
<p>The numbers tell the story, but here&rsquo;s what&rsquo;s actually happening under the hood:</p>
<ol>
<li><strong>Serialization Overhead</strong>: Converting SharePoint field values to JSON strings requires multiple allocations and string operations</li>
<li><strong>Memory Pressure</strong>: JSON approach allocated nearly 50% more memory (4.67KB vs 3.17KB per operation)</li>
<li><strong>Type Conversion Issues</strong>: JSON serialization doesn&rsquo;t handle SharePoint&rsquo;s quirky field types the way we need</li>
<li><strong>Garbage Collection</strong>: More allocations = more GC pressure = slower overall performance</li>
</ol>
<p>When you&rsquo;re processing hundreds or thousands of list items in batch operations, that 3-5x performance difference really adds up. Plus, the custom approach gives us complete control over how different field types are compared, which JSON comparison simply can&rsquo;t provide.</p>
<h2 id="putting-it-all-together-the-real-world-implementation">Putting It All Together: The Real-World Implementation</h2>
<p>Here&rsquo;s how I actually use this in my APIs:</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">async</span> Task&lt;<span style="color:#66d9ef">bool</span>&gt; UpdateListItemAsync(<span style="color:#66d9ef">int</span> itemId, Dictionary&lt;<span style="color:#66d9ef">string</span>, <span style="color:#66d9ef">object?</span>&gt; newValues)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> clientContext = GetClientContext();
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> list = clientContext.Web.Lists.GetByTitle(<span style="color:#e6db74">&#34;YourList&#34;</span>);
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> listItem = list.GetItemById(itemId);
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    clientContext.Load(listItem);
</span></span><span style="display:flex;"><span>    clientContext.ExecuteQuery();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// The moment of truth - what actually changed?</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> differences = GetDifferences(listItem, newValues, treatEmptyStringAsNull: <span style="color:#66d9ef">true</span>);
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (!differences.Any())
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#75715e">// Nothing changed! Skip the update entirely</span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> <span style="color:#66d9ef">false</span>; <span style="color:#75715e">// &#34;Thanks for playing, but you didn&#39;t actually change anything&#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:#75715e">// Only update the fields that actually changed</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">foreach</span> (<span style="color:#66d9ef">var</span> (fieldName, newValue) <span style="color:#66d9ef">in</span> differences)
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        listItem[fieldName] = newValue;
</span></span><span style="display:flex;"><span>    }
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    listItem.Update();
</span></span><span style="display:flex;"><span>    clientContext.ExecuteQuery();
</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 style="color:#75715e">// &#34;Something actually happened!&#34;</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h2 id="the-numbers-dont-lie-and-theyre-pretty-great">The Numbers Don&rsquo;t Lie (And They&rsquo;re Pretty Great)</h2>
<p>After implementing this change detection across our applications, here&rsquo;s what we typically see:</p>
<p><strong>Before implementing change detection:</strong></p>
<ul>
<li>Applications making thousands of update requests per day</li>
<li>Every single one triggered a SharePoint <code>ExecuteQuery()</code></li>
<li>High API call volumes and occasional throttling issues</li>
</ul>
<p><strong>After implementing change detection:</strong></p>
<ul>
<li>Same number of update requests from users/systems</li>
<li>60-80% contained no actual changes and were skipped</li>
<li>Dramatically reduced SharePoint API consumption</li>
<li>Much lower throttling risk</li>
</ul>
<p><strong>The typical impact:</strong></p>
<ul>
<li><strong>Significant reduction in monthly API calls</strong></li>
<li><strong>Cost savings</strong> with Service Prioritization in SharePoint (varies by usage)</li>
<li><strong>Reduced throttling risk</strong> during busy periods</li>
<li><strong>Faster API responses</strong> because skipped operations are basically instant</li>
</ul>
<p>But here&rsquo;s what really matters: the performance improvement isn&rsquo;t just about the numbers. Users notice when applications feel more responsive, and developers notice when they stop getting throttling alerts.</p>
<h2 id="the-gotchas-because-there-are-always-gotchas">The Gotchas (Because There Are Always Gotchas)</h2>
<h3 id="when-this-approach-might-not-be-for-you">When This Approach Might Not Be For You</h3>
<ol>
<li>
<p><strong>Audit Requirements</strong>: If you need to log every single &ldquo;save&rdquo; action regardless of whether anything changed, this might not work for your use case.</p>
</li>
<li>
<p><strong>Always Update Timestamps</strong>: Some business requirements dictate that &ldquo;LastModified&rdquo; should always be updated when a user clicks save, even if the content is identical.</p>
</li>
<li>
<p><strong>Super Simple Scenarios</strong>: If you&rsquo;re only updating one field and it&rsquo;s a simple string comparison, the overhead of this elaborate comparison might not be worth it.</p>
</li>
</ol>
<h3 id="the-sharepoint-field-types-that-made-me-question-my-life-choices">The SharePoint Field Types That Made Me Question My Life Choices</h3>
<p>Some field types need special handling:</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">// Calculated fields - don&#39;t even try to update these</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">if</span> (field.ReadOnlyField || field.FieldTypeKind == FieldType.Calculated)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">continue</span>; <span style="color:#75715e">// SharePoint will just ignore you anyway</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">// Attachment fields - these need completely different logic</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">if</span> (field.FieldTypeKind == FieldType.Attachments)
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Handle separately - attachments are their own special nightmare</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">continue</span>;
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h2 id="wrapping-up-and-why-this-matters-more-than-you-think">Wrapping Up (And Why This Matters More Than You Think)</h2>
<p>Look, I know this might seem like over-engineering for a simple &ldquo;update SharePoint item&rdquo; operation. But here&rsquo;s the thing: those small inefficiencies add up fast.</p>
<p>In my case, this one change:</p>
<ul>
<li><strong>Improved user experience</strong> with faster response times</li>
<li><strong>Reduced throttling headaches</strong> during busy periods</li>
<li><strong>Made me feel like a responsible developer</strong> (this one&rsquo;s important too!)</li>
</ul>
<p>The pattern I&rsquo;ve shown you isn&rsquo;t just about SharePoint or just about API optimization. It&rsquo;s about asking the fundamental question: <strong>&ldquo;Is this operation actually necessary?&rdquo;</strong></p>
<p>That question has made me a better developer across all the platforms I work with, not just SharePoint.</p>
<p>So next time you&rsquo;re building any kind of update operation—whether it&rsquo;s SharePoint, a database, or that JSON file you&rsquo;re definitely not using as a database—pause for a moment and ask: &ldquo;Did anything actually change?&rdquo;</p>
<p>Your future self (and your API bills) will thank you.</p>
<p><strong>Pro tip</strong>: Start implementing this pattern on your highest-traffic endpoints first. That&rsquo;s where you&rsquo;ll see the biggest impact, and it&rsquo;ll give you the confidence to roll it out everywhere else.</p>
<p>Now go forth and eliminate those unnecessary API calls. Your SharePoint environment will purr like a happy cat.</p>
<p>Change detection is one of five techniques in <a href="https://jeppe-spanggaard.dk/blogs/sharepoint-csom-performance-playbook/">The SharePoint CSOM Performance Playbook</a>. If you want the whole picture of where CSOM calls leak, start there.</p>
]]></content:encoded></item><item><title>Stop Retrying Everything: Smart Graph Batch Retry Logic</title><link>https://jeppe-spanggaard.dk/blogs/graph-batch-smart-retry/</link><pubDate>Mon, 22 Sep 2025 00:00:00 +0000</pubDate><author>Jeppe</author><guid>https://jeppe-spanggaard.dk/blogs/graph-batch-smart-retry/</guid><description>Learn smart retry logic for Microsoft Graph batching to optimize API calls, reduce throttling, and enhance user experience.</description><content:encoded><![CDATA[<h2 id="the-day-my-batch-requests-started-fighting-back">The Day My Batch Requests Started Fighting Back</h2>
<p>Picture this: It&rsquo;s 2 AM, you&rsquo;re on your third cup of coffee, and you&rsquo;re watching your perfectly crafted Microsoft Graph batch request fail spectacularly. Again.</p>
<p>You&rsquo;ve got 25 files to download from SharePoint. Your batch processes 24 of them perfectly, then one lonely file decides to throw a throttling tantrum. What does your retry logic do? It throws away all 24 successful downloads and starts over. From scratch. Like a digital Groundhog Day, but less amusing and more soul-crushing.</p>
<p>Sound familiar? Welcome to the &ldquo;retry everything&rdquo; club – where perfectly good API calls go to die unnecessarily. 😅</p>
<h2 id="the-grocery-cart-problem-or-why-were-doing-this-wrong">The Grocery Cart Problem (Or: Why We&rsquo;re Doing This Wrong)</h2>
<p>Let me paint you a picture. You&rsquo;re at the grocery store with a cart full of 20 items. You get to checkout, and the cashier says, &ldquo;Sorry, we&rsquo;re out of milk.&rdquo;</p>
<p>What would you do?</p>
<ul>
<li><strong>Option A:</strong> Put back everything, go home, and come back later to shop for all 20 items again</li>
<li><strong>Option B:</strong> Buy the 19 items you can get, then come back just for the milk</li>
</ul>
<p>If you picked Option A, congratulations – you think like most API retry logic! If you picked Option B, you&rsquo;re ready to learn about smart retries.</p>
<p><strong>The &ldquo;retry everything&rdquo; approach is like Option A, and here&rsquo;s why it&rsquo;s bonkers:</strong></p>
<ul>
<li>🔄 <strong>Wasted effort</strong>: You&rsquo;re re-requesting stuff that already worked perfectly</li>
<li>🐌 <strong>Slower performance</strong>: Users wait longer while you redo successful work</li>
<li>📈 <strong>Throttling amplification</strong>: You&rsquo;re actually making the problem worse by hitting successful endpoints again</li>
<li>🔍 <strong>Poor debugging</strong>: Can&rsquo;t easily identify which specific requests are the real troublemakers</li>
</ul>
<p>I learned this the hard way when I watched a simple file sync turn into an API call avalanche. 20 requests became 40, then 80, then&hellip; well, let&rsquo;s just say Microsoft&rsquo;s throttling system got very acquainted with my application.</p>
<h2 id="the-aha-moment-its-simpler-than-you-think">The &ldquo;Aha!&rdquo; Moment (It&rsquo;s Simpler Than You Think)</h2>
<p>The solution hit me during one of those 2 AM debugging sessions: <strong>What if we only retry the stuff that actually failed?</strong></p>
<p>Revolutionary, right? 😏</p>
<p>Here&rsquo;s the beautiful thing – this isn&rsquo;t some PhD-level computer science. It&rsquo;s just common sense applied to code. Keep the winners, retry the losers. Simple.</p>
<p>But (there&rsquo;s always a &ldquo;but&rdquo;), there&rsquo;s one sneaky technical challenge that makes this trickier than it sounds. Microsoft&rsquo;s Graph SDK has a helpful method called <code>NewBatchWithFailedRequests()</code>, but it has a quirk: it generates brand new request IDs. This breaks your ability to map responses back to your original data.</p>
<p>Think of it like this: You order pizza for table 5, but when they bring the replacement slice, they call it table 23. Good luck figuring out who ordered what!</p>
<p>If you&rsquo;re new to Graph batching or request mapping, I&rsquo;d recommend checking out my post on <a href="https://jeppe-spanggaard.dk/blogs/graph-batching-file-content-mapping/">Graph Batching for File Content: Mapping Requests to Responses</a> first. It&rsquo;s like the prequel to this story – explains how to keep track of what&rsquo;s what when dealing with batch responses.</p>
<h2 id="quick-win-summary-for-the-impatient-developers">Quick Win Summary (For the Impatient Developers)</h2>
<p><strong>The Problem:</strong> Your retry logic is like that friend who starts the entire conversation over when they missed one word. Inefficient and annoying.</p>
<p><strong>The Solution:</strong> A drop-in extension method that only retries the actual failures while keeping successful responses safe and sound.</p>
<p><strong>The Payoff:</strong></p>
<ul>
<li>⚡ Faster operations (no more re-downloading working files)</li>
<li>📉 Fewer API calls (your rate limits will thank you)</li>
<li>🎯 Less throttling (stop beating dead endpoints)</li>
<li>😌 Happier users (and happier you at 2 AM)</li>
</ul>
<p><strong>The Catch:</strong> You need to understand request-to-response mapping. Don&rsquo;t worry, it&rsquo;s not rocket science, and I&rsquo;ve got a whole post about it.</p>
<p><strong>Time Investment:</strong> About 5 minutes to implement, countless hours of frustration saved.</p>
<p>Ready for the nitty-gritty? Let&rsquo;s dive in! 👇</p>
<h2 id="the-hero-of-our-story-the-smart-retry-extension">The Hero of Our Story: The Smart Retry Extension</h2>
<p>Okay, here&rsquo;s where we get our hands dirty. The main challenge isn&rsquo;t just filtering out successful requests – it&rsquo;s that pesky <code>NewBatchWithFailedRequests</code> method that scrambles your request IDs like eggs at Sunday brunch.</p>
<p>Here&rsquo;s the extension method that saves the day:</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-cs" data-lang="cs"><span style="display:flex;"><span><span style="color:#66d9ef">internal</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">GraphServiceClientExtensions</span> 
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">internal</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">async</span> Task&lt;(IReadOnlyDictionary&lt;<span style="color:#66d9ef">string</span>, HttpStatusCode&gt; Statuses, Dictionary&lt;<span style="color:#66d9ef">string</span>, HttpResponseMessage&gt; BatchResponse)&gt; 
</span></span><span style="display:flex;"><span>        PostBatchWithFailedDependencyRetriesAsync(<span style="color:#66d9ef">this</span> GraphServiceClient graphClient, BatchRequestContentCollection originalBatch) 
</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> maxRetries = <span style="color:#ae81ff">5</span>;
</span></span><span style="display:flex;"><span>        TimeSpan delay = TimeSpan.FromSeconds(<span style="color:#ae81ff">1</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        Dictionary&lt;<span style="color:#66d9ef">string</span>, HttpResponseMessage&gt; allResponses = <span style="color:#66d9ef">new</span> Dictionary&lt;<span style="color:#66d9ef">string</span>, HttpResponseMessage&gt;();
</span></span><span style="display:flex;"><span>        Dictionary&lt;<span style="color:#66d9ef">string</span>, HttpStatusCode&gt; allStatuses = <span style="color:#66d9ef">new</span> Dictionary&lt;<span style="color:#66d9ef">string</span>, HttpStatusCode&gt;();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        BatchRequestContentCollection batchToSend = originalBatch;
</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;= maxRetries; attempt++) 
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            BatchResponseContentCollection batchResponse = <span style="color:#66d9ef">await</span> graphClient.Batch.PostAsync(batchToSend);
</span></span><span style="display:flex;"><span>            Dictionary&lt;<span style="color:#66d9ef">string</span>, HttpStatusCode&gt; responses = <span style="color:#66d9ef">await</span> batchResponse.GetResponsesStatusCodesAsync();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// Filter out failures (excluding redirects which are normal for file content)</span>
</span></span><span style="display:flex;"><span>            Dictionary&lt;<span style="color:#66d9ef">string</span>, HttpStatusCode&gt; failedRequests = responses
</span></span><span style="display:flex;"><span>                .Where(kvp =&gt; !BatchResponseContent.IsSuccessStatusCode(kvp.Value) &amp;&amp; kvp.Value != HttpStatusCode.Found)
</span></span><span style="display:flex;"><span>                .ToDictionary(kvp =&gt; kvp.Key, kvp =&gt; kvp.Value);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// Collect all responses from this attempt</span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">foreach</span> (<span style="color:#66d9ef">var</span> kvp <span style="color:#66d9ef">in</span> responses) 
</span></span><span style="display:flex;"><span>            {
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">var</span> response = <span style="color:#66d9ef">await</span> batchResponse.GetResponseByIdAsync(kvp.Key);
</span></span><span style="display:flex;"><span>                allResponses[kvp.Key] = response;
</span></span><span style="display:flex;"><span>                allStatuses[kvp.Key] = kvp.Value;
</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">if</span> (failedRequests.Count == <span style="color:#ae81ff">0</span> || attempt == maxRetries) 
</span></span><span style="display:flex;"><span>            {
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">break</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> Task.Delay(delay);
</span></span><span style="display:flex;"><span>            delay = TimeSpan.FromSeconds(delay.TotalSeconds * <span style="color:#ae81ff">2</span>);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// The key problem: NewBatchWithFailedRequests creates new request IDs!</span>
</span></span><span style="display:flex;"><span>            batchToSend = batchToSend.NewBatchWithFailedRequests(responses);
</span></span><span style="display:flex;"><span>            
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// This is why we need this method - restore the original request IDs</span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">await</span> RestoreOriginalRequestIdsAsync(batchToSend, originalBatch);
</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> (allStatuses, allResponses);
</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">private</span> <span style="color:#66d9ef">static</span> <span style="color:#66d9ef">async</span> Task RestoreOriginalRequestIdsAsync(
</span></span><span style="display:flex;"><span>        BatchRequestContentCollection newBatch, 
</span></span><span style="display:flex;"><span>        BatchRequestContentCollection originalBatch) 
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> stepsSnapshot = newBatch.BatchRequestSteps.ToArray();
</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> kvp <span style="color:#66d9ef">in</span> stepsSnapshot) 
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">var</span> oldStepId = kvp.Key;
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">var</span> step = kvp.Value;
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">var</span> requestPath = step.Request.RequestUri!.AbsolutePath;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// Find the original request ID by matching the request path</span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">var</span> matchingOriginal = originalBatch.BatchRequestSteps
</span></span><span style="display:flex;"><span>                .First(x =&gt; x.Value.Request.RequestUri!.AbsolutePath == requestPath);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">var</span> originalStepId = matchingOriginal.Key;
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">if</span> (oldStepId != originalStepId) 
</span></span><span style="display:flex;"><span>            {
</span></span><span style="display:flex;"><span>                newBatch.RemoveBatchRequestStepWithId(oldStepId);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">var</span> newStep = <span style="color:#66d9ef">new</span> BatchRequestStep(
</span></span><span style="display:flex;"><span>                    requestId: originalStepId,
</span></span><span style="display:flex;"><span>                    httpRequestMessage: step.Request,
</span></span><span style="display:flex;"><span>                    dependsOn: step.DependsOn);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>                newBatch.AddBatchRequestStep(newStep);
</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><strong>What&rsquo;s happening here?</strong> Think of it as a diplomatic negotiator for your API calls:</p>
<ol>
<li><strong>The ID Shuffle Problem</strong>: <code>NewBatchWithFailedRequests</code> gives failed requests shiny new IDs, like witness protection for HTTP requests</li>
<li><strong>The Detective Work</strong>: <code>RestoreOriginalRequestIdsAsync</code> plays detective, matching requests by their paths to find their original identities</li>
<li><strong>The Happy Reunion</strong>: Failed requests get their original IDs back, so your mapping dictionary doesn&rsquo;t break down in tears</li>
</ol>
<p>It&rsquo;s like having a really good wedding planner who makes sure everyone sits at the right table, even after the venue changes.</p>
<h2 id="showtime-watching-smart-retries-in-action">Showtime: Watching Smart Retries in Action</h2>
<p>Now let&rsquo;s see our smart retry logic work its magic in a real-world scenario. Imagine you&rsquo;re building a document sync tool and need to download 25 files from SharePoint. Some will work perfectly, others might throw tantrums due to throttling or network hiccups.</p>
<p>Here&rsquo;s how the new approach handles it like a champ:</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-cs" data-lang="cs"><span style="display:flex;"><span><span style="color:#75715e">// Let&#39;s say you need to download content from 25 SharePoint files</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> batch = <span style="color:#66d9ef">new</span> BatchRequestContentCollection(graphClient);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> fileMapping = <span style="color:#66d9ef">new</span> Dictionary&lt;<span style="color:#66d9ef">string</span>, FileContentRequest&gt;();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Build the batch for file content downloads</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> filesToDownload = <span style="color:#66d9ef">await</span> GetFilesToProcess(); <span style="color:#75715e">// Your method to get file list</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> file <span style="color:#66d9ef">in</span> filesToDownload) 
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> requestInfo = graphClient.Sites[siteId]
</span></span><span style="display:flex;"><span>                                .Drives[driveId]
</span></span><span style="display:flex;"><span>                                .Items[file.DriveItemId]
</span></span><span style="display:flex;"><span>                                .Content
</span></span><span style="display:flex;"><span>                                .ToGetRequestInformation();
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> requestId = <span style="color:#66d9ef">await</span> batch.AddBatchRequestStepAsync(requestInfo);
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#75715e">// Map the request ID to your file info (same pattern as previous post)</span>
</span></span><span style="display:flex;"><span>    fileMapping[requestId] = <span style="color:#66d9ef">new</span> FileContentRequest 
</span></span><span style="display:flex;"><span>    { 
</span></span><span style="display:flex;"><span>        DriveItemId = file.DriveItemId,
</span></span><span style="display:flex;"><span>        FileName = file.Name,
</span></span><span style="display:flex;"><span>        ExpectedSize = file.Size,
</span></span><span style="display:flex;"><span>        DownloadStartTime = DateTime.Now
</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:#75715e">// 🎯 Here&#39;s where the magic happens - just one line change!</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> (statuses, responses) = <span style="color:#66d9ef">await</span> graphClient.PostBatchWithFailedDependencyRetriesAsync(batch);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#75715e">// Process results - this is where the retry really shines</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> successfulDownloads = <span style="color:#66d9ef">new</span> List&lt;FileDownloadResult&gt;();
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> failedDownloads = <span style="color:#66d9ef">new</span> List&lt;<span style="color:#66d9ef">string</span>&gt;();
</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> kvp <span style="color:#66d9ef">in</span> fileMapping) 
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> requestId = kvp.Key;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> fileRequest = kvp.Value;
</span></span><span style="display:flex;"><span>    
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (responses.TryGetValue(requestId, <span style="color:#66d9ef">out</span> <span style="color:#66d9ef">var</span> response)) 
</span></span><span style="display:flex;"><span>    {
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">var</span> statusCode = statuses[requestId];
</span></span><span style="display:flex;"><span>        
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> (BatchResponseContent.IsSuccessStatusCode(statusCode)) 
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// Success! Handle the file content</span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">var</span> contentBytes = <span style="color:#66d9ef">await</span> response.Content.ReadAsByteArrayAsync();
</span></span><span style="display:flex;"><span>            
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// Save to your desired location</span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">var</span> localPath = Path.Combine(downloadFolder, fileRequest.FileName);
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">await</span> File.WriteAllBytesAsync(localPath, contentBytes);
</span></span><span style="display:flex;"><span>            
</span></span><span style="display:flex;"><span>            successfulDownloads.Add(<span style="color:#66d9ef">new</span> FileDownloadResult 
</span></span><span style="display:flex;"><span>            { 
</span></span><span style="display:flex;"><span>                FileName = fileRequest.FileName,
</span></span><span style="display:flex;"><span>                LocalPath = localPath,
</span></span><span style="display:flex;"><span>                ActualSize = contentBytes.Length,
</span></span><span style="display:flex;"><span>                ExpectedSize = fileRequest.ExpectedSize,
</span></span><span style="display:flex;"><span>                DownloadTime = DateTime.Now - fileRequest.DownloadStartTime
</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">else</span> 
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// Even after smart retries, this file failed</span>
</span></span><span style="display:flex;"><span>            failedDownloads.Add(<span style="color:#e6db74">$&#34;{fileRequest.FileName} ({statusCode})&#34;</span>);
</span></span><span style="display:flex;"><span>            
</span></span><span style="display:flex;"><span>            <span style="color:#75715e">// Log the specific failure for debugging</span>
</span></span><span style="display:flex;"><span>            Console.WriteLine(<span style="color:#e6db74">$&#34;Failed to download {fileRequest.FileName}: {statusCode}&#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:#75715e">// Always clean up the response</span>
</span></span><span style="display:flex;"><span>        response.Dispose();
</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>Console.WriteLine(<span style="color:#e6db74">$&#34;Successfully downloaded: {successfulDownloads.Count} files&#34;</span>);
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">if</span> (failedDownloads.Any())
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    Console.WriteLine(<span style="color:#e6db74">$&#34;Failed downloads: {string.Join(&#34;</span>, <span style="color:#e6db74">&#34;, failedDownloads)}&#34;</span>);
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><p><strong>The beautiful part?</strong> Look at that line with the magic emoji 🎯. That&rsquo;s literally the only change you need to make to your existing batch processing code. Everything else stays exactly the same.</p>
<p><strong>Here&rsquo;s what&rsquo;s happening behind the scenes:</strong></p>
<ol>
<li><strong>First batch attempt</strong>: Say 20 files succeed, 5 fail due to throttling</li>
<li><strong>Smart filtering</strong>: Keep those 20 successful responses safe</li>
<li><strong>Targeted retry</strong>: Build a new batch with just the 5 failures</li>
<li><strong>ID preservation</strong>: Make sure those 5 retries still map to your original file info</li>
<li><strong>Rinse and repeat</strong>: Maybe 4 of the 5 succeed on retry, leaving just 1 persistent troublemaker</li>
</ol>
<p><strong>The result?</strong> Instead of making 250 API calls (25 files × 5 retry attempts for the unlucky ones), you might only make 35 total calls. Your throttling problems become manageable, and files download way faster.</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-cs" data-lang="cs"><span style="display:flex;"><span><span style="color:#75715e">// Supporting classes for the example above</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">FileContentRequest</span> 
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">string</span> DriveItemId { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">set</span>; } = <span style="color:#66d9ef">string</span>.Empty;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">string</span> FileName { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">set</span>; } = <span style="color:#66d9ef">string</span>.Empty;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">long</span> ExpectedSize { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">set</span>; }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> DateTime DownloadStartTime { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">set</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">public</span> <span style="color:#66d9ef">class</span> <span style="color:#a6e22e">FileDownloadResult</span> 
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">string</span> FileName { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">set</span>; } = <span style="color:#66d9ef">string</span>.Empty;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">string</span> LocalPath { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">set</span>; } = <span style="color:#66d9ef">string</span>.Empty;
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">long</span> ActualSize { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">set</span>; }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> <span style="color:#66d9ef">long</span> ExpectedSize { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">set</span>; }
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">public</span> TimeSpan DownloadTime { <span style="color:#66d9ef">get</span>; <span style="color:#66d9ef">set</span>; }
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h2 id="the-method-to-the-madness-whats-really-happening">The Method to the Madness (What&rsquo;s Really Happening)</h2>
<p>I know that extension method looks intimidating – like trying to read assembly instructions in a foreign language. But once you break it down, it&rsquo;s actually pretty logical. Let me walk you through the step-by-step dance:</p>
<p><strong>Step 1: The First Attempt</strong>
&ldquo;Let&rsquo;s try everything once and see what happens&rdquo;</p>
<p>Sends your original batch of 25 files and carefully captures every single response and status code. No throwing anything away yet.</p>
<p><strong>Step 2: The Great Sorting</strong>
&ldquo;Okay, who succeeded and who&rsquo;s being difficult?&rdquo;</p>
<p>Separates the winners from the losers, but (and this is important) ignores redirect responses. Why? Because when you&rsquo;re downloading large files, redirects are totally normal – SharePoint often redirects you to the actual storage location.</p>
<p><strong>Step 3: The Preservation Society</strong>
&ldquo;Keep the good stuff safe while we deal with the troublemakers&rdquo;</p>
<p>All successful responses get stored in a safe place while we build a new, smaller batch containing only the failed requests. It&rsquo;s like having a really good filing system for your API responses.</p>
<p><strong>Step 4: The Identity Crisis Resolution</strong>
&ldquo;Wait, who are you again? Let me check your original ID&hellip;&rdquo;</p>
<p>This is the tricky bit! The <code>NewBatchWithFailedRequests</code> method gives everyone new IDs, like a witness protection program for HTTP requests. Our <code>RestoreOriginalRequestIdsAsync</code> method plays detective, matching requests by their URL paths to restore their original identities.</p>
<p><strong>Step 5: The Polite Wait</strong>
&ldquo;Let&rsquo;s not be pushy – maybe try again in a second?&rdquo;</p>
<p>Implements <a href="https://docs.microsoft.com/en-us/azure/architecture/patterns/retry">exponential backoff</a> – starts with a 1-second wait, then 2 seconds, then 4 seconds, etc. This prevents your app from being that annoying person who keeps knocking on the door every second.</p>
<p><strong>Step 6: The Safety Net</strong>
&ldquo;Okay, we tried 5 times. Some files just aren&rsquo;t meant to be downloaded today.&rdquo;</p>
<p>Gives up after 5 attempts to prevent infinite retry loops. Because sometimes you need to know when to walk away from the poker table.</p>
<h2 id="why-this-actually-works-the-science-behind-the-magic">Why This Actually Works (The Science Behind the Magic)</h2>
<p>Here&rsquo;s what makes this approach so much better than the &ldquo;retry everything&rdquo; strategy:</p>
<p><strong>🎯 Surgical Precision</strong>
Only retry what actually failed – it&rsquo;s like having a really good therapist who focuses on the actual problems instead of rehashing everything from childhood.</p>
<p>No wasted API calls on requests that already succeeded. If 24 out of 25 files downloaded perfectly, why punish them with another round trip?</p>
<p><strong>⚡ Speed Demon</strong>
Successful requests don&rsquo;t get repeated, so everything finishes faster – sometimes dramatically faster.</p>
<p>Users see their successful downloads immediately while you quietly retry the problematic ones in the background.</p>
<p><strong>🤝 Throttling-Friendly</strong>
Fewer total requests means you&rsquo;re less likely to hit Microsoft&rsquo;s rate limits, and when you do, recovery is faster.</p>
<p>Instead of amplifying throttling issues, you&rsquo;re actually helping to resolve them by reducing load on the endpoints that are already struggling.</p>
<p><strong>🔄 Drop-in Simplicity</strong>
Change literally one line of code and you&rsquo;re done. No architectural rewrites, no complex state management – just swap out the method call.</p>
<p>Your existing error handling, logging, and business logic all stay exactly the same.</p>
<p><strong>🔍 Debug Paradise</strong>
Easy to see exactly which requests are consistently failing, making troubleshooting a breeze instead of a nightmare.</p>
<p>When file &ldquo;ImportantDocument.pdf&rdquo; fails on every retry attempt, you know there&rsquo;s something specific about that file, not your entire batch logic.</p>
<h2 id="the-before-and-after-moment">The &ldquo;Before and After&rdquo; Moment</h2>
<p>Let me paint you a picture of how this changes your life:</p>
<p><strong>Before Smart Retries:</strong></p>
<ul>
<li>25 file batch fails on 3 files due to throttling</li>
<li>Retry all 25 files → now 5 files fail due to increased throttling</li>
<li>Retry all 25 files again → now 8 files fail</li>
<li>You&rsquo;re now in the throttling spiral of doom</li>
<li>Users are staring at loading spinners</li>
<li>You&rsquo;re questioning your career choices</li>
</ul>
<p><strong>After Smart Retries:</strong></p>
<ul>
<li>25 file batch fails on 3 files due to throttling</li>
<li>Keep the 22 successful files, retry only the 3 failures</li>
<li>Maybe 2 of the 3 succeed on retry, leaving 1 stubborn file</li>
<li>Final retry gets the last file, or you log it as a persistent issue</li>
<li>Users get 24/25 files quickly, you sleep better at night</li>
</ul>
<p>It&rsquo;s the difference between being stuck in traffic because one lane is blocked (and everyone keeps switching to that lane), versus just using the open lanes and going around the problem.</p>
<h2 id="the-bottom-line-and-why-your-future-self-will-thank-you">The Bottom Line (And Why Your Future Self Will Thank You)</h2>
<p>I&rsquo;ll be real with you – when I first started working with Microsoft Graph batching, I thought the built-in retry policies were enough. &ldquo;How hard could it be?&rdquo; I thought. &ldquo;APIs fail sometimes, just retry them!&rdquo;</p>
<p>Then I built my first real-world document sync application. Suddenly, I was dealing with users uploading hundreds of files, enterprise throttling limits, and the occasional network hiccup that would bring the whole operation to a screeching halt.</p>
<p><strong>That&rsquo;s when I learned the hard way that &ldquo;retry everything&rdquo; is like using a sledgehammer to hang a picture frame.</strong> Sure, it might work, but you&rsquo;re probably going to break some stuff in the process.</p>
<p>This selective retry approach has been a game-changer. Not just for performance (though users definitely notice when their bulk operations actually complete), but for debugging too. When you can see that <code>ImportantReport_v23_FINAL_REALLY_FINAL.docx</code> is the file that keeps failing, you can actually do something about it.</p>
<p><strong>The best part?</strong> Once you have this extension method in your toolkit, it becomes muscle memory. You&rsquo;re not adding complexity to your day-to-day development – you&rsquo;re just swapping out one method call for a smarter one. It&rsquo;s like upgrading from a flip phone to a smartphone – you wonder how you ever lived without it.</p>
<p><strong>Pro tip:</strong> After implementing this, keep an eye on your application logs. You&rsquo;ll start to notice patterns in failures that you never saw before. Maybe certain file types are more prone to issues, or maybe there&rsquo;s a specific time of day when throttling gets worse. This kind of insight is pure gold for optimization.</p>
<p>The moral of the story? Sometimes the biggest performance improvements come not from doing things faster, but from doing fewer unnecessary things. And sometimes, the best debugging tool is just&hellip; not breaking the working stuff while you fix the broken stuff.</p>
<p>Your 2 AM debugging sessions will never be the same. 😌</p>
<h2 id="want-to-learn-more-the-reading-list">Want to Learn More? (The Reading List)</h2>
<ul>
<li><strong><a href="https://docs.microsoft.com/en-us/graph/json-batching">Microsoft Graph JSON batching</a></strong> - The official documentation (surprisingly readable!)</li>
<li><strong><a href="https://jeppe-spanggaard.dk/blogs/graph-batching-file-content-mapping/">Graph Batching for File Content: Mapping Requests to Responses</a></strong> - My previous post that sets up the foundation for this one</li>
<li><strong><a href="https://docs.microsoft.com/en-us/graph/throttling">Microsoft Graph throttling guidance</a></strong> - Understanding what makes Microsoft&rsquo;s APIs cranky</li>
<li><strong><a href="https://developer.microsoft.com/en-us/graph/graph-explorer">Graph Explorer</a></strong> - Test your batch requests interactively (great for experimenting)</li>
<li><strong><a href="https://docs.microsoft.com/en-us/azure/architecture/patterns/retry">Exponential Backoff Pattern</a></strong> - The polite way to retry things</li>
</ul>
<p>Now go forth and batch smarter, not harder! 🚀</p>
]]></content:encoded></item><item><title>DevProxy: How to Test API Rate Limiting and Throttling in C# Development</title><link>https://jeppe-spanggaard.dk/blogs/devproxy-throttling-testing/</link><pubDate>Sun, 10 Aug 2025 00:00:00 +0000</pubDate><author>Jeppe</author><guid>https://jeppe-spanggaard.dk/blogs/devproxy-throttling-testing/</guid><description>Discover how to simulate Microsoft Graph and SharePoint throttling locally using DevProxy, and prevent production slowdowns before they happen.</description><content:encoded><![CDATA[<h2 id="the-problem-when-parallel-programming-backfires">The Problem: When Parallel Programming Backfires</h2>
<p>If you’ve ever optimized your C# API calls with parallel programming, you might know this story.</p>
<p>Your client wants faster performance. You run multiple API requests in parallel. Locally, everything flies — especially late at night when traffic is low. But the next morning, on the final pre-deployment test, disaster strikes.</p>
<p><strong>Random errors. Requests delayed for 45 seconds.</strong><br>
Microsoft Graph or SharePoint has slammed you with throttling and rate limits. Your blazing-fast local solution crumbles under production-like conditions.</p>
<hr>
<h2 id="how-crud-operations-can-secretly-burn-through-your-limits--and-how-to-catch-them-with-devproxy">How CRUD Operations Can Secretly Burn Through Your Limits — and How to Catch Them with DevProxy</h2>
<p>Here’s the thing:<br>
SharePoint Online charges “Resource Units” (RUs) for every request you make. Think of RUs as an invisible currency — every API call you send deducts from your allowance. Run out too fast, and throttling kicks in.</p>
<p>And those “simple” operations? They’re not as cheap as you think.</p>
<p><strong>From Microsoft’s RU table</strong>:</p>
<table>
  <thead>
      <tr>
          <th>Operation Type</th>
          <th>RU Cost</th>
          <th>What That Means</th>
      </tr>
  </thead>
  <tbody>
      <tr>
          <td><strong>Single item query</strong></td>
          <td>1 RU</td>
          <td>Reading one specific list item</td>
      </tr>
      <tr>
          <td><strong>Multi-item query</strong></td>
          <td>2 RUs</td>
          <td>Listing children, filtering, sorting</td>
      </tr>
      <tr>
          <td><strong>Create / Update / Delete / Upload</strong></td>
          <td>2 RUs</td>
          <td>Per individual operation (bulk operations may be more efficient)</td>
      </tr>
      <tr>
          <td><strong>Permission expansion</strong> (<code>$expand=permissions</code>)</td>
          <td>5 RUs</td>
          <td>Heavy permission lookups</td>
      </tr>
  </tbody>
</table>
<blockquote>
<p><strong>Source:</strong> <a href="https://learn.microsoft.com/en-us/sharepoint/dev/general-development/how-to-avoid-getting-throttled-or-blocked-in-sharepoint-online#resource-units">Microsoft&rsquo;s official SharePoint throttling documentation</a></p>
</blockquote>
<p>Permission expansions are just one type of &ldquo;expensive&rdquo; call. Another common scenario that can impact RU consumption is <strong>making multiple separate queries instead of using CAML joins</strong> — something I explored in <a href="https://jeppe-spanggaard.dk/blogs/joining-multiple-lists-csom-caml/">my CAML join post</a>.<br>
While joining multiple lists in a single query is actually more efficient than separate calls, poorly structured queries or retrieving unnecessarily large datasets can still consume RUs quickly if not optimized properly.</p>
<hr>
<h3 id="why-this-sneaks-up-on-you">Why This Sneaks Up on You</h3>
<p>When coding locally, it’s easy to run a handful of queries without noticing.<br>
But in production, with real concurrency and volume, these calls pile up in seconds.</p>
<p>Imagine:</p>
<ul>
<li>10 parallel updates (2 RUs each) = <strong>20 RUs in one burst</strong></li>
<li>Add a few joins/expansions or large list queries, and you’re suddenly <em>burning through limits 5x faster</em>.</li>
</ul>
<hr>
<h3 id="how-devproxy-can-show-you-the-pain-before-production">How DevProxy Can Show You the Pain Before Production</h3>
<p>Here’s where DevProxy shines.<br>
If you configure it to simulate throttling based on these RU-heavy calls, you’ll <em>see</em> the impact locally:</p>
<ol>
<li><strong>Enable throttling plugins</strong> in your <code>devproxy.json</code> (as shown earlier).</li>
<li>Point <code>urlsToWatch</code> at your SharePoint endpoints.</li>
<li>Run your CRUD-heavy code.</li>
</ol>
<p>DevProxy will start throwing 429s (Too Many Requests) once your “fake” RU budget is exhausted — just like SharePoint would in production.</p>
<p>The beautiful part?<br>
You can crank the limits <em>down</em> during testing to make expensive patterns obvious. Even a single large query or unbatched <code>Update</code> will light up your logs.</p>
<p>Example DevProxy log when hitting a throttling simulation:</p>
<pre tabindex="0"><code>[Warning] Throttling triggered: 2 parallel Create calls exceeded RU limit (RateLimitingPlugin)
Retry after: 30 seconds
</code></pre><p><strong>Pro tip:</strong><br>
Use DevProxy as a <strong>budget meter</strong> for your API calls. Treat every 2-RU and 5-RU operation as “spending big” — and redesign those spots <em>before</em> they become a production outage.</p>
<h2 id="what-is-devproxy">What is DevProxy?</h2>
<p><a href="https://github.com/dotnet/dev-proxy">DevProxy</a> is an open-source HTTP/HTTPS proxy server that can simulate real-world network issues, including:</p>
<ul>
<li><a href="https://learn.microsoft.com/en-us/microsoft-cloud/dev/dev-proxy/concepts/what-is-rate-limiting"><strong>Rate limiting</strong></a></li>
<li><a href="https://learn.microsoft.com/en-us/microsoft-cloud/dev/dev-proxy/concepts/what-is-throttling"><strong>Throttling</strong></a></li>
<li><a href="https://learn.microsoft.com/en-us/microsoft-cloud/dev/dev-proxy/how-to/simulate-slow-api-responses"><strong>Network delays</strong></a></li>
<li><a href="https://learn.microsoft.com/en-us/microsoft-cloud/dev/dev-proxy/how-to/test-my-app-with-random-errors"><strong>Intermittent errors</strong></a></li>
</ul>
<p>It’s free, open source, and designed for developers who want to <strong>catch performance bottlenecks before they reach production</strong>.</p>
<hr>
<h2 id="installing-devproxy">Installing DevProxy</h2>
<p>Follow the official setup guide here:<br>
<a href="https://learn.microsoft.com/en-us/microsoft-cloud/dev/dev-proxy/get-started/set-up">DevProxy Installation Documentation</a></p>
<hr>
<h2 id="basic-usage">Basic Usage</h2>
<p>Run DevProxy with the default configuration:</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
</span></span></code></pre></div><p>It will begin intercepting all HTTP/HTTPS requests.</p>
<blockquote>
<p><strong>Tip:</strong> Start DevProxy <em>before</em> running your own code — otherwise, it won’t capture the traffic.</p>
</blockquote>
<hr>
<h2 id="simulating-microsoft-graph-throttling">Simulating Microsoft Graph Throttling</h2>
<p>Here’s how to configure DevProxy to reproduce Microsoft Graph and SharePoint throttling issues locally.</p>
<h3 id="1-create-a-devproxyjson-configuration-file">1. Create a <code>devproxy.json</code> configuration file</h3>
<p>This is the exact configuration I used when testing my problematic parallel 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-json" data-lang="json"><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">&#34;$schema&#34;</span>: <span style="color:#e6db74">&#34;https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v0.27.0/rc.schema.json&#34;</span>,
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">&#34;rate&#34;</span>: <span style="color:#ae81ff">25</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/dev-proxy-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;RateLimitingPlugin&#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/dev-proxy-plugins.dll&#34;</span>,
</span></span><span style="display:flex;"><span>      <span style="color:#f92672">&#34;configSection&#34;</span>: <span style="color:#e6db74">&#34;rateLimitingPlugin&#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/dev-proxy-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/v1.0/*&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://graph.microsoft.com/beta/*&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://graph.microsoft.us/v1.0/*&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://graph.microsoft.us/beta/*&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://dod-graph.microsoft.us/v1.0/*&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://dod-graph.microsoft.us/beta/*&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://microsoftgraph.chinacloudapi.cn/v1.0/*&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://microsoftgraph.chinacloudapi.cn/beta/*&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://*.sharepoint.*/*_api/web/GetClientSideComponents&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://*.sharepoint.*/*_api/*&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://*.sharepoint.*/*_vti_bin/*&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://*.sharepoint-df.*/*_api/*&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;https://*.sharepoint-df.*/*_vti_bin/*&#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;$schema&#34;</span>: <span style="color:#e6db74">&#34;https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v0.27.0/graphrandomerrorplugin.schema.json&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&#34;allowedErrors&#34;</span>: [
</span></span><span style="display:flex;"><span>      <span style="color:#ae81ff">429</span>,
</span></span><span style="display:flex;"><span>      <span style="color:#ae81ff">503</span>,
</span></span><span style="display:flex;"><span>      <span style="color:#ae81ff">504</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;rateLimitingPlugin&#34;</span>: {
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&#34;$schema&#34;</span>: <span style="color:#e6db74">&#34;https://raw.githubusercontent.com/dotnet/dev-proxy/main/schemas/v0.27.0/ratelimitingplugin.schema.json&#34;</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&#34;costPerRequest&#34;</span>: <span style="color:#ae81ff">2</span>,
</span></span><span style="display:flex;"><span>    <span style="color:#f92672">&#34;rateLimit&#34;</span>: <span style="color:#ae81ff">120</span>
</span></span><span style="display:flex;"><span>  },
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">&#34;logLevel&#34;</span>: <span style="color:#e6db74">&#34;information&#34;</span>,
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">&#34;newVersionNotification&#34;</span>: <span style="color:#e6db74">&#34;stable&#34;</span>,
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">&#34;showSkipMessages&#34;</span>: <span style="color:#66d9ef">true</span>,
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">&#34;showTimestamps&#34;</span>: <span style="color:#66d9ef">true</span>
</span></span><span style="display:flex;"><span>}
</span></span></code></pre></div><h3 id="2-start-devproxy-with-your-configuration">2. Start DevProxy with your configuration</h3>
<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 devproxy.json
</span></span></code></pre></div><hr>
<h2 id="example-of-problematic-code">Example of Problematic Code</h2>
<p>Here’s the snippet that caused my throttling nightmare. It uses <code>Parallel.ForEachAsync</code> to query SharePoint in bulk:</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">// ❌ This will likely trigger throttling in production</span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">var</span> customers = <span style="color:#66d9ef">new</span> ConcurrentBag&lt;CustomerDTO&gt;();
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">await</span> Parallel.ForEachAsync(departmentIds, <span style="color:#66d9ef">async</span> (departmentId, token) =&gt; 
</span></span><span style="display:flex;"><span>{
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> clonedContext = _clientContext.Clone(_clientContext.Url);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> query = Camlex.Query()
</span></span><span style="display:flex;"><span>        .ViewFields(<span style="color:#66d9ef">new</span> CustomerDTO().ViewFields().ToArray().Append(<span style="color:#e6db74">&#34;DepartmentId&#34;</span>))
</span></span><span style="display:flex;"><span>        .LeftJoin(x =&gt; x[<span style="color:#e6db74">&#34;DepartmentLookup&#34;</span>].ForeignList(DEPARTMENT_LIST_GUID))
</span></span><span style="display:flex;"><span>        .ProjectedField(x =&gt; x[<span style="color:#e6db74">&#34;DepartmentId&#34;</span>].List(DEPARTMENT_LIST_GUID).ShowField(<span style="color:#e6db74">&#34;ID&#34;</span>))
</span></span><span style="display:flex;"><span>        .Where(x =&gt; x[<span style="color:#e6db74">&#34;DepartmentId&#34;</span>] == departmentId);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">var</span> departmentCustomers = <span style="color:#66d9ef">await</span> SharePointService.GetItemsFromListByQuery&lt;CustomerDTO&gt;(
</span></span><span style="display:flex;"><span>        CUSTOMER_LIST_GUID,
</span></span><span style="display:flex;"><span>        clonedContext,
</span></span><span style="display:flex;"><span>        query);
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> (departmentCustomers?.Any() == <span style="color:#66d9ef">true</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> customer <span style="color:#66d9ef">in</span> departmentCustomers)
</span></span><span style="display:flex;"><span>        {
</span></span><span style="display:flex;"><span>            customers.Add(customer);
</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><hr>
<h2 id="why-this-code-fails-in-production">Why This Code Fails in Production</h2>
<ol>
<li><strong>No throttling safeguards</strong> — Multiple parallel requests overwhelm SharePoint.</li>
<li><strong>No retry logic</strong> — Requests fail instead of recovering.</li>
<li><strong>No request limiting</strong> — All departments are processed simultaneously.</li>
<li><strong>Silent failures</strong> — Errors are ignored without logging or fallback.</li>
</ol>
<hr>
<h2 id="the-better-way">The Better Way</h2>
<p>Instead of hard-coding fixes here, I recommend Bert Jansen’s detailed guide on throttling and rate limit handling:<br>
<a href="https://github.com/OneDrive/samples/blob/master/scenarios/throttling-ratelimit-handling/readme.md">Throttling &amp; Rate Limit Handling Patterns</a></p>
<p>Key principles:</p>
<ul>
<li><strong>Limit concurrency</strong> with <code>SemaphoreSlim</code>.</li>
<li><strong>Use exponential backoff</strong> for retries.</li>
<li><strong>Monitor rate limit headers</strong> to adjust requests dynamically.</li>
<li><strong>Handle errors explicitly</strong> to prevent silent failures.</li>
</ul>
<hr>
<h2 id="conclusion">Conclusion</h2>
<p>DevProxy has become an essential tool in my Microsoft 365 development workflow. It helps me:</p>
<ul>
<li>Catch throttling issues <strong>before</strong> production.</li>
<li>Test error handling and retry logic <strong>locally</strong>.</li>
<li>Deliver applications that can survive real-world API limits.</li>
</ul>
<p>If I’d used DevProxy from the start, I could have avoided the last-minute throttling meltdown entirely.</p>
<p>💡 <strong>Pro tip:</strong> Make DevProxy part of your <em>early</em> development process, not your emergency toolkit.</p>
<hr>
<h2 id="additional-resources">Additional Resources</h2>
<ul>
<li><a href="https://github.com/dotnet/dev-proxy">DevProxy GitHub Repository</a></li>
<li><a href="https://docs.microsoft.com/en-us/graph/throttling">Microsoft Graph Throttling Guidelines</a></li>
<li><a href="https://aka.ms/devproxy/docs">DevProxy Documentation</a></li>
</ul>
]]></content:encoded></item></channel></rss>