<?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:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by joehom on Medium]]></title>
        <description><![CDATA[Stories by joehom on Medium]]></description>
        <link>https://medium.com/@joehom0416?source=rss-675d8d70865f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UieEdxDYvGhsahcU.jpg</url>
            <title>Stories by joehom on Medium</title>
            <link>https://medium.com/@joehom0416?source=rss-675d8d70865f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 09:33:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joehom0416/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stop Putting Passwords in appsettings.json]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://joehom0416.medium.com/stop-putting-passwords-in-appsettings-json-2c2091486293?source=rss-675d8d70865f------2"><img src="https://cdn-images-1.medium.com/max/600/1*jlbJqaBxmcJvUJTZ6pFAoQ.png" width="600"></a></p><p class="medium-feed-snippet">A plain-English guide to passwordless apps on Azure with Managed Identity</p><p class="medium-feed-link"><a href="https://joehom0416.medium.com/stop-putting-passwords-in-appsettings-json-2c2091486293?source=rss-675d8d70865f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://joehom0416.medium.com/stop-putting-passwords-in-appsettings-json-2c2091486293?source=rss-675d8d70865f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c2091486293</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[joehom]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 13:54:14 GMT</pubDate>
            <atom:updated>2026-11-18T13:54:14.118Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[I Run 5 AI Coding Assistants. This Is the System I Built So They Don’t Break My Flow.]]></title>
            <link>https://joehom0416.medium.com/i-run-5-ai-coding-assistants-this-is-the-system-i-built-so-they-dont-break-my-flow-7fd6228a3ac9?source=rss-675d8d70865f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fd6228a3ac9</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[development-tools]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[claude]]></category>
            <dc:creator><![CDATA[joehom]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 15:56:34 GMT</pubDate>
            <atom:updated>2026-03-10T15:56:34.617Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Most AI tooling conversations focus on model quality. My bottleneck was operations.</em></p><h3><strong>The Operational Problem Behind “AI Productivity”</strong></h3><p>I build and maintain custom agent skills constantly: review checklists, architecture constraints, release workflows, onboarding instructions.</p><p>The problem was never writing those assets.</p><p>The problem was distributing and maintaining them across tools and projects.</p><p>At work I rotate between Claude Code, Windsurf, and Cursor.</p><p>On personal projects I also use Codex, Gemini CLI, and GitHub Copilot.</p><p>Each switch carried hidden setup debt.</p><h3><strong>What Was Actually Slowing Me Down</strong></h3><p>Tool switching is normal. Rate limits happen. Different models are better at different tasks.</p><p>The real tax was context portability.</p><p>Every assistant expected its own config structure, file location, and capability wiring. That meant repeating the same setup logic over and over:</p><ul><li>MCP server definitions</li><li>skill file placement</li><li>project-scoped vs global config differences</li><li>format mismatches (JSON, TOML, editor-specific config)</li></ul><p>This is the unglamorous work that quietly kills velocity.</p><h3><strong>Why Existing Setup Patterns Don’t Scale</strong></h3><p>As teams adopt more assistants, config sprawl compounds.</p><p>Typical reality:</p><ul><li>Project A: Windsurf + Claude Code</li><li>Project B: Claude Code + Cursor</li><li>Project C: Codex + Gemini CLI</li></ul><p>Without a unifying layer, every project becomes a bespoke integration exercise.</p><p>Worse, you lose consistency: one tool is fully configured, another is missing critical MCPs, and a mid-session switch breaks momentum.</p><h3><strong>A Second Insight: More Integrations != Better Outcomes</strong></h3><p>I also made an early mistake: enabling everything everywhere.</p><p>The result:</p><ul><li>noisier responses</li><li>weaker instruction adherence</li><li>faster context bloat</li></ul><p>The highest-leverage setup is not maximum capability.</p><p>It is <strong>minimum necessary capability per project</strong>.</p><p>That became the core design principle.</p><h3><strong>The Product: AWM (Agent Workspace Manager)</strong></h3><p>I built <strong>AWM</strong> to centralize capability management and make project setup deterministic.</p><p>AWM has two layers.</p><p><strong>1) Global Registry</strong></p><p>`~/.agent-workspace/registry/` stores MCP and skill definitions once.</p><p>Register once. Reuse everywhere.</p><p><strong>2) Project Contract (`.awm.json`)</strong></p><p>Each repository declares:</p><ul><li>target tools</li><li>active MCPs</li><li>active skills</li></ul><p>Run one command and AWM materializes the correct config for each tool, in the right format, in the right location.</p><p>This turns assistant setup from ad hoc manual work into an explicit, versioned contract.</p><h3><strong>Quick Walkthrough</strong></h3><h3>Install</h3><pre>npm i @joehom/awm-cli -g</pre><p>First install seeds core MCPs: github, filesystem, memory, fetch.</p><h3>Initialize a Workspace</h3><pre>cd /path/to/project<br>awm init</pre><p>Creates .awm.json at project root.</p><h3>Activate MCPs</h3><pre>awm mcp add</pre><p>Select from registry; AWM writes tool-specific MCP config automatically.</p><h3>Activate Skills</h3><pre>awm skill add</pre><p>Select skills; AWM places them into each tool’s expected folder.</p><h3>Import Existing Tool State</h3><p>You might want to import the skill or mcp from global path of the AI tool, use pull</p><pre>awm pull<br>awm pull skills<br>awm pull mcps<br>awm pull --tool claude-code --dry-run</pre><p>AWM reads existing configs and normalizes them into the central registry.</p><h3>Reconcile After Manual Changes</h3><pre>awm sync</pre><p>If .awm.json changes, sync reapplies the declared state across tools.</p><p>This is only a slice of what AWM can do, not the full feature set. visit <a href="https://github.com/joehom0416/awm-cli">https://github.com/joehom0416/awm-cli</a> and run it in your own workflow, and pressure-test it yourself.</p><h3>How This Changed My Workflow</h3><h3>Company repos</h3><p>Windsurf + Claude Code, only project-relevant MCPs and two focused skills.</p><h3>Personal SaaS</h3><p>Claude Code + Cursor, continuity-focused MCP set and one DB conventions skill.</p><h3>Open source libraries</h3><p>Codex + Gemini CLI, minimal configuration (github, filesystem).</p><p>Each repo commits .awm.json, so setup is reproducible on any machine.</p><p>When I switch assistants mid-session, I no longer lose operational context.</p><h3>Extensibility Is a Core Feature</h3><p>AWM supports new assistants through JSON tool definitions.</p><p>Example (trimmed):</p><pre>{<br>  &quot;id&quot;: &quot;claude-code&quot;,<br>  &quot;name&quot;: &quot;Claude Code&quot;,<br>  &quot;supports&quot;: { &quot;mcp&quot;: true, &quot;skills&quot;: true },<br>  &quot;mcp&quot;: {<br>    &quot;format&quot;: &quot;json&quot;,<br>    &quot;project&quot;: {<br>      &quot;targetFile&quot;: &quot;.mcp.json&quot;,<br>      &quot;rootObject&quot;: &quot;mcpServers&quot;<br>    },<br>    &quot;global&quot;: {<br>      &quot;targetFile&quot;: &quot;~/.claude.json&quot;,<br>      &quot;rootObject&quot;: &quot;mcpServers&quot;<br>    }<br>  },<br>  &quot;skills&quot;: {<br>    &quot;project&quot;: { &quot;targetFolder&quot;: &quot;.claude/skills&quot; },<br>    &quot;global&quot;: { &quot;targetFolder&quot;: &quot;~/.claude/skills&quot; }<br>  }<br>}</pre><p>A definition encodes:</p><ul><li>config file targets</li><li>serialization format</li><li>root object expectations</li><li>skill destination paths</li></ul><p>Add a file to ~/.agent-workspace/registry/tools/, and the tool is available immediately. No core release needed.</p><h3>What I’m Building Next</h3><ul><li>community-maintained definition registry</li><li>reusable profiles (fullstack, minimal, etc.)</li><li>change detection and optional auto-sync from tool config updates</li></ul><h3>If You’re Managing Multi-Tool AI Workflows</h3><p>Source: <a href="https://github.com/joehom0416/awm-cli">https://github.com/joehom0416/awm-cli</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fd6228a3ac9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth 2.0: Protecting APIs with Azure Entra — A Beginner’s Guide]]></title>
            <link>https://joehom0416.medium.com/oauth-2-0-protecting-apis-with-azure-entra-a-beginners-guide-33dec79d7a8a?source=rss-675d8d70865f------2</link>
            <guid isPermaLink="false">https://medium.com/p/33dec79d7a8a</guid>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[microsoft-entra-id]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[joehom]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 07:08:37 GMT</pubDate>
            <atom:updated>2026-02-10T09:58:38.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMXAXBsmPqcWkz3LlkxrXg.png" /></figure><p>If you’re building APIs and wondering how to make sure only the <em>right</em> apps and users can access them, you’re in the right place.</p><p><strong>OAuth 2.0</strong> is the industry-standard way to handle this. And <strong>Azure Entra</strong> (formerly Azure Active Directory) is Microsoft’s implementation of it.</p><p>This article will give you a clear mental model for how OAuth actually works — no protocol trivia, just practical understanding</p><h3>The One Mistake That Inspired This Article</h3><p>Over the years, I’ve seen the same shortcut repeated across real projects:</p><p><strong>Using a single App Registration in Azure Entra for both the API and the client that calls it.</strong></p><p>It seems harmless — fewer things to configure, and it works. But it quietly breaks the whole point of OAuth, which is built on one simple idea:</p><blockquote>A client asks for permission to access a protected resource. They are not the same thing.</blockquote><p>Think of it like a hotel. The <strong>guest</strong> (client) asks the <strong>front desk</strong> (Azure Entra) for a <strong>key card</strong> (token) to access a <strong>specific room</strong> (API). If the guest and the room were the same thing, the whole system would stop making sense.</p><p>This article is here to reset that mental model.</p><h3>The Two Sides of OAuth</h3><p>Every OAuth interaction has two sides. Understanding this separation is the single most important concept in this entire article.</p><h4>Side 1: The API (the thing you’re protecting)</h4><p>This is your backend — the endpoints you don’t want just anyone hitting.</p><p>Examples:</p><ul><li>/api/orders</li><li>/api/reports</li><li>/api/tenant/{id}/users</li></ul><p>The API’s job is to:</p><ul><li><strong>Define</strong> what permissions exist (e.g. “read orders”, “write reports”)</li><li><strong>Validate</strong> incoming tokens</li><li><strong>Enforce</strong> who can do what</li></ul><p>In Azure Entra, you represent this as an <strong>App Registration</strong> for the API. On this registration, you <strong>expose permissions</strong> — you’re essentially publishing a menu of “here’s what callers can ask for.”</p><blockquote>You don’t <em>assign</em> permissions on the API side. You just <em>define</em> them.</blockquote><h4>Side 2: The Client (the thing calling your API)</h4><p>This is the application that wants to access the API.</p><p>Examples:</p><ul><li>A web app (Angular, React)</li><li>A mobile app</li><li>A background service or scheduled job</li><li>Another microservice</li></ul><p>The client’s job is to:</p><ul><li>Get a token from Azure Entra</li><li>Attach that token to API calls</li><li>Never handle user passwords directly</li></ul><p>In Azure Entra, you represent this as a <strong>separate App Registration</strong> for the client. On this registration, you <strong>add permissions</strong> — you’re telling Entra “this app needs access to <em>that</em> API.”</p><h4>The Golden Rule</h4><blockquote><strong><em>APIs expose permissions. Clients request Permission.</em></strong></blockquote><p>If you remember nothing else from this article, remember this.</p><h3>How It All Fits Together</h3><p>Here’s the full lifecycle from defining permissions to enforcing them, step by step:</p><p><strong>Step 1 — Expose:</strong> The API defines what permissions exist (scopes, roles).</p><p><strong>Step 2 — Request:</strong> The client selects which of those permissions it needs.</p><p><strong>Step 3 — Consent:</strong> A user or admin approves the access.</p><p><strong>Step 4 — Token:</strong> Azure Entra issues an access token (a small piece of signed data).</p><p><strong>Step 5 — Call:</strong> The client sends the token with every API request.</p><p><strong>Step 6 — Enforce:</strong> The API checks the token and decides whether to allow the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*3AEgIhOPWvrXucrEhcxnKA.png" /><figcaption>end-to-end flow</figcaption></figure><p>Azure Entra plays two roles in this flow:</p><ul><li><strong>Authorization Server</strong> — it decides who gets tokens and what’s in them</li><li><strong>Policy Engine</strong> — it tracks which clients have which permissions</li></ul><h3>Two Ways to Get a Token</h3><p>OAuth supports different “flows” depending on the situation. The two most common are:</p><h4>Flow 1: Authorization Code Flow (a user is involved)</h4><p><strong>Use this when:</strong> a real person is using your app — web apps, SPAs, mobile apps.</p><p>How it works:</p><ol><li>The user signs in through Azure Entra (a browser redirect)</li><li>The user sees a consent screen (“This app wants to read your orders — allow?”)</li><li>Entra gives the client an authorization code</li><li>The client exchanges that code for an access token</li><li>The client calls the API using the token</li></ol><p>The key idea here is:</p><blockquote><strong><em>The app is acting on behalf of the user.</em></strong></blockquote><p>The token will contain information about <em>both</em> the user and the client app. It includes a claim called scp (scopes) that lists what the user allowed.</p><p>Example of what’s inside the token:</p><pre>scp: &quot;orders.read reports.write&quot;</pre><p>This means: “The user allowed this app to read orders and write reports.”</p><h3>Flow 2: Client Credentials Flow (no user, machine-to-machine)</h3><p><strong>Use this when:</strong> there’s no human involved — background jobs, microservices calling each other, automation scripts.</p><p>How it works:</p><ol><li>The client proves its identity using a <strong>secret</strong> or <strong>certificate</strong> (like an API key, but more secure)</li><li>Entra verifies the identity</li><li>Entra issues a token</li><li>The client calls the API</li></ol><p>The key idea here is:</p><blockquote><strong><em>The app is acting as itself.</em></strong><em> There’s no user, no login screen, no consent prompt.</em></blockquote><p>The token will contain a claim called roles listing what the app is allowed to do.</p><p>Example of what’s inside the token:</p><pre>roles: [&quot;Orders.Read.All&quot;]</pre><h3>Quick Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*hm4CPxm82OIsATWFKXm3rA.png" /><figcaption>authorization code vs client credential</figcaption></figure><h3>Scopes vs App Roles — What’s the Difference?</h3><p>This is where many beginners get confused. Let’s break it down with a simple analogy.</p><h4>Scopes (Delegated Permissions)</h4><p>Think of scopes like a <strong>power of attorney</strong>. A user is saying:</p><blockquote><em>“I allow this app to do </em>these specific things<em> on my behalf.”</em></blockquote><ul><li>Scopes are <strong>user-driven</strong> — the user has to consent</li><li>They appear in tokens as the scp claim</li><li>They represent what a <em>user</em> allows an <em>app</em> to do</li></ul><p>Examples: orders.read, profile.read, orders.write</p><h4>App Roles (Application Permissions)</h4><p>Think of app roles like a <strong>company badge</strong>. An admin is saying:</p><blockquote><em>“This application is authorized to do </em>these things<em> — no user needed.”</em></blockquote><ul><li>App roles are <strong>admin-assigned</strong> — no user consent involved</li><li>They appear in tokens as the roles claim</li><li>They represent what an <em>app</em> is allowed to do on its own</li></ul><p>Examples: Orders.Read.All, Orders.Write.All, Admin</p><h4>Why Scopes Don’t Apply to Client Credentials</h4><p>This trips people up all the time. Here’s the simple logic:</p><ul><li>Scopes represent <strong>user consent</strong></li><li>Client Credentials flow has <strong>no user</strong></li><li>No user = no consent = <strong>scopes don’t make sense</strong></li></ul><p>In Client Credentials flow, you still technically pass a scope parameter, but it&#39;s always:</p><pre>scope=api://&lt;your-api&gt;/.default</pre><p>The .default part is just saying: &quot;Give me all the app roles that an admin has already assigned to this client.&quot; It&#39;s not requesting specific scopes — it&#39;s collecting pre-approved roles.</p><h4>Can Users Have App Roles Too?</h4><p>So far, we’ve presented a clean split: <strong>scopes for users, app roles for applications</strong>. That’s the most common pattern, and it’s the right mental model to start with.</p><p>But here’s something that surprises many beginners: <strong>App Roles can also be assigned to users and groups</strong>, not just to daemon applications.</p><h4>Why Would You Do This?</h4><p>Scopes answer the question: <em>“What is this app allowed to do on behalf of the user?”</em></p><p>App Roles assigned to users answer a different question: <em>“What role does this user have in the system?”</em></p><p>This is useful when your API needs <strong>role-based access control (RBAC)</strong>. For example:</p><ul><li>Only users with the Admin role can manage tenant settings</li><li>Users with the Reviewer role can approve reports</li><li>Users with the Reader role can only view data</li></ul><p>When a user with an assigned role signs in through the Authorization Code flow, the token will contain <strong>both</strong> scp (scopes) and roles (their assigned roles):</p><pre>scp: &quot;orders.read&quot;<br>roles: [&quot;Admin&quot;]</pre><h3>How Your API Should Check Tokens</h3><p>Once your API receives a request with a token, it needs to:</p><ol><li><strong>Verify the token is legitimate</strong> — check the signature and issuer</li><li><strong>Check the audience</strong> — make sure the token was meant for <em>this</em> API (the aud claim)</li><li><strong>Enforce permissions</strong> — look at the claims and decide if the request is allowed</li></ol><p>The good news is that <strong>all three steps are handled by Microsoft’s library</strong>. In ASP.NET Core, Microsoft.Identity.Web takes care of token validation, audience checking, <em>and</em> permission enforcement.</p><p><strong>Your job as a developer is simply to declare what’s required.</strong> You do this with attributes on your controllers or actions:</p><p>For <strong>user-delegated</strong> calls, use [RequiredScope]:</p><pre>[Authorize]<br>[RequiredScope(&quot;orders.read&quot;)]<br>public IEnumerable&lt;Order&gt; Get() { ... }</pre><p>For <strong>machine-to-machine</strong> calls, use [Authorize(Roles = &quot;...&quot;)] or ValidateAppRole:</p><pre>[Authorize(Roles = &quot;login-as-machine&quot;)]<br>public IEnumerable&lt;Order&gt; Get() { ... }<br></pre><p>The library does the heavy lifting — you just tell it <em>what</em> to enforce. <strong>Don’t mix these up.</strong> User tokens and app tokens carry different claims (scp vs roles), and your API should handle each type clearly.</p><h3>Common Mistakes to Avoid</h3><p>Here are the pitfalls I see most often:</p><p><strong>Treating OAuth as login.</strong> OAuth is about <em>authorization</em> (what you’re allowed to do), not <em>authentication</em> (proving who you are). Azure Entra handles both, but they’re different concerns.</p><p><strong>Using scopes for service-to-service calls.</strong> If there’s no user, use app roles. Scopes only make sense when a user is delegating access.</p><p><strong>Putting tenant or user IDs in headers instead of reading them from the token.</strong> The token is the source of truth — don’t trust anything the client sends separately.</p><p><strong>Using a single app registration for both the API and the client.</strong> This is the anti-pattern that started this article. Keep them separate.</p><p><strong>Stuffing business data into tokens.</strong> Tokens should carry identity and permissions, not order details or business logic.</p><h3>Summary</h3><p>OAuth becomes surprisingly simple once you internalize three questions:</p><ol><li><strong>Who is acting?</strong> → A user (delegated) or an application (app-only)?</li><li><strong>What is being protected?</strong> → Which API and which endpoints?</li><li><strong>How is permission granted?</strong> → Through scopes (user consent) or app roles (admin assignment)?</li></ol><p>Azure Entra maps these concepts cleanly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*Ft_Or6IOvKbSSqk3MuyURA.png" /></figure><p>And the golden rule one more time:</p><blockquote><strong><em>If you can’t clearly answer “who is the client and who is the resource,” your OAuth design needs rethinking.</em></strong></blockquote><h3>Further Reading</h3><p>If you want to go deeper, here are the key references:</p><ul><li><a href="https://datatracker.ietf.org/doc/html/rfc6749"><strong>RFC 6749</strong></a> — The official OAuth 2.0 specification. It defines the four roles (Resource Owner, Client, Authorization Server, Resource Server) and makes the client/resource separation explicit.</li><li><a href="https://datatracker.ietf.org/doc/html/rfc6750"><strong>RFC 6750</strong></a> — How bearer tokens are used in practice.</li><li><a href="https://datatracker.ietf.org/doc/rfc9700/"><strong>RFC 9700</strong></a> — OAuth security best practices, including why clear trust boundaries between clients and resources matter.</li><li><strong>Microsoft Learn</strong> — Search for “Expose an API,” “Authorization code flow,” and “Application permissions vs delegated permissions” for Azure-specific walkthroughs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33dec79d7a8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passing Parameters to APIs in ASP.NET Core: Best Practices, Pitfalls, and Clean Patterns]]></title>
            <link>https://joehom0416.medium.com/passing-parameters-to-apis-in-asp-net-core-best-practices-pitfalls-and-clean-patterns-c6479086d6f3?source=rss-675d8d70865f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6479086d6f3</guid>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[joehom]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 07:56:17 GMT</pubDate>
            <atom:updated>2026-02-03T07:56:17.787Z</atom:updated>
            <content:encoded><![CDATA[<p>When you design an API, “how do I pass parameters?” sounds basic — but in my day‑to‑day work coaching developers on designing REST‑compliant APIs, I’ve found this is one of the areas teams spend the most time debating. The choices you make here directly affect security, caching, maintainability, versioning, and client experience.</p><p>In this post, I’ll walk through the practical ways to pass parameters to an API in <strong>ASP.NET Core</strong>, when to use each method, and the best practices that keep your endpoints clean and predictable.</p><h3>The 5 Main Places Parameters Live</h3><h3>1) Route parameters (path)</h3><p>Use route parameters when the value <strong>identifies the resource</strong>.</p><p><strong>Good </strong>for:</p><ul><li>Resource IDs</li><li>Natural keys (e.g., code)</li><li>Hierarchical resources (e.g., company → officers)</li></ul><p><strong>Example</strong></p><ul><li>GET /api/customers/123</li><li>GET /api/companies/abc/officers</li></ul><pre>app.MapGet(&quot;/api/customers/{id:guid}&quot;, (Guid id) =&gt;<br>{<br>    // Fetch customer by id<br>    return Results.Ok(new { id });<br>});</pre><p><strong>Best practices</strong></p><ul><li>Keep routes stable and resource-oriented (nouns, not verbs)</li><li>Use route constraints ({id:guid}, {year:int})</li><li>Avoid putting optional filters in route — use query instead</li></ul><h3>Hidden Constraint for Route Parameters</h3><p>I once worked on a project where the system allowed clients to <strong>define their own IDs</strong>. These IDs were <em>not</em> database primary keys — they were business identifiers intended to be displayed and exposed directly in the API resources.</p><p>On paper, this sounded flexible and client-friendly. In reality, it quickly became a problem.</p><p>Because the system allowed <strong>any characters</strong> in the ID, clients started using values like INV/2024/01, ACME:EU, or even IDs with spaces and symbols. The moment these IDs were used in API routes or URLs, routing broke, encoding became inconsistent, and edge cases appeared across browsers, proxies, and API gateways.</p><p>Route (path) parameters live inside the URL path, which means they are subject to URL encoding rules. Not all characters are safe or convenient to use in a path segment.</p><p>There are reserved characters defined by the URL specification (RFC 3986). If your ID contains reserved characters such as:</p><pre>! * &#39; ( ) ; : @ &amp; = + $ , / ? # [ ]</pre><p>or unsafe characters like:</p><pre>` ^ { }</pre><p><strong>do not use route parameters</strong>. Instead, pass the value using a query string or request body.</p><p>This avoids routing ambiguity, encoding issues, and inconsistent behavior across proxies, gateways, and clients.</p><h3>2) Query string parameters</h3><p>Use query parameters for <strong>filtering, sorting, paging, searching</strong>, and optional modifiers.</p><p><strong>Good </strong>for:</p><ul><li>Search terms: ?q=alice</li><li>Filters: ?status=active</li><li>Pagination: ?page=2&amp;pageSize=50</li><li>Sorting: ?sort=-createdAt</li></ul><p>ASP.NET Core example:</p><pre>app.MapGet(&quot;/api/customers&quot;, (<br>    string? q,<br>    string? status,<br>    int page = 1,<br>    int pageSize = 20) =&gt;<br>{<br>    return Results.Ok(new { q, status, page, pageSize });<br>});</pre><p><strong>Best practices</strong></p><ul><li>Default your paging values and cap them (protect your DB)</li><li>Treat query params as optional; don’t overload them with required data</li><li>Be consistent: always page/pageSize, or always skip/take—not both</li></ul><h3>3) Request body parameters (JSON)</h3><p>Use the request body when you are <strong>creating or updating a resource</strong>, or sending a <strong>complex object</strong>. This is the most common and default choice when no special constraints apply. Note that <strong>GET requests should not use a request body</strong> — while the HTTP spec does not strictly forbid it, ASP.NET Core does not support binding a body for GET, and many clients, proxies, and caches ignore it entirely.</p><p><strong>Good </strong>for:</p><ul><li>POST create</li><li>PUT / PATCH update</li><li>Complex filters that don’t fit nicely in a query string</li></ul><p>ASP.NET Core example:</p><pre>public record CreateCustomerRequest(string Name, string Email);<br>app.MapPost(&quot;/api/customers&quot;, (CreateCustomerRequest request) =&gt;<br>{<br>    // Validate + create<br>    return Results.Created($&quot;/api/customers/{Guid.NewGuid()}&quot;, request);<br>});</pre><p><strong>Best practices</strong></p><ul><li>Prefer DTOs / records (don’t bind EF entities directly)</li><li>Validate body input at the API boundary</li><li>Keep body models versionable (avoid over-sharing internal fields)</li></ul><h3>4) Headers (metadata, not business data)</h3><p>Headers are for <strong>metadata about the request</strong>, not domain data. From my experience reviewing and coaching teams, I’ve seen APIs pass values like UserId or OrganisationId through custom headers for authorization decisions. This creates a serious security risk: headers are <strong>client-controlled</strong>, meaning an attacker can trivially inject or modify them to impersonate another user or organization if the server blindly trusts these values. Unless every header value is cryptographically validated against the authenticated identity, this can lead to cross-tenant or unauthorized data access.</p><p>There is also an operational concern: many firewalls, API gateways, and WAFs block or strip <strong>custom headers by default</strong> as a security hardening measure. This can cause requests to behave differently across environments (local vs staging vs production) and lead to hard-to-debug authorization failures. For authorization, always derive identity and tenancy from trusted tokens (e.g. JWT claims), not from arbitrary request headers.</p><p><strong>Good </strong>for:</p><ul><li>Authentication (Authorization: Bearer ...)</li><li>Correlation IDs (X-Correlation-Id)</li><li>Idempotency keys (Idempotency-Key)</li><li>Content negotiation (Accept, Content-Type)</li></ul><p>ASP.NET Core example:</p><pre>app.MapPost(&quot;/api/payments&quot;, (HttpRequest httpRequest) =&gt;<br>{<br>    var idempotencyKey = httpRequest.Headers[&quot;Idempotency-Key&quot;].ToString();<br>    return Results.Ok(new { idempotencyKey });<br>});</pre><p><strong>Best practices</strong></p><ul><li>Don’t put business data (e.g., customerId) in headers</li><li>Standardize header names and document them</li></ul><h3>5) Token claims (identity-derived parameters)</h3><p>Token claims are parameters <strong>derived from a trusted authentication token</strong> (typically a JWT), not directly supplied by the client as request data.</p><p>From my experience, this is often the <strong>safest and most overlooked way</strong> to pass parameters related to <strong>identity, tenancy, and authorization context</strong>.</p><p><strong>Good </strong>for:</p><ul><li>UserId</li><li>TenantId / OrganisationId</li><li>Roles and permissions</li><li>Site or environment context tied to identity</li></ul><p>Instead of accepting these values via headers, query strings, or body (which are client-controlled), the API <strong>extracts them from validated token claims</strong>.</p><p>ASP.NET Core example:</p><pre>app.MapGet(&quot;/api/profile&quot;, (ClaimsPrincipal user) =&gt;<br>{<br>    var userId = user.FindFirst(&quot;user_id&quot;)?.Value;<br>    var organisationId = user.FindFirst(&quot;organisation_id&quot;)?.Value;<br>   return Results.Ok(new { userId, organisationId });<br>});</pre><p><strong>Why this matters</strong></p><ul><li>Token claims are <strong>cryptographically trusted</strong></li><li>Clients cannot spoof or inject values</li><li>Eliminates cross-tenant data leakage risks</li><li>Works consistently across gateways, proxies, and WAFs</li></ul><p><strong>Best practices</strong></p><ul><li>Use claims only for authorization and identity context</li><li>Keep claims small and stable (avoid large payloads)</li><li>Never mix claim-based identity with client-supplied identity parameters</li></ul><h3>Common API Parameter Mistakes</h3><h3>Mistake 1: Putting sensitive data in the query string</h3><p>Query strings are often logged by proxies and servers.</p><p>❌ Bad:</p><pre>GET /api/users?email=someone@company.com&amp;password=...</pre><p>✅ Better: Use a secure authentication flow and request body where appropriate.</p><h3>Mistake 2: “Action routes” for everything</h3><p>❌ Bad:</p><pre>POST /api/order/SubmitOrder</pre><p>✅ Better:</p><ul><li>POST /api/orders (create)</li><li>POST /api/orders/{id}/submit (state transition, if needed)</li></ul><h3>Mistake 3: Turning query strings into a mini-language</h3><p>Once query parameters become deeply nested or contain complex AND/OR logic, they become hard to maintain.</p><p>✅ Better approach:</p><pre>public record CustomerSearchRequest(<br>    string? Query,<br>    string? Status,<br>    int Page = 1,<br>    int PageSize = 20<br>);<br><br>app.MapPost(&quot;/api/customers/search&quot;, (CustomerSearchRequest request) =&gt;<br>{<br>    return Results.Ok(request);<br>});</pre><h3>Validation: Don’t Let Bad Parameters Leak Into Your Domain</h3><p>If you accept parameters, validate them — especially query and body input.</p><p>Minimal example:</p><pre>app.MapGet(&quot;/api/customers&quot;, (int page = 1, int pageSize = 20) =&gt;<br>{<br>    if (page &lt;= 0) return Results.BadRequest(&quot;page must be &gt;= 1&quot;);<br>    if (pageSize is &lt; 1 or &gt; 100)<br>        return Results.BadRequest(&quot;pageSize must be between 1 and 100&quot;);<br>     return Results.Ok(new { page, pageSize });<br>});</pre><p><strong>Best practices</strong></p><ul><li>Validate at the API boundary</li><li>Use consistent error responses (Problem Details)</li></ul><h3>Versioning and Compatibility Tips</h3><p>Parameter choices affect versioning because changing routes or renaming parameters will break clients.</p><h3>What counts as a breaking change?</h3><p>Common examples include:</p><ul><li>Removing or renaming endpoints or parameters</li><li>Changing the behavior of existing endpoints</li><li>Changing the response contract or error codes</li></ul><h3>Practical versioning in ASP.NET Core</h3><p>In ASP.NET Core, a common approach is to use the <strong>Asp.Versioning</strong> packages and configure versioning once in Program.cs, then let endpoints opt into versions.</p><p>Typical strategies:</p><ul><li><strong>URL segment versioning</strong>: /api/v1/customers</li><li><strong>Header versioning</strong>: X-Api-Version: 1</li><li><strong>Query versioning</strong>: ?api-version=1</li></ul><p>As a rule of thumb:</p><ul><li>Prefer <strong>non-breaking additions</strong> (new optional query parameters, new response fields)</li><li>Avoid renaming parameters — clients hardcode them</li><li>For breaking changes, introduce a new version (v2) and keep v1 running until clients migrate</li></ul><h3>Minimal APIs (high level)</h3><ul><li>Define an ApiVersionSet (e.g., supports v1 and v2)</li><li>Use a route group like api/v{version:apiVersion}</li><li>Map endpoints to specific versions (MapToApiVersion(1) / MapToApiVersion(2))</li></ul><h3>Controllers (high level)</h3><ul><li>Add [ApiVersion(1)] / [ApiVersion(2)] on the controller</li><li>Use v{v:apiVersion} in the route template</li><li>Map each action to a concrete version with [MapToApiVersion(1)]</li></ul><h3>Deprecation</h3><p>When you’re ready to retire a version, mark the old version as deprecated so clients can detect it via response headers and plan migration.</p><h3>Naming Conventions That Keep APIs Predictable</h3><ul><li>Route parameters: {customerId}, {orderId}</li><li>Query parameters: page, pageSize, sort, q</li><li>Sorting: -field for descending (sort=-createdAt)</li><li>JSON properties: camelCase (ASP.NET Core default)</li></ul><h3>A Complete Example: Route + Query + Header + Body</h3><p><strong>Scenario:</strong> Add an item to an order, with correlation ID and optional dryRun.</p><pre>public record AddOrderItemRequest(string Sku, int Quantity);<br>app.MapPost(&quot;/api/orders/{orderId:guid}/items&quot;, (<br>    Guid orderId,<br>    bool dryRun,<br>    AddOrderItemRequest body,<br>    HttpRequest http) =&gt;<br>{<br>    var correlationId = http.Headers[&quot;X-Correlation-Id&quot;].ToString();<br>    if (body.Quantity &lt;= 0)<br>        return Results.BadRequest(&quot;Quantity must be &gt; 0&quot;);<br>    return Results.Ok(new<br>    {<br>        orderId,<br>        dryRun,<br>        body.Sku,<br>        body.Quantity,<br>        correlationId<br>    });<br>});</pre><p><strong>Why this is clean</strong></p><ul><li>orderId belongs to the resource path</li><li>dryRun is a query modifier</li><li>Request content lives in the JSON body</li><li>Correlation ID is request metadata</li></ul><h3>Final Checklist</h3><p>Before shipping an endpoint, ask:</p><ul><li>Is each parameter in the correct place (route, query, body, header)?</li><li>Are required vs optional parameters clear?</li><li>Are defaults and limits safe?</li><li>Are inputs validated consistently?</li><li>Are naming conventions consistent across endpoints?</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6479086d6f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Simplified Clean Architecture Without the Repository Pattern (using EF core)]]></title>
            <link>https://joehom0416.medium.com/why-i-simplified-clean-architecture-without-the-repository-pattern-using-ef-core-cc7751660ea7?source=rss-675d8d70865f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc7751660ea7</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <dc:creator><![CDATA[joehom]]></dc:creator>
            <pubDate>Sat, 24 Jan 2026 09:06:58 GMT</pubDate>
            <atom:updated>2026-01-24T09:06:58.647Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When implementing Clean Architecture in .NET, one of the most debated decisions is whether to use the Repository pattern. After building numerous enterprise applications, I’ve made a deliberate choice to simplify my Clean Architecture template by <strong>removing the Repository pattern entirely</strong> in favor of a leaner abstraction.</p><p>This isn’t to say the Repository pattern is wrong — it has its place. But for many modern .NET applications using <strong>Entity Framework Core</strong>, I believe it often adds unnecessary complexity. This article explains my reasoning and the trade-offs I’ve considered.</p><h3>The Traditional Approach</h3><p>In traditional Clean Architecture implementations, you’ll often see this layered abstraction:</p><pre>Application Layer (IRepository interface)<br>    ↓<br>Infrastructure Layer (Repository implementation)<br>    ↓<br>Entity Framework Core (DbContext)<br>    ↓<br>Database</pre><p>This creates a triple abstraction:</p><ol><li>The repository interface</li><li>The repository implementation</li><li>Entity Framework Core itself</li></ol><h3>My Simplified Approach</h3><p>Instead, I use a single, focused abstraction:</p><pre>// Application Layer - IApplicationDbContext.cs<br>public interface IApplicationDbContext<br>{<br>    DbSet&lt;User&gt; Users { get; }<br>    DbSet&lt;Transaction&gt; Transactions { get; }<br>    Task&lt;int&gt; SaveChangesAsync(CancellationToken cancellationToken = default);<br>}<br><br>// Infrastructure Layer - ApplicationDbContext.cs<br>public sealed class ApplicationDbContext : DbContext, IApplicationDbContext<br>{<br>    public DbSet&lt;User&gt; Users { get; set; }<br>    public DbSet&lt;Transaction&gt; Transactions { get; set; }<br>    // ... implementation<br>}</pre><p>This creates a cleaner abstraction chain:</p><pre>Application Layer (IApplicationDbContext interface)<br>    ↓<br>Infrastructure Layer (ApplicationDbContext with EF Core)<br>    ↓<br>Database</pre><h3>Why I Prefer This Approach</h3><h3>1. Entity Framework Core Already Provides Repository-Like Abstractions</h3><p>Here’s my key observation: <strong>EF Core’s </strong><strong>DbSet&lt;T&gt; already implements many Repository pattern characteristics</strong>.</p><ul><li>DbSet&lt;T&gt; provides abstraction over data access</li><li>It offers generic CRUD operations</li><li>It includes query composition capabilities</li><li>It implements the Unit of Work pattern via DbContext</li></ul><p>In my view, adding another repository layer on top of EF Core often feels redundant — like adding an extra wrapper that doesn’t provide significant value for most scenarios.</p><h3>2. Reduces Abstraction Layers (in Most Cases)</h3><p>The repository pattern made sense historically when we needed to abstract away complex ADO.NET code or frequently switch between ORMs. In my experience with modern applications using EF Core, this need has diminished:</p><p><strong>Traditional approach</strong> (unnecessary complexity):</p><pre>// Repository interface<br>public interface ITransactionRepository<br>{<br>    Task&lt;Transaction?&gt; GetByIdAsync(Guid id);<br>    Task&lt;List&lt;Transaction&gt;&gt; GetAllAsync();<br>    void Add(Transaction transaction);<br>    void Update(Transaction transaction);<br>    void Delete(Transaction transaction);<br>}<br><br>// Repository implementation (just forwarding to DbContext)<br>public class TransactionRepository : ITransactionRepository<br>{<br>    private readonly ApplicationDbContext _context;<br>    public async Task&lt;Transaction?&gt; GetByIdAsync(Guid id)<br>        =&gt; await _context.Transactions.FindAsync(id);<br>    public async Task&lt;List&lt;Transaction&gt;&gt; GetAllAsync()<br>        =&gt; await _context.Transactions.ToListAsync();<br>    // ... more forwarding code<br>}<br>// Command handler<br>public class CreateTransactionCommandHandler<br>{<br>    private readonly ITransactionRepository _repository;<br>    public async Task&lt;Result&lt;Guid&gt;&gt; Handle(CreateTransactionCommand command)<br>    {<br>        var transaction = new Transaction { /* ... */ };<br>        _repository.Add(transaction);<br>        await _unitOfWork.SaveChangesAsync(); // Another abstraction!<br>        return transaction.Id;<br>    }<br>}</pre><p><strong>My simplified approach</strong>:</p><pre>// Command handler - direct and clear<br>public class CreateTransactionCommandHandler(<br>    IApplicationDbContext context,<br>    IDateTimeProvider dateTimeProvider,<br>    IUserContext userContext)<br>    : ICommandHandler&lt;CreateTransactionCommand, Guid&gt;<br>{<br>    public async Task&lt;Result&lt;Guid&gt;&gt; Handle(CreateTransactionCommand command, CancellationToken cancellationToken)<br>    {<br>        // Authorization check<br>        if (userContext.UserId != command.UserId)<br>        {<br>            return Result.Failure&lt;Guid&gt;(UserErrors.Unauthorized());<br>        }<br>// Business validation<br>        User? user = await context.Users<br>            .AsNoTracking()<br>            .SingleOrDefaultAsync(u =&gt; u.Id == command.UserId, cancellationToken);<br>        if (user is null)<br>        {<br>            return Result.Failure&lt;Guid&gt;(UserErrors.NotFound(command.UserId));<br>        }<br>        // Create entity<br>        var transaction = new Transaction<br>        {<br>            UserId = user.Id,<br>            Amount = command.Amount,<br>            Category = command.Category,<br>            Description = command.Description,<br>            TransactionDate = command.TransactionDate,<br>            Type = command.Type,<br>            CreatedAt = dateTimeProvider.UtcNow<br>        };<br>        // Raise domain event<br>        transaction.Raise(new TransactionCreatedDomainEvent(transaction.Id));<br>        // Persist<br>        context.Transactions.Add(transaction);<br>        await context.SaveChangesAsync(cancellationToken);<br>        return transaction.Id;<br>    }<br>}</pre><h3>3. Avoids Constructor Parameter Explosion</h3><p>With the repository pattern, complex use cases often require injecting multiple repositories into a single handler. This can quickly lead to constructor parameter bloat:</p><p><strong>Traditional approach</strong> (parameter explosion):</p><pre>public class ProcessOrderCommandHandler(<br>    IOrderRepository orderRepository,<br>    ICustomerRepository customerRepository,<br>    IProductRepository productRepository,<br>    IInventoryRepository inventoryRepository,<br>    IPaymentRepository paymentRepository,<br>    IShippingRepository shippingRepository,<br>    INotificationRepository notificationRepository,<br>    IUnitOfWork unitOfWork)  // 8 parameters!<br>    : ICommandHandler&lt;ProcessOrderCommand, Guid&gt;<br>{<br>    // Implementation...<br>}</pre><p>This triggers <strong>SonarQube rule S107</strong> (csharpsquid:S107), which warns when constructors have more than 7 parameters by default. While you can suppress or configure this rule, the underlying issue remains: you&#39;re injecting many dependencies just to access different data sets.</p><p><strong>My simplified approach</strong> (single context):</p><pre>public class ProcessOrderCommandHandler(<br>    IApplicationDbContext context,<br>    IPaymentService paymentService,<br>    INotificationService notificationService)<br>    : ICommandHandler&lt;ProcessOrderCommand, Guid&gt;<br>{<br>    public async Task&lt;Result&lt;Guid&gt;&gt; Handle(ProcessOrderCommand command, CancellationToken cancellationToken)<br>    {<br>        // Access all entities through a single context<br>        var customer = await context.Customers.FindAsync(command.CustomerId);<br>        var products = await context.Products.Where(p =&gt; command.ProductIds.Contains(p.Id)).ToListAsync();<br>        var inventory = await context.Inventory.Where(i =&gt; command.ProductIds.Contains(i.ProductId)).ToListAsync();<br>// Business logic...<br>        var order = new Order { /* ... */ };<br>        context.Orders.Add(order);<br>        await context.SaveChangesAsync(cancellationToken);<br>        return order.Id;<br>    }<br>}</pre><p>With a single IApplicationDbContext, you have access to all your entities without injecting a repository for each aggregate. This keeps constructor parameters manageable and focused on actual service dependencies rather than data access concerns.</p><h3>4. Better Query Composition</h3><p>Repositories often force you into predefined query methods. With direct DbSet access through the abstraction, you get full LINQ power:</p><pre>// D<br>public async Task&lt;Result&lt;List&lt;TransactionResponse&gt;&gt;&gt; Handle(GetTransactionsQuery query, CancellationToken cancellationToken)<br>{<br>    List&lt;TransactionResponse&gt; transactions = await context.Transactions<br>        .Where(t =&gt; t.UserId == query.UserId)<br>        .Where(t =&gt; t.TransactionDate &gt;= query.StartDate)  // Easy filtering<br>        .Where(t =&gt; t.TransactionDate &lt;= query.EndDate)<br>        .OrderByDescending(t =&gt; t.TransactionDate)          // Easy sorting<br>        .Select(t =&gt; new TransactionResponse                // Projection<br>        {<br>            Id = t.Id,<br>            Amount = t.Amount,<br>            Category = t.Category,<br>            Description = t.Description,<br>            // ... map to DTO<br>        })<br>        .ToListAsync(cancellationToken);<br><br>return transactions;<br>}</pre><p>With repositories, you’d need to either:</p><ul><li>Create a new repository method for every query variation</li><li>Use specification pattern (adding more complexity)</li><li>Pass complex filter objects to generic methods</li></ul><h3>5. Maintains Architectural Boundaries</h3><p>The key insight: <strong>the abstraction (</strong><strong>IApplicationDbContext) is what maintains the boundary, not the Repository pattern itself</strong>.</p><p>My architecture still enforces:</p><ul><li>✅ <strong>Domain layer</strong> has zero infrastructure dependencies</li><li>✅ <strong>Application layer</strong> depends only on the IApplicationDbContext interface</li><li>✅ <strong>Infrastructure layer</strong> implements the interface</li><li>✅ <strong>Dependency Inversion Principle</strong> is fully respected</li></ul><p>The Application layer never references:</p><ul><li>Microsoft.EntityFrameworkCore (only the interface)</li><li>Npgsql or any database provider</li><li>Any infrastructure concerns</li></ul><h3>6. Easier Testing</h3><p>Testing is simpler because you mock a single interface instead of multiple repositories:</p><pre>// Unit test setup<br>var mockContext = Substitute.For&lt;IApplicationDbContext&gt;();<br>mockContext.Users.Returns(MockDbSet(users));<br>mockContext.Transactions.Returns(MockDbSet(transactions));<br><br>var handler = new CreateTransactionCommandHandler(<br>    mockContext,<br>    dateTimeProvider,<br>    userContext<br>);<br>// Test execution<br>var result = await handler.Handle(command, CancellationToken.None);</pre><p>For integration tests, I use the real ApplicationDbContext with Aspire orchestration - no repository fakes needed.</p><h3>7. Domain Events Integration</h3><p>My ApplicationDbContext handles domain events automatically:</p><pre>public override async Task&lt;int&gt; SaveChangesAsync(CancellationToken cancellationToken = default)<br>{<br>    int result = await base.SaveChangesAsync(cancellationToken);<br>// Automatically publish domain events after persistence<br>    await PublishDomainEventsAsync();<br>    return result;<br>}</pre><p>With separate repositories, you’d need additional orchestration to ensure domain events are published after all repository operations complete.</p><h3>8. CQRS Alignment</h3><p>My approach aligns perfectly with CQRS:</p><p><strong>Commands</strong> (write operations):</p><ul><li>Use DbSet&lt;T&gt;.Add(), DbSet&lt;T&gt;.Update(), DbSet&lt;T&gt;.Remove()</li><li>Simple, focused operations</li><li>Change tracking enabled</li></ul><p><strong>Queries</strong> (read operations):</p><ul><li>Use .AsNoTracking() for performance</li><li>Project directly to DTOs</li><li>Full LINQ query composition</li></ul><pre>// Optimized query with projection<br>List&lt;TransactionResponse&gt; transactions = await context.Transactions<br>    .AsNoTracking()  // No change tracking overhead<br>    .Where(t =&gt; t.UserId == userId)<br>    .Select(t =&gt; new TransactionResponse { /* ... */ })  // Project to DTO<br>    .ToListAsync(cancellationToken);</pre><h3>When You SHOULD Use Repository Pattern</h3><p>To be fair, repositories make sense when:</p><ol><li><strong>Multiple data sources</strong>: You’re aggregating data from SQL + Azure Blob Table + external APIs</li><li><strong>Complex data access logic</strong>: Your queries require business logic that belongs in a separate abstraction</li><li><strong>Switching ORMs</strong>: You genuinely need to switch between different ORMs, example Dapper for reading database, EF Core for writing database</li><li><strong>Team constraints</strong>: Your team is more familiar with repository pattern</li></ol><h3>Common Concerns Addressed</h3><h3>“What if we need to switch from EF Core?”</h3><p><strong>My experience</strong>: In my years of .NET development, I’ve rarely seen teams switch ORMs mid-project. The cost of changing ORMs is significant regardless of whether you use repositories — your query logic, relationships, and migrations all need rewriting.</p><p>That said, if your context genuinely requires ORM flexibility (perhaps you’re building a framework or multi-tenant system with varied data sources), repositories might be worth the trade-off. For most business applications, I find that changing the ApplicationDbContext implementation would be sufficient if this rare scenario occurs.</p><h3>“Doesn’t this couple Application layer to EF Core?”</h3><p><strong>No.</strong> The Application layer depends on IApplicationDbContext, not EF Core. The DbSet&lt;T&gt; type comes from EF Core, but it&#39;s just a type - the Application layer doesn&#39;t reference the EF Core package.</p><p>This is similar to how you might use IQueryable&lt;T&gt; or IEnumerable&lt;T&gt; - they&#39;re abstraction types that enable powerful composition.</p><h3>“What about testing?”</h3><p><strong>Testing is easier.</strong> You mock one interface instead of multiple repositories. For integration tests, you use the real implementation with a test database (via Aspire in my case).</p><h3>Real-World Observations</h3><p>After using this approach in several production systems, I’ve noticed:</p><ol><li><strong>Less boilerplate</strong> — roughly 20–30% less code compared to repository-based architectures</li><li><strong>Faster feature development</strong> — no need to create repository methods for every query variation (although nowadays, AI can speed up this process)</li><li><strong>Easier onboarding</strong> — new developers can trace the flow from handler to database more directly</li><li><strong>Better query performance</strong> — direct LINQ queries with projections are easier to optimize</li><li><strong>Reduced maintenance</strong> — fewer abstractions mean fewer places to update when requirements change</li></ol><p>Your mileage may vary depending on team size, experience, and specific domain requirements.</p><h3>Conclusion</h3><p>The Repository pattern isn’t inherently bad — it’s a well-established pattern that has served the industry well for decades. However, I believe it’s often <strong>unnecessary when you’re already using a modern ORM like Entity Framework Core</strong> for straightforward CRUD and query scenarios.</p><p>By using a simple IApplicationDbContext abstraction:</p><ul><li>✅ You maintain clean architectural boundaries</li><li>✅ You preserve testability</li><li>✅ You reduce code complexity (in most cases)</li><li>✅ You get better query composition</li><li>✅ You align with CQRS naturally</li></ul><p><strong>My philosophy</strong>: Don’t add abstractions for theoretical benefits that rarely materialize in your specific context. Add them when you have concrete, demonstrable needs.</p><p>Clean Architecture is about maintaining the right boundaries and dependencies, not about maximizing the number of abstraction layers. This simplified approach achieves similar architectural goals with less ceremony — but it’s not the only valid approach.</p><p><strong>Consider your context</strong>: Team experience, domain complexity, performance requirements, and future scalability needs should all factor into your decision. What works for my projects might not work for yours, and that’s perfectly fine.</p><h3>Further Reading</h3><ul><li><a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/cqrs">CQRS Pattern</a></li><li><a href="https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/">Entity Framework Core DbContext</a></li><li><a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean Architecture by Robert C. Martin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc7751660ea7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing the Right Collection Type in C#: IList, ICollection, IEnumerable, IQueryable and More…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">When I was a university student, one of my favourite courses was &#x201C;Data Structures and Algorithms.&#x201D; It taught us how data can be organised&#x2026;</p><p class="medium-feed-link"><a href="https://joehom0416.medium.com/choosing-the-right-collection-type-in-c-ilist-icollection-ienumerable-iqueryable-and-more-5e7abed75dc5?source=rss-675d8d70865f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://joehom0416.medium.com/choosing-the-right-collection-type-in-c-ilist-icollection-ienumerable-iqueryable-and-more-5e7abed75dc5?source=rss-675d8d70865f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e7abed75dc5</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[joehom]]></dc:creator>
            <pubDate>Tue, 25 Nov 2025 14:18:25 GMT</pubDate>
            <atom:updated>2025-11-25T14:18:25.940Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[From Monolith to Microservices — and Back Again]]></title>
            <link>https://joehom0416.medium.com/from-monolith-to-microservices-and-back-again-38ddd2318012?source=rss-675d8d70865f------2</link>
            <guid isPermaLink="false">https://medium.com/p/38ddd2318012</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[engineering-leadership]]></category>
            <dc:creator><![CDATA[joehom]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 11:29:42 GMT</pubDate>
            <atom:updated>2025-11-11T06:16:28.850Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Monolith to Microservices — and Back Again</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XWpHeBRQOdbTawCNIDuL_A@2x.jpeg" /><figcaption>Photo by <a href="https://growtika.com/">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>After going through multiple microservice projects, I started thinking about something different.</p><p>Last year, our architecture team (I am one of them) kicked off several brand-new projects.<br> We decided to embrace <strong>microservice architecture</strong> from day one: clean boundaries, event-driven design, and clear ownership. Every developers were excited.</p><p>We split the system into <strong>five microservices</strong>, all managed by one team. The diagrams looked great, the boundaries felt clean, and everyone was optimistic.</p><p>A year later, the reality hit us: the communication between services had become <strong>surprisingly complicated.</strong></p><p>We needed documentation for everything, what each service does, what contracts exist between them, what requests and responses look like, which version is compatible with which.<br> Integration testing became painful, you only can test the service layer.</p><p>That was my turning point.<br> I began to rethink the entire setup: could this have been a <strong>monolith</strong> instead?<br> The answer, surprisingly, was <strong>yes</strong>.</p><p>I started digging deeper — and found that we weren’t alone. Many companies that once championed microservices are now quietly returning to monolith-style systems.</p><h3>What Problem Are Microservices Trying to Solve?</h3><p>When a system grows too large, a single small mistake can bring the entire platform down.<br> <strong>Microservices</strong> emerged as an <strong>engineering response to uncertainty</strong> — a way to accept that failures will happen and to contain them before they spread.</p><p>But this isolation comes at a cost.<br>Microservices trade <strong>simplicity for reliability</strong>, <strong>cost for autonomy</strong>, and <strong>clarity for distributed complexity</strong>.</p><p>Without strong <strong>monitoring</strong>, <strong>automation</strong>, <strong>fault tolerance</strong>, and <strong>API governance</strong>, microservices can quickly descend into <strong>dependency hell</strong>.</p><h3>What “Dependency Hell” Looks Like</h3><p>Many teams adopt event-driven microservices to reduce direct dependencies. In my case, we faced a similar issue. I’ll use a different example here to explain it more clearly.</p><p>Imagine an e-commerce platform with five services:<br> User, Order, Inventory, Payment, and Notification.</p><p>When an order is created, the Order service publishes an event:</p><pre>{<br>  &quot;event&quot;: &quot;OrderCreated&quot;,<br>  &quot;orderId&quot;: &quot;12345&quot;,<br>  &quot;orderTotal&quot;: 499.00,<br>  &quot;currency&quot;: &quot;USD&quot;<br>}</pre><p>Three other services listen to this event:</p><ul><li>Inventory deducts stock</li><li>Payment processes the charge</li><li>Notification sends an email confirmation</li></ul><p>Now the business team decides to introduce multi-currency support.<br> The Order service updates its event schema:</p><pre>{<br>  &quot;event&quot;: &quot;OrderCreated&quot;,<br>  &quot;orderId&quot;: &quot;12345&quot;,<br>  &quot;totalAmount&quot;: { &quot;value&quot;: 499.00, &quot;currency&quot;: &quot;USD&quot; }<br>}</pre><p>It seems like a harmless improvement — but suddenly, <strong>every consumer breaks</strong>.</p><ul><li>The Payment service fails deserialization because it expects a flat orderTotal field.</li><li>The Inventory service stops processing stock updates because the event no longer matches its schema.</li><li>The Notification service silently drops messages since its handler can’t parse the new structure.</li></ul><p>Worse, not all services fail immediately. Some silently process partial data or re-emit broken downstream events, creating <strong>data drift</strong> across the system.</p><p>Even though these services communicate asynchronously, they’re <strong>semantically coupled</strong> through the event schema.<br> Every change to an event means a coordinated rollout, versioning strategy, and backward-compatibility plan — the very coordination microservices were supposed to avoid.</p><p>Before long, you have multiple versions of OrderCreated events flowing through your message bus:</p><pre>OrderCreated.v1<br>OrderCreated.v2<br>OrderCreated.v3</pre><p>and a dozen consumers each handling them differently.<br> You’re not managing microservices anymore — you’re managing <strong>micro-protocols</strong>.<br> you’ve reduced synchronous dependencies, but replaced them with <strong>invisible asynchronous contracts</strong> that are even harder to trace, version, and govern.</p><h3>When Microservices Go Too Far — Real-World Reversals</h3><p>After a decade of microservice enthusiasm, some of the world’s best-known engineering teams have <strong>reversed course</strong>, and their lessons are worth studying.</p><h4>Amazon Prime Video</h4><p>In 2024, Amazon Prime Video engineers revealed that a major video-monitoring workflow was <strong>migrated from microservices to a monolith</strong>, achieving <strong>over 90 % cost reduction</strong> and simpler scaling.<br> The microservice version introduced excessive network hops and orchestration overhead.<br> A well-structured monolith simply performed better. <a href="https://devclass.com/2023/05/05/reduce-costs-by-90-by-moving-from-microservices-to-monolith-amazon-internal-case-study-raises-eyebrows">Source from here</a></p><h4>Segment</h4><p>Segment’s data infrastructure had expanded into dozens of services.<br> Operational overhead — version mismatches, duplicated logic, and sluggish deployments — became unbearable.<br> The team merged multiple services back into one and instantly regained developer velocity.<br> As one engineer put it: <em>“We didn’t need microservices — we needed better boundaries inside a monolith.” </em><a href="https://www.infoq.com/news/2018/07/segment-microservices">Source from here</a></p><h4>InVision</h4><p>Several InVision teams rolled back microservice splits after realizing their so-called “microservices” were just tightly coupled modules communicating over HTTP.<br> Merging them restored reliability and drastically reduced deployment friction. <a href="https://www.conf-micro.services/2023/papers/06-su-back-to-the-monolith.pdf">Source from here</a></p><p>These aren’t isolated stories.<br> They highlight a broader realization: <strong>microservices are a tool, not a destination</strong>.</p><h3>When Microservices Make Sense</h3><p>For an early-stage product, a <strong>monolith</strong> means <strong>speed and certainty</strong>.<br> For a large, mature ecosystem with multiple autonomous teams, <strong>microservices</strong> can be a <strong>necessary defense line</strong> against chaos.</p><p>The key question isn’t whether you <em>can</em> build microservices — but whether you <em>should.</em></p><p>Ask yourself three questions:</p><ol><li><strong>Is your team large enough to need strict ownership boundaries?</strong></li><li><strong>Is your tech stack so diverse that decoupling is essential?</strong></li><li><strong>Are changes so frequent that full releases have become a bottleneck?</strong></li></ol><p>If none of these apply, microservices aren’t a savior — they’re an <strong>anchor</strong>.</p><p>And for developers , especially architects, the most important lesson is this:<br> <strong>Don’t chase trends. Understand your context.</strong></p><p>Often, what seems to require microservices just needs <strong>cleaner code and clearer boundaries</strong>.</p><h3>Architecture Should Evolve Gradually</h3><p>In real-world engineering, architecture should evolve <strong>step by step</strong>, not through revolution.</p><p>When business grows and teams expand, don’t rip everything apart overnight.<br> Start decomposing only modules with <strong>clear boundaries</strong> and <strong>frequent changes</strong>, and transition gradually using <strong>event buses</strong>, <strong>API gateways</strong>, or <strong>service registries</strong>.</p><p>Let <strong>monitoring</strong>, <strong>observability</strong>, <strong>rollback</strong>, and <strong>automation</strong> mature first — <em>then</em> talk about microservices.</p><p>Only when your foundations of <strong>observability, governance, and resilience</strong> are strong can microservices truly succeed.<br> Otherwise, you’re just <strong>creating chaos in a more distributed way</strong>.</p><h3>Final Thought</h3><p>Architecture isn’t a religion, it’s a reflection of context.<br> Monoliths aren’t outdated, and microservices aren’t magic.</p><p>The right architecture depends on <strong>team maturity, system complexity, and operational readiness</strong> — not fashion.</p><p>So before you split your system into a hundred services, ask yourself:<br> Do you really need microservices?<br> Or do you just need <strong>cleaner, well-structured code?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38ddd2318012" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Factory to Simplify Azure Function Integration Testing]]></title>
            <link>https://joehom0416.medium.com/i-built-a-factory-to-simplify-azure-function-integration-testing-91e1fabf3816?source=rss-675d8d70865f------2</link>
            <guid isPermaLink="false">https://medium.com/p/91e1fabf3816</guid>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dot-net-developers]]></category>
            <dc:creator><![CDATA[joehom]]></dc:creator>
            <pubDate>Sun, 02 Nov 2025 07:54:01 GMT</pubDate>
            <atom:updated>2025-11-02T07:54:01.228Z</atom:updated>
            <content:encoded><![CDATA[<p>Two weeks ago, I published a post discussing <strong>Azure Function Integration Tests</strong> — <a href="https://medium.com/@joehom0416/building-integration-tests-for-azure-functions-a-practical-guide-c2e0ff1260c1">Building Integration Tests for Azure Functions: A Practical Guide</a>. After that, I received several requests asking me to share the source code.</p><p>To make this process simpler and more reusable, I decided to build a solution similar to WebApplicationFactory. I spent the weekend developing it, and you can now find the source code on GitHub: <a href="https://github.com/joehom0416/azure-functions-integration-tests?tab=readme-ov-file">azure-functions-integration-tests</a>. It’s also available as a NuGet package for easy installation.</p><p>⭐ <strong>If you find this project useful, please consider giving it a star on GitHub, your support means a lot!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91e1fabf3816" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Integration Tests for Azure Functions: A Practical Guide]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Introduction to Azure Functions</p><p class="medium-feed-link"><a href="https://joehom0416.medium.com/building-integration-tests-for-azure-functions-a-practical-guide-c2e0ff1260c1?source=rss-675d8d70865f------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://joehom0416.medium.com/building-integration-tests-for-azure-functions-a-practical-guide-c2e0ff1260c1?source=rss-675d8d70865f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2e0ff1260c1</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[azure-function-app]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[joehom]]></dc:creator>
            <pubDate>Tue, 21 Oct 2025 09:49:05 GMT</pubDate>
            <atom:updated>2025-10-21T09:49:05.572Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Database-Generated vs Application-Generated IDs: What Every Developer Should Know]]></title>
            <link>https://joehom0416.medium.com/database-generated-vs-application-generated-ids-what-every-developer-should-know-1281efb31291?source=rss-675d8d70865f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1281efb31291</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[joehom]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 05:12:34 GMT</pubDate>
            <atom:updated>2026-01-24T10:23:43.686Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Understanding how ID generation strategy affects performance, scalability, and system design — in EF Core and beyond.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_l4e-E3JqnYMhoLBpaAGg.png" /></figure><p>Most developers don’t realize that the way they generate IDs could silently slow down every insert their system makes.</p><p>Choosing the right ID generation strategy is not just a database concern — it’s a design decision that affects performance, scalability, data consistency, and how well your system scales across services.<br> In modern distributed or multi-tenant environments, the wrong ID approach can introduce unnecessary database round-trips, index fragmentation, and throughput bottlenecks that only become visible under real-world load.</p><p>Broadly, ID generation can be categorized into <strong>two methods</strong>:</p><ol><li><strong>Database-generated IDs</strong> — the database handles ID creation using functions like NEWID(), NEWSEQUENTIALID(), IDENTITY, AUTO_INCREMENT, or sequence generators.</li><li><strong>Application-generated IDs</strong> — the application itself creates IDs using algorithms like UUID v4, v5, or v7, or even custom deterministic keys.</li></ol><p>This article explores how these two strategies differ, why database-generated IDs can hurt performance at scale, and why many modern systems — including those built with EF Core, Hibernate, and Prisma — are moving toward application-generated UUIDs for better scalability and control.</p><h3><strong>Quick Summary</strong></h3><ul><li>Database-generated IDs are simple but add hidden latency and round-trips.</li><li>Application-generated UUIDs (v5/v7) eliminate extra trips and improve scalability.</li><li>For multi-tenant systems, UUIDv5 with TenantId clustering gives the best long-term performance.</li></ul><p>Now that we understand the two main approaches, let’s start by looking at <strong>database-generated IDs</strong>.<br> This is the most common pattern across frameworks like EF Core, Hibernate, and Django ORM, where the database is responsible for creating the ID value.<br> However, this approach has some hidden behaviors that can affect how and when you get the ID back in your application.</p><h3>Why You Don’t Get the ID After AddAsync</h3><h4>How EF Core Handles Database-Generated Keys Internally</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*gCr4MXJiPOSGOAqyfg42eA.png" /></figure><p>When you call:</p><pre>await dbContext.AddAsync(entity);</pre><p>EF Core only <em>tracks</em> the entity. It does not talk to the database yet.</p><p>If your primary key is generated by the database (for example, NEWID() or IDENTITY), EF marks it as <em>“to be generated on insert.”</em></p><p>The actual ID is only populated <strong>after</strong> you call:</p><pre>await dbContext.SaveChangesAsync();</pre><p>At that point, EF executes the INSERT statement and retrieves the generated value.<br> Until then, your entity’s ID remains Guid.Empty.</p><p><strong>Notice:</strong> EF Core only assigns the ID <em>after</em> saving to the database. Until that moment, the entity has no usable key value.</p><p>This behavior is consistent for:</p><ul><li>NEWID() or NEWSEQUENTIALID()</li><li>Identity columns (IDENTITY(1,1))</li><li>Computed or generated columns</li></ul><h4>You Created a Database Trip Just to Get an ID</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*pcNtlCQQJ4YLZR26JsCxGA.png" /></figure><p>One common mistake is forcing an extra database round-trip just to retrieve an ID for a foreign key.</p><p>Example:</p><pre>var customer = new Customer { Name = &quot;Alice&quot; };<br>await dbContext.AddAsync(customer);<br>await dbContext.SaveChangesAsync(); // Forces DB trip just to get the ID<br><br>var order = new Order<br>{<br>    CustomerId = customer.Id,<br>    Amount = 500<br>};<br>await dbContext.AddAsync(order);<br>await dbContext.SaveChangesAsync();</pre><p>This triggers <strong>two database trips</strong>:</p><ol><li>Insert Customer and retrieve its generated ID</li><li>Insert Order with that ID</li></ol><p>At small scale, this seems fine.<br> But at multi-tenant scale or in bulk operations, these extra trips cause significant performance issues.</p><p><strong>What to notice:</strong> the first SaveChangesAsync() exists solely to fetch an ID. That round-trip is avoidable.</p><p>If IDs were generated in the application (for example, using Guid.NewGuid() or Guid.CreateVersion7()), you could skip that first trip entirely.<br> Let’s see how.</p><h4>Application-Generated IDs: Getting the ID Before Saving</h4><p><strong>Generating the ID Yourself</strong></p><p>If your logic requires the ID early, generate it yourself:</p><pre>entity.Id = Guid.NewGuid();<br>await dbContext.AddAsync(entity);</pre><p>And configure EF Core to respect it:</p><pre>builder.Property(x =&gt; x.Id)<br>    .ValueGeneratedNever();</pre><p>This gives you full control of the ID lifecycle and removes dependency on the database for key generation.</p><h3>Why Application-Generated IDs Are Better</h3><p><strong>Reduced Round-Trips and Better Batching</strong></p><p>Let’s revisit the earlier example, but now using application-generated IDs.</p><pre>// .NET 9 UUID v7 (time-ordered)<br>var customer = new Customer<br>{<br>    Id = Guid.CreateVersion7(),<br>    Name = &quot;Alice&quot;<br>};<br><br>var order = new Order<br>{<br>    Id = Guid.CreateVersion7(),<br>    CustomerId = customer.Id,<br>    Amount = 500<br>};<br><br>// One SaveChanges call, both inserted together<br>await dbContext.Customers.AddAsync(customer);<br>await dbContext.Orders.AddAsync(order);<br>await dbContext.SaveChangesAsync();</pre><p>Because both entities already have IDs:</p><ul><li>EF Core can batch inserts into a single database round-trip</li><li>No pre-save fetch is needed</li><li>Throughput improves significantly under concurrency</li></ul><p><strong>Notice:</strong> EF Core can now treat both inserts as one operation because it already knows their IDs in advance.</p><p>If you are still on .NET 8 or below, use Guid.NewGuid(). It works the same way, just without the ordered index benefit of UUID v7.</p><h3>Database-Generated vs Application-Generated IDs</h3><p>Here’s a quick side-by-side look at how both approaches behave in real-world scenarios:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*6zETEXQFCNhbJveDDIQKmg.png" /></figure><h3>When to Use Database-Generated IDs</h3><p>Database-generated IDs are not obsolete. They still make sense in simpler systems where:</p><ul><li>Inserts are low volume or not latency-sensitive</li><li>The database is the single source of truth (for example, traditional monoliths)</li><li>You want to delegate ID uniqueness to the database</li><li>You are using incremental numeric keys (IDENTITY, AUTO_INCREMENT, or sequences) for reporting or human readability</li></ul><p>In such cases, using database-generated IDs is perfectly fine. It reduces application logic and leverages the database’s built-in generation mechanism.<br> However, for high-scale, multi-tenant, or distributed systems, database-generated IDs quickly become a bottleneck.</p><h3>Clustered Index Considerations</h3><p>Many developers choose NEWSEQUENTIALID() or database sequences for better clustered index performance, and that is valid.</p><p>But in .NET 9 (and conceptually, in any modern language), you now have an equivalent:<br> <strong>UUID v7</strong>, a time-ordered UUID designed for efficient database indexing and high write throughput.</p><pre>var entity = new Order<br>{<br>    Id = Guid.CreateVersion7(),<br>    OrderDate = DateTime.UtcNow<br>};</pre><p>This provides the same insertion efficiency as NEWSEQUENTIALID, while allowing you to generate IDs in the application layer consistently across distributed systems.</p><h3>Recommended Pattern for Multi-Tenant SaaS Systems</h3><p>So far, we’ve looked at individual insert operations.<br> But the impact of ID generation becomes even more dramatic when you scale across multiple tenants and services.</p><p>In multi-tenant systems, performance must be one of the core considerations.<br> Every extra database trip compounds under load.</p><p>If each insert waits for a DB-generated ID:</p><ul><li>10,000 inserts = 10,000 round-trips</li><li>More latency, connection pool stress, and slower ingestion</li></ul><p>By switching to application-generated IDs, you can:</p><ul><li>Stage entities in memory</li><li>Insert in bulk or batches efficiently</li><li>Maintain tenant-level data locality</li></ul><h3><strong>Conclusion</strong></h3><p>The way you generate IDs affects more than uniqueness. It influences performance, scalability, and the architecture of your entire system.</p><p>Database-generated IDs are simple and still valuable for small or centralized systems.<br> But for modern, distributed applications, application-generated UUIDs (especially v5 and v7) offer:</p><ul><li>Fewer database trips</li><li>Higher throughput</li><li>Better multi-tenant performance</li><li>Deterministic and globally unique identifiers</li></ul><p>With UUID v7 now supported natively in modern platforms like .NET 9 (you can build your own as long as you follow the <a href="https://datatracker.ietf.org/doc/html/rfc4122">RFC standard)</a> , you can achieve sequential index performance and complete control over ID generation — without waiting for a database to assign it.</p><blockquote>Stop letting your database decide.<br> Start owning your IDs — because in modern distributed systems, performance begins where your identifiers are born.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1281efb31291" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>