<?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 Keval Balar on Medium]]></title>
        <description><![CDATA[Stories by Keval Balar on Medium]]></description>
        <link>https://medium.com/@kevalbalar1995?source=rss-b426c1c72296------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Zsewyq9XNwi_AF4A6pFAAw.png</url>
            <title>Stories by Keval Balar on Medium</title>
            <link>https://medium.com/@kevalbalar1995?source=rss-b426c1c72296------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:39:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kevalbalar1995/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[Azure App Service Deployment: A Practical Guide from Code to Production]]></title>
            <link>https://medium.com/@kevalbalar1995/azure-app-service-deployment-guide-f762a7686df4?source=rss-b426c1c72296------2</link>
            <guid isPermaLink="false">https://medium.com/p/f762a7686df4</guid>
            <category><![CDATA[microsoft-azure]]></category>
            <category><![CDATA[azure-app-service]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Keval Balar]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 11:12:25 GMT</pubDate>
            <atom:updated>2026-08-25T11:12:25.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OonzM2ivk2OlDpUM7ez5jw.png" /></figure><p>Deploying a web application to production can involve servers, operating systems, networking, SSL certificates, scaling, monitoring, and deployment pipelines. <strong>Azure App Service</strong> simplifies much of this infrastructure by providing a managed platform for hosting web applications, REST APIs, and backend services.</p><p>In this article, we’ll walk through the fundamentals of Azure App Service deployment, common deployment approaches, configuration, CI/CD, troubleshooting, and recommended practices.</p><h3>What Is Azure App Service?</h3><p>Azure App Service is a fully managed platform from Microsoft Azure for hosting web applications and APIs without managing the underlying servers.</p><p>It supports several popular application stacks, including:</p><ul><li>.NET / ASP.NET Core</li><li>Java</li><li>Node.js</li><li>Python</li><li>PHP</li><li>Containers</li></ul><p>Instead of provisioning a virtual machine and manually configuring a web server, you deploy your application to an App Service and let Azure manage much of the underlying infrastructure.</p><p>A simplified deployment architecture looks like this:</p><pre>Developer<br>   |<br>   | git push<br>   v<br>GitHub / Azure DevOps<br>   |<br>   | CI/CD Pipeline<br>   v<br>Azure App Service<br>   |<br>   +---- Application<br>   +---- Configuration<br>   +---- Logs<br>   +---- Monitoring</pre><h3>Why Use Azure App Service?</h3><p>Azure App Service is useful when you want to deploy applications quickly while avoiding unnecessary infrastructure management.</p><p>Some key capabilities include:</p><ul><li>Managed hosting</li><li>Automatic scaling options</li><li>Custom domains</li><li>HTTPS/TLS support</li><li>Deployment slots</li><li>Application settings</li><li>Built-in authentication options</li><li>Integration with GitHub and Azure DevOps</li><li>Application logging</li><li>Integration with Azure Monitor and Application Insights</li><li>Support for containers</li></ul><p>The main advantage is that developers can focus on the application instead of spending time maintaining operating systems and web servers.</p><h3>Creating an Azure App Service</h3><p>Before deploying an application, you need an Azure App Service.</p><p>You can create one through the Azure Portal, Azure CLI, ARM/Bicep, Terraform, or other infrastructure-as-code tools.</p><p>Using the Azure CLI, a basic setup might look like this:</p><pre>az login<br><br>az group create \<br>  --name my-app-rg \<br>  --location westeurope<br>az appservice plan create \<br>  --name my-app-plan \<br>  --resource-group my-app-rg \<br>  --sku B1 \<br>  --is-linux<br>az webapp create \<br>  --name my-demo-app \<br>  --resource-group my-app-rg \<br>  --plan my-app-plan \<br>  --runtime &quot;NODE:20-lts&quot;</pre><p>The exact runtime and SKU should be selected according to your application’s requirements and the Azure region you are using.</p><p>After creation, Azure provides an application URL similar to:</p><pre>https://my-demo-app.azurewebsites.net</pre><h3>Deployment Methods</h3><p>There are several ways to deploy an application to Azure App Service.</p><h4>1. Azure Portal</h4><p>The Azure Portal provides a graphical interface for configuring and deploying applications.</p><p>This can be useful for:</p><ul><li>Initial deployments</li><li>Testing</li><li>Learning Azure</li><li>Manual troubleshooting</li></ul><p>However, manual deployments are generally not ideal for production because they are difficult to reproduce consistently.</p><h4>2. Azure CLI</h4><p>Azure CLI is useful when you want deployments to be scriptable.</p><p>For example:</p><pre>az webapp deploy \<br>  --resource-group my-app-rg \<br>  --name my-demo-app \<br>  --src-path app.zip</pre><p>This approach works well with shell scripts and automated deployment systems.</p><h4>3. GitHub Actions</h4><p>For modern development workflows, GitHub Actions is one of the most convenient options.</p><p>A typical workflow is:</p><pre>Developer<br>    |<br>    v<br>GitHub Repository<br>    |<br>    v<br>GitHub Actions<br>    |<br>    +--&gt; Build<br>    |<br>    +--&gt; Test<br>    |<br>    +--&gt; Package<br>    |<br>    +--&gt; Deploy<br>    |<br>    v<br>Azure App Service</pre><p>A simplified GitHub Actions workflow could look like:</p><pre>name: Deploy to Azure App Service<br>on:<br>  push:<br>    branches:<br>      - main<br>jobs:<br>  build-and-deploy:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Checkout source<br>        uses: actions/checkout@v4<br>      - name: Setup Node.js<br>        uses: actions/setup-node@v4<br>        with:<br>          node-version: &#39;20&#39;<br>      - name: Install dependencies<br>        run: npm ci<br>      - name: Run tests<br>        run: npm test<br>      - name: Build application<br>        run: npm run build<br>      - name: Deploy to Azure<br>        uses: azure/webapps-deploy@v3<br>        with:<br>          app-name: my-demo-app<br>          publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }}</pre><p>For production environments, credentials and secrets should never be committed directly to the repository.</p><h3>Configuring Application Settings</h3><p>One of the most important concepts in App Service is separating configuration from application code.</p><p>For example, an application might require:</p><pre>DATABASE_URL<br>API_KEY<br>APP_ENV<br>REDIS_CONNECTION</pre><p>These values should normally be configured through App Service settings or an appropriate secrets-management solution rather than hard-coded into the source code.</p><p>You can configure settings using Azure CLI:</p><pre>az webapp config appsettings set \<br>  --resource-group my-app-rg \<br>  --name my-demo-app \<br>  --settings \<br>    APP_ENV=production \<br>    DATABASE_URL=&quot;your-database-connection-string&quot;</pre><p>Your application can then read these values from environment variables.</p><p>This approach makes it possible to deploy the same application package to multiple environments while changing only the environment-specific configuration.</p><p>For example:</p><pre>Application Package<br>       |<br>       +---- Development Configuration<br>       |<br>       +---- Staging Configuration<br>       |<br>       +---- Production Configuration</pre><h3>Deployment Slots</h3><p>Deployment slots are particularly useful for production applications.</p><p>Instead of deploying a new version directly to production, you can create a staging slot:</p><pre>App Service<br>|<br>+-- Production<br>|<br>+-- Staging</pre><p>The new application version can first be deployed to the staging slot.</p><p>You can then test it before swapping staging with production.</p><p>The workflow becomes:</p><pre>Code<br> |<br> v<br>Build<br> |<br> v<br>Staging Slot<br> |<br> | Testing<br> v<br>Swap<br> |<br> v<br>Production</pre><p>This reduces deployment risk and can significantly improve release workflows.</p><p>A typical command to create a staging slot is:</p><pre>az webapp deployment slot create \<br>  --name my-demo-app \<br>  --resource-group my-app-rg \<br>  --slot staging</pre><p>You can then deploy to the staging slot rather than directly to production.</p><h3>Scaling Azure App Service</h3><p>Applications rarely have a constant workload.</p><p>A small application may receive only a few requests per minute, while a production application might receive thousands.</p><p>App Service provides two important scaling concepts:</p><h3>Scale Up</h3><p>Scale up means moving to a more powerful App Service plan.</p><p>For example:</p><pre>Small Instance<br>     |<br>     v<br>Larger CPU / Memory Instance</pre><h3>Scale Out</h3><p>Scale out means running multiple application instances.</p><pre>+--&gt; Instance 1<br>             |<br>Traffic ----&gt;+--&gt; Instance 2<br>             |<br>             +--&gt; Instance 3</pre><p>Scale-out can help applications handle increased traffic and improve availability.</p><p>For production systems, scaling decisions should be based on actual metrics such as CPU, memory, request volume, response time, and application-specific performance indicators.</p><h3>Monitoring and Troubleshooting</h3><p>Deployment is only part of the process. Once an application is running, you need visibility into its health.</p><p>Azure App Service provides several diagnostic capabilities, including application logs and integration with Azure monitoring services.</p><p>When troubleshooting a failed deployment, check:</p><ol><li>Deployment logs</li><li>Application logs</li><li>HTTP status codes</li><li>Application settings</li><li>Runtime version</li><li>Startup configuration</li><li>Network connectivity</li><li>Database connectivity</li><li>Memory and CPU usage</li></ol><p>For example, if an application returns:</p><pre>HTTP 500 - Internal Server Error</pre><p>the deployment itself may have succeeded while the application failed during startup or request processing.</p><p>This distinction is important:</p><pre>Deployment successful<br>        ≠<br>Application healthy</pre><p>A successful deployment pipeline only tells you that the deployment process completed. It does not guarantee that the application is functioning correctly.</p><h3>Using Application Insights</h3><p>For production workloads, application monitoring should be part of the deployment architecture.</p><p>Azure Application Insights can provide telemetry such as:</p><ul><li>Request performance</li><li>Failed requests</li><li>Exceptions</li><li>Dependency calls</li><li>Availability information</li><li>Application metrics</li></ul><p>A useful production architecture can therefore look like:</p><pre>Users<br>  |<br>  v<br>Azure App Service<br>  |<br>  +---- Application<br>  |<br>  +---- Application Insights<br>           |<br>           +---- Requests<br>           +---- Exceptions<br>           +---- Dependencies<br>           +---- Performance</pre><p>This makes it easier to identify problems that may not be visible from deployment logs alone.</p><h3>Custom Domains and HTTPS</h3><p>The default Azure URL is useful for testing, but production applications commonly use a custom domain.</p><p>For example:</p><pre>https://my-demo-app.azurewebsites.net</pre><p>can become:</p><pre>https://www.example.com</pre><p>When configuring a production application, HTTPS should be enabled and properly configured.</p><p>A typical production request flow is:</p><pre>User<br> |<br> | HTTPS<br> v<br>Custom Domain<br> |<br> v<br>Azure App Service<br> |<br> v<br>Application</pre><p>Always verify DNS configuration, certificates, domain bindings, and HTTPS behavior before moving a production application to the new domain.</p><h3>Recommended CI/CD Workflow</h3><p>A robust deployment pipeline should not simply copy code to a server.</p><p>A better workflow is:</p><pre>Developer Push<br>      |<br>      v<br>Source Control<br>      |<br>      v<br>Build<br>      |<br>      v<br>Automated Tests<br>      |<br>      v<br>Security / Quality Checks<br>      |<br>      v<br>Package<br>      |<br>      v<br>Deploy to Staging<br>      |<br>      v<br>Validation<br>      |<br>      v<br>Production</pre><p>This provides a repeatable and auditable deployment process.</p><p>For larger teams, infrastructure should also be managed through infrastructure-as-code tools such as Bicep or Terraform rather than relying entirely on manual portal configuration.</p><h3>Common Deployment Problems</h3><h4>1. Application Starts Locally but Fails in Azure</h4><p>This is often caused by differences in:</p><ul><li>Environment variables</li><li>Runtime versions</li><li>File paths</li><li>Network access</li><li>Database configuration</li><li>Startup commands</li></ul><p>Do not assume that a locally working application automatically has all the configuration required in Azure.</p><h4>2. Missing Environment Variables</h4><p>An application may depend on environment variables that exist on the developer’s machine but were never configured in App Service.</p><p>Review the application’s required configuration and compare it with the App Service settings.</p><h4>3. Incorrect Startup Configuration</h4><p>Some runtimes require a specific startup command or application configuration.</p><p>If the platform starts successfully but the application does not respond, inspect the startup configuration and application logs.</p><h4>4. Database Connectivity</h4><p>A common production issue is that the application can connect to a database locally but cannot connect from Azure.</p><p>Check:</p><ul><li>Firewall rules</li><li>Private networking</li><li>Connection strings</li><li>Authentication</li><li>DNS resolution</li><li>TLS requirements</li></ul><h4>5. Insufficient Resources</h4><p>High CPU or memory utilization can cause slow responses, crashes, or restarts.</p><p>Monitor resource usage before simply increasing the App Service plan size. Sometimes the underlying problem is inefficient application code or an external dependency.</p><h3>Azure App Service Deployment Best Practices</h3><p>For production deployments, consider the following practices:</p><h4>1. Automate deployments</h4><p>Use CI/CD rather than relying on manual deployments.</p><h4>2. Separate configuration from code</h4><p>Use environment-specific application settings and appropriate secret-management solutions.</p><h4>3. Use deployment slots</h4><p>Deploy and validate new versions before switching production traffic.</p><h4>4. Enable monitoring</h4><p>Use application telemetry and platform metrics to detect problems quickly.</p><h4>5. Keep dependencies updated</h4><p>Regularly update application frameworks, libraries, and runtime versions while testing compatibility.</p><h4>6. Use infrastructure as code</h4><p>Define your Azure resources through Bicep, Terraform, or another supported infrastructure-as-code approach.</p><h4>7. Protect production</h4><p>Use appropriate authentication, access controls, network restrictions, HTTPS, and secret-management practices.</p><h4>8. Test rollback procedures</h4><p>A deployment strategy is incomplete if you have not tested how to recover from a failed release.</p><h3>A Simple Production Deployment Strategy</h3><p>For a small-to-medium application, a practical architecture could be:</p><pre>                    GitHub<br>                       |<br>                       v<br>                GitHub Actions<br>                       |<br>              +--------+--------+<br>              |                 |<br>            Build             Tests<br>              |                 |<br>              +--------+--------+<br>                       |<br>                       v<br>               Azure App Service<br>                       |<br>                +------+------+<br>                |             |<br>             Staging      Production<br>                |<br>             Validation<br>                |<br>                +---- Swap ----&gt;</pre><p>This provides a relatively simple path from source code to production while retaining a staging environment for validation.</p><h3>Final Thoughts</h3><p>Azure App Service removes much of the infrastructure complexity traditionally associated with web application hosting. Instead of managing servers directly, developers can focus on application code, configuration, deployment automation, and observability.</p><p>A good App Service deployment strategy is more than simply uploading an application. It should include:</p><ul><li>Automated CI/CD</li><li>Environment-specific configuration</li><li>Secure secret management</li><li>Staging and deployment slots</li><li>Monitoring and logging</li><li>Scaling</li><li>HTTPS and domain configuration</li><li>A tested rollback strategy</li></ul><p>Once these practices are in place, Azure App Service can provide a straightforward foundation for deploying and operating web applications in the cloud.</p><p><strong>The goal is not just to deploy an application — it is to create a deployment process that is repeatable, observable, secure, and easy to recover when something goes wrong.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f762a7686df4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes for .NET Developers: A Practical Guide from ASP.NET Core to Production]]></title>
            <link>https://medium.com/@kevalbalar1995/kubernetes-for-dotnet-developers-aspnet-core-f7246d263b0f?source=rss-b426c1c72296------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7246d263b0f</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Keval Balar]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 06:26:56 GMT</pubDate>
            <atom:updated>2026-08-10T06:26:56.071Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical, beginner-friendly guide to deploying and managing ASP.NET Core applications with Docker and Kubernetes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OonzM2ivk2OlDpUM7ez5jw.png" /></figure><p><strong>Docker. Kubernetes. Containers. Microservices. Cloud Native.</strong></p><p>You may already know how to build APIs with ASP.NET Core. You may have created Docker images and deployed applications to a VM or cloud service.</p><p>But Kubernetes can initially feel like a completely different world.</p><p>It doesn’t have to.</p><p>The easiest way to understand Kubernetes as a .NET developer is to map Kubernetes concepts to things you already know.</p><p>In this article, we’ll build that mental model and deploy a simple ASP.NET Core API to Kubernetes.</p><h3>What is Kubernetes?</h3><p>Kubernetes is a platform for running and managing containerized applications.</p><p>Instead of manually doing this:</p><pre>Build application<br>      ↓<br>Create server<br>      ↓<br>Install .NET<br>      ↓<br>Copy application<br>      ↓<br>Start application<br>      ↓<br>Monitor application<br>      ↓<br>Restart if it crashes<br>      ↓<br>Repeat for multiple servers</pre><p>Kubernetes automates much of this operational work.</p><p>You tell Kubernetes what you want:</p><blockquote><em>“I want three instances of my API running.”</em></blockquote><p>Kubernetes continuously works toward making the actual environment match that desired state.</p><p>This is one of the most important ideas to understand:</p><p><strong>Kubernetes is declarative.</strong></p><p>You describe the desired state, usually using YAML, and Kubernetes takes care of maintaining it.</p><h3>Why should a .NET developer care about Kubernetes?</h3><p>ASP.NET Core is particularly well suited to containerized environments.</p><p>It runs across Windows, Linux, macOS, and Docker, and modern ASP.NET Core applications can be packaged as containers and deployed to cloud platforms.</p><p>For example, imagine you have an ASP.NET Core API:</p><pre>MyCompany.OrderService</pre><p>Without containers, your deployment might look like:</p><pre>Load Balancer<br>      |<br>      +---- VM 1<br>      |      └── OrderService<br>      |<br>      +---- VM 2<br>             └── OrderService</pre><p>With Kubernetes:</p><pre>Kubernetes Cluster<br>                       |<br>             +---------+---------+<br>             |                   |<br>          Pod 1               Pod 2<br>             |                   |<br>      OrderService        OrderService</pre><p>Need another instance?</p><pre>Pod 1<br>Pod 2<br>Pod 3<br>Pod 4</pre><p>Kubernetes can manage the replicas for you.</p><h3>First, Understand the Kubernetes Mental Model</h3><p>If you’re coming from the .NET world, Kubernetes can feel unfamiliar at first. The easiest way to understand it is to map Kubernetes concepts to things you already know as a .NET developer.</p><p>Here is a simple mental model:</p><p><strong>.NET Application → Container</strong></p><p>Your ASP.NET Core application runs inside a container.</p><p><strong>Application Instance → Pod</strong></p><p>A Kubernetes Pod is the smallest deployable unit in Kubernetes. A typical ASP.NET Core application runs as one container inside a Pod.</p><p><strong>Multiple Application Instances → ReplicaSet</strong></p><p>A ReplicaSet ensures that the desired number of Pod instances are running.</p><p><strong>Deployment → Kubernetes Deployment</strong></p><p>A Kubernetes Deployment manages the desired state of your application, including how many replicas should run and how updates should be performed.</p><p><strong>Network Endpoint → Kubernetes Service</strong></p><p>A Service provides a stable network endpoint for accessing a group of Pods.</p><p><strong>Application Configuration → ConfigMap</strong></p><p>A ConfigMap allows you to keep non-sensitive configuration outside your application container.</p><p><strong>Passwords and Secrets → Kubernetes Secret</strong></p><p>Secrets are used for sensitive configuration such as passwords, tokens, and connection information.</p><p><strong>Server → Kubernetes Node</strong></p><p>A Node is a machine — virtual or physical — on which Kubernetes runs Pods.</p><p><strong>Group of Servers → Kubernetes Cluster</strong></p><p>A Kubernetes Cluster is a collection of Nodes managed by Kubernetes.</p><p><strong>Reverse Proxy / Entry Point → Ingress or Gateway</strong></p><p>Ingress or Gateway provides a way to route external HTTP/HTTPS traffic to services inside the Kubernetes cluster.</p><p><strong>Health Check → Liveness and Readiness Probes</strong></p><p>Kubernetes uses probes to determine whether your application is alive and whether it is ready to receive traffic.</p><h3>The Big Picture</h3><p>You can think about the relationship like this:</p><pre>.NET Application<br>       ↓<br>Docker Container<br>       ↓<br>      Pod<br>       ↓<br>  Deployment<br>       ↓<br>    Service<br>       ↓<br>Ingress / Gateway<br>       ↓<br>     Users</pre><p>And Kubernetes manages the infrastructure around your application:</p><pre>Kubernetes Cluster<br>                         │<br>              ┌──────────┴──────────┐<br>              │                     │<br>            Node                  Node<br>              │                     │<br>        ┌─────┴─────┐         ┌─────┴─────┐<br>        │           │         │           │<br>       Pod         Pod       Pod         Pod<br>        │           │         │           │<br>     .NET API    .NET API  .NET API    .NET API</pre><p>Once you understand these relationships, Kubernetes becomes much easier to work with.</p><p>You don’t need to think of Kubernetes as a completely different programming platform. Your ASP.NET Core application is still your ASP.NET Core application.</p><p>Kubernetes is responsible for <strong>running, networking, scaling, updating, and managing that application</strong>.</p><h4>Step 1: Create an ASP.NET Core API</h4><p>Let’s start with a simple API.</p><pre>dotnet new webapi -n KubernetesDemo<br>cd KubernetesDemo</pre><p>Run it locally:</p><pre>dotnet run</pre><p>You should now have a normal ASP.NET Core application.</p><p>At this point, Kubernetes doesn’t know anything about your application.</p><p>That’s where Docker comes in.</p><h4>Step 2: Containerize the .NET application</h4><p>Kubernetes works with containers.</p><p>So instead of giving Kubernetes:</p><pre>KubernetesDemo.dll</pre><p>we give it a container image.</p><p>A typical Dockerfile for an ASP.NET Core application looks like this:</p><pre>FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base<br>WORKDIR /app<br>EXPOSE 8080<br>FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build<br>WORKDIR /src<br>COPY [&quot;KubernetesDemo/KubernetesDemo.csproj&quot;, &quot;KubernetesDemo/&quot;]<br>RUN dotnet restore &quot;KubernetesDemo/KubernetesDemo.csproj&quot;<br>COPY . .<br>WORKDIR &quot;/src/KubernetesDemo&quot;<br>RUN dotnet publish &quot;KubernetesDemo.csproj&quot; \<br>    -c Release \<br>    -o /app/publish \<br>    /p:UseAppHost=false<br>FROM base AS final<br>WORKDIR /app<br>COPY --from=build /app/publish .<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;KubernetesDemo.dll&quot;]</pre><p>The Dockerfile uses a multi-stage build.</p><p>The first image contains the SDK and is used to compile the application.</p><p>The final image contains only what is required to run the application.</p><p>This keeps the runtime image smaller and avoids shipping the SDK unnecessarily.</p><h4>Step 3: Build the Docker image</h4><p>From the solution directory:</p><pre>docker build -t kubernetes-demo:1.0 .</pre><p>Check the image:</p><pre>docker images</pre><p>You should see something similar to:</p><pre>REPOSITORY          TAG<br>kubernetes-demo     1.0</pre><p>Run it:</p><pre>docker run -p 8080:8080 kubernetes-demo:1.0</pre><p>Now your application is running inside a container.</p><p>This is an important milestone.</p><p>You have moved from:</p><pre>.NET Application</pre><p>to:</p><pre>.NET Application<br>       ↓<br>Docker Container</pre><p>The next step is:</p><pre>Docker Container<br>       ↓<br>Kubernetes</pre><h4>Step 4: What is a Pod?</h4><p>This is where many developers get confused.</p><p>A Kubernetes Pod is <strong>not the same thing as a container</strong>.</p><p>A Pod is the smallest deployable unit in Kubernetes.</p><p>A Pod can contain one or more containers.</p><p>For a typical ASP.NET Core application, you will often have:</p><pre>Pod<br> |<br> └── ASP.NET Core Container</pre><p>So you can think of a simple Pod as the Kubernetes environment in which your application container runs.</p><p>For example:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: kubernetes-demo<br>spec:<br>  containers:<br>    - name: kubernetes-demo<br>      image: kubernetes-demo:1.0<br>      ports:<br>        - containerPort: 8080</pre><p>However, in real applications, you generally don’t create Pods directly.</p><p>Instead, you use a <strong>Deployment</strong>.</p><h4>Step 5: Kubernetes Deployment</h4><p>A Deployment tells Kubernetes how your application should be deployed.</p><p>For example:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: kubernetes-demo<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: kubernetes-demo<br>  template:<br>    metadata:<br>      labels:<br>        app: kubernetes-demo<br>    spec:<br>      containers:<br>        - name: kubernetes-demo<br>          image: kubernetes-demo:1.0<br>          ports:<br>            - containerPort: 8080</pre><p>The important line is:</p><pre>replicas: 3</pre><p>It means:</p><blockquote><em>Keep three Pods running.</em></blockquote><p>Kubernetes will attempt to maintain that desired state.</p><p>If one Pod crashes:</p><pre>Before:<br>Pod 1<br>Pod 2<br>Pod 3</pre><p>After Pod 2 fails:</p><pre>Pod 1<br>Pod 3</pre><p>Kubernetes notices that only two replicas are running.</p><p>It creates another:</p><pre>Pod 1<br>Pod 3<br>Pod 4</pre><p>The exact replacement behavior depends on the workload and cluster, but the key idea is that Kubernetes continuously reconciles the actual state with the desired state.</p><p>This is one of the biggest differences between traditional deployment and Kubernetes.</p><h4>Step 6: How does traffic reach the Pods?</h4><p>Now imagine we have:</p><pre>Pod 1<br>Pod 2<br>Pod 3</pre><p>Should your users connect directly to the Pods?</p><p>No.</p><p>Pods are considered ephemeral.</p><p>They can be recreated and their IP addresses can change.</p><p>This is where a Kubernetes <strong>Service</strong> comes in.</p><h4>Step 7: Kubernetes Service</h4><p>A Service provides a stable network endpoint for a group of Pods.</p><p>For our application:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: kubernetes-demo<br>spec:<br>  selector:<br>    app: kubernetes-demo<br>ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 8080<br>  type: ClusterIP</pre><p>Notice:</p><pre>port: 80<br>targetPort: 8080</pre><p>The Service listens on port 80 and forwards traffic to port 8080 on the application Pods.</p><p>The architecture now looks like:</p><pre>Kubernetes Service<br>                    |<br>          +---------+---------+<br>          |         |         |<br>        Pod 1     Pod 2     Pod 3<br>          |         |         |<br>       .NET       .NET      .NET<br>       API        API       API</pre><p>The Service doesn’t care which specific Pod handles the request.</p><p>That is exactly what we want.</p><h4>Step 8: Deployment vs Service</h4><p>A common beginner question is:</p><blockquote><em>Why do I need both?</em></blockquote><p>Because they solve different problems.</p><h4>Deployment</h4><p>Answers:</p><blockquote><em>How many application instances should exist?</em></blockquote><h4>Service</h4><p>Answers:</p><blockquote><em>How should other applications connect to those instances?</em></blockquote><p>For example:</p><pre>Deployment<br>    |<br>    +---- Pod<br>    +---- Pod<br>    +---- Pod<br><br>Service<br>    |<br>    +---- Pod<br>    +---- Pod<br>    +---- Pod</pre><p>A useful rule:</p><p><strong>Deployment manages Pods. Service exposes Pods.</strong></p><h4>Step 9: Configuration in Kubernetes</h4><p>.NET developers are already familiar with configuration.</p><p>You might have:</p><pre>{<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;DefaultConnection&quot;: &quot;...&quot;<br>  }<br>}</pre><p>In Kubernetes, configuration is commonly externalized using a <strong>ConfigMap</strong>.</p><p>Example:</p><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: kubernetes-demo-config<br>data:<br>  ASPNETCORE_ENVIRONMENT: &quot;Production&quot;</pre><p>You can then inject it into the container:</p><pre>envFrom:<br>  - configMapRef:<br>      name: kubernetes-demo-config</pre><p>Your ASP.NET Core application can access the value through the normal .NET configuration system.</p><p>This is an important cloud-native principle:</p><p><strong>Don’t hard-code environment-specific configuration into your application image.</strong></p><p>The same Docker image should ideally be deployable to development, staging, and production with different configuration.</p><h4>Step 10: What about passwords and API keys?</h4><p>Don’t put sensitive information in a normal ConfigMap.</p><p>For example, don’t do this:</p><pre>data:<br>  DatabasePassword: &quot;MySuperSecretPassword&quot;</pre><p>Use a Kubernetes Secret for sensitive configuration.</p><p>Example:</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: kubernetes-demo-secret<br>type: Opaque<br>stringData:<br>  DatabasePassword: &quot;MySuperSecretPassword&quot;</pre><p>Then inject it into the application.</p><p>However, production environments often use dedicated secret-management systems rather than treating Kubernetes Secrets as the complete security solution.</p><p>For example, a cloud environment may integrate Kubernetes with an external secrets manager.</p><p>The important architectural principle is:</p><pre>Application<br>     |<br>     +---- Non-sensitive config → ConfigMap<br>     |<br>     +---- Sensitive config → Secret / external secret store</pre><h4>Step 11: Health checks</h4><p>Here’s another area where Kubernetes works particularly well with ASP.NET Core.</p><p>Imagine your API is running:</p><pre>Pod 1<br>Pod 2<br>Pod 3</pre><p>But Pod 2 is technically running while the application inside it cannot process requests correctly.</p><p>Kubernetes needs a way to determine application health.</p><p>ASP.NET Core supports health checks.</p><p>For example:</p><pre>builder.Services.AddHealthChecks();<br>var app = builder.Build();<br>app.MapHealthChecks(&quot;/health&quot;);<br>app.Run();</pre><p>Now you have:</p><pre>GET /health</pre><p>Kubernetes can use this endpoint.</p><h4>Liveness vs Readiness</h4><p>These two concepts are extremely important.</p><h4>Liveness</h4><p>Liveness answers:</p><blockquote><em>Is the application alive?</em></blockquote><p>If the liveness check repeatedly fails, Kubernetes can restart the container.</p><p>Example:</p><pre>livenessProbe:<br>  httpGet:<br>    path: /health<br>    port: 8080<br>  initialDelaySeconds: 10<br>  periodSeconds: 10</pre><h4>Readiness</h4><p>Readiness answers:</p><blockquote><em>Is the application ready to receive traffic?</em></blockquote><p>For example, your application may be running but still waiting for a dependency to initialize.</p><p>In that situation, you may not want Kubernetes to send user traffic to it.</p><p>Example:</p><pre>readinessProbe:<br>  httpGet:<br>    path: /health<br>    port: 8080<br>  initialDelaySeconds: 5<br>  periodSeconds: 5</pre><p>The distinction is simple:</p><p><strong>Liveness = restart me if I’m broken.</strong></p><p><strong>Readiness = don’t send traffic to me yet.</strong></p><h4>Step 12: Resource limits</h4><p>A common mistake is to deploy applications without specifying resource requirements.</p><p>For example:</p><pre>resources:<br>  requests:<br>    cpu: &quot;100m&quot;<br>    memory: &quot;128Mi&quot;<br>  limits:<br>    cpu: &quot;500m&quot;<br>    memory: &quot;512Mi&quot;</pre><p>Requests tell Kubernetes approximately what resources the container needs.</p><p>Limits define an upper boundary.</p><p>For a production application, resource sizing should be based on actual application behaviour and load testing rather than blindly copying values from examples.</p><h4>Step 13: Scaling a .NET API</h4><p>Suppose your API normally runs with three replicas:</p><pre>replicas: 3</pre><p>Traffic increases.</p><p>You could manually increase it:</p><pre>replicas: 6</pre><p>But Kubernetes can also support automated scaling.</p><p>The Horizontal Pod Autoscaler can adjust the number of Pods based on metrics.</p><p>Conceptually:</p><pre>Low traffic<br>    ↓<br>3 Pods<br><br>High traffic<br>    ↓<br>6 Pods<br>Very high traffic<br>    ↓<br>10 Pods</pre><p>This is one of the main reasons Kubernetes is attractive for workloads with changing demand.</p><h4>Step 14: Rolling deployments</h4><p>Now imagine version 1 of your API is running:</p><pre>Pod 1 → v1<br>Pod 2 → v1<br>Pod 3 → v1</pre><p>You release version 2.</p><p>A Kubernetes Deployment can perform a rolling update.</p><p>Instead of immediately destroying everything:</p><pre>v1 → v1 → v1</pre><p>it can progressively replace Pods:</p><pre>v1 → v1 → v2</pre><p>then:</p><pre>v1 → v2 → v2</pre><p>and finally:</p><pre>v2 → v2 → v2</pre><p>This can allow deployments with significantly less downtime.</p><p>You can also roll back if the new version causes problems.</p><p>For example:</p><pre>kubectl rollout undo deployment/kubernetes-demo</pre><p>This is especially useful for teams deploying frequently.</p><h4>Step 15: The complete architecture</h4><p>At this point, our application looks like this:</p><pre>                   Internet<br>                       |<br>                       v<br>               Ingress / Gateway<br>                       |<br>                       v<br>                Kubernetes Service<br>                       |<br>          +------------+------------+<br>          |            |            |<br>          v            v            v<br>       Pod 1         Pod 2        Pod 3<br>          |            |            |<br>       ASP.NET       ASP.NET      ASP.NET<br>        Core          Core         Core<br>          |            |            |<br>          +------------+------------+<br>                       |<br>                 External Services<br>                 /       |       \<br>             Database   Redis   Message Bus</pre><p>This is a much more realistic mental model of a Kubernetes-hosted .NET application.</p><h4>Step 16: Deploy everything</h4><p>You might organize your Kubernetes files like this:</p><pre>k8s/<br>├── deployment.yaml<br>├── service.yaml<br>├── configmap.yaml<br>└── secret.yaml</pre><p>Then apply them:</p><pre>kubectl apply -f k8s/</pre><p>Check the Pods:</p><pre>kubectl get pods</pre><p>You might see:</p><pre>NAME                               READY   STATUS<br>kubernetes-demo-7d8f6b9c8-x1abc   1/1     Running<br>kubernetes-demo-7d8f6b9c8-x2def   1/1     Running<br>kubernetes-demo-7d8f6b9c8-x3ghi   1/1     Running</pre><p>Check the Deployment:</p><pre>kubectl get deployments</pre><p>Check the Service:</p><pre>kubectl get services</pre><p>And when something goes wrong:</p><pre>kubectl describe pod &lt;pod-name&gt;</pre><p>or:</p><pre>kubectl logs &lt;pod-name&gt;</pre><p>These commands will become some of your most frequently used Kubernetes tools.</p><h4>Step 17: Kubernetes commands every .NET developer should know</h4><p>You don’t need to memorize hundreds of commands.</p><p>Start with these:</p><h4>List Pods</h4><pre>kubectl get pods</pre><h4>List Deployments</h4><pre>kubectl get deployments</pre><h4>List Services</h4><pre>kubectl get services</pre><h4>View application logs</h4><pre>kubectl logs &lt;pod-name&gt;</pre><h4>Follow logs</h4><pre>kubectl logs -f &lt;pod-name&gt;</pre><h4>Inspect a Pod</h4><pre>kubectl describe pod &lt;pod-name&gt;</pre><h4>Apply configuration</h4><pre>kubectl apply -f deployment.yaml</pre><h4>Delete a resource</h4><pre>kubectl delete -f deployment.yaml</pre><h4>Check rollout</h4><pre>kubectl rollout status deployment/kubernetes-demo</pre><h4>Roll back</h4><pre>kubectl rollout undo deployment/kubernetes-demo</pre><p>These commands will take you surprisingly far.</p><h4>Step 18: Kubernetes isn’t a replacement for Docker</h4><p>This distinction is important.</p><p>Docker and Kubernetes solve different problems.</p><p>Docker answers:</p><blockquote><em>How do I package and run my application as a container?</em></blockquote><p>Kubernetes answers:</p><blockquote><em>How do I run, network, scale, update, and manage many containers?</em></blockquote><p>Think about it this way:</p><pre>.NET<br> ↓<br>Application<br><br>Docker<br> ↓<br>Container<br>Kubernetes<br> ↓<br>Container orchestration</pre><p>They complement each other.</p><h4>Step 19: What changes for ASP.NET Core developers?</h4><p>The good news is that Kubernetes doesn’t require you to rewrite your application.</p><p>Your controller might still look like:</p><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class OrdersController : ControllerBase<br>{<br>    [HttpGet]<br>    public IActionResult Get()<br>    {<br>        return Ok(new[]<br>        {<br>            new { Id = 1, Status = &quot;Completed&quot; },<br>            new { Id = 2, Status = &quot;Pending&quot; }<br>        });<br>    }<br>}</pre><p>Nothing Kubernetes-specific is required here.</p><p>Instead, Kubernetes operates around your application:</p><pre>             Kubernetes<br>                  |<br>        +---------+---------+<br>        |                   |<br>   Deployment            Service<br>        |                   |<br>        v                   |<br>      Pod &lt;-----------------+<br>        |<br>   ASP.NET Core<br>        |<br>   Controllers<br>   Services<br>   EF Core<br>   Business Logic</pre><p>This separation is one of the most powerful aspects of containers and orchestration.</p><p>Your application focuses on business functionality.</p><p>Kubernetes focuses on running the application.</p><h4>Step 20: Common mistakes .NET developers make</h4><h4>1. Treating a Pod like a server</h4><p>A Pod is ephemeral.</p><p>Don’t design your application assuming:</p><blockquote><em>“This particular Pod will always exist.”</em></blockquote><p>It won’t.</p><h4>2. Storing files inside the container</h4><p>If your application writes:</p><pre>/app/uploads/file.pdf</pre><p>don’t assume that file will permanently exist.</p><p>A Pod can be replaced.</p><p>For persistent data, use appropriate external storage or Kubernetes persistent storage mechanisms.</p><h4>3. Hard-coding configuration</h4><p>Avoid:</p><pre>var connectionString =<br>    &quot;Server=production-db;Password=secret&quot;;</pre><p>Use environment-aware configuration and secret management.</p><h4>4. Ignoring health checks</h4><p>An application that is running isn’t necessarily healthy.</p><p>Implement health endpoints and configure appropriate readiness and liveness probes.</p><h4>5. Using latest image tags</h4><p>Avoid:</p><pre>image: kubernetes-demo:latest</pre><p>Prefer immutable or traceable versions:</p><pre>image: kubernetes-demo:1.4.2</pre><p>or preferably a versioned image digest in production.</p><p>You want to know exactly which application version is running.</p><h4>6. Running everything as root</h4><p>Container security matters.</p><p>Use a non-root runtime user where appropriate, minimize the container image, and follow your platform’s security requirements.</p><h4>7. Treating Kubernetes as magic</h4><p>Kubernetes doesn’t automatically make bad architecture good.</p><p>If your application:</p><ul><li>leaks memory,</li><li>has inefficient database queries,</li><li>has no timeouts,</li><li>has poor logging,</li><li>has no observability,</li><li>or cannot handle concurrent requests,</li></ul><p>putting it in Kubernetes doesn’t fix those problems.</p><p>Kubernetes manages workloads.</p><p>It doesn’t replace good software engineering.</p><h4>Step 21: Logging and observability</h4><p>In a traditional application, you might SSH into a server and inspect log files.</p><p>That approach doesn’t work well with ephemeral containers.</p><p>Instead, applications should produce logs to standard output/error and use centralized logging.</p><p>For .NET applications, structured logging is particularly useful.</p><p>For example:</p><pre>logger.LogInformation(<br>    &quot;Order {OrderId} created for customer {CustomerId}&quot;,<br>    orderId,<br>    customerId);</pre><p>Instead of:</p><pre>logger.LogInformation(<br>    &quot;Order created: &quot; + orderId);</pre><p>Structured logs make it easier to search and analyze application behavior across multiple Pods.</p><p>For production Kubernetes environments, observability typically includes:</p><pre>Logs<br>  +<br>Metrics<br>  +<br>Distributed Traces<br>  +<br>Health Checks</pre><p>OpenTelemetry is increasingly common for this type of instrumentation.</p><h4>Step 22: Kubernetes and microservices</h4><p>Kubernetes is frequently associated with microservices.</p><p>For example:</p><pre>                   Kubernetes<br>                        |<br>       +----------------+----------------+<br>       |                |                |<br>       v                v                v<br> Order Service     Payment Service   Notification Service<br>       |                |                |<br>       v                v                v<br>   Database          Database         Message Bus</pre><p>Each service can have its own:</p><ul><li>Deployment</li><li>Service</li><li>Configuration</li><li>Scaling rules</li><li>Health checks</li><li>Release cycle</li></ul><p>But there’s an important warning:</p><p><strong>Don’t introduce microservices just because you’re using Kubernetes.</strong></p><p>A well-designed modular monolith can also run perfectly well in Kubernetes.</p><p>Kubernetes is a deployment and orchestration platform, not a requirement for microservices.</p><h4>Step 23: Kubernetes in Azure</h4><p>If you’re a .NET developer working in the Microsoft ecosystem, you will probably encounter <strong>Azure Kubernetes Service (AKS)</strong>.</p><p>The architecture becomes:</p><pre>Developer<br>    |<br>    v<br>Docker Image<br>    |<br>    v<br>Container Registry<br>    |<br>    v<br>AKS<br>    |<br>    +---- Node<br>    |      |<br>    |      +---- Pod<br>    |<br>    +---- Node<br>           |<br>           +---- Pod</pre><p>The underlying Kubernetes concepts remain the same.</p><p>You’re simply using a managed Kubernetes service rather than building and maintaining the entire cluster yourself.</p><p>This is one reason it’s useful to learn Kubernetes concepts independently of a specific cloud provider.</p><h4>Step 24: What should a .NET developer learn first?</h4><p>If Kubernetes is completely new to you, don’t start by learning everything.</p><p>Use this progression:</p><h4>Level 1 — Containers</h4><p>Learn:</p><pre>Dockerfile<br>Images<br>Containers<br>Volumes<br>Networks<br>Registries</pre><h4>Level 2 — Kubernetes fundamentals</h4><p>Learn:</p><pre>Cluster<br>Node<br>Pod<br>Deployment<br>Service<br>Namespace<br>ConfigMap<br>Secret</pre><h4>Level 3 — Application operations</h4><p>Learn:</p><pre>Health checks<br>Readiness<br>Liveness<br>Resource requests<br>Resource limits<br>Logs<br>Rolling updates<br>Rollback</pre><h4>Level 4 — Networking</h4><p>Learn:</p><pre>Service types<br>Ingress<br>Gateway<br>DNS<br>TLS<br>Network policies</pre><h4>Level 5 — Scaling</h4><p>Learn:</p><pre>Horizontal Pod Autoscaler<br>Cluster Autoscaler<br>Resource metrics<br>Load testing</pre><h4>Level 6 — Production</h4><p>Learn:</p><pre>Security<br>Observability<br>CI/CD<br>Secrets management<br>Backup<br>Disaster recovery<br>Cost management</pre><p>This progression is much easier than trying to learn Kubernetes as one enormous topic.</p><h3>A useful mental model</h3><p>If you remember only one diagram from this article, remember this:</p><pre>.NET Application<br>       |<br>       v<br>Docker Image<br>       |<br>       v<br>Kubernetes Deployment<br>       |<br>       v<br>      Pods<br>       |<br>       v<br>   Kubernetes<br>    Service<br>       |<br>       v<br>Ingress / Gateway<br>       |<br>       v<br>      Users</pre><p>And around the application:</p><pre>        +-----------------------+<br>        |       Kubernetes      |<br>        |                       |<br>        |  ConfigMap   Secret   |<br>        |       |        |      |<br>        |       v        v      |<br>        |    ASP.NET Core       |<br>        |       |               |<br>        |   Health Checks       |<br>        |       |               |<br>        |   Logs / Metrics      |<br>        +-----------------------+</pre><p>Once this model makes sense, Kubernetes becomes much less intimidating.</p><h3>Final thoughts</h3><p>For a .NET developer, Kubernetes isn’t really about learning a completely new way of building software.</p><p>You’re still writing:</p><pre>C#<br>ASP.NET Core<br>Entity Framework Core<br>REST APIs<br>Background Services</pre><p>The major change is how your application is packaged and operated.</p><p>Instead of thinking:</p><blockquote><em>“I have an application running on a server.”</em></blockquote><p>you start thinking:</p><blockquote><em>“I have a containerized workload whose desired state is managed by Kubernetes.”</em></blockquote><p>That shift is the foundation of cloud-native development.</p><p>Start small.</p><p>Build one ASP.NET Core API.</p><p>Containerize it.</p><p>Run it locally.</p><p>Create a Deployment.</p><p>Create a Service.</p><p>Add health checks.</p><p>Add configuration.</p><p>Scale it.</p><p>Break it.</p><p>Read the logs.</p><p>Deploy a new version.</p><p>Roll it back.</p><p>Once you’ve done that yourself, Kubernetes stops being a collection of YAML files and starts becoming a practical tool for running .NET applications reliably at scale.</p><p>And that’s the point where Kubernetes becomes useful rather than just another technology to put on your résumé.</p><h3>References</h3><ul><li>Microsoft .NET Support Policy — .NET 10 is currently an LTS release, supported through November 2028.</li><li>Microsoft ASP.NET Core hosting and deployment documentation.</li><li>Microsoft ASP.NET Core overview and container support.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7246d263b0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker for ASP.NET Core: A Complete Production Deployment Guide Using Docker Compose]]></title>
            <link>https://medium.com/@kevalbalar1995/docker-aspnet-core-production-deployment-docker-compose-guide-85b6d25b1285?source=rss-b426c1c72296------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b6d25b1285</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aspdotnetcore]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Keval Balar]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 06:34:54 GMT</pubDate>
            <atom:updated>2026-08-06T06:37:17.800Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to containerize and deploy ASP.NET Core applications with Docker and Docker Compose using production-ready practices, SQL Server integration, and a real-world deployment example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zni9wvJE0v5jqAEqUUcy-Q.png" /></figure><h3>Introduction</h3><p>Deploying an ASP.NET Core application used to involve installing the .NET runtime, configuring IIS or Nginx, managing dependencies, and troubleshooting environment-specific issues.</p><p>Docker changes that workflow completely.</p><p>Instead of deploying your application and hoping the server has everything configured correctly, Docker packages your application together with everything it needs to run. Whether you’re deploying to your local machine, a staging server, or production, the application behaves the same.</p><p>In this article, we’ll build and deploy an ASP.NET Core Web API using Docker and Docker Compose on an Ubuntu server. I’ll also cover production best practices that teams commonly use in real projects.</p><p>By the end of this guide, you’ll know how to:</p><ul><li>Containerize an ASP.NET Core application</li><li>Build optimized Docker images</li><li>Configure Docker Compose</li><li>Deploy to a Linux server</li><li>Persist application data</li><li>Handle environment variables</li><li>Perform application updates with minimal downtime</li></ul><h3>Why Docker?</h3><p>Before Docker, deployments often failed because:</p><ul><li>Different .NET versions were installed.</li><li>Missing libraries caused runtime errors.</li><li>Manual server configuration introduced inconsistencies.</li><li>Applications worked on the developer’s machine but failed in production.</li></ul><p>Docker solves these problems by packaging:</p><ul><li>Your application</li><li>.NET Runtime</li><li>Required libraries</li><li>Configuration</li><li>Dependencies</li></ul><p>The result is a consistent deployment across every environment.</p><h3>Our Example Project</h3><p>Suppose we have a simple ASP.NET Core Web API.</p><pre>ProductApi<br>│<br>├── Controllers<br>├── Models<br>├── Services<br>├── appsettings.json<br>├── Program.cs<br>└── ProductApi.csproj</pre><p>The API exposes endpoints like:</p><pre>GET /api/products<br>POST /api/products<br>GET /api/products/5</pre><p>Now let’s containerize it.</p><h4>Step 1: Create a Dockerfile</h4><p>Inside the project root, create a file named:</p><pre>Dockerfile</pre><p>Add the following:</p><pre># Build Stage<br>FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build<br>WORKDIR /src<br>COPY . .<br>RUN dotnet restore<br>RUN dotnet publish -c Release -o /app/publish<br># Runtime Stage<br>FROM mcr.microsoft.com/dotnet/aspnet:9.0<br>WORKDIR /app<br>COPY --from=build /app/publish .<br>EXPOSE 8080<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;ProductApi.dll&quot;]</pre><h4>Why Multi-Stage Builds?</h4><p>Without multi-stage builds:</p><ul><li>SDK remains inside the final image.</li><li>Image size becomes much larger.</li></ul><p>With multi-stage builds:</p><ul><li>Only the runtime is included.</li><li>Smaller image</li><li>Faster deployment</li><li>Better security</li></ul><h4>Step 2: Build the Docker Image</h4><p>Run:</p><pre>docker build -t productapi .</pre><p>Verify:</p><pre>docker images</pre><p>Expected output:</p><pre>REPOSITORY      TAG<br>productapi      latest</pre><h4>Step 3: Run the Container</h4><pre>docker run -d \<br>-p 8080:8080 \<br>--name productapi \<br>productapi</pre><p>Open:</p><pre>http://localhost:8080/swagger</pre><p>Your API is now running inside Docker.</p><h4>Step 4: Add Environment Variables</h4><p>Avoid hardcoding secrets.</p><p>Instead:</p><pre>docker run -d \<br>-p 8080:8080 \<br>-e ASPNETCORE_ENVIRONMENT=Production \<br>-e ConnectionStrings__Default=Server=db;Database=Products;User=sa;Password=Password123; \<br>productapi</pre><p>ASP.NET Core automatically maps:</p><pre>ConnectionStrings__Default</pre><p>to</p><pre>ConnectionStrings:Default</pre><h4>Step 5: Add SQL Server Using Docker Compose</h4><p>A production application usually requires a database.</p><p>Create:</p><pre>docker-compose.yml<br>version: &quot;3.9&quot;<br><br>services:<br>  api:<br>    image: productapi<br>    container_name: productapi<br>    ports:<br>      - &quot;8080:8080&quot;<br>    environment:<br>      ASPNETCORE_ENVIRONMENT: Production<br>      ConnectionStrings__Default: Server=db;Database=Products;User=sa;Password=YourStrongPassword123!;TrustServerCertificate=True<br>    depends_on:<br>      - db<br>  db:<br>    image: mcr.microsoft.com/mssql/server:2022-latest<br>    container_name: sqlserver<br>    environment:<br>      ACCEPT_EULA: &quot;Y&quot;<br>      SA_PASSWORD: &quot;YourStrongPassword123!&quot;<br>    ports:<br>      - &quot;1433:1433&quot;<br>    volumes:<br>      - sqlvolume:/var/opt/mssql<br>volumes:<br>  sqlvolume:</pre><p>Start everything:</p><pre>docker compose up -d</pre><p>Check:</p><pre>docker ps</pre><p>You’ll see:</p><pre>productapi<br>sqlserver</pre><h4>Step 6: Deploy to an Ubuntu Server</h4><p>Install Docker:</p><pre>sudo apt update<br>sudo apt install docker.io -y</pre><p>Install Docker Compose:</p><pre>sudo apt install docker-compose-v2 -y</pre><p>Clone your repository:</p><pre>git clone https://github.com/your-company/ProductApi.git<br>cd ProductApi</pre><p>Build:</p><pre>docker compose build</pre><p>Run:</p><pre>docker compose up -d</pre><p>The application is now running on the server.</p><h4>Step 7: Updating the Application</h4><p>Suppose you fix a bug and push new code.</p><p>Deployment becomes simple:</p><pre>git pull<br>docker compose build<br>docker compose up -d</pre><p>Docker recreates only the application container while leaving the SQL Server data intact because the database uses a persistent Docker volume.</p><h3>Real Production Example</h3><p>Let’s look at a practical deployment scenario.</p><p>A retail company hosts an ASP.NET Core Web API that serves a React frontend used by more than 5,000 customers each day.</p><h3>Architecture</h3><pre>Internet<br>     │<br>     ▼<br> Nginx Reverse Proxy<br>     │<br>     ▼<br>ASP.NET Core Container<br>     │<br>     ▼<br>SQL Server Container</pre><h3>Deployment Workflow</h3><p>A developer pushes code to GitHub.</p><p>The production server executes:</p><pre>git pull<br>docker compose build<br>docker compose up -d</pre><p>The API restarts with the new version while SQL Server continues using the existing Docker volume, so customer data is preserved.</p><p>The deployment process takes only a few minutes and does not require reinstalling the .NET runtime or reconfiguring the server.</p><h3>Best Practices for Production</h3><h4>1. Use Multi-Stage Builds</h4><p>Keep Docker images small and secure.</p><h4>2. Never Store Secrets in Images</h4><p>Use environment variables or a secrets manager.</p><p>Avoid:</p><pre>ENV PASSWORD=123456</pre><h4>3. Use Docker Volumes</h4><p>Without a volume:</p><pre>Container Deleted<br>        ↓<br>Database Deleted</pre><p>With a volume:</p><pre>Container Deleted<br>         ↓<br>Database Still Exists</pre><h4>4. Use Health Checks</h4><p>Example:</p><pre>HEALTHCHECK CMD curl --fail http://localhost:8080/health || exit 1</pre><p>This helps orchestrators detect unhealthy containers.</p><h4>5. Restart Containers Automatically</h4><pre>restart: always</pre><p>The application will restart automatically after a server reboot or an unexpected crash.</p><h4>6. Keep Images Updated</h4><p>Regularly update the base images to receive security patches and runtime improvements.</p><h3>Common Docker Commands</h3><p>Build:</p><pre>docker build -t productapi .</pre><p>Run:</p><pre>docker run -d -p 8080:8080 productapi</pre><p>View logs:</p><pre>docker logs productapi</pre><p>Open a shell inside the container:</p><pre>docker exec -it productapi bash</pre><p>Stop:</p><pre>docker stop productapi</pre><p>Remove:</p><pre>docker rm productapi</pre><p>Docker Compose:</p><pre>docker compose up -d<br>docker compose down<br>docker compose build<br>docker compose logs</pre><h3>Common Mistakes</h3><ul><li>Using the SDK image as the runtime image.</li><li>Storing passwords directly in the Dockerfile.</li><li>Forgetting to persist database data with volumes.</li><li>Running containers as the root user.</li><li>Not exposing the correct application port.</li><li>Ignoring application logs when troubleshooting.</li></ul><h3>Final Thoughts</h3><p>Docker simplifies ASP.NET Core deployments by making applications portable, repeatable, and easier to manage across development, staging, and production environments.</p><p>With Docker Compose, you can define your application stack — including the API, database, and supporting services — in a single configuration file. This reduces manual server setup, improves consistency, and makes updates predictable.</p><p>Whether you’re deploying a small internal API or a high-traffic production service, learning Docker is a valuable investment for any .NET developer.</p><p>If you’re just starting, begin by containerizing a simple API, then gradually introduce Docker Compose, reverse proxies, HTTPS, and automated CI/CD pipelines as your applications grow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b6d25b1285" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bounded Context Communication in Domain-Driven Design: Domain Events vs Integration Events]]></title>
            <link>https://medium.com/@kevalbalar1995/bounded-context-communication-domain-events-integration-events-ddd-14e3722b9b58?source=rss-b426c1c72296------2</link>
            <guid isPermaLink="false">https://medium.com/p/14e3722b9b58</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Keval Balar]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 12:17:50 GMT</pubDate>
            <atom:updated>2026-07-27T12:17:50.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgQ-TJev_c49HMw2lCU1yQ.png" /></figure><p>In a previous article, we explored some of the core building blocks of Domain-Driven Design (DDD), including aggregates, value objects, repositories, and bounded contexts.</p><p>A natural next question is:</p><blockquote><em>How do different bounded contexts communicate with each other?</em></blockquote><p>For example, imagine an e-commerce system with separate bounded contexts:</p><ul><li><strong>Ordering</strong></li><li><strong>Payment</strong></li><li><strong>Inventory</strong></li><li><strong>Shipping</strong></li><li><strong>Notifications</strong></li></ul><p>Each context has its own domain model and business rules. The challenge is to allow these contexts to collaborate without tightly coupling them together.</p><p>This is where <strong>domain events</strong> and <strong>integration events</strong> become important.</p><h3>What Is a Bounded Context?</h3><p>A bounded context defines the boundary within which a particular domain model and its terminology are valid.</p><p>For example, the word <strong>Order</strong> may mean different things in different contexts.</p><h4>Ordering Context</h4><pre>public class Order<br>{<br>    public Guid Id { get; private set; }<br>    public OrderStatus Status { get; private set; }<br><br>    public void Confirm()<br>    {<br>        Status = OrderStatus.Confirmed;<br>    }<br>}</pre><h4>Shipping Context</h4><p>The Shipping context may not need the complete Order model. It may only need information required to deliver the order:</p><pre>public class Shipment<br>{<br>    public Guid OrderId { get; private set; }<br>    public Address DeliveryAddress { get; private set; }<br>}</pre><p>These contexts have different responsibilities and models.</p><p>The goal is not to create one large model shared by the entire system.</p><p>Instead:</p><blockquote><em>Each bounded context should own its model and communicate through well-defined contracts.</em></blockquote><h3>Why Bounded Contexts Need Communication</h3><p>Although bounded contexts should be independent, business workflows often span multiple contexts.</p><p>Consider a simple e-commerce workflow:</p><pre>Customer places order<br>        ↓<br>Order is confirmed<br>        ↓<br>Payment is processed<br>        ↓<br>Inventory is reserved<br>        ↓<br>Shipment is created<br>        ↓<br>Customer receives notification</pre><p>These steps may belong to different bounded contexts.</p><p>For example:</p><pre>Ordering<br>    ↓<br>Payment<br>    ↓<br>Inventory<br>    ↓<br>Shipping<br>    ↓<br>Notifications</pre><p>The question is:</p><blockquote><em>How can these contexts communicate without directly depending on each other’s internal domain models?</em></blockquote><p>The answer is event-based communication.</p><h3>What Is a Domain Event?</h3><p>A <strong>domain event</strong> represents something important that happened within a domain.</p><p>Examples:</p><pre>OrderPlaced<br>PaymentCompleted<br>InventoryReserved<br>ShipmentCreated</pre><p>A domain event usually represents a business fact.</p><p>For example:</p><pre>public record OrderPlacedDomainEvent(<br>    Guid OrderId,<br>    Guid CustomerId,<br>    decimal TotalAmount<br>);</pre><p>The name is written in the past tense:</p><pre>OrderPlaced<br>PaymentCompleted<br>InventoryReserved</pre><p>This indicates that the event describes something that has already happened.</p><h3>Domain Events Usually Belong Inside a Bounded Context</h3><p>Suppose the Ordering context contains the following aggregate:</p><pre>public class Order : AggregateRoot<br>{<br>    public Guid Id { get; private set; }<br>    public void Place()<br>    {<br>        // Business rules<br>        AddDomainEvent(<br>            new OrderPlacedDomainEvent(<br>                Id<br>            )<br>        );<br>    }<br>}</pre><p>The aggregate records the event:</p><pre>public abstract class AggregateRoot<br>{<br>    private readonly List&lt;IDomainEvent&gt; _domainEvents = new();<br><br>    public IReadOnlyCollection&lt;IDomainEvent&gt; DomainEvents =&gt;<br>        _domainEvents.AsReadOnly();<br>    protected void AddDomainEvent(IDomainEvent domainEvent)<br>    {<br>        _domainEvents.Add(domainEvent);<br>    }<br>}</pre><p>After the transaction is committed, the application can dispatch the domain event.</p><p>For example:</p><pre>public class OrderPlacedDomainEventHandler<br>{<br>    public async Task Handle(<br>        OrderPlacedDomainEvent notification)<br>    {<br>        // Execute business logic within the Ordering context<br>    }<br>}</pre><p>The important point is:</p><blockquote><em>A domain event is primarily an internal domain mechanism.</em></blockquote><p>It allows different parts of the same bounded context to react to business events without directly coupling everything together.</p><h3>Example: Domain Event Inside the Ordering Context</h3><p>Imagine the following:</p><pre>Order Aggregate<br>      ↓<br>OrderPlacedDomainEvent<br>      ↓<br> ┌──────────────┐<br> │ Handler 1    │ → Update order history<br> └──────────────┘<br> ┌──────────────┐<br> │ Handler 2    │ → Create audit record<br> └──────────────┘<br> ┌──────────────┐<br> │ Handler 3    │ → Start internal workflow<br> └──────────────┘</pre><p>The Order aggregate does not need to know about these handlers.</p><p>This is better than:</p><pre>public class Order<br>{<br>    public void Place()<br>    {<br>        SaveOrderHistory();<br>        CreateAuditLog();<br>        StartWorkflow();<br>    }<br>}</pre><p>The aggregate should focus on business rules.</p><p>Instead:</p><pre>public class Order<br>{<br>    public void Place()<br>    {<br>        // Validate business rules<br><br>        AddDomainEvent(<br>            new OrderPlacedDomainEvent(Id)<br>        );<br>    }<br>}</pre><p>The event allows other components to react independently.</p><h3>What Is an Integration Event?</h3><p>An <strong>integration event</strong> is used to communicate between bounded contexts or separate services.</p><p>For example:</p><pre>Ordering Context<br>        │<br>        │ Integration Event<br>        ▼<br>Payment Context</pre><p>The Ordering context may publish:</p><pre>public record OrderPlacedIntegrationEvent(<br>    Guid OrderId,<br>    decimal TotalAmount<br>);</pre><p>The Payment context consumes the event:</p><pre>public class OrderPlacedIntegrationEventHandler<br>{<br>    public async Task Handle(<br>        OrderPlacedIntegrationEvent message)<br>    {<br>        // Create payment request<br>    }<br>}</pre><p>The Payment context does not need to know about the internal Order aggregate.</p><p>It only knows about the integration contract:</p><pre>OrderId<br>TotalAmount</pre><p>This creates a clear boundary between the two contexts.</p><h3>Domain Events vs Integration Events</h3><p>The distinction can be summarised like this:</p><p>FeatureDomain EventIntegration EventScopeInside a bounded contextBetween bounded contextsPurposeNotify internal componentsCommunicate across boundariesCouplingInternal domain modelExternal contractDeliveryOften in-processUsually message broker or APIReliabilityUsually localRequires delivery strategyExampleOrderPlacedDomainEventOrderPlacedIntegrationEvent</p><p>A simple rule is:</p><blockquote><em>Domain events describe what happened inside a bounded context. Integration events communicate what other bounded contexts need to know.</em></blockquote><h3>A Common Mistake: Sharing Domain Events Between Contexts</h3><p>Consider this:</p><pre>public class OrderPlacedDomainEvent<br>{<br>    public Guid OrderId { get; set; }<br>    public Customer Customer { get; set; }<br>    public List&lt;OrderItem&gt; Items { get; set; }<br>}</pre><p>Now suppose the Payment context consumes this event directly.</p><p>This creates a problem.</p><p>The Payment context is now coupled to the Ordering context’s internal domain model.</p><p>For example:</p><pre>Ordering Context<br>      │<br>      │<br>      ▼<br>OrderPlacedDomainEvent<br>      │<br>      │<br>      ▼<br>Payment Context</pre><p>If the Ordering context changes its domain event:</p><pre>public class OrderPlacedDomainEvent<br>{<br>    public Customer Customer { get; set; }<br>}</pre><p>The Payment context may also break.</p><p>This is exactly the type of coupling bounded contexts are designed to avoid.</p><h3>The Better Approach: Translate Domain Events into Integration Events</h3><p>A common architecture is:</p><pre>┌───────────────────────┐<br>│   Ordering Context    │<br>│                       │<br>│   Order Aggregate     │<br>│          │            │<br>│          ▼            │<br>│   Domain Event        │<br>│          │            │<br>│          ▼            │<br>│ Integration Event     │<br>└───────────┬───────────┘<br>            │<br>            ▼<br>       Message Broker<br>            │<br>            ▼<br>┌───────────────────────┐<br>│    Payment Context    │<br>│                       │<br>│ Integration Handler   │<br>│          │            │<br>│          ▼            │<br>│ Payment Aggregate     │<br>└───────────────────────┘</pre><p>For example:</p><pre>public record OrderPlacedDomainEvent(<br>    Guid OrderId,<br>    decimal TotalAmount<br>);</pre><p>The Ordering context handles the domain event:</p><pre>public class OrderPlacedDomainEventHandler<br>{<br>    private readonly IEventBus _eventBus;<br><br>    public async Task Handle(<br>        OrderPlacedDomainEvent domainEvent)<br>    {<br>        var integrationEvent =<br>            new OrderPlacedIntegrationEvent(<br>                domainEvent.OrderId,<br>                domainEvent.TotalAmount<br>            );<br>        await _eventBus.PublishAsync(<br>            integrationEvent<br>        );<br>    }<br>}</pre><p>The Payment context receives its own contract:</p><pre>public record OrderPlacedIntegrationEvent(<br>    Guid OrderId,<br>    decimal TotalAmount<br>);</pre><p>The Payment context does not know or care about the internal domain model of Ordering.</p><h3>Why Should Integration Events Be Separate?</h3><p>Because each bounded context owns its own model.</p><p>Suppose the Ordering context has:</p><pre>public class Order<br>{<br>    public Guid Id { get; private set; }<br>    public Customer Customer { get; private set; }<br>    public List&lt;OrderItem&gt; Items { get; private set; }<br>    public Money Total { get; private set; }<br>}</pre><p>The Payment context may only need:</p><pre>public record PaymentRequest(<br>    Guid OrderId,<br>    decimal Amount<br>);</pre><p>The Inventory context may need:</p><pre>public record InventoryReservationRequest(<br>    Guid OrderId,<br>    IReadOnlyCollection&lt;ProductQuantity&gt; Products<br>);</pre><p>The Shipping context may need:</p><pre>public record ShipmentRequest(<br>    Guid OrderId,<br>    Address DeliveryAddress<br>);</pre><p>The same business event can produce different messages for different contexts.</p><p>This is important.</p><p>There is no requirement for every bounded context to receive the same data.</p><h3>Example: Complete Order Workflow</h3><p>Let’s look at a simplified workflow.</p><h4>Step 1: Order Is Placed</h4><p>The customer places an order.</p><pre>public class Order<br>{<br>    public void Place()<br>    {<br>        AddDomainEvent(<br>            new OrderPlacedDomainEvent(<br>                Id,<br>                TotalAmount<br>            )<br>        );<br>    }<br>}</pre><p>The Ordering context publishes:</p><pre>OrderPlacedIntegrationEvent</pre><h4>Step 2: Payment Context Receives the Event</h4><pre>Ordering<br>    │<br>    ▼<br>OrderPlacedIntegrationEvent<br>    │<br>    ▼<br>Payment</pre><p>The Payment context processes the payment:</p><pre>public class PaymentHandler<br>{<br>    public async Task Handle(<br>        OrderPlacedIntegrationEvent message)<br>    {<br>        await ProcessPayment(<br>            message.OrderId,<br>            message.TotalAmount<br>        );<br>    }<br>}</pre><p>After payment succeeds:</p><pre>public record PaymentCompletedIntegrationEvent(<br>    Guid OrderId,<br>    Guid PaymentId<br>);</pre><h4>Step 3: Inventory Context Receives the Event</h4><pre>Payment<br>    │<br>    ▼<br>PaymentCompletedIntegrationEvent<br>    │<br>    ▼<br>Inventory</pre><p>The Inventory context reserves the products.</p><pre>public class PaymentCompletedHandler<br>{<br>    public async Task Handle(<br>        PaymentCompletedIntegrationEvent message)<br>    {<br>        await ReserveInventory(<br>            message.OrderId<br>        );<br>    }<br>}</pre><p>After successful reservation:</p><pre>public record InventoryReservedIntegrationEvent(<br>    Guid OrderId<br>);</pre><h4>Step 4: Shipping Context Receives the Event</h4><pre>Inventory<br>    │<br>    ▼<br>InventoryReservedIntegrationEvent<br>    │<br>    ▼<br>Shipping</pre><p>The Shipping context creates a shipment:</p><pre>public class InventoryReservedHandler<br>{<br>    public async Task Handle(<br>        InventoryReservedIntegrationEvent message)<br>    {<br>        await CreateShipment(<br>            message.OrderId<br>        );<br>    }<br>}</pre><p>The overall workflow becomes:</p><pre>Order Placed<br>     ↓<br>Payment Completed<br>     ↓<br>Inventory Reserved<br>     ↓<br>Shipment Created</pre><p>Each bounded context performs its own responsibility.</p><h3>Synchronous vs Asynchronous Communication</h3><p>Bounded contexts can communicate in different ways.</p><h4>Synchronous Communication</h4><p>One context directly calls another.</p><pre>Ordering<br>    │<br>    │ HTTP Request<br>    ▼<br>Payment</pre><p>Example:</p><pre>var response = await paymentClient<br>    .ProcessPaymentAsync(request);</pre><h4>Advantages</h4><ul><li>Simple to understand</li><li>Immediate response</li><li>Easy for straightforward operations</li></ul><h4>Disadvantages</h4><ul><li>Creates runtime dependency</li><li>The other service must be available</li><li>Can create cascading failures</li><li>Increases coupling</li></ul><p>For example:</p><pre>Ordering<br>   │<br>   ▼<br>Payment<br>   │<br>   ▼<br>Inventory<br>   │<br>   ▼<br>Shipping</pre><p>If one service is unavailable, the entire workflow may fail.</p><h4>Asynchronous Communication</h4><p>Contexts communicate using messages or events.</p><pre>Ordering<br>    │<br>    ▼<br>Message Broker<br>    │<br>    ▼<br>Payment</pre><p>The sender does not need to wait for the receiver to complete immediately.</p><p>For example:</p><pre>await eventBus.PublishAsync(<br>    new OrderPlacedIntegrationEvent(<br>        orderId,<br>        totalAmount<br>    )<br>);</pre><p>The Payment context processes the event independently.</p><h4>Advantages</h4><ul><li>Reduced coupling</li><li>Better resilience</li><li>Supports independent scaling</li><li>Enables eventual consistency</li></ul><h4>Disadvantages</h4><ul><li>More complex</li><li>Requires message delivery guarantees</li><li>Debugging can be more difficult</li><li>Data may not be immediately consistent</li></ul><h3>Eventual Consistency</h3><p>When using asynchronous communication, different contexts may temporarily have different views of the system.</p><p>For example:</p><pre>Time 1:<br>Ordering:  Order Placed<br>Payment:   Payment Pending<br>Inventory: Not Reserved<br>Shipping:  Not Created</pre><p>After some time:</p><pre>Time 2:<br>Ordering:  Order Placed<br>Payment:   Payment Completed<br>Inventory: Reserved<br>Shipping:  Shipment Created</pre><p>The system becomes consistent through a sequence of events.</p><p>This is called <strong>eventual consistency</strong>.</p><p>The system may not be immediately consistent across all bounded contexts, but it eventually reaches a consistent state.</p><h3>The Outbox Pattern</h3><p>One important problem with integration events is reliability.</p><p>Consider this code:</p><pre>await database.SaveChangesAsync();<br><br>await eventBus.PublishAsync(<br>    new OrderPlacedIntegrationEvent(...)<br>);</pre><p>What happens if:</p><pre>Database Save       ✓<br>Event Publishing    ✗</pre><p>The order is saved, but the event is lost.</p><p>The Payment context never receives the message.</p><p>This creates an inconsistent system.</p><p>The <strong>Outbox Pattern</strong> solves this problem.</p><p>Instead of immediately publishing the event, the application stores the event in the same database transaction.</p><pre>┌────────────────────────┐<br>│ Database Transaction   │<br>│                        │<br>│ Order                  │<br>│ Outbox Message         │<br>└────────────┬───────────┘<br>             │<br>             ▼<br>       Transaction Commit<br>             │<br>             ▼<br>      Background Worker<br>             │<br>             ▼<br>        Message Broker</pre><p>Example:</p><pre>public async Task Handle(<br>    OrderPlacedDomainEvent domainEvent)<br>{<br>    var integrationEvent =<br>        new OrderPlacedIntegrationEvent(<br>            domainEvent.OrderId,<br>            domainEvent.TotalAmount<br>        );<br><br>    await _outboxRepository.AddAsync(<br>        integrationEvent<br>    );<br>}</pre><p>The Order and Outbox message are saved in the same transaction.</p><p>A background process later publishes the message:</p><pre>public async Task ProcessOutboxMessages()<br>{<br>    var messages =<br>        await _outboxRepository<br>            .GetPendingMessagesAsync();<br><br>    foreach (var message in messages)<br>    {<br>        await _eventBus.PublishAsync(message);<br>        await _outboxRepository<br>            .MarkAsProcessedAsync(message.Id);<br>    }<br>}</pre><p>This helps ensure that important integration events are not lost.</p><h3>Idempotency</h3><p>In distributed systems, messages may occasionally be delivered more than once.</p><p>For example:</p><pre>OrderPlacedEvent<br>       ↓<br>Payment Service<br>       ↓<br>Payment Processed</pre><p>The same event might be delivered again:</p><pre>OrderPlacedEvent<br>       ↓<br>Payment Service<br>       ↓<br>Payment Processed Again?</pre><p>If the system is not designed correctly, the customer could be charged twice.</p><p>Therefore, event handlers should be <strong>idempotent</strong>.</p><p>An idempotent operation can be executed multiple times without producing an incorrect result.</p><p>Example:</p><pre>public async Task Handle(<br>    OrderPlacedIntegrationEvent message)<br>{<br>    var existingPayment =<br>        await _paymentRepository<br>            .GetByOrderIdAsync(message.OrderId);<br><br>    if (existingPayment != null)<br>    {<br>        return;<br>    }<br>    var payment = new Payment(<br>        message.OrderId,<br>        message.TotalAmount<br>    );<br>    await _paymentRepository<br>        .AddAsync(payment);<br>}</pre><p>The handler first checks whether the payment already exists.</p><p>This prevents duplicate processing.</p><h3>Integration Events Are Public Contracts</h3><p>An integration event should be treated as a contract.</p><p>For example:</p><pre>public record OrderPlacedIntegrationEvent(<br>    Guid OrderId,<br>    decimal TotalAmount<br>);</pre><p>Once another bounded context depends on this event, changing it can affect other systems.</p><p>Therefore, integration events should be:</p><ul><li>Explicit</li><li>Stable</li><li>Small</li><li>Versionable</li><li>Independent of internal domain models</li></ul><p>Avoid exposing internal domain objects:</p><pre>public record OrderPlacedIntegrationEvent(<br>    Order Order<br>);</pre><p>Prefer a dedicated contract:</p><pre>public record OrderPlacedIntegrationEvent(<br>    Guid OrderId,<br>    decimal TotalAmount<br>);</pre><p>This keeps the boundary clear.</p><h3>Event Versioning</h3><p>As systems evolve, integration events may need to change.</p><p>For example, version one:</p><pre>public record OrderPlacedIntegrationEventV1(<br>    Guid OrderId,<br>    decimal TotalAmount<br>);</pre><p>Later, the system may require currency:</p><pre>public record OrderPlacedIntegrationEventV2(<br>    Guid OrderId,<br>    decimal TotalAmount,<br>    string Currency<br>);</pre><p>A versioning strategy allows consumers to migrate gradually.</p><p>The important principle is:</p><blockquote><em>Internal domain models can change freely. External integration contracts require more care.</em></blockquote><h3>A Practical Architecture</h3><p>A typical architecture may look like this:</p><pre>┌──────────────────────────────────┐<br>│        Ordering Context          │<br>│                                  │<br>│  Order Aggregate                 │<br>│        │                         │<br>│        ▼                         │<br>│  Domain Event                    │<br>│        │                         │<br>│        ▼                         │<br>│  Integration Event               │<br>│        │                         │<br>│        ▼                         │<br>│      Outbox                      │<br>└───────────────┬──────────────────┘<br>                │<br>                ▼<br>        ┌───────────────┐<br>        │ Message Broker│<br>        └───────┬───────┘<br>                │<br>       ┌────────┴─────────┐<br>       │                  │<br>       ▼                  ▼<br>┌──────────────┐   ┌──────────────┐<br>│   Payment    │   │  Inventory   │<br>│   Context    │   │   Context    │<br>└──────────────┘   └──────────────┘<br>       │                  │<br>       ▼                  ▼<br> Payment Completed   Inventory Reserved<br>       │                  │<br>       └────────┬─────────┘<br>                ▼<br>         Shipping Context</pre><p>Each bounded context:</p><ul><li>Owns its domain model</li><li>Owns its business rules</li><li>Owns its database</li><li>Publishes integration events</li><li>Consumes integration events</li><li>Avoids direct access to another context’s domain model</li></ul><h3>A Simple Mental Model</h3><p>The difference between domain events and integration events can be remembered like this:</p><pre>Domain Event<br>     ↓<br>Something important happened<br>inside my bounded context.<br><br>Integration Event<br>     ↓<br>Something important happened<br>and another bounded context may need to know.</pre><p>For example:</p><pre>Order Aggregate<br>       │<br>       ▼<br>OrderPlacedDomainEvent<br>       │<br>       ▼<br>Ordering Context<br>       │<br>       ▼<br>OrderPlacedIntegrationEvent<br>       │<br>       ▼<br>Payment Context</pre><p>The domain event belongs to the internal domain model.</p><p>The integration event belongs to the communication boundary.</p><h3>Conclusion</h3><p>Bounded contexts allow us to divide a complex business domain into smaller, focused models.</p><p>However, separating contexts creates an important architectural question:</p><blockquote><em>How should these contexts collaborate?</em></blockquote><p>Domain events and integration events provide a clear answer.</p><p><strong>Domain events</strong> are useful for communicating important business events inside a bounded context.</p><p><strong>Integration events</strong> are used to communicate across bounded-context boundaries.</p><p>A typical flow looks like this:</p><pre>Aggregate<br>   ↓<br>Domain Event<br>   ↓<br>Integration Event<br>   ↓<br>Outbox<br>   ↓<br>Message Broker<br>   ↓<br>Other Bounded Context</pre><p>The key principle is:</p><blockquote><em>Keep domain models internal. Communicate between bounded contexts through explicit integration contracts.</em></blockquote><p>When combined with asynchronous messaging, the Outbox Pattern, idempotent handlers, and careful event versioning, this approach allows different bounded contexts to collaborate while remaining independently modelled and loosely coupled.</p><p>This is one of the most powerful ideas in Domain-Driven Design:</p><blockquote><em>Bounded contexts do not need to share the same model to collaborate. They only need to agree on how to communicate.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14e3722b9b58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modular Monolith vs Microservices: The .NET Architecture Decision Most Teams Get Wrong]]></title>
            <link>https://medium.com/@kevalbalar1995/modular-monolith-vs-microservices-dotnet-architecture-79c8fe77a7fc?source=rss-b426c1c72296------2</link>
            <guid isPermaLink="false">https://medium.com/p/79c8fe77a7fc</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[modular-monolith]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Keval Balar]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 06:42:05 GMT</pubDate>
            <atom:updated>2026-07-23T06:42:05.494Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41prGgi6AFdLvVMlW2rkGA.png" /></figure><p>When starting a new .NET application, one architectural question appears repeatedly:</p><blockquote><strong><em>Should we build a modular monolith or use microservices?</em></strong></blockquote><p>The answer is often treated as a technology preference.</p><p>Some teams believe microservices are the natural choice for modern applications.</p><p>Others believe monoliths are simpler and therefore always better.</p><p>Both positions are incomplete.</p><p>The real architecture decision depends on your:</p><ul><li>Team structure</li><li>Business domain</li><li>Deployment requirements</li><li>Scaling needs</li><li>Data ownership</li><li>Failure-isolation requirements</li><li>Operational maturity</li></ul><p>The biggest mistake is choosing microservices before the system has a real reason to be distributed.</p><p>For many .NET applications, a well-designed modular monolith is the better starting point.</p><p>Not because microservices are bad.</p><p>Because distributed systems introduce complexity that should be justified by real requirements.</p><h3>What Is a Modular Monolith?</h3><p>A modular monolith is a single deployable application that is internally divided into well-defined business modules.</p><p>A typical structure might look like this:</p><pre>Application<br>│<br>├── Catalog<br>│   ├── Domain<br>│   ├── Application<br>│   └── Infrastructure<br>│<br>├── Orders<br>│   ├── Domain<br>│   ├── Application<br>│   └── Infrastructure<br>│<br>├── Payments<br>│   ├── Domain<br>│   ├── Application<br>│   └── Infrastructure<br>│<br>└── Notifications</pre><p>The application may be deployed as one ASP.NET Core application.</p><p>However, each module has a clear responsibility.</p><p>The Catalog module owns catalog behavior.</p><p>The Orders module owns order behavior.</p><p>The Payments module owns payment behavior.</p><p>The goal is to prevent every part of the system from depending directly on every other part.</p><p>A modular monolith should have:</p><ul><li>Clear module boundaries</li><li>Explicit contracts</li><li>Controlled dependencies</li><li>Encapsulated business logic</li><li>Clear ownership of data and behavior</li></ul><p>The deployment model is monolithic.</p><p>The internal architecture is modular.</p><p>That is the key distinction.</p><h3>What Are Microservices?</h3><p>Microservices divide an application into independently deployable services.</p><p>Each service typically owns a specific business capability.</p><p>For example:</p><pre>                    ┌───────────────┐<br>                    │   API Gateway │<br>                    └───────┬───────┘<br>                            │<br>          ┌─────────────────┼─────────────────┐<br>          │                 │                 │<br>     ┌────▼────┐       ┌────▼────┐       ┌────▼────┐<br>     │ Catalog │       │ Orders  │       │Payments │<br>     │ Service │       │ Service │       │ Service │<br>     └────┬────┘       └────┬────┘       └────┬────┘<br>          │                 │                 │<br>     Database A        Database B        Database C</pre><p>The important characteristic is not simply that the code is separated.</p><p>The important characteristic is that services can potentially be:</p><ul><li>Deployed independently</li><li>Scaled independently</li><li>Owned independently</li><li>Versioned independently</li><li>Operated independently</li></ul><p>This introduces flexibility.</p><p>It also introduces distributed-system complexity.</p><p>Communication that once happened inside a process may now happen through:</p><ul><li>HTTP</li><li>gRPC</li><li>Message brokers</li><li>Events</li><li>Queues</li></ul><p>That means the architecture must handle:</p><ul><li>Network failures</li><li>Timeouts</li><li>Retries</li><li>Duplicate messages</li><li>Eventual consistency</li><li>Distributed tracing</li><li>Service authentication</li></ul><p>Microservices are therefore not just a code organization technique.</p><p>They are an operational and architectural commitment.</p><h3>The Core Difference: Deployment Independence</h3><p>The most important difference between a modular monolith and microservices is usually deployment independence.</p><h4>Modular monolith</h4><pre>Change in Orders<br>       │<br>       ▼<br>Build application<br>       │<br>       ▼<br>Deploy application</pre><h4>Microservices</h4><pre>Change in Orders<br>       │<br>       ▼<br>Build Orders Service<br>       │<br>       ▼<br>Deploy Orders Service</pre><p>This matters when different parts of the system genuinely need different release schedules.</p><p>For example:</p><ul><li>The Payments team releases several times per week.</li><li>The Catalog team releases once per month.</li><li>The Reporting system has a separate deployment lifecycle.</li></ul><p>In that situation, independent deployment may provide significant value.</p><p>But if the entire team deploys the application together, microservices may provide little practical benefit.</p><p>You may be paying the cost of independent deployment without actually using it.</p><h3>Why Many Teams Choose Microservices Too Early</h3><p>Microservices are often selected based on expected future requirements.</p><p>A team may say:</p><ul><li>“We will eventually have millions of users.”</li><li>“We will probably have many teams.”</li><li>“This service may need to scale independently.”</li><li>“We might need different technologies later.”</li></ul><p>These are possible future scenarios.</p><p>They may become real.</p><p>But designing for every possible future problem can create immediate complexity.</p><p>A better approach is to ask:</p><blockquote><strong><em>What problem are we solving with this service boundary today?</em></strong></blockquote><p>If there is no clear answer, the boundary may be premature.</p><p>Architecture should be based on meaningful constraints.</p><p>Not hypothetical complexity.</p><h3>When a Modular Monolith Is Usually the Better Choice</h3><h4>1. The Team Is Small or Medium-Sized</h4><p>Microservices increase operational responsibilities.</p><p>A team may need to manage:</p><ul><li>Multiple deployment pipelines</li><li>Service-to-service authentication</li><li>Centralized logging</li><li>Distributed tracing</li><li>Monitoring</li><li>Alerting</li><li>Message brokers</li><li>Container infrastructure</li><li>Network failures</li></ul><p>For a small team, this can create a significant maintenance burden.</p><p>A modular monolith allows the team to maintain clear architecture while keeping the operational model simpler.</p><h4>2. The Domain Is Still Evolving</h4><p>Business boundaries are rarely obvious at the beginning of a project.</p><p>A team may initially identify:</p><pre>Customer<br>Orders<br>Payments<br>Inventory</pre><p>Later, it may discover that:</p><ul><li>Customer and Orders are tightly coupled.</li><li>Payment is mostly an external integration.</li><li>Inventory is the real scalability problem.</li><li>Notifications should be asynchronous.</li></ul><p>If these boundaries were implemented as separate services from day one, changing them can require:</p><ul><li>API changes</li><li>Data migration</li><li>Contract versioning</li><li>Deployment coordination</li><li>Service communication changes</li></ul><p>Inside a modular monolith, changing internal boundaries is often less expensive.</p><p>This makes modular architecture particularly useful when the domain is not yet fully understood.</p><h4>3. Most Features Cross Multiple Business Areas</h4><p>Consider a feature that requires:</p><pre>Orders<br>   ↓<br>Payments<br>   ↓<br>Inventory<br>   ↓<br>Notifications</pre><p>Inside a modular monolith, these interactions can happen through explicit in-process contracts.</p><p>In a microservices architecture, the same workflow may require:</p><ul><li>HTTP calls</li><li>Retries</li><li>Timeouts</li><li>Events</li><li>Message queues</li><li>Idempotency</li><li>Eventual consistency</li></ul><p>Distributed communication may be the correct solution.</p><p>But it should be introduced because the benefits justify the complexity.</p><p>Not because the modules exist.</p><h3>When Microservices Become a Stronger Choice</h3><p>Microservices become more attractive when independent service boundaries solve concrete problems.</p><h4>1. Independent Scaling Is Required</h4><p>Suppose an application contains:</p><pre>Catalog       → Low traffic<br>Orders        → Medium traffic<br>Reporting     → High CPU usage</pre><p>If the entire application must scale together, resources may be wasted.</p><p>A separate reporting service may allow:</p><pre>Reporting traffic increases<br>          │<br>          ▼<br>Scale Reporting Service</pre><p>without scaling Catalog or Orders unnecessarily.</p><p>This is a legitimate reason to consider a separate service.</p><p>However, other solutions may also be appropriate:</p><ul><li>Background workers</li><li>Separate processes</li><li>Job queues</li><li>Read models</li><li>Serverless workloads</li></ul><p>The problem is independent scaling.</p><p>Microservices are only one possible solution.</p><h4>2. Multiple Teams Need Real Autonomy</h4><p>Microservices can help larger organizations reduce coordination between teams.</p><p>For example:</p><ul><li>Team A owns Identity.</li><li>Team B owns Orders.</li><li>Team C owns Payments.</li><li>Team D owns Search.</li></ul><p>If these teams need to release independently, separate services may reduce coordination costs.</p><p>However, service boundaries alone do not create autonomy.</p><p>If every deployment still requires coordination between all teams, the organization may have created a distributed monolith.</p><p>The question is not:</p><blockquote><em>“Do we have multiple teams?”</em></blockquote><p>The question is:</p><blockquote><strong><em>“Do these teams genuinely need independent ownership and deployment?”</em></strong></blockquote><h4>3. Failure Isolation Is a Business Requirement</h4><p>Some components should be able to fail without taking down the entire application.</p><p>For example:</p><pre>Recommendation Service fails<br>            │<br>            ▼<br>Users can still browse and purchase</pre><p>This is a strong reason to isolate the component.</p><p>But not every part of an application requires independent failure isolation.</p><p>A payment failure may need to stop an order.</p><p>A recommendation failure may not.</p><p>Architecture should reflect business consequences.</p><h3>The Distributed Monolith Problem</h3><p>One of the most common microservices mistakes is creating a distributed monolith.</p><p>It may look like this:</p><pre>Order Service<br>      │<br>      ▼<br>Payment Service<br>      │<br>      ▼<br>Inventory Service<br>      │<br>      ▼<br>Shipping Service</pre><p>Every service is deployed separately.</p><p>But every request depends on the next service.</p><p>Now a single user request may require:</p><pre>API<br> │<br> ▼<br>Orders<br> │<br> ▼<br>Payments<br> │<br> ▼<br>Inventory<br> │<br> ▼<br>Shipping</pre><p>If one service is slow, the entire request may become slow.</p><p>If one service is unavailable, the entire workflow may fail.</p><p>The architecture is distributed.</p><p>The coupling remains.</p><p>This is one of the most important questions to ask:</p><blockquote><strong><em>Are we reducing coupling, or are we moving coupling across the network?</em></strong></blockquote><p>A network call is still a dependency.</p><p>It is simply a more expensive and failure-prone dependency.</p><h3>Data Ownership Is More Important Than Service Count</h3><p>Many teams create multiple services while allowing all of them to access the same database.</p><p>For example:</p><pre>Orders Service ──────┐<br>                     │<br>Payments Service ────┼──► Shared Database<br>                     │<br>Inventory Service ───┘</pre><p>This creates a problem.</p><p>The services may be deployed separately, but their data model is still tightly coupled.</p><p>A stronger service boundary looks like:</p><pre>Orders Service<br>      │<br>      ▼<br>Orders Database</pre><p>The service owns its data.</p><p>Other services interact through explicit APIs or events.</p><p>This does not mean every microservice must immediately have its own physical database.</p><p>The deeper principle is:</p><blockquote><strong><em>A service should own the data and business rules required for its capability.</em></strong></blockquote><p>If multiple services directly depend on the same internal database schema, the service boundary may not be meaningful.</p><h3>A Practical .NET Architecture Decision Framework</h3><p>Before choosing microservices, evaluate six areas.</p><h4>1. Team Structure</h4><p>Ask:</p><ul><li>How many development teams exist?</li><li>Do they own separate business capabilities?</li><li>Do they need independent releases?</li><li>Can they operate services independently?</li></ul><p>If the team is small and works on the entire product together, a modular monolith is often a strong default.</p><h4>2. Deployment Requirements</h4><p>Ask:</p><blockquote><strong><em>Which parts of the system need to be deployed independently?</em></strong></blockquote><p>If the answer is “none,” microservices may not be necessary.</p><p>If multiple areas require independent deployment, service boundaries become more valuable.</p><h4>3. Scaling Requirements</h4><p>Ask:</p><blockquote><strong><em>Does one component need to scale independently?</em></strong></blockquote><p>If yes, determine whether the problem can be solved with:</p><ul><li>A worker</li><li>A queue</li><li>A separate process</li><li>A read model</li><li>A dedicated service</li></ul><p>Do not automatically create a microservice.</p><h4>4. Data Ownership</h4><p>Ask:</p><blockquote><strong><em>Can this business capability own its data?</em></strong></blockquote><p>If not, the boundary may be too artificial.</p><p>Strong service boundaries usually have clear ownership of:</p><ul><li>Data</li><li>Business rules</li><li>APIs</li><li>Operational responsibility</li></ul><h4>5. Failure Isolation</h4><p>Ask:</p><blockquote><strong><em>Which failures must be isolated?</em></strong></blockquote><p>A component that can safely fail independently may be a good candidate for separation.</p><p>A component that must always participate in a single transaction may be better kept closer to the workflow.</p><h4>6. Operational Maturity</h4><p>Ask:</p><ul><li>Do we have centralized logging?</li><li>Do we have distributed tracing?</li><li>Can we monitor service health?</li><li>Can we deploy services automatically?</li><li>Can we manage secrets securely?</li><li>Can we debug cross-service failures?</li></ul><p>If the answer is mostly no, adding more services will likely increase operational risk.</p><h3>A Simple Scoring Model</h3><p>Use the following questions as a discussion tool.</p><p>Score each from <strong>0 to 2</strong>:</p><ul><li>Multiple teams need independent deployments.</li><li>Components need independent scaling.</li><li>Business capabilities can own data independently.</li><li>Failure isolation is critical.</li><li>Strong DevOps and observability exist.</li><li>Domain boundaries are well understood.</li></ul><h4>Score: 0–4</h4><p>Start with a modular monolith.</p><h4>Score: 5–8</h4><p>Use a modular monolith with selective asynchronous processing or extraction where necessary.</p><h4>Score: 9–12</h4><p>Microservices may be justified.</p><p>This is not a mathematical formula.</p><p>It is a way to make architecture decisions based on actual constraints rather than trends.</p><h3>A Strong Starting Architecture for Many .NET Applications</h3><p>A modular .NET application might be organized like this:</p><pre>src/<br>│<br>├── Catalog/<br>│   ├── Catalog.Domain/<br>│   ├── Catalog.Application/<br>│   └── Catalog.Infrastructure/<br>│<br>├── Orders/<br>│   ├── Orders.Domain/<br>│   ├── Orders.Application/<br>│   └── Orders.Infrastructure/<br>│<br>├── Payments/<br>│   ├── Payments.Domain/<br>│   ├── Payments.Application/<br>│   └── Payments.Infrastructure/<br>│<br>└── Web/</pre><p>The structure itself is not enough.</p><p>The important part is dependency control.</p><p>For example:</p><pre>Orders Module<br>      │<br>      ▼<br>Orders Public Contract<br>      │<br>      ▼<br>Other Modules</pre><p>Other modules should not directly depend on private implementation details.</p><p>A simple contract might look like:</p><pre>public interface IOrderService<br>{<br>    Task&lt;OrderResult&gt; CreateOrderAsync(<br>        CreateOrderCommand command);<br>}</pre><p>The exact implementation can change without forcing every other module to change.</p><p>This gives the system architectural flexibility.</p><h3>Modular Monolith to Microservices: An Evolutionary Path</h3><p>Architecture does not need to be permanent.</p><p>A system can evolve gradually.</p><h4>Stage 1: Modular Monolith</h4><pre>┌───────────────────────────────┐<br>│       Modular Monolith        │<br>│                               │<br>│ Catalog | Orders | Payments   │<br>│ Reports | Notifications       │<br>└───────────────────────────────┘</pre><h4>Stage 2: One Module Develops a Real Need</h4><p>For example:</p><ul><li>Reporting requires independent scaling.</li><li>Notifications need a separate processing model.</li><li>Payments require independent deployment.</li></ul><p>Extract only that module.</p><pre>┌───────────────────────┐       ┌─────────────┐<br>│   Modular Monolith    │──────►│  Reporting  │<br>│ Catalog | Orders      │       │   Service   │<br>│ Payments              │       └─────────────┘<br>└───────────────────────┘</pre><h4>Stage 3: Additional Extraction Only When Justified</h4><pre>┌──────────┐   ┌──────────┐   ┌─────────────┐<br>│ Catalog  │   │ Orders   │   │ Reporting   │<br>│ Service  │   │ Service  │   │  Service    │<br>└──────────┘   └──────────┘   └─────────────┘</pre><p>This approach is often called an evolutionary architecture.</p><p>The system changes as requirements become clearer.</p><p>The important principle is:</p><blockquote><strong><em>Extract services because a real problem requires independence.</em></strong></blockquote><p>Not because a diagram has room for more boxes.</p><h3>The Architecture Decision in One Sentence</h3><p>Choose a <strong>modular monolith</strong> when you need strong internal boundaries but do not yet need independent deployment.</p><p>Choose <strong>microservices</strong> when independent deployment, scaling, ownership, or failure isolation creates enough value to justify distributed-system complexity.</p><p>That is the real decision.</p><h3>Final Recommendation</h3><p>For many new .NET applications, the most practical default is:</p><ol><li>Start with a modular monolith.</li><li>Define business modules clearly.</li><li>Enforce boundaries in code.</li><li>Avoid unrestricted access to other modules’ data.</li><li>Measure real scaling and deployment problems.</li><li>Extract services only when there is a concrete reason.</li></ol><p>This approach provides a balance between simplicity and architectural discipline.</p><p>You do not need to predict the final architecture on day one.</p><p>You need to build an architecture that can evolve.</p><p>The most important rule is simple:</p><blockquote><strong><em>Make modules independent in code before making services independent in deployment.</em></strong></blockquote><p>Microservices are not the opposite of good architecture.</p><p>Neither is a monolith.</p><p>The right architecture is the one that matches the actual complexity of the system, the team, and the business.</p><p>And for many .NET teams, that means starting modular before going distributed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79c8fe77a7fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain-Driven Design in C#: A Practical Guide to DDD in .NET]]></title>
            <link>https://medium.com/@kevalbalar1995/domain-driven-design-csharp-ddd-dotnet-guide-146f548968b3?source=rss-b426c1c72296------2</link>
            <guid isPermaLink="false">https://medium.com/p/146f548968b3</guid>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[ddd-clean-architecture]]></category>
            <dc:creator><![CDATA[Keval Balar]]></dc:creator>
            <pubDate>Mon, 20 Jul 2026 06:44:09 GMT</pubDate>
            <atom:updated>2026-07-20T06:44:09.336Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to implement Domain-Driven Design in C# and .NET using Entities, Value Objects, Aggregates, Domain Events, Repositories, and Clean Architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lmu8BuGg_Y1ojBg5jhLmKQ.png" /></figure><p><strong>Domain-Driven Design (DDD) in C#</strong> is one of the most effective approaches for building complex and maintainable .NET applications.</p><p>As software systems grow, business logic becomes more complicated. A simple application can quickly evolve into a system with orders, payments, customers, inventory, shipping, discounts, and complex business rules.</p><p>At that point, simply creating more classes and database tables is not enough.</p><p>The real challenge is:</p><blockquote><strong><em>How do we design software that accurately represents the business?</em></strong></blockquote><p>This is the problem that <strong>Domain-Driven Design</strong> helps solve.</p><p>In this article, you will learn:</p><ul><li>What Domain-Driven Design is</li><li>Why DDD is useful in C# and .NET</li><li>Entities and Value Objects</li><li>Aggregates and Aggregate Roots</li><li>Repositories</li><li>Domain Services</li><li>Domain Events</li><li>Bounded Contexts</li><li>DDD with Clean Architecture</li><li>A practical C# example</li><li>Common DDD mistakes</li></ul><h3>What Is Domain-Driven Design?</h3><p><strong>Domain-Driven Design (DDD)</strong> is a software development approach that focuses on modeling software around the business domain.</p><p>The domain is the business problem that your application solves.</p><p>For example, an e-commerce system may have the following domain concepts:</p><pre>Customer<br>Order<br>Product<br>Payment<br>Shipment<br>Discount</pre><p>Each concept has business rules.</p><p>For example:</p><ul><li>An order must contain at least one product.</li><li>A customer cannot place an order without a valid address.</li><li>An order cannot be shipped before payment is completed.</li><li>A cancelled order cannot be shipped.</li><li>A discount can only be applied to eligible customers.</li></ul><p>These are not simply database rules.</p><p>They are <strong>business rules</strong>.</p><p>In DDD, these rules should be represented directly in the domain model.</p><h3>Why Use Domain-Driven Design in C#?</h3><p>C# and .NET are widely used for enterprise applications where business logic can become complex.</p><p>Without a clear architecture, a large application can become difficult to maintain.</p><p>A typical problematic application may look like this:</p><pre>Controller<br>    ↓<br>Service<br>    ↓<br>Repository<br>    ↓<br>Database</pre><p>The problem is that business rules may be spread across:</p><ul><li>Controllers</li><li>Services</li><li>Repositories</li><li>Database triggers</li><li>Utility classes</li></ul><p>This makes the system difficult to understand.</p><p>With Domain-Driven Design, business rules are organized around the domain:</p><pre>API<br> │<br> ▼<br>Application Layer<br> │<br> ▼<br>Domain Layer<br> │<br> ▼<br>Business Rules</pre><p>The domain becomes the center of the application.</p><h3>The Core Building Blocks of DDD</h3><p>Let’s explore the most important Domain-Driven Design concepts using C# examples.</p><h4>1. Entity in Domain-Driven Design</h4><p>An <strong>Entity</strong> is an object that has a unique identity.</p><p>The identity is more important than its individual properties.</p><p>Consider two customers:</p><pre>Customer A<br>Id: 1<br>Name: John Smith<br><br>Customer B<br>Id: 2<br>Name: John Smith</pre><p>Even though both customers have the same name, they are different customers because they have different identities.</p><p>A C# Entity might look like this:</p><pre>public class Customer<br>{<br>    public Guid Id { get; private set; }<br>    public string Name { get; private set; }<br>    public Customer(Guid id, string name)<br>    {<br>        Id = id;<br>        Name = name;<br>    }<br>}</pre><p>The key characteristic of an Entity is:</p><blockquote><strong><em>An Entity is defined by its identity, not only by its attributes.</em></strong></blockquote><h4>2. Value Objects in C#</h4><p>A <strong>Value Object</strong> does not have its own identity.</p><p>It is defined by its values.</p><p>Common examples include:</p><ul><li>Email Address</li><li>Money</li><li>Address</li><li>Phone Number</li><li>Coordinates</li><li>Date Range</li></ul><p>Instead of using a primitive type:</p><pre>public string Email { get; set; }</pre><p>we can create a domain-specific type:</p><pre>public sealed class Email<br>{<br>    public string Value { get; }<br>    private Email(string value)<br>    {<br>        Value = value;<br>    }<br>    public static Email Create(string value)<br>    {<br>        if (string.IsNullOrWhiteSpace(value))<br>            throw new ArgumentException(<br>                &quot;Email is required.&quot;);<br>        if (!value.Contains(&quot;@&quot;))<br>            throw new ArgumentException(<br>                &quot;Invalid email address.&quot;);<br>        return new Email(value);<br>    }<br>    public override string ToString()<br>    {<br>        return Value;<br>    }<br>}</pre><p>Now the domain model becomes:</p><pre>public class Customer<br>{<br>    public Email Email { get; private set; }<br>}</pre><p>This is more expressive than:</p><pre>public string Email { get; set; }</pre><p>The Email type now owns its validation rules.</p><p>This is one of the benefits of using <strong>Value Objects in Domain-Driven Design</strong>.</p><h4>3. Aggregates in Domain-Driven Design</h4><p>An <strong>Aggregate</strong> is a group of related domain objects that are treated as a single consistency boundary.</p><p>Consider an Order:</p><pre>Order<br>│<br>├── OrderItem<br>├── OrderItem<br>└── OrderItem</pre><p>The Order contains multiple OrderItem objects.</p><p>The order may have rules such as:</p><ul><li>An order must contain at least one item.</li><li>Quantity must be greater than zero.</li><li>A cancelled order cannot be modified.</li><li>A paid order can be shipped.</li></ul><p>These rules should be controlled by the aggregate.</p><p>Example:</p><pre>public class Order<br>{<br>    private readonly List&lt;OrderItem&gt; _items = new();<br><br>    public Guid Id { get; private set; }<br>    public IReadOnlyCollection&lt;OrderItem&gt; Items =&gt;<br>        _items.AsReadOnly();<br>    public void AddItem(<br>        Guid productId,<br>        decimal price,<br>        int quantity)<br>    {<br>        if (quantity &lt;= 0)<br>        {<br>            throw new InvalidOperationException(<br>                &quot;Quantity must be greater than zero.&quot;);<br>        }<br>        _items.Add(<br>            new OrderItem(<br>                productId,<br>                price,<br>                quantity));<br>    }<br>}</pre><p>Notice that the collection is private:</p><pre>private readonly List&lt;OrderItem&gt; _items = new();</pre><p>External code cannot directly modify it.</p><p>Instead, it must use domain behavior:</p><pre>order.AddItem(productId, price, quantity);</pre><p>This allows the Order aggregate to protect its own business rules.</p><h4>4. What Is an Aggregate Root?</h4><p>The main entity of an aggregate is called the <strong>Aggregate Root</strong>.</p><p>In this example:</p><pre>Order<br>│<br>└── OrderItem</pre><p>Order is the Aggregate Root.</p><p>External code should interact with the aggregate through the root:</p><pre>order.AddItem(...);</pre><p>It should not directly manipulate the internal OrderItem objects.</p><p>The Aggregate Root protects the consistency of the entire aggregate.</p><h4>5. Business Logic Should Live in the Domain</h4><p>One of the most important DDD principles is:</p><blockquote><strong><em>Business rules should live inside the domain model.</em></strong></blockquote><p>Consider this approach:</p><pre>public class Order<br>{<br>    public string Status { get; set; }<br>}</pre><p>Then the application layer contains:</p><pre>if (order.Status == &quot;Paid&quot;)<br>{<br>    order.Status = &quot;Shipped&quot;;<br>}</pre><p>This is dangerous because any part of the application can modify the status incorrectly.</p><p>A better approach is to put the behavior inside the domain:</p><pre>public class Order<br>{<br>    public OrderStatus Status { get; private set; }<br>    public void Ship()<br>    {<br>        if (Status != OrderStatus.Paid)<br>        {<br>            throw new InvalidOperationException(<br>                &quot;Only paid orders can be shipped.&quot;);<br>        }<br>        Status = OrderStatus.Shipped;<br>    }<br>}</pre><p>Now the application simply calls:</p><pre>order.Ship();</pre><p>The domain decides whether the operation is valid.</p><p>This is the difference between a <strong>data-centric model</strong> and a <strong>behavior-rich domain model</strong>.</p><h4>6. Repositories in DDD</h4><p>A <strong>Repository</strong> provides access to domain aggregates.</p><p>For example:</p><pre>public interface IOrderRepository<br>{<br>    Task&lt;Order?&gt; GetByIdAsync(Guid id);<br>    Task AddAsync(Order order);<br>    Task UpdateAsync(Order order);<br>}</pre><p>The application layer depends on the abstraction:</p><pre>Application<br>     │<br>     ▼<br>IOrderRepository<br>     │<br>     ▼<br>Infrastructure<br>     │<br>     ▼<br>Entity Framework Core<br>     │<br>     ▼<br>Database</pre><p>The domain does not need to know whether the application uses:</p><ul><li>SQL Server</li><li>PostgreSQL</li><li>MySQL</li><li>MongoDB</li></ul><p>The implementation detail belongs to the Infrastructure layer.</p><p>Example:</p><pre>public class OrderRepository : IOrderRepository<br>{<br>    private readonly AppDbContext _context;<br>    public OrderRepository(AppDbContext context)<br>    {<br>        _context = context;<br>    }<br>    public async Task&lt;Order?&gt; GetByIdAsync(Guid id)<br>    {<br>        return await _context.Orders<br>            .FirstOrDefaultAsync(x =&gt; x.Id == id);<br>    }<br>    public async Task AddAsync(Order order)<br>    {<br>        await _context.Orders.AddAsync(order);<br>    }<br>}</pre><p>The important idea is:</p><blockquote><strong><em>The domain depends on abstractions, not infrastructure details.</em></strong></blockquote><h4>7. Domain Services</h4><p>Sometimes business logic does not naturally belong to a single Entity or Aggregate.</p><p>For example, imagine calculating shipping costs based on:</p><ul><li>Customer location</li><li>Product weight</li><li>Delivery method</li><li>Shipping zone</li></ul><p>This logic may involve multiple domain concepts.</p><p>A Domain Service can be used:</p><pre>public class ShippingCostService<br>{<br>    public decimal Calculate(<br>        Address address,<br>        decimal weight)<br>    {<br>        return weight * 10;<br>    }<br>}</pre><p>A Domain Service is useful when the logic:</p><ul><li>Is important to the business</li><li>Does not naturally belong to one Entity</li><li>Uses multiple domain objects</li></ul><h4>8. Domain Events</h4><p>A <strong>Domain Event</strong> represents something important that happened in the domain.</p><p>Examples include:</p><pre>OrderPlaced<br>PaymentCompleted<br>OrderShipped<br>CustomerRegistered</pre><p>A Domain Event can be represented in C#:</p><pre>public record OrderPlacedDomainEvent(<br>    Guid OrderId);</pre><p>When an order is placed, the system can publish the event:</p><pre>OrderPlaced<br>     │<br>     ├── Send Confirmation Email<br>     ├── Update Inventory<br>     ├── Notify Shipping System<br>     └── Publish Analytics Event</pre><p>This reduces direct coupling between different parts of the system.</p><p>Instead of the Order class directly calling:</p><pre>Email Service<br>Inventory Service<br>Shipping Service</pre><p>the Order publishes an event.</p><p>Other components can react to it.</p><h4>9. Bounded Contexts</h4><p>Large systems often contain multiple business areas.</p><p>For example:</p><pre>E-Commerce System<br>│<br>├── Sales<br>├── Inventory<br>├── Payments<br>└── Shipping</pre><p>Each area may have its own domain model.</p><p>For example, the concept of a Product may mean different things in different contexts.</p><h4>Sales Context</h4><pre>Product<br>- Name<br>- Price<br>- Description</pre><h4>Inventory Context</h4><pre>Product<br>- SKU<br>- Quantity<br>- Warehouse Location</pre><h4>Shipping Context</h4><pre>Product<br>- Weight<br>- Dimensions<br>- Shipping Category</pre><p>Trying to create one giant Product class for every business area can create unnecessary coupling.</p><p>A <strong>Bounded Context</strong> defines the boundary within which a particular domain model is valid.</p><p>This is one of the most important concepts in large-scale Domain-Driven Design.</p><h3>DDD and Clean Architecture in .NET</h3><p>Domain-Driven Design is often combined with Clean Architecture.</p><p>A typical project structure might look like this:</p><pre>MyApplication<br>│<br>├── Domain<br>│   ├── Entities<br>│   ├── ValueObjects<br>│   ├── Aggregates<br>│   ├── DomainEvents<br>│   ├── Services<br>│   └── Repositories<br>│<br>├── Application<br>│   ├── Commands<br>│   ├── Queries<br>│   ├── Handlers<br>│   └── DTOs<br>│<br>├── Infrastructure<br>│   ├── Persistence<br>│   ├── Repositories<br>│   └── ExternalServices<br>│<br>└── API<br>    ├── Controllers<br>    └── Middleware</pre><p>The dependency direction should generally point inward:</p><pre>API<br> │<br> ▼<br>Application<br> │<br> ▼<br>Domain</pre><p>Infrastructure implements interfaces defined by the inner layers.</p><p>The Domain layer should not depend directly on:</p><ul><li>Entity Framework Core</li><li>ASP.NET Core</li><li>SQL Server</li><li>External APIs</li></ul><p>This keeps the business logic independent from technical details.</p><h3>A Practical DDD Example in C#</h3><p>Let’s consider a simple order workflow.</p><p>The business requirement is:</p><blockquote><em>A customer can place an order only if the order contains at least one item.</em></blockquote><p>A weak implementation might look like this:</p><pre>if (order.Items.Count == 0)<br>{<br>    throw new Exception(<br>        &quot;Order must contain at least one item.&quot;);<br>}</pre><p>This rule could be forgotten in another part of the application.</p><p>A better domain model is:</p><pre>public class Order<br>{<br>    private readonly List&lt;OrderItem&gt; _items = new();<br>    public OrderStatus Status { get; private set; }<br>    public void Place()<br>    {<br>        if (!_items.Any())<br>        {<br>            throw new InvalidOperationException(<br>                &quot;An order must contain at least one item.&quot;);<br>        }<br>        Status = OrderStatus.Placed;<br>    }<br>}</pre><p>Now the business rule is always enforced when the order is placed.</p><p>The application layer does not need to understand the internal rule:</p><pre>order.Place();</pre><p>The domain model is responsible for protecting its own consistency.</p><h3>Common Domain-Driven Design Mistakes</h3><h4>1. Creating Anemic Domain Models</h4><p>An Anemic Domain Model contains only properties:</p><pre>public class Order<br>{<br>    public decimal Total { get; set; }<br>    public string Status { get; set; }<br>}</pre><p>All business logic is placed in service classes.</p><p>This often leads to large service classes and weak domain objects.</p><p>A richer domain model contains behavior:</p><pre>order.AddItem();<br>order.Pay();<br>order.Ship();<br>order.Cancel();</pre><p>The domain object knows how to protect its own rules.</p><h4>2. Using DDD for Every Application</h4><p>DDD is not required for every application.</p><p>A simple CRUD application may not need:</p><ul><li>Aggregates</li><li>Domain Events</li><li>Complex Value Objects</li><li>Multiple Bounded Contexts</li></ul><p>Use DDD when the domain is complex enough to justify it.</p><p>The goal is not to add complexity.</p><p>The goal is to manage complexity.</p><h4>3. Putting Business Logic in Controllers</h4><p>Avoid this:</p><pre>[HttpPost]<br>public IActionResult ShipOrder(Guid orderId)<br>{<br>    var order = repository.Get(orderId);<br>    if (order.Status == &quot;Paid&quot;)<br>    {<br>        order.Status = &quot;Shipped&quot;;<br>    }<br>    return Ok();<br>}</pre><p>The controller should not contain important business rules.</p><p>Instead:</p><pre>order.Ship();</pre><p>The domain should decide whether the order can be shipped.</p><h4>4. Treating DDD as Only a Folder Structure</h4><p>Creating these folders:</p><pre>Domain<br>Application<br>Infrastructure<br>API</pre><p>does not automatically mean you are using Domain-Driven Design.</p><p>DDD is primarily about:</p><ul><li>Understanding the business</li><li>Modeling the business domain</li><li>Protecting business rules</li><li>Using a shared language</li><li>Defining clear boundaries</li></ul><p>Architecture supports DDD, but folders alone do not create a domain model.</p><h3>When Should You Use Domain-Driven Design?</h3><p>DDD is a good choice when:</p><ul><li>Your business domain is complex.</li><li>The application contains many business rules.</li><li>The software is expected to evolve for many years.</li><li>Multiple teams work on different business areas.</li><li>Business correctness is important.</li><li>The application is the core of the business.</li></ul><p>DDD may be unnecessary for:</p><ul><li>Simple CRUD applications</li><li>Basic administration systems</li><li>Small internal tools</li><li>Applications with very little business logic</li></ul><p>The right question is not:</p><blockquote><em>“Should I always use DDD?”</em></blockquote><p>The better question is:</p><blockquote><em>“How much domain complexity does my application actually have?”</em></blockquote><h3>Final Thoughts</h3><p>Domain-Driven Design is more than a collection of software patterns.</p><p>It is a way of designing software around the business domain.</p><p>Instead of creating classes that simply represent database tables:</p><pre>order.Status = 2;<br>order.Total = 100;<br>order.IsActive = false;</pre><p>DDD encourages meaningful domain behavior:</p><pre>order.AddItem();<br>order.Pay();<br>order.Ship();<br>order.Cancel();</pre><p>The second approach communicates business intent much more clearly.</p><p>The ultimate goal of Domain-Driven Design is not to create more classes.</p><p>It is not to create more layers.</p><p>It is not to use complex architecture for its own sake.</p><p>The goal is to create software that reflects the business accurately and protects its business rules.</p><blockquote><strong><em>Good software speaks the language of the business.</em></strong></blockquote><p>And that is the real power of Domain-Driven Design in C# and .NET.</p><h3>Frequently Asked Questions</h3><h4>What is Domain-Driven Design in C#?</h4><p>Domain-Driven Design in C# is an approach to software development that models the application around business concepts, rules, and processes using concepts such as Entities, Value Objects, Aggregates, Domain Services, and Domain Events.</p><h4>Is DDD the same as Clean Architecture?</h4><p>No. DDD focuses on modeling the business domain, while Clean Architecture focuses on organizing dependencies and separating business logic from technical infrastructure. They are often used together.</p><h4>Is DDD suitable for small applications?</h4><p>Usually, simple applications do not need the full complexity of DDD. DDD is most valuable when the business domain contains significant complexity.</p><h4>What are the main building blocks of DDD?</h4><p>The main building blocks include:</p><ul><li>Entities</li><li>Value Objects</li><li>Aggregates</li><li>Aggregate Roots</li><li>Repositories</li><li>Domain Services</li><li>Domain Events</li><li>Bounded Contexts</li></ul><h4>Is Entity Framework Core compatible with DDD?</h4><p>Yes. Entity Framework Core is commonly used in DDD-based .NET applications. However, the domain model should ideally remain independent of infrastructure concerns where practical.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=146f548968b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT Authentication in C# (.NET]]></title>
            <link>https://medium.com/@kevalbalar1995/jwt-authentication-in-net-8-build-a-secure-web-api-step-by-step-1b3a51f4b377?source=rss-b426c1c72296------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b3a51f4b377</guid>
            <category><![CDATA[access-token]]></category>
            <category><![CDATA[jwt-bearer-authentication]]></category>
            <category><![CDATA[net-8-web-api]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <dc:creator><![CDATA[Keval Balar]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 05:10:16 GMT</pubDate>
            <atom:updated>2026-07-13T05:17:40.446Z</atom:updated>
            <content:encoded><![CDATA[<h3>JWT Authentication in C# (.NET 8): A Complete Guide with to Build a Secure Web API with Production-Ready Examples</h3><p>Learn how to implement JWT Authentication in .NET 8 Web API from scratch. Configure JWT Bearer Authentication, generate access tokens, secure API endpoints, and test everything with Swagger using practical C# examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1YuIVFScUHLR4OSbHJpIw.png" /></figure><h3>Why JWT?</h3><p>Almost every modern application needs authentication. Whether you’re building a React frontend, a mobile app, or a REST API, you need a secure way to identify users after they log in.</p><p>Since HTTP is stateless, the server doesn’t remember previous requests. Every request must include proof that the user has already been authenticated.</p><p>This is where <strong>JSON Web Token (JWT)</strong> comes in.</p><p>Instead of storing user sessions on the server, JWT allows the client to send a signed token with every request. The API validates the token and grants access if it’s valid.</p><p>The authentication flow looks like this:</p><pre>Client<br>   │<br>Login Request<br>   │<br>   ▼<br>ASP.NET Core API<br>   │<br>Validate User<br>   │<br>Generate JWT<br>   │<br>   ▼<br>Client Stores Token<br>   │<br>Authorization: Bearer &lt;token&gt;<br>   │<br>   ▼<br>Protected APIs</pre><p>Let’s build it.</p><h3>Create a .NET 8 Web API</h3><p>Create a new project.</p><pre>dotnet new webapi -n JwtAuthenticationDemo</pre><p>Move into the project.</p><pre>cd JwtAuthenticationDemo</pre><p>Install the JWT package.</p><pre>dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer</pre><h3>Configure JWT Settings</h3><p>Open <strong>appsettings.json</strong> and add the following configuration.</p><pre>{<br>  &quot;Jwt&quot;: {<br>    &quot;Key&quot;: &quot;ThisIsMySuperSecretKey123456789&quot;,<br>    &quot;Issuer&quot;: &quot;JwtAuthenticationDemo&quot;,<br>    &quot;Audience&quot;: &quot;JwtAuthenticationDemoUsers&quot;,<br>    &quot;ExpiryInMinutes&quot;: 30<br>  }<br>}</pre><p>These settings are used when generating and validating JWT tokens.</p><blockquote><strong><em>Note:</em></strong><em> Never store your secret key in source control. In production, use environment variables or a secure secret manager.</em></blockquote><h3>Configure JWT Authentication</h3><p>Open <strong>Program.cs</strong>.</p><p>Add the required namespaces.</p><pre>using Microsoft.AspNetCore.Authentication.JwtBearer;<br>using Microsoft.IdentityModel.Tokens;<br>using System.Text;</pre><p>Now register JWT Authentication.</p><pre>builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)<br>.AddJwtBearer(options =&gt;<br>{<br>    options.TokenValidationParameters = new TokenValidationParameters<br>    {<br>        ValidateIssuer = true,<br>        ValidateAudience = true,<br>        ValidateLifetime = true,<br>        ValidateIssuerSigningKey = true,<br>        ValidIssuer = builder.Configuration[&quot;Jwt:Issuer&quot;],<br>        ValidAudience = builder.Configuration[&quot;Jwt:Audience&quot;],<br>        IssuerSigningKey = new SymmetricSecurityKey(<br>            Encoding.UTF8.GetBytes(<br>                builder.Configuration[&quot;Jwt:Key&quot;]!))<br>    };<br>});<br>builder.Services.AddAuthorization();</pre><p>Finally, enable the middleware.</p><pre>app.UseAuthentication();<br>app.UseAuthorization();</pre><p>The order matters.</p><p>Authentication must execute before authorization. Otherwise, the framework won’t know who the current user is.</p><h3>Create a User Model</h3><p>For this tutorial, we’ll use a simple model instead of a database.</p><pre>public class User<br>{<br>    public int Id { get; set; }<br>    public string Username { get; set; } = string.Empty;<br>    public string Email { get; set; } = string.Empty;<br>    public string Role { get; set; } = string.Empty;<br>}</pre><p>Later, you can replace this with Entity Framework Core and SQL Server.</p><h3>Create the JWT Service</h3><p>Instead of generating tokens inside the controller, create a dedicated service.</p><p>First, define the interface.</p><pre>public interface IJwtService<br>{<br>    string GenerateToken(User user);<br>}</pre><p>Now create <strong>JwtService.cs</strong>.</p><pre>using Microsoft.IdentityModel.Tokens;<br>using System.IdentityModel.Tokens.Jwt;<br>using System.Security.Claims;<br>using System.Text;<br>public class JwtService : IJwtService<br>{<br>    private readonly IConfiguration _configuration;<br>    public JwtService(IConfiguration configuration)<br>    {<br>        _configuration = configuration;<br>    }<br>    public string GenerateToken(User user)<br>    {<br>        var claims = new[]<br>        {<br>            new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),<br>            new Claim(ClaimTypes.Name, user.Username),<br>            new Claim(ClaimTypes.Email, user.Email),<br>            new Claim(ClaimTypes.Role, user.Role)<br>        };<br>        var key = new SymmetricSecurityKey(<br>            Encoding.UTF8.GetBytes(_configuration[&quot;Jwt:Key&quot;]!));<br>        var credentials = new SigningCredentials(<br>            key,<br>            SecurityAlgorithms.HmacSha256);<br>        var token = new JwtSecurityToken(<br>            issuer: _configuration[&quot;Jwt:Issuer&quot;],<br>            audience: _configuration[&quot;Jwt:Audience&quot;],<br>            claims: claims,<br>            expires: DateTime.UtcNow.AddMinutes(<br>                Convert.ToDouble(_configuration[&quot;Jwt:ExpiryInMinutes&quot;])),<br>            signingCredentials: credentials);<br>        return new JwtSecurityTokenHandler().WriteToken(token);<br>    }<br>}</pre><p>Although this class looks long, the logic is straightforward:</p><ul><li>Create claims.</li><li>Create a signing key.</li><li>Generate the JWT.</li><li>Return it as a string.</li></ul><p>That’s all a JWT service really needs to do.</p><h3>Register the Service</h3><p>Register the service inside <strong>Program.cs</strong>.</p><pre>builder.Services.AddScoped&lt;IJwtService, JwtService&gt;();</pre><p>Now the service can be injected anywhere in the application.</p><h3>Project Structure</h3><p>At this stage, your project should look something like this.</p><pre>JwtAuthenticationDemo<br>│<br>├── Controllers<br>│<br>├── Models<br>│      User.cs<br>│<br>├── Services<br>│      IJwtService.cs<br>│      JwtService.cs<br>│<br>├── appsettings.json<br>│<br>└── Program.cs</pre><p>Keeping authentication logic separate from controllers makes the project easier to maintain as it grows.</p><h3>Create the Login Endpoint</h3><p>Now that our JwtService is ready, we need an endpoint where users can log in and receive a JWT.</p><p>For this example, we’ll use a hardcoded user. In a real application, you would validate the credentials against a database.</p><p>Create a LoginRequest model.</p><pre>public class LoginRequest<br>{<br>    public string Username { get; set; } = string.Empty;<br>    public string Password { get; set; } = string.Empty;<br>}</pre><p>Now create an AuthController.</p><pre>using Microsoft.AspNetCore.Mvc;<br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class AuthController : ControllerBase<br>{<br>    private readonly IJwtService _jwtService;<br>    public AuthController(IJwtService jwtService)<br>    {<br>        _jwtService = jwtService;<br>    }<br>    [HttpPost(&quot;login&quot;)]<br>    public IActionResult Login(LoginRequest request)<br>    {<br>        if (request.Username != &quot;admin&quot; ||<br>            request.Password != &quot;Password@123&quot;)<br>        {<br>            return Unauthorized(&quot;Invalid username or password.&quot;);<br>        }<br>        var user = new User<br>        {<br>            Id = 1,<br>            Username = &quot;admin&quot;,<br>            Email = &quot;admin@example.com&quot;,<br>            Role = &quot;Admin&quot;<br>        };<br>        var token = _jwtService.GenerateToken(user);<br>        return Ok(new<br>        {<br>            AccessToken = token<br>        });<br>    }<br>}</pre><p>The flow is simple:</p><ol><li>Validate the user’s credentials.</li><li>Create a user object.</li><li>Generate a JWT.</li><li>Return the token to the client.</li></ol><p>If the credentials are invalid, return <strong>401 Unauthorized</strong>.</p><h3>Secure an API Endpoint</h3><p>Generating a token is only half the job. The real benefit of JWT is protecting your APIs.</p><p>Create another controller.</p><pre>using Microsoft.AspNetCore.Authorization;<br>using Microsoft.AspNetCore.Mvc;<br>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class UserController : ControllerBase<br>{<br>    [Authorize]<br>    [HttpGet(&quot;profile&quot;)]<br>    public IActionResult Profile()<br>    {<br>        return Ok(new<br>        {<br>            Message = &quot;Welcome! This is a protected endpoint.&quot;<br>        });<br>    }<br>}</pre><p>The [Authorize] attribute tells ASP.NET Core that this endpoint requires a valid JWT.</p><p>If the request doesn’t include a valid token, the framework automatically returns:</p><pre>401 Unauthorized</pre><p>You don’t need to write any additional validation logic.</p><h3>Access User Claims</h3><p>One of the advantages of JWT is that the authenticated user’s information is available through the User object.</p><pre>[Authorize]<br>[HttpGet(&quot;me&quot;)]<br>public IActionResult Me()<br>{<br>    return Ok(new<br>    {<br>        Username = User.Identity?.Name,<br>        Email = User.FindFirst(ClaimTypes.Email)?.Value,<br>        Role = User.FindFirst(ClaimTypes.Role)?.Value<br>    });<br>}</pre><p>These values come directly from the claims stored inside the JWT.</p><p>Because ASP.NET Core validates the token before your controller executes, you can safely use these claims throughout your application.</p><h3>Test Using Swagger</h3><p>Run the application.</p><p>Swagger should open automatically.</p><h4>Step 1: Login</h4><p>Call the login endpoint.</p><pre>POST /api/auth/login</pre><p>Request body:</p><pre>{<br>    &quot;username&quot;: &quot;admin&quot;,<br>    &quot;password&quot;: &quot;Password@123&quot;<br>}</pre><p>You’ll receive a response like this.</p><pre>{<br>    &quot;accessToken&quot;: &quot;eyJhbGciOiJIUzI1NiIs...&quot;<br>}</pre><p>Copy the token.</p><h4>Step 2: Authorize</h4><p>Click the <strong>Authorize</strong> button in Swagger.</p><p>Enter the token using the following format.</p><pre>Bearer eyJhbGciOiJIUzI1NiIs...</pre><p>Click <strong>Authorize</strong>.</p><p>Swagger will automatically include the JWT in every secured request.</p><h4>Step 3: Call the Protected Endpoint</h4><p>Now execute:</p><pre>GET /api/user/profile</pre><p>Because the request contains a valid JWT, you’ll receive a successful response.</p><p>If you remove the token and try again, the API responds with <strong>401 Unauthorized</strong>.</p><p>That’s the authentication middleware doing exactly what it was designed to do.</p><h3>Common Mistakes</h3><p>When developers first implement JWT authentication, a few issues appear repeatedly.</p><h4>1. Forgetting UseAuthentication()</h4><p>Always add:</p><pre>app.UseAuthentication();<br>app.UseAuthorization();</pre><p>Authentication must run before authorization.</p><h4>2. Using a Weak Secret Key</h4><p>Avoid keys such as:</p><pre>secret123</pre><p>Use a long, randomly generated secret and store it securely using environment variables or a secret management service.</p><h4>3. Putting Sensitive Data Inside JWT</h4><p>Remember that JWT payloads are <strong>encoded</strong>, not encrypted.</p><p>Never include:</p><ul><li>Passwords</li><li>Credit card details</li><li>API keys</li><li>Personal identification numbers</li></ul><p>Only include claims that your application actually needs.</p><h4>4. Long-Lived Access Tokens</h4><p>A JWT valid for several days increases the risk if it’s compromised.</p><p>For most APIs, an expiration time of <strong>15–30 minutes</strong> is a sensible default.</p><p>If users need to stay signed in, use <strong>refresh tokens</strong>, which can be implemented as a separate authentication flow.</p><h3>Final Thoughts</h3><p>JWT authentication in ASP.NET Core is surprisingly straightforward once you understand the building blocks.</p><p>The framework already provides everything needed to validate tokens, populate user claims, and secure endpoints. Your main responsibility is to generate tokens correctly and configure authentication with sensible defaults.</p><p>In this article, we built a complete JWT authentication flow that:</p><ul><li>Configures JWT authentication in .NET 8</li><li>Generates signed access tokens</li><li>Implements a login endpoint</li><li>Protects APIs using [Authorize]</li><li>Reads user claims from the token</li><li>Tests authentication using Swagger</li></ul><p>This foundation is suitable for learning and small applications. For production systems, consider extending it with:</p><ul><li>Refresh Tokens</li><li>ASP.NET Core Identity</li><li>Role-Based and Policy-Based Authorization</li><li>Secure secret management</li><li>Token revocation</li><li>Multi-Factor Authentication (MFA)</li></ul><p>Authentication is a core part of almost every modern application. Understanding how JWT works — and why each piece exists — will help you build APIs that are both secure and maintainable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b3a51f4b377" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture + Vertical Slice Architecture in .NET]]></title>
            <link>https://medium.com/@kevalbalar1995/clean-architecture-vertical-slice-architecture-in-net-b315143dfccd?source=rss-b426c1c72296------2</link>
            <guid isPermaLink="false">https://medium.com/p/b315143dfccd</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Keval Balar]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 05:37:31 GMT</pubDate>
            <atom:updated>2026-07-08T05:37:31.170Z</atom:updated>
            <content:encoded><![CDATA[<h3>Clean Architecture + Vertical Slice Architecture in .NET 8: The Ultimate Guide for Building Scalable ASP.NET Core APIs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zTu_IS9Eg0jdmh8BT4PhnQ.png" /></figure><p>Most software projects don’t become difficult because of complex business logic — they become difficult because of poor organization.</p><p>If you’ve worked on an ASP.NET Core application for a few years, you’ve probably encountered a familiar pattern: controllers, services, repositories, validators, and DTOs spread across dozens of folders. Even a simple feature update requires navigating multiple layers, making development slower and increasing the risk of unintended changes.</p><p>Modern software teams are moving toward a different approach. Instead of organizing code by technical layers, they organize it around business features while still preserving clear architectural boundaries.</p><p>This is where <strong>Clean Architecture</strong> and <strong>Vertical Slice Architecture</strong> work exceptionally well together. Clean Architecture keeps your business logic independent of frameworks and infrastructure, while Vertical Slice Architecture groups everything related to a specific feature into a single, cohesive unit.</p><p>In this article, you’ll learn how these two architectural styles complement each other, why they’re becoming the preferred choice for modern .NET applications, and how to implement them using .NET 8, CQRS, MediatR, FluentValidation, and Minimal APIs to build scalable, maintainable, and production-ready APIs.</p><h3>Why This Matters</h3><p>As applications grow, architecture becomes more important than code.</p><p>Most software projects don’t fail because developers write poor C#.</p><p>They fail because the architecture makes change expensive.</p><p>Consider a common layered architecture:</p><pre>API<br> ↓<br>Application<br> ↓<br>Domain<br> ↓<br>Infrastructure<br> ↓<br>Database</pre><p>While this separation looks clean, feature implementations are often spread across multiple layers. A single business change may require edits in five or six different locations.</p><p>Common problems include:</p><ul><li>Large service classes with hundreds of methods</li><li>Controllers that depend on many services</li><li>Shared utility classes becoming dumping grounds</li><li>Merge conflicts due to multiple developers editing the same files</li><li>Difficult onboarding for new team members</li></ul><p>These issues slow development and increase maintenance costs.</p><p>Vertical Slice Architecture approaches the problem differently.</p><p>Instead of organizing code by technical responsibility, it organizes code by business capability.</p><p>For example:</p><pre>Customers<br>    Create<br>    Update<br>    Delete<br>    Search<br>Orders<br>    Create<br>    Cancel<br>    Ship<br>Products<br>    Create<br>    Update<br>    Search</pre><p>Each feature becomes an independent slice of the application.</p><p>Developers can work on one slice without needing to understand unrelated parts of the system.</p><p>This reduces coupling and improves productivity.</p><p>However, Vertical Slice alone does not replace Clean Architecture. Without clear boundaries, feature slices can become tightly coupled to infrastructure or persistence concerns.</p><p>That’s why combining both approaches creates a balanced architecture.</p><h3>Understanding the Fundamentals</h3><p>Before integrating the two patterns, it’s important to understand their individual responsibilities.</p><h4>What Is Clean Architecture?</h4><p>Proposed by Robert C. Martin (Uncle Bob), Clean Architecture is based on one fundamental principle:</p><blockquote><em>Business rules should not depend on frameworks, databases, or user interfaces.</em></blockquote><p>Instead, dependencies should always point inward toward the domain.</p><p>A typical Clean Architecture consists of four layers:</p><pre>Presentation<br>↓<br>Application<br>↓<br>Domain<br>↓<br>Infrastructure</pre><h4>Domain Layer</h4><p>The Domain layer is the heart of the application.</p><p>It contains:</p><ul><li>Entities</li><li>Value Objects</li><li>Domain Services</li><li>Business Rules</li><li>Domain Events</li></ul><p>The domain should have no knowledge of:</p><ul><li>Entity Framework</li><li>ASP.NET Core</li><li>SQL Server</li><li>HTTP</li><li>Logging frameworks</li></ul><p>This independence allows the business model to remain stable even as technologies change.</p><h4>Application Layer</h4><p>The Application layer coordinates business use cases.</p><p>It typically contains:</p><ul><li>Commands</li><li>Queries</li><li>Interfaces</li><li>DTOs</li><li>Validators</li><li>Use Cases</li></ul><p>Importantly, it depends on the Domain layer but not on Infrastructure.</p><h4>Infrastructure Layer</h4><p>Infrastructure contains implementation details such as:</p><ul><li>Entity Framework Core</li><li>File Storage</li><li>Email Services</li><li>External APIs</li><li>Redis</li><li>Azure Services</li><li>Authentication Providers</li></ul><p>Because these are implementation details, they can change without affecting the Domain.</p><h4>Presentation Layer</h4><p>This is the application’s entry point.</p><p>Examples include:</p><ul><li>ASP.NET Core Web API</li><li>Minimal APIs</li><li>MVC</li><li>Blazor</li><li>gRPC</li></ul><p>Its job is to receive requests and delegate work to the Application layer.</p><h3>What Is Vertical Slice Architecture?</h3><p>Vertical Slice Architecture organizes code around <strong>features instead of technical layers</strong>.</p><p>Instead of this:</p><pre>Controllers<br>Services<br>Repositories<br>Validators<br>DTOs<br>Entities</pre><p>You organize the project like this:</p><pre>Features<br>Customers<br>    CreateCustomer<br>        Command.cs<br>        Validator.cs<br>        Handler.cs<br>        Endpoint.cs<br>Products<br>    CreateProduct<br>    UpdateProduct<br>Orders<br>    CreateOrder<br>    CancelOrder</pre><p>Each folder contains everything required for a single use case.</p><p>This organization offers several advantages:</p><ul><li>High cohesion</li><li>Lower coupling</li><li>Easier navigation</li><li>Simpler maintenance</li><li>Better scalability</li><li>Reduced merge conflicts</li></ul><p>The focus shifts from “where should this class go?” to “which business feature does this belong to?”</p><h3>Why Vertical Slice Is Becoming the Preferred Approach</h3><p>Traditional layered architectures encourage sharing.</p><p>While reuse is valuable, excessive sharing often creates unnecessary dependencies.</p><p>Vertical Slice Architecture promotes feature isolation.</p><p>Each feature owns its logic, validation, mapping, and request handling.</p><p>As a result:</p><ul><li>Features evolve independently.</li><li>Teams work in parallel with fewer conflicts.</li><li>Changes remain localized.</li><li>Refactoring becomes safer.</li></ul><p>This is particularly beneficial in agile environments where business requirements change frequently.</p><h3>Clean Architecture + Vertical Slice: Better Together</h3><p>At first glance, these approaches may seem to compete with each other.</p><p>In reality, they solve different problems.</p><p><strong>Clean Architecture</strong> answers:</p><blockquote><em>How should dependencies be managed?</em></blockquote><p><strong>Vertical Slice Architecture</strong> answers:</p><blockquote><em>How should features be organized?</em></blockquote><p>One focuses on <strong>dependency direction</strong>.</p><p>The other focuses on <strong>code organization</strong>.</p><p>When combined, you get both clear architectural boundaries and feature-centric development.</p><p>A practical project structure might look like this:</p><pre>src<br>│<br>├── Api<br>│<br>├── Application<br>│   └── Features<br>│       ├── Customers<br>│       │   ├── CreateCustomer<br>│       │   ├── UpdateCustomer<br>│       │   └── GetCustomer<br>│       │<br>│       └── Products<br>│<br>├── Domain<br>│<br>└── Infrastructure</pre><p>Notice that the Application layer no longer contains generic folders like Commands, Queries, or Services. Instead, every use case is grouped by feature, making the solution easier to navigate and maintain.</p><p>This structure also aligns naturally with <strong>CQRS</strong>, where each command or query becomes an independent slice with its own request model, handler, validator, and tests.</p><h3>Architecture Overview</h3><p>The following workflow illustrates how a request flows through both architectural styles without violating dependency rules.</p><pre>Client<br>   │<br>   ▼<br>Minimal API / Controller<br>   │<br>   ▼<br>MediatR<br>   │<br>   ▼<br>Feature Slice<br>(CreateCustomer)<br>   │<br>   ├── Validator<br>   ├── Handler<br>   ├── Mapping<br>   │<br>   ▼<br>Domain<br>   │<br>   ▼<br>Repository Interface<br>   │<br>   ▼<br>Infrastructure (EF Core)<br>   │<br>   ▼<br>SQL Server</pre><p>Each layer has a single responsibility:</p><ul><li>The API receives the request.</li><li>MediatR dispatches it to the correct feature.</li><li>The feature validates and executes the business use case.</li><li>The Domain enforces business rules.</li><li>Infrastructure persists data.</li><li>The response flows back through the same path.</li></ul><p>This design keeps the Domain independent, the Application focused on use cases, and the Infrastructure replaceable without affecting business logic.</p><h3>Project Structure for a Modern .NET 8 Solution</h3><p>A clean starting point for a production-ready application is:</p><pre>src<br>│<br>├── Api<br>│   ├── Endpoints<br>│   ├── Middleware<br>│   └── Program.cs<br>│<br>├── Application<br>│   └── Features<br>│       ├── Customers<br>│       │   ├── CreateCustomer<br>│       │   ├── UpdateCustomer<br>│       │   ├── DeleteCustomer<br>│       │   └── GetCustomer<br>│       │<br>│       └── Orders<br>│<br>├── Domain<br>│   ├── Entities<br>│   ├── ValueObjects<br>│   ├── Events<br>│   └── Interfaces<br>│<br>├── Infrastructure<br>│   ├── Persistence<br>│   ├── Services<br>│   └── Identity<br>│<br>└── Tests</pre><p>This structure scales naturally as new features are added. Rather than expanding horizontal layers with hundreds of unrelated files, each new business capability becomes a self-contained slice.</p><h3>Building a Production-Ready Vertical Slice in .NET 8</h3><p>Now that we’ve covered the theory behind combining <strong>Clean Architecture</strong> and <strong>Vertical Slice Architecture</strong>, it’s time to put those concepts into practice.</p><p>We’ll build a simple <strong>Create Customer</strong> feature using:</p><ul><li>.NET 8</li><li>ASP.NET Core Minimal APIs</li><li>CQRS</li><li>MediatR</li><li>FluentValidation</li><li>Entity Framework Core</li><li>Clean Architecture</li><li>Vertical Slice Architecture</li></ul><p>The goal isn’t to build an entire application — it’s to demonstrate how a single feature becomes completely self-contained.</p><h4>Step 1: Feature Folder Structure</h4><p>Instead of scattering files across multiple folders, place everything related to the feature in one location.</p><pre>Application<br>└── Features<br>    └── Customers<br>        └── CreateCustomer<br>            ├── CreateCustomerCommand.cs<br>            ├── CreateCustomerHandler.cs<br>            ├── CreateCustomerValidator.cs<br>            ├── CreateCustomerResponse.cs<br>            └── CreateCustomerEndpoint.cs</pre><p>Everything required to create a customer lives in one folder.</p><p>If another developer needs to modify this feature, they know exactly where to look.</p><h4>Step 2: Define the Command</h4><p>A <strong>Command</strong> represents an operation that changes the application’s state.</p><pre>using MediatR;<br>namespace Application.Features.Customers.CreateCustomer;<br>public sealed record CreateCustomerCommand(<br>    string FirstName,<br>    string LastName,<br>    string Email<br>) : IRequest&lt;CreateCustomerResponse&gt;;</pre><h4>Step 3: Validate the Request</h4><p>Validation should occur before business logic executes.</p><p>FluentValidation makes this clean and expressive.</p><pre>using FluentValidation;<br>namespace Application.Features.Customers.CreateCustomer;<br>public sealed class CreateCustomerValidator<br>    : AbstractValidator&lt;CreateCustomerCommand&gt;<br>{<br>    public CreateCustomerValidator()<br>    {<br>        RuleFor(x =&gt; x.FirstName)<br>            .NotEmpty()<br>            .MaximumLength(100);<br>        RuleFor(x =&gt; x.LastName)<br>            .NotEmpty()<br>            .MaximumLength(100);<br>        RuleFor(x =&gt; x.Email)<br>            .NotEmpty()<br>            .EmailAddress();<br>    }<br>}</pre><h4>Step 4: Define the Response</h4><p>Avoid returning entities directly.</p><p>Instead, return a response model tailored to the API consumer.</p><pre>namespace Application.Features.Customers.CreateCustomer;<br>public sealed record CreateCustomerResponse(<br>    Guid Id,<br>    string FullName,<br>    string Email<br>);</pre><p>Returning DTOs prevents leaking internal implementation details and gives you flexibility to evolve your API independently of your domain model.</p><h4>Step 5: Create the Domain Entity</h4><p>The Domain layer contains business rules and entities.</p><pre>namespace Domain.Entities;<br>public class Customer<br>{<br>    public Guid Id { get; private set; }<br>    public string FirstName { get; private set; }<br>    public string LastName { get; private set; }<br>    public string Email { get; private set; }<br>    private Customer() { }<br>    public Customer(string firstName,<br>                    string lastName,<br>                    string email)<br>    {<br>        Id = Guid.NewGuid();<br>        FirstName = firstName;<br>        LastName = lastName;<br>        Email = email;<br>    }<br>    public string FullName =&gt;<br>        $&quot;{FirstName} {LastName}&quot;;<br>}</pre><p>Notice that the entity has:</p><ul><li>No Entity Framework attributes</li><li>No controller references</li><li>No HTTP knowledge</li><li>No dependency on MediatR</li></ul><p>It represents the business, nothing else.</p><h4>Step 6: Repository Contract</h4><p>The Application layer depends on abstractions.</p><pre>namespace Application.Common.Interfaces;<br>public interface ICustomerRepository<br>{<br>    Task&lt;bool&gt; EmailExistsAsync(<br>        string email,<br>        CancellationToken cancellationToken);<br>    Task AddAsync(<br>        Customer customer,<br>        CancellationToken cancellationToken);<br>    Task SaveChangesAsync(<br>        CancellationToken cancellationToken);<br>}</pre><p>The implementation lives in the Infrastructure layer.</p><p>This keeps the Application independent of Entity Framework.</p><h4>Step 7: Implement the Handler</h4><p>The handler is the heart of the feature.</p><p>It coordinates the use case.</p><pre>using MediatR;<br>namespace Application.Features.Customers.CreateCustomer;<br>public sealed class CreateCustomerHandler<br>    : IRequestHandler&lt;<br>        CreateCustomerCommand,<br>        CreateCustomerResponse&gt;<br>{<br>    private readonly ICustomerRepository _repository;<br>    public CreateCustomerHandler(<br>        ICustomerRepository repository)<br>    {<br>        _repository = repository;<br>    }<br>    public async Task&lt;CreateCustomerResponse&gt; Handle(<br>        CreateCustomerCommand request,<br>        CancellationToken cancellationToken)<br>    {<br>        if (await _repository.EmailExistsAsync(<br>            request.Email,<br>            cancellationToken))<br>        {<br>            throw new InvalidOperationException(<br>                &quot;Email already exists.&quot;);<br>        }<br>        var customer = new Customer(<br>            request.FirstName,<br>            request.LastName,<br>            request.Email);<br>        await _repository.AddAsync(<br>            customer,<br>            cancellationToken);<br>        await _repository.SaveChangesAsync(<br>            cancellationToken);<br>        return new CreateCustomerResponse(<br>            customer.Id,<br>            customer.FullName,<br>            customer.Email);<br>    }<br>}</pre><h4>Step 8: Infrastructure Implementation</h4><p>Now let’s implement the repository using Entity Framework Core.</p><pre>public sealed class CustomerRepository<br>    : ICustomerRepository<br>{<br>    private readonly AppDbContext _context;<br>    public CustomerRepository(<br>        AppDbContext context)<br>    {<br>        _context = context;<br>    }<br>    public async Task&lt;bool&gt; EmailExistsAsync(<br>        string email,<br>        CancellationToken cancellationToken)<br>    {<br>        return await _context.Customers<br>            .AnyAsync(x =&gt; x.Email == email,<br>                cancellationToken);<br>    }<br>    public async Task AddAsync(<br>        Customer customer,<br>        CancellationToken cancellationToken)<br>    {<br>        await _context.Customers<br>            .AddAsync(customer, cancellationToken);<br>    }<br>    public async Task SaveChangesAsync(<br>        CancellationToken cancellationToken)<br>    {<br>        await _context.SaveChangesAsync(<br>            cancellationToken);<br>    }<br>}</pre><p>This implementation can be replaced without affecting the Application layer.</p><p>Today it’s SQL Server.</p><p>Tomorrow it could be PostgreSQL, Cosmos DB, or another data source.</p><h4>Step 9: Expose the Endpoint</h4><p>Minimal APIs reduce boilerplate while keeping endpoints focused.</p><pre>public static class CustomerEndpoints<br>{<br>    public static IEndpointRouteBuilder<br>        MapCustomerEndpoints(<br>        this IEndpointRouteBuilder app)<br>    {<br>        app.MapPost(&quot;/customers&quot;,<br>            async (<br>                CreateCustomerCommand command,<br>                ISender sender) =&gt;<br>            {<br>                var result =<br>                    await sender.Send(command);<br>                    return Results.Created(<br>                    $&quot;/customers/{result.Id}&quot;,<br>                    result);<br>            });<br>        return app;<br>    }<br>}</pre><h4>Step 10: Register Dependencies</h4><p>Finally, configure dependency injection.</p><pre>builder.Services.AddMediatR(cfg =&gt;<br>{<br>    cfg.RegisterServicesFromAssembly(<br>        typeof(CreateCustomerHandler).Assembly);<br>});<br>builder.Services.AddValidatorsFromAssembly(<br>    typeof(CreateCustomerValidator).Assembly);<br>builder.Services.AddScoped&lt;<br>    ICustomerRepository,<br>    CustomerRepository&gt;();</pre><p>Dependency injection ensures that the handler receives the correct implementation without depending on concrete classes.</p><h3>End-to-End Request Flow</h3><p>Let’s trace a request through the system.</p><pre>POST /customers<br>        │<br>        ▼<br>Minimal API Endpoint<br>        │<br>        ▼<br>CreateCustomerCommand<br>        │<br>        ▼<br>MediatR<br>        │<br>        ▼<br>CreateCustomerHandler<br>        │<br>        ├── Validate request<br>        ├── Check duplicate email<br>        ├── Create Customer<br>        └── Save changes<br>        │<br>        ▼<br>Repository<br>        │<br>        ▼<br>Entity Framework Core<br>        │<br>        ▼<br>SQL Server<br>        │<br>        ▼<br>CreateCustomerResponse<br>        │<br>        ▼<br>HTTP 201 Created</pre><p>This flow illustrates the separation of responsibilities:</p><ul><li><strong>Presentation Layer</strong> receives the HTTP request.</li><li><strong>Application Layer</strong> executes the use case.</li><li><strong>Domain Layer</strong> models the business.</li><li><strong>Infrastructure Layer</strong> handles persistence.</li></ul><p>Each layer has a single purpose, and dependencies always point inward.</p><h3>Why This Combination Works So Well</h3><p>By integrating Clean Architecture with Vertical Slice Architecture, each feature becomes:</p><ul><li><strong>Self-contained</strong>: All related files are in one place.</li><li><strong>Testable</strong>: Handlers can be unit tested without HTTP or EF Core.</li><li><strong>Maintainable</strong>: Changes remain localized to a single slice.</li><li><strong>Scalable</strong>: New features are added without expanding generic folders.</li><li><strong>Independent</strong>: Infrastructure can evolve without impacting business logic.</li></ul><p>This approach also aligns naturally with CQRS. Every command or query becomes its own vertical slice, encapsulating validation, request handling, and response generation. The result is a codebase that remains organized even as the application grows from a handful of endpoints to hundreds of business capabilities.</p><p>In the next part, we’ll look at the practical considerations that separate a good architecture from a production-ready one, including best practices, common pitfalls, performance optimization, security, future trends, and the final checklist for building maintainable ASP.NET Core applications.</p><h3>Best Practices for Combining Clean Architecture and Vertical Slice</h3><p>Architecture is not just about organizing files — it’s about creating a codebase that remains maintainable as the application grows. The following practices have proven effective in production environments.</p><h4>1. Keep Features Self-Contained</h4><p>Each feature should own everything it needs:</p><ul><li>Command or Query</li><li>Handler</li><li>Validator</li><li>DTOs</li><li>Mapping</li><li>Endpoint</li><li>Unit Tests</li></ul><p>Avoid sharing code unless it represents a genuine cross-cutting concern.</p><p>Good:</p><pre>Features<br> ├── Customers<br> │    └── CreateCustomer<br> └── Orders<br>      └── CreateOrder</pre><p>Avoid:</p><pre>Common<br> ├── Validators<br> ├── DTOs<br> ├── Helpers<br> └── Mappers</pre><p>Over time, “Common” folders often become dumping grounds for unrelated code.</p><h4>2. Keep Handlers Focused</h4><p>A handler should represent <strong>one business use case</strong>.</p><p>Good examples include:</p><ul><li>Create Customer</li><li>Update Product</li><li>Cancel Order</li><li>Approve Invoice</li></ul><p>Avoid handlers that try to perform multiple responsibilities.</p><p>Instead of:</p><pre>CustomerService<br>    Create()<br>    Update()<br>    Delete()<br>    Get()<br>    Search()<br>    Export()<br>    Import()</pre><p>Prefer:</p><pre>Features<br>    CreateCustomer<br>    UpdateCustomer<br>    DeleteCustomer<br>    GetCustomer<br>    SearchCustomers</pre><p>Smaller handlers are easier to understand, test, and maintain.</p><h4>3. Protect Your Domain</h4><p>The Domain layer should remain independent of frameworks.</p><p>Your entities should not reference:</p><ul><li>ASP.NET Core</li><li>Entity Framework Core</li><li>MediatR</li><li>AutoMapper</li><li>JSON serialization libraries</li></ul><p>The Domain should express business rules — not infrastructure concerns.</p><h4>4. Use Dependency Injection Correctly</h4><p>Depend on abstractions rather than implementations.</p><p>Instead of:</p><pre>var repository = new CustomerRepository();</pre><p>Use constructor injection:</p><pre>public CreateCustomerHandler(<br>    ICustomerRepository repository)<br>{<br>    _repository = repository;<br>}</pre><p>This makes your application easier to test and allows infrastructure implementations to change without affecting business logic.</p><h4>5. Use Pipelines for Cross-Cutting Concerns</h4><p>Avoid repeating validation, logging, or performance monitoring in every handler.</p><p>With MediatR pipeline behaviors, you can centralize concerns such as:</p><ul><li>Validation</li><li>Logging</li><li>Performance timing</li><li>Exception handling</li><li>Authorization</li><li>Caching</li></ul><p>This keeps handlers focused solely on business logic.</p><h3>Common Mistakes</h3><p>Even well-designed architectures can become difficult to maintain if common pitfalls are ignored.</p><h4>Mistake 1: Creating Generic Services</h4><p>Many developers introduce a CustomerService that eventually contains dozens of unrelated methods.</p><p>Example:</p><pre>CustomerService<br>    Create<br>    Update<br>    Delete<br>    Search<br>    Export<br>    SendEmail<br>    Import</pre><p>This violates the Single Responsibility Principle.</p><p>Vertical Slice Architecture eliminates this by giving each operation its own handler.</p><h4>Mistake 2: Sharing Too Much Code</h4><p>Excessive reuse often increases coupling.</p><p>Before moving code into a shared library, ask:</p><blockquote><em>Will this genuinely be reused across multiple features?</em></blockquote><p>If not, duplication may be the better choice.</p><p>A small amount of duplication is often preferable to unnecessary abstraction.</p><h4>Mistake 3: Treating the Domain as a Database Model</h4><p>Your domain entities should represent business concepts — not database tables.</p><p>Avoid filling entities with persistence-specific attributes or API concerns.</p><p>Instead, keep them focused on business behavior and invariants.</p><h4>Mistake 4: Returning Entities from APIs</h4><p>Returning EF Core entities directly exposes internal implementation details.</p><p>Prefer dedicated response models:</p><pre>public record CustomerResponse(<br>    Guid Id,<br>    string Name,<br>    string Email);</pre><p>This keeps your API contract stable even if the domain model changes.</p><h4>Mistake 5: Ignoring Feature Boundaries</h4><p>If multiple features constantly access each other’s internal classes, the benefits of Vertical Slice Architecture begin to disappear.</p><p>Features should communicate through well-defined contracts rather than internal implementation details.</p><h3>Performance Considerations</h3><p>A clean architecture should not come at the expense of performance.</p><p>Fortunately, the architectural patterns discussed here introduce very little overhead.</p><h4>Optimize Database Queries</h4><p>Avoid retrieving more data than necessary.</p><p>Instead of:</p><pre>var customers = await context.Customers.ToListAsync();</pre><p>Project directly into DTOs:</p><pre>var customers = await context.Customers<br>    .Select(c =&gt; new CustomerResponse(<br>        c.Id,<br>        c.FullName,<br>        c.Email))<br>    .ToListAsync();</pre><p>This reduces memory usage and network traffic.</p><h4>Use Asynchronous Operations</h4><p>Leverage asynchronous APIs throughout the request pipeline.</p><p>Examples include:</p><ul><li>ToListAsync()</li><li>FirstOrDefaultAsync()</li><li>SaveChangesAsync()</li></ul><p>Asynchronous operations improve scalability by preventing thread blocking.</p><h4>Minimize Database Round Trips</h4><p>Batch operations where appropriate and avoid unnecessary queries.</p><p>For example, avoid loading an entity only to check if it exists when a simple AnyAsync() will suffice.</p><h4>Cache Read-Heavy Queries</h4><p>Frequently requested data such as:</p><ul><li>Product catalogs</li><li>Country lists</li><li>Application settings</li></ul><p>can be cached using technologies like Redis or the in-memory cache.</p><p>This reduces database load and improves response times.</p><h3>Security Considerations</h3><p>Architecture alone does not make an application secure.</p><p>Security should be integrated into every layer.</p><h4>Validate All Input</h4><p>Never trust client input.</p><p>Use FluentValidation to validate requests before they reach business logic.</p><h4>Protect Sensitive Data</h4><p>Never expose:</p><ul><li>Password hashes</li><li>Internal IDs when unnecessary</li><li>Connection strings</li><li>Security tokens</li></ul><p>Return only the data required by the client.</p><h3>Future Trends</h3><p>The .NET ecosystem continues to evolve, and several trends align naturally with this architectural approach.</p><h4>Minimal APIs Continue to Mature</h4><p>Minimal APIs reduce boilerplate and integrate seamlessly with Vertical Slice Architecture, making them an excellent choice for modern ASP.NET Core applications.</p><h4>Native AOT</h4><p>.NET’s Native AOT compilation improves startup time and reduces memory usage, making it particularly attractive for cloud-native and serverless applications.</p><p>Keeping dependencies well-structured makes applications more compatible with AOT scenarios.</p><h4>Cloud-Native Development</h4><p>Modern applications increasingly rely on:</p><ul><li>Containers</li><li>Kubernetes</li><li>Event-driven architecture</li><li>Microservices</li><li>Distributed messaging</li></ul><p>A feature-based architecture simplifies the transition to these environments.</p><h4>AI-Assisted Development</h4><p>AI tools are becoming part of everyday software development.</p><p>A well-organized codebase enables AI assistants to generate more accurate code suggestions, understand feature boundaries, and reduce implementation errors.</p><h3>Key Takeaways</h3><p>If you remember only a few things from this article, let them be these:</p><ul><li>Clean Architecture manages <strong>dependency direction</strong>.</li><li>Vertical Slice Architecture manages <strong>feature organization</strong>.</li><li>The two patterns complement rather than replace each other.</li><li>Each feature should be self-contained.</li><li>Handlers should represent a single business use case.</li><li>Keep the Domain independent of frameworks.</li><li>Use CQRS and MediatR to simplify request handling.</li><li>Minimize unnecessary abstractions.</li><li>Optimize database access before worrying about architectural overhead.</li><li>Build features that are easy to understand, test, and evolve.</li></ul><h3>Conclusion</h3><p>Clean Architecture and Vertical Slice Architecture aren’t competing approaches — they solve different problems and complement each other effectively.</p><p>Clean Architecture ensures your business logic remains independent of frameworks, databases, and external services. Vertical Slice Architecture improves developer productivity by organizing code around business capabilities instead of technical layers. Together, they create applications that are easier to understand, test, and maintain as they grow.</p><p>Whether you’re starting a new .NET 8 project or modernizing an existing one, adopting this combination can significantly reduce complexity and make feature development more predictable. By keeping each feature self-contained and enforcing clear dependency boundaries, your codebase remains flexible as requirements evolve.</p><p>Architecture is an investment in your application’s future. Choosing patterns that prioritize maintainability today will save countless hours of debugging, refactoring, and onboarding tomorrow.</p><p>If you’re building modern ASP.NET Core applications, integrating Clean Architecture with Vertical Slice Architecture is a practical approach that scales with both your application and your team.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b315143dfccd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building AI Applications with C# and .NET 8: The Complete Developer Guide]]></title>
            <link>https://medium.com/@kevalbalar1995/ai-with-net-and-c-the-complete-guide-to-building-intelligent-applications-in-net-8-55542cef130e?source=rss-b426c1c72296------2</link>
            <guid isPermaLink="false">https://medium.com/p/55542cef130e</guid>
            <category><![CDATA[ai-with-dotnet]]></category>
            <dc:creator><![CDATA[Keval Balar]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 16:45:09 GMT</pubDate>
            <atom:updated>2026-07-09T10:10:13.635Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-j91LGCiqP5uzbhwo1WjA.png" /></figure><p>Artificial Intelligence is no longer reserved for data scientists and research laboratories.</p><p>Today, every software developer has an opportunity to build intelligent applications that can understand language, generate content, analyze documents, automate workflows, and even reason through complex problems.</p><p>If you’re a C# developer, you might wonder:</p><blockquote><strong><em>“Do I need to learn Python before I can build AI applications?”</em></strong></blockquote><p>The answer is <strong>no</strong>.</p><p>Microsoft has invested heavily in making .NET one of the best platforms for AI development. With libraries like <strong>Microsoft.Extensions.AI</strong>, <strong>Semantic Kernel</strong>, <strong>ML.NET</strong>, and seamless integration with OpenAI and Azure OpenAI, C# developers can create sophisticated AI-powered applications without leaving the .NET ecosystem.</p><p>Imagine this scenario.</p><p>A customer submits a support request. Instead of routing it manually, your application instantly understands the issue, summarizes the conversation, identifies the customer’s sentiment, retrieves relevant documentation, and drafts a personalized response — all before a human agent opens the ticket.</p><p>This isn’t science fiction. It’s the kind of intelligent workflow that modern .NET applications can deliver today.</p><p>In this guide, we’ll explore how AI and .NET work together, the key technologies involved, and the architectural patterns that help you build secure, scalable, and maintainable AI solutions.</p><p>Whether you’re building enterprise software, APIs, SaaS products, internal tools, or personal projects, understanding AI in the .NET ecosystem is quickly becoming a valuable skill.</p><p>Let’s dive in.</p><h3>Why This Matters</h3><p>Artificial Intelligence is changing software development in much the same way cloud computing transformed application deployment a decade ago.</p><p>Instead of writing explicit rules for every possible scenario, developers can now build applications that interpret natural language, summarize large volumes of text, generate code, answer questions, classify documents, and automate complex business processes.</p><p>For organizations, this means:</p><ul><li>Faster customer support</li><li>Improved productivity</li><li>Smarter search experiences</li><li>Reduced operational costs</li><li>Better decision-making through AI-assisted insights</li></ul><p>For developers, it opens the door to a new generation of software.</p><p>Rather than replacing traditional programming, AI complements it. Your business logic, APIs, databases, and architecture remain essential. AI becomes another service in your application — one that enhances user experiences and automates tasks that were once difficult or impossible.</p><h3>Why .NET Is an Excellent Choice</h3><p>Microsoft has positioned .NET as a first-class platform for AI development.</p><p>Some key advantages include:</p><ul><li>Excellent performance</li><li>Cross-platform support</li><li>Mature tooling with Visual Studio and VS Code</li><li>Rich dependency injection ecosystem</li><li>Built-in cloud integration</li><li>Enterprise-grade security</li><li>Extensive Azure AI support</li><li>Rapidly growing open-source AI ecosystem</li></ul><p>For teams already invested in ASP.NET Core, integrating AI often requires adding a few well-designed services rather than rebuilding applications from scratch.</p><h3>Understanding the Fundamentals</h3><p>Before writing any code, it’s important to understand the core concepts that power modern AI applications.</p><p>Many developers use terms like <em>Artificial Intelligence</em>, <em>Machine Learning</em>, <em>Large Language Models</em>, and <em>Generative AI</em> interchangeably, but they represent different layers of the technology stack.</p><p>Let’s clarify the terminology.</p><h4>Artificial Intelligence (AI)</h4><p>Artificial Intelligence is the broad field of creating systems capable of performing tasks that typically require human intelligence.</p><p>Examples include:</p><ul><li>Understanding language</li><li>Recognizing images</li><li>Making recommendations</li><li>Translating text</li><li>Planning tasks</li><li>Answering questions</li></ul><p>Think of AI as the umbrella term that encompasses many specialized technologies.</p><h4>Machine Learning (ML)</h4><p>Machine Learning is a subset of AI.</p><p>Instead of following hard-coded rules, machine learning models learn patterns from data.</p><p>For example, rather than manually defining every characteristic of spam email, a machine learning model analyzes thousands of examples to determine what spam typically looks like.</p><p>.NET developers can build traditional ML solutions using <strong>ML.NET</strong>, especially for scenarios such as:</p><ul><li>Fraud detection</li><li>Recommendation systems</li><li>Price prediction</li><li>Sales forecasting</li><li>Classification problems</li></ul><h4>Large Language Models (LLMs)</h4><p>Large Language Models are deep learning models trained on enormous datasets containing books, websites, articles, documentation, and code.</p><p>Examples include:</p><ul><li>GPT models</li><li>Llama</li><li>Claude</li><li>Gemini</li><li>Mistral</li></ul><p>These models can:</p><ul><li>Answer questions</li><li>Generate code</li><li>Summarize documents</li><li>Translate languages</li><li>Extract structured data</li><li>Create content</li><li>Assist developers</li></ul><p>Rather than relying on predefined rules, LLMs predict the most appropriate response based on the context they receive.</p><h4>Generative AI</h4><p>Generative AI refers to AI systems capable of creating new content.</p><p>This includes:</p><ul><li>Text</li><li>Images</li><li>Code</li><li>Audio</li><li>Video</li><li>Structured data</li></ul><p>When you ask an AI assistant to write an email, generate SQL, summarize a PDF, or explain an exception in your C# application, you’re using Generative AI.</p><h3>AI Models vs AI Applications</h3><p>A common misconception is that developers need to train AI models themselves.</p><p>In reality, most enterprise applications consume pre-trained models through APIs or managed AI services.</p><p>Think of it this way:</p><ul><li><strong>The AI model</strong> is the engine.</li><li><strong>Your .NET application</strong> is the vehicle.</li><li><strong>Your business logic</strong> determines where the vehicle goes and how it delivers value.</li></ul><p>This distinction is important because your focus as a .NET developer is typically on integrating AI responsibly into your application’s architecture rather than building foundational models from scratch.</p><h3>The Role of .NET in Modern AI</h3><p>Modern .NET serves as the orchestration layer for AI-powered systems.</p><p>A typical application might:</p><ol><li>Receive a user request.</li><li>Validate the input.</li><li>Query a database.</li><li>Retrieve relevant business data.</li><li>Send contextual information to an AI model.</li><li>Process the AI response.</li><li>Apply business rules.</li><li>Return a secure, user-friendly result.</li></ol><p>In this architecture, AI becomes one component within a broader, well-structured software system — not a replacement for good engineering practices.</p><p>As we’ll see in the next section, understanding how these components interact is the key to building reliable, maintainable, and production-ready AI applications with C# and .NET.</p><h3>How It Works</h3><p>Now that we’ve covered the fundamentals, it’s time to answer the question every developer eventually asks:</p><blockquote><strong><em>“What actually happens when my .NET application talks to an AI model?”</em></strong></blockquote><p>Although AI may seem like magic, the overall workflow is surprisingly straightforward. Your application doesn’t “become intelligent”; instead, it orchestrates interactions with a specialized AI service while applying your own business rules.</p><p>At a high level, the request lifecycle looks like this:</p><ol><li>A user submits a request.</li><li>Your ASP.NET Core API validates the input.</li><li>The application retrieves any relevant business data.</li><li>A prompt is constructed with the necessary context.</li><li>The AI model processes the prompt.</li><li>The model returns a response.</li><li>Your application validates, filters, and formats the output.</li><li>The final result is sent back to the user.</li></ol><p>The AI is just one component in the request pipeline. Your application remains responsible for authentication, authorization, validation, logging, caching, rate limiting, persistence, and business logic.</p><h3>Architecture / Workflow</h3><p>A production-ready AI application should follow the same architectural principles as any modern enterprise system. Clean Architecture is an excellent choice because it keeps AI providers isolated behind abstractions, making it easy to swap implementations or add new capabilities later.</p><p>A simplified folder structure might look like this:</p><pre>src/<br>│<br>├── Api/<br>│   ├── Controllers/<br>│   ├── Middleware/<br>│   └── Program.cs<br>│<br>├── Application/<br>│   ├── Interfaces/<br>│   ├── Services/<br>│   ├── DTOs/<br>│   └── Features/<br>│<br>├── Domain/<br>│   ├── Entities/<br>│   ├── ValueObjects/<br>│   └── Interfaces/<br>│<br>├── Infrastructure/<br>│   ├── AI/<br>│   ├── Persistence/<br>│   ├── ExternalServices/<br>│   └── DependencyInjection.cs<br>│<br>└── Tests/</pre><p>Notice that the AI implementation lives in the <strong>Infrastructure</strong> layer. The <strong>Application</strong> layer depends only on interfaces, not on a specific AI provider.</p><p>This approach adheres to the <strong>Dependency Inversion Principle (DIP)</strong> and makes your application more testable and maintainable.</p><h3>Building an AI Service</h3><p>Let’s start by defining an interface that the rest of the application can depend on.</p><pre>public interface IAIService<br>{<br>    Task&lt;string&gt; GenerateAsync(<br>        string prompt,<br>        CancellationToken cancellationToken = default);<br>}</pre><h4>Implementing the Service</h4><p>Using the official OpenAI .NET SDK, an implementation might look like this:</p><pre>using OpenAI.Chat;<br><br>public sealed class OpenAiService : IAIService<br>{<br>    private readonly ChatClient _chatClient;<br>    public OpenAiService(ChatClient chatClient)<br>    {<br>        _chatClient = chatClient;<br>    }<br>    public async Task&lt;string&gt; GenerateAsync(<br>        string prompt,<br>        CancellationToken cancellationToken = default)<br>    {<br>        var response = await _chatClient.CompleteChatAsync(<br>        [<br>            new UserChatMessage(prompt)<br>        ], cancellationToken);<br>        return response.Value.Content[0].Text;<br>    }<br>}</pre><p>A few things to note:</p><ul><li>The application depends on the IAIService abstraction.</li><li>The OpenAI SDK is isolated within the Infrastructure layer.</li><li>Swapping to Azure OpenAI or another compatible provider requires minimal changes.</li></ul><h4>Dependency Injection</h4><p>Register the AI service with ASP.NET Core’s built-in dependency injection container.</p><pre>builder.Services.AddSingleton&lt;ChatClient&gt;(_ =&gt;<br>{<br>    return new ChatClient(<br>        model: &quot;gpt-4.1&quot;,<br>        apiKey: builder.Configuration[&quot;OpenAI:ApiKey&quot;]);<br>});<br><br>builder.Services.AddScoped&lt;IAIService, OpenAiService&gt;();</pre><p>This keeps your application modular and testable.</p><h4>Using the Service in an Application Layer</h4><p>Your application service remains unaware of the underlying AI provider.</p><pre>public class ArticleGenerator<br>{<br>    private readonly IAIService _ai;<br>    public ArticleGenerator(IAIService ai)<br>    {<br>        _ai = ai;<br>    }<br>    public async Task&lt;string&gt; GenerateSummary(string article)<br>    {<br>        return await _ai.GenerateAsync(<br>            $&quot;Summarize this article:\n\n{article}&quot;);<br>    }<br>}</pre><p>This separation of concerns is one of the biggest advantages of Clean Architecture.</p><h3>Prompt Engineering</h3><p>Many developers assume better AI results require more powerful models. In practice, better prompts often have a greater impact.</p><p>Consider the following prompt:</p><pre>Explain Clean Architecture.</pre><p>While valid, it’s vague.</p><p>A more effective prompt provides context and expectations:</p><pre>You are a senior .NET architect.<br>Explain Clean Architecture to an intermediate C# developer.<br>Use practical examples.<br>Limit the explanation to 400 words.<br>Return Markdown.</pre><p>By specifying the role, audience, scope, and output format, you significantly improve the quality and consistency of the response.</p><h3>Structured Output</h3><p>One of the most valuable AI capabilities is generating structured data instead of plain text.</p><p>For example, suppose a user submits product feedback:</p><blockquote><em>“The checkout page is slow, and I encountered a payment error.”</em></blockquote><p>Rather than asking the AI for a free-form summary, request JSON:</p><pre>Extract:<br>- Sentiment<br>- Category<br>- Priority<br>- Summary<br>Return JSON only.</pre><p>The model can respond with:</p><pre>{<br>  &quot;sentiment&quot;: &quot;Negative&quot;,<br>  &quot;category&quot;: &quot;Payments&quot;,<br>  &quot;priority&quot;: &quot;High&quot;,<br>  &quot;summary&quot;: &quot;Customer experienced payment failure during checkout.&quot;<br>}</pre><p>Your .NET application can deserialize this response into a strongly typed object, making it easier to automate workflows.</p><h3>Real-World Examples</h3><p>Let’s explore practical scenarios where AI adds tangible value.</p><h4>1. Customer Support</h4><p>Instead of searching through lengthy conversations, support agents receive:</p><ul><li>Conversation summaries</li><li>Suggested replies</li><li>Sentiment analysis</li><li>Recommended knowledge base articles</li></ul><p>This reduces response times while improving consistency.</p><h4>2. Document Processing</h4><p>AI can extract information from invoices, contracts, resumes, and reports.</p><p>Examples include:</p><ul><li>Invoice numbers</li><li>Due dates</li><li>Customer names</li><li>Contract clauses</li><li>Key obligations</li></ul><p>Combined with OCR, AI can automate document-heavy business processes.</p><h4>3. Internal Knowledge Assistants</h4><p>Organizations often have information scattered across wikis, PDFs, emails, and documentation.</p><p>AI-powered assistants can answer questions such as:</p><blockquote><em>“How do I deploy our payment service?”</em></blockquote><p>or</p><blockquote><em>“What’s the vacation policy?”</em></blockquote><p>By integrating Retrieval-Augmented Generation (RAG), responses are grounded in company-specific data.</p><h4>4. Developer Productivity</h4><p>AI can assist developers by:</p><ul><li>Explaining stack traces</li><li>Generating unit tests</li><li>Refactoring code</li><li>Creating documentation</li><li>Reviewing pull requests</li><li>Generating SQL queries</li></ul><p>Rather than replacing developers, AI accelerates routine tasks, allowing engineers to focus on higher-value work.</p><h3>Example: AI-Powered Product Description Generator</h3><p>Suppose you’re building an e-commerce platform.</p><pre>public class ProductDescriptionService<br>{<br>    private readonly IAIService _ai;<br>    public ProductDescriptionService(IAIService ai)<br>    {<br>        _ai = ai;<br>    }<br>    public async Task&lt;string&gt; GenerateDescription(<br>        string productName,<br>        string features)<br>    {<br>        var prompt = $&quot;&quot;&quot;<br>        Write a professional product description.<br>        Product:<br>        {productName}<br>        Features:<br>        {features}<br>        Use persuasive language.<br>        Keep it under 200 words.<br>        &quot;&quot;&quot;;<br>        return await _ai.GenerateAsync(prompt);<br>    }<br>}</pre><p>This service encapsulates prompt creation and delegates AI interaction to the IAIService, keeping responsibilities well-defined.</p><h4>Example: AI Email Assistant</h4><p>Another common use case is drafting emails.</p><pre>public class EmailAssistant<br>{<br>    private readonly IAIService _ai;<br><br>    public EmailAssistant(IAIService ai)<br>    {<br>        _ai = ai;<br>    }<br><br>    public async Task&lt;string&gt; DraftReply(string customerMessage)<br>    {<br>        var prompt = $&quot;&quot;&quot;<br>        Draft a professional reply.<br>        Customer message:<br>        {customerMessage}<br>        Be friendly and concise.<br>        &quot;&quot;&quot;;<br>        return await _ai.GenerateAsync(prompt);<br>    }<br>}</pre><p>This pattern can be reused across various domains, from HR and finance to customer service.</p><h3>Designing for Multiple AI Providers</h3><p>Avoid hardcoding your application to a single vendor. By relying on abstractions, you can support multiple providers with minimal changes.</p><pre>IAIService<br>                         │<br>        ┌────────────────┼────────────────┐<br>        ▼                ▼                ▼<br>   OpenAIService   AzureOpenAIService   LocalLlmService</pre><p>Benefits include:</p><ul><li>Easier testing with mock implementations.</li><li>Reduced vendor lock-in.</li><li>Flexibility to adopt newer models.</li><li>Simplified migration strategies.</li></ul><p>This design aligns with SOLID principles and ensures your AI layer evolves independently of the rest of the application.</p><h3>Looking Ahead</h3><p>At this point, we’ve built a solid foundation:</p><ul><li>A clean architecture that isolates AI concerns.</li><li>A reusable service abstraction.</li><li>Dependency injection for loose coupling.</li><li>Practical prompt engineering techniques.</li><li>Real-world use cases that demonstrate immediate business value.</li></ul><p>In the next part, we’ll focus on what separates prototypes from production systems: best practices, performance optimization, security, common pitfalls, emerging trends, and actionable guidance for building reliable AI-powered .NET applications at scale.</p><h3>Best Practices</h3><p>Building an AI-powered application is relatively straightforward. Building one that is secure, scalable, maintainable, and cost-effective requires thoughtful engineering. The following practices will help you move from a working prototype to a production-ready solution.</p><h4>1. Keep AI Behind an Abstraction</h4><p>Avoid scattering AI SDK calls throughout your codebase.</p><p>Instead of calling the AI provider directly from controllers or services, encapsulate all interactions behind an interface such as IAIService.</p><p><strong>Benefits:</strong></p><ul><li>Easier testing</li><li>Cleaner architecture</li><li>Reduced vendor lock-in</li><li>Simpler migrations to newer models</li></ul><h4>2. Design Better Prompts</h4><p>The quality of AI output depends heavily on the quality of the input.</p><p>A good prompt should include:</p><ul><li>The AI’s role</li><li>Clear instructions</li><li>Relevant context</li><li>Desired output format</li><li>Constraints (length, tone, style)</li></ul><p>Avoid vague prompts whenever possible.</p><h4>3. Validate AI Responses</h4><p>Large Language Models can produce incorrect or unexpected output.</p><p>Never assume AI-generated content is correct.</p><p>Always:</p><ul><li>Validate structured responses</li><li>Check for required fields</li><li>Sanitize generated text</li><li>Apply business rules before returning results</li></ul><p>Think of AI as an intelligent assistant — not an authoritative source.</p><h4>4. Use Strongly Typed Models</h4><p>Rather than passing strings throughout your application, map AI responses to DTOs or domain models.</p><pre>public sealed record ProductReviewAnalysis(<br>    string Sentiment,<br>    string Category,<br>    string Summary,<br>    int Priority);</pre><p>Strong typing improves readability, maintainability, and error handling.</p><h4>5. Log Responsibly</h4><p>Logging is essential for troubleshooting AI applications, but avoid recording sensitive information.</p><p>Instead of logging entire prompts, consider logging:</p><ul><li>Request IDs</li><li>Processing time</li><li>Model name</li><li>Token usage</li><li>Success or failure</li><li>Error details</li></ul><p>This approach supports observability while protecting user privacy.</p><h4>6. Build for Provider Flexibility</h4><p>The AI landscape evolves rapidly.</p><p>By designing against abstractions, you can switch providers with minimal changes.</p><p>Today’s preferred model may not be tomorrow’s best choice.</p><h4>7. Monitor Token Usage</h4><p>Every prompt and response consumes tokens, which directly impact cost and latency.</p><p>Optimize prompts by:</p><ul><li>Removing unnecessary context</li><li>Limiting response length</li><li>Reusing system prompts</li><li>Summarizing long conversations</li></ul><p>Efficient prompt design benefits both performance and budget.</p><h3>Common Mistakes</h3><p>Many teams encounter the same challenges when adopting AI. Recognizing these pitfalls early can save significant time and effort.</p><h3>Treating AI as Deterministic</h3><p>Traditional software behaves predictably: the same input produces the same output.</p><p>LLMs, however, are probabilistic. Slight variations in prompts or model updates can lead to different responses.</p><p>Design your application to accommodate this variability.</p><h3><em>I</em>gnoring Error Handling</h3><p>AI requests can fail due to:</p><ul><li>Rate limits</li><li>Network issues</li><li>Timeouts</li><li>Invalid responses</li><li>Service outages</li></ul><p>Implement retry policies, graceful fallbacks, and meaningful error messages to ensure a robust user experience.</p><h3>Embedding Business Logic in Prompts</h3><p>Prompts should describe tasks, not replace your application’s business rules.</p><p>Keep critical business logic within your .NET codebase, where it can be tested, versioned, and maintained.</p><h3>Sending Excessive Context</h3><p>Including unnecessary information in prompts increases:</p><ul><li>Token consumption</li><li>Response latency</li><li>Operational costs</li></ul><p>Provide only the context required for the current task.</p><h3>Skipping Human Oversight</h3><p>For high-impact scenarios such as legal advice, medical recommendations, or financial decisions, incorporate human review before acting on AI-generated content.</p><h3>Performance Considerations</h3><p>Performance becomes increasingly important as AI adoption grows within your applications.</p><h4>Minimize Latency</h4><p>Reduce response times by:</p><ul><li>Caching frequent responses</li><li>Reusing HTTP connections</li><li>Streaming responses when supported</li><li>Parallelizing independent operations</li><li>Selecting models appropriate to the task</li></ul><p>Not every use case requires the largest or most capable model.</p><h4>Asynchronous Processing</h4><p>Long-running AI tasks should not block user interactions.</p><p>Use background processing for operations such as:</p><ul><li>Document summarization</li><li>Batch analysis</li><li>Report generation</li><li>Content creation</li></ul><p>Technologies like hosted services or background job processors can improve responsiveness.</p><h3>Implement Caching</h3><p>Many prompts produce identical results.</p><p>Caching these responses can:</p><ul><li>Reduce API calls</li><li>Lower costs</li><li>Improve user experience</li><li>Decrease latency</li></ul><p>Cache duration should align with the volatility of the underlying data.</p><h3>Measure Everything</h3><p>Track key metrics such as:</p><ul><li>Response time</li><li>Token usage</li><li>Request volume</li><li>Success rate</li><li>Failure rate</li><li>Average cost per request</li></ul><p>Data-driven insights enable informed optimization decisions.</p><h3>Security Considerations</h3><p>Integrating AI introduces new security considerations beyond traditional application development.</p><h3>Protect Sensitive Data</h3><p>Avoid sending confidential information to external AI services unless you have appropriate safeguards in place.</p><p>Consider masking or anonymizing:</p><ul><li>Personal information</li><li>Financial records</li><li>Medical data</li><li>Authentication credentials</li><li>Proprietary business information</li></ul><h3>Defend Against Prompt Injection</h3><p>Prompt injection occurs when users attempt to manipulate the model into ignoring system instructions or revealing sensitive information.</p><p>Mitigation strategies include:</p><ul><li>Validating user input</li><li>Separating system prompts from user prompts</li><li>Applying output filtering</li><li>Restricting available tools and permissions</li></ul><h3>Manage Secrets Securely</h3><p>Never hardcode API keys.</p><p>Use secure secret management solutions such as:</p><ul><li>Environment variables</li><li>Azure Key Vault</li><li>AWS Secrets Manager</li><li>HashiCorp Vault</li></ul><p>Rotate credentials regularly and enforce the principle of least privilege.</p><h3>Apply Authorization</h3><p>Not every user should access every AI capability.</p><p>Implement role-based or policy-based authorization to control access to sensitive features.</p><h3>Future Trends</h3><p>AI and .NET continue to evolve at an extraordinary pace. Several trends are shaping the future of intelligent applications.</p><h3>AI Agents</h3><p>Modern applications are moving beyond simple prompts toward autonomous agents capable of:</p><ul><li>Planning tasks</li><li>Calling APIs</li><li>Executing workflows</li><li>Coordinating multiple tool</li></ul><p>These agents enable more dynamic and intelligent user experiences.</p><h3>Retrieval-Augmented Generation (RAG)</h3><p>RAG enhances AI responses by retrieving relevant information from trusted data sources before generating an answer.</p><p>Benefits include:</p><ul><li>Improved factual accuracy</li><li>Access to up-to-date information</li><li>Reduced hallucinations</li><li>Better enterprise knowledge integration</li></ul><h3>Smaller, Specialized Models</h3><p>Organizations increasingly adopt compact models tailored to specific tasks.</p><p>Advantages include:</p><ul><li>Lower infrastructure costs</li><li>Faster inference</li><li>Improved privacy</li><li>On-device deployment</li></ul><h3>Multimodal AI</h3><p>Future applications will seamlessly combine:</p><ul><li>Text</li><li>Images</li><li>Audio</li><li>Video</li><li>Documents</li></ul><p>This enables richer interactions, from analyzing diagrams to understanding spoken conversations.</p><h3>AI-Native Applications</h3><p>Rather than adding AI as an afterthought, new applications are being designed around AI capabilities from the outset.</p><p>This shift influences user experience, workflows, and software architecture.</p><h3>Key Takeaways</h3><ul><li>AI is becoming a core capability of modern software development.</li><li>.NET 8 provides a powerful ecosystem for integrating AI into enterprise applications.</li><li>Clean Architecture helps isolate AI providers and improve maintainability.</li><li>Prompt engineering significantly influences response quality.</li><li>Strong abstractions reduce vendor lock-in.</li><li>Structured outputs simplify downstream processing.</li><li>Performance optimization reduces latency and operational costs.</li><li>Security, privacy, and validation remain essential responsibilities.</li><li>AI should augment — not replace — sound software engineering practices.</li><li>Continuous experimentation and learning are key to building successful AI-powered systems.</li></ul><h3>Conclusion</h3><p>Artificial Intelligence is no longer a niche technology reserved for research teams. It has become a practical tool that developers can use to build smarter, more responsive, and more efficient applications.</p><p>For C# developers, this represents a significant opportunity. You already possess many of the skills needed to create production-grade AI solutions: designing clean architectures, building reliable APIs, applying SOLID principles, and delivering maintainable software.</p><p>The next step is learning how to integrate AI responsibly into those existing strengths.</p><p>Start small.</p><p>Build a document summarizer, an intelligent search feature, or an AI-assisted customer support tool. Experiment with different models, refine your prompts, measure performance, and iterate based on real user feedback.</p><p>As the .NET ecosystem continues to evolve, AI will become an increasingly natural part of everyday application development. Developers who embrace these technologies today will be well positioned to create the next generation of intelligent software.</p><p>The future of .NET isn’t just cloud-native or cross-platform — it’s AI-powered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55542cef130e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modular Monolith Architecture in C#: The Pragmatic Path to Scalable .NET Applications]]></title>
            <link>https://medium.com/@kevalbalar1995/modular-monolith-architecture-in-c-the-pragmatic-path-to-scalable-net-applications-a3e8726d347e?source=rss-b426c1c72296------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3e8726d347e</guid>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[modular-monolith]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Keval Balar]]></dc:creator>
            <pubDate>Fri, 03 Jul 2026 04:14:07 GMT</pubDate>
            <atom:updated>2026-07-03T04:14:07.451Z</atom:updated>
            <content:encoded><![CDATA[<h4>I Stopped Building Microservices — Here’s Why Modular Monolith Changed Everything</h4><p>Let me tell you about the worst project of my career.</p><p>It was 2021. We were building a SaaS platform for a fast-growing logistics company. The CTO had read about Netflix. The product owner had watched a YouTube video about Amazon. Everyone wanted microservices.</p><p>We delivered fourteen microservices. Each had its own database. Each had its own deployment pipeline. Each had its own monitoring dashboard. We were so proud.</p><p>Six months later, we were drowning.</p><p>A simple feature that should have taken two days took two weeks. Debugging required tracing requests across seven services. A minor database migration brought down three services simultaneously. We spent more time managing infrastructure than shipping code.</p><p>The team was miserable. The product was behind schedule. The CTO kept asking why things were so slow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NfiiJexki8B4pEtVSYYGqA.png" /></figure><h3>Why This Matters</h3><h4>The Architecture Trap We All Fall Into</h4><p>Here’s what I’ve learned after fifteen years of building software: we architects have a bias toward complexity.</p><p>We think we’re going to build the next Netflix. We think our system will need to handle millions of requests per second from day one. So we start with microservices. We Kubernetes everything. We distribute before we need to.</p><p>The reality is much more mundane. Most of us are building business applications. E-commerce platforms. Internal tools. B2B SaaS products. These systems need to be maintainable, testable, and reliable. They don’t need Google-scale infrastructure.</p><p><strong>Traditional monoliths</strong> start simple, then descend into chaos. You’ve seen it. The codebase where changing the customer module breaks the inventory system. Where business logic lives in controllers because nobody knows where else to put it. Where one team’s deployment blocks another team’s deployment.</p><p><strong>Microservices</strong> promised salvation. Independent teams! Technology diversity! Selective scaling! But the reality hit hard. Each service requires its own CI pipeline, deployment, monitoring, security review, and on-call rotation. Network calls add latency and failure modes. Distributed transactions become debugging nightmares. Your team spends more time managing complexity than shipping features.</p><p>The industry has started admitting what many of us have known for years: most organizations aren’t ready for microservices. A 2024 industry survey showed that over 40% of companies regret at least some of their microservices decisions.</p><p>The problem isn’t microservices. The problem is starting with them before you understand your domain boundaries or have the operational maturity to support them.</p><h3>The Third Way</h3><p>A modular monolith is a single deployment unit organized internally into clear modules with strong boundaries. Think of it like a well-organized apartment building versus a sprawling suburban development.</p><p>In a <strong>traditional monolith</strong>, everything is tangled together. All the wiring runs everywhere. You can’t renovate one apartment without affecting the whole building.</p><p>In <strong>microservices</strong>, each apartment is a separate building with its own plumbing, electricity, and road access. You can renovate independently, but coordinating changes across buildings is complex.</p><p>In a <strong>modular monolith</strong>, you have one building, but each apartment has clearly defined walls, separate entrances, and explicit interfaces. You can remodel one apartment without affecting the others, as long as you respect the walls and don’t knock them down.</p><p>The key insight: <strong>deployment boundaries are not the same as logical boundaries</strong>. You can have clean, decoupled code without deploying thirty different services.</p><h3>Understanding the Fundamentals</h3><h4>What Makes a Module a Module?</h4><p>Before we dive into implementation, let’s get clear on what a module actually is in this context.</p><p>A module is a self-contained unit of business functionality. It encapsulates everything needed for that business capability — entities, business logic, data access, and API endpoints. In an e-commerce system, modules might include:</p><ul><li>Catalog: Products, categories, pricing, inventory</li><li>Orders: Shopping cart, checkout, order tracking</li><li>Customers: Registration, profiles, authentication</li><li>Payments: Payment methods, transactions, refunds</li></ul><p>Each module should be independently understandable. A developer should be able to understand how the Orders module works without understanding how Catalog works, just as you can understand the checkout process at a store without knowing how they stock the shelves.</p><h3>Domain-Driven Design and Bounded Contexts</h3><p>Domain-Driven Design (DDD) provides the vocabulary for this. The concept of <strong>bounded contexts</strong> is crucial here: within its own boundary, a term like “Customer” has a specific meaning. The Orders module might care about the customer’s shipping address and payment history. The Marketing module might care about the customer’s preferences and engagement history. Same customer, different contexts.</p><p>This is okay. In fact, it’s essential. When we try to create one universal “Customer” model that works for everyone, we end up with bloated, coupled code. By letting each module define its own version of a customer, we keep things clean and focused.</p><h3>The Shared Kernel</h3><p>Some things need to be shared across modules. Authentication. Logging. Common data types. Base classes. This is the <strong>shared kernel — </strong>infrastructure that multiple modules safely depend on.</p><p>The key word is “safely.” The shared kernel should contain only things that are stable and truly cross-cutting. It should never contain business logic. If you find yourself putting domain concepts in the shared kernel, you’ve likely identified a bounded context incorrectly.</p><h3>How It Works</h3><h4>The Project Structure That Changed Everything</h4><p>I’ve tried many ways to structure modular monoliths, and this pattern has worked best for my teams:</p><p>Solution.ModularMonolith/<br>├── src/<br>│ ├── Host/<br>│ │ └── Api/ # Entry point and bootstrapping<br>│ ├── Modules/<br>│ │ ├── Catalog/<br>│ │ │ ├── Catalog.Api/ # Controllers and API concerns<br>│ │ │ ├── Catalog.Core/ # Business logic and entities<br>│ │ │ ├── Catalog.Infrastructure/ # Data access and external services<br>│ │ │ └── Catalog.Contracts/ # Public interfaces and DTOs<br>│ │ └── Orders/<br>│ │ ├── Orders.Api/<br>│ │ ├── Orders.Core/<br>│ │ ├── Orders.Infrastructure/<br>│ │ └── Orders.Contracts/<br>│ └── Shared/<br>│ ├── Shared.Kernel/ # Common utilities and base classes<br>│ ├── Shared.Infrastructure/ # Cross-cutting infrastructure<br>│ └── Shared.Contracts/ # Shared data contracts<br>└── tests/<br> ├── Modules/<br> │ ├── Catalog.UnitTests/<br> │ └── Orders.UnitTests/<br> └── IntegrationTests/</p><p>This structure enforces module boundaries at the compilation level. The Catalog module cannot reference the Orders module’s internal implementation — it can only reference its contracts.</p><h3>Module Communication Patterns</h3><p>Modules need to talk to each other. In a modular monolith, this can happen in several ways:</p><p>Direct Interface Calls (Synchronous)</p><p>The simplest approach. One module calls another through a well-defined interface. The Orders module asks the Catalog module to validate stock levels. The call is just a method call — no network, no serialization, no latency.</p><p>The beauty of this in a modular monolith is that you get the performance of in-process communication with the decoupling of an interface. You can mock the Catalog module in tests. You can replace the implementation without changing the Orders module. But you can also inspect the call stack and debug like a normal application.</p><p>Event-Driven Communication (Asynchronous)</p><p>For true decoupling, use an in-memory event bus. When an order is confirmed, the Orders module publishes an OrderConfirmed event. The Inventory module handles this event and reserves the items. The Orders module doesn&#39;t need to know about Inventory—it just publishes events.</p><p>This is the same pattern used in microservices, but without the network overhead. The event bus is in-memory, so the events are delivered almost instantly. You get the decoupling benefits of asynchronous communication without the operational complexity.</p><h3>Real-World Examples</h3><h4>Shopify: Processing 30TB Per Minute</h4><p>Shopify processes massive transaction volumes using modular monolith principles. At the scale they operate — over a million requests per minute — they’ve proven that modular monoliths can handle enterprise-level load.</p><p>Their key insight is worth repeating: even at Shopify’s scale, the operational simplicity of a single deployment unit outweighed the benefits of distributed services. They maintain strong internal boundaries while keeping deployment simple. They’ve demonstrated that you can run a massive e-commerce platform on a modular monolith, and then selectively extract services only when scaling demands it.</p><h4>Amazon’s “Microservices Back” Movement</h4><p>This one is telling. Amazon famously pioneered microservices. They literally wrote the book on it. And yet, in recent years, they’ve transitioned certain services back to monolithic architectures.</p><p>Why? Because the operational costs of distribution sometimes exceed the benefits. When a service has simple scaling requirements and clear internal boundaries, the overhead of running it as a separate microservice isn’t justified.</p><p>If Amazon, of all companies, is pulling back from microservices in some cases, maybe we should think twice before adopting them universally.</p><h3>Architecture and Implementation</h3><h4>Step 1: Identify Your Bounded Contexts</h4><p>Start by mapping your business domain. Don’t start with code. Start with whiteboards and sticky notes. Identify the major business capabilities in your system.</p><p>For an e-commerce platform:</p><ul><li>Customer Management (registration, profiles, preferences)</li><li>Catalog Management (products, categories, pricing)</li><li>Order Processing (cart, checkout, fulfillment)</li><li>Payment Processing (payment methods, transactions)</li><li>Inventory Management (stock levels, warehouse operations)</li></ul><p>These bounded contexts should feel natural to your business stakeholders. The test of a good bounded context is that a business person can understand it without understanding code.</p><h4>Step 2: Design Module Boundaries</h4><p>For each bounded context, define three things:</p><ol><li><strong>What belongs inside the module</strong> (entities, business logic, data access)</li><li><strong>What the module exposes</strong> (public interfaces, DTOs, events)</li><li><strong>What the module depends on</strong> (other modules, shared infrastructure)</li></ol><p>The key insight here: define the dependencies before writing code. This prevents the natural tendency to make everything public and accessible. If you define what others can use ahead of time, you think more carefully about your module’s design.</p><h4>Step 3: Create the Project Structure</h4><p>Set up the physical project structure from earlier. Use .NET 8 with Central Package Management. This ensures consistent dependencies across modules and prevents version conflicts.</p><h4>Step 4: Define Module Contracts</h4><p>The Contracts project is your module’s public API. It should contain only DTOs, interface definitions, and event types. No implementation details. No database entities. No infrastructure references.</p><p>Here’s a simple example:</p><pre>// Catalog.Contracts/ICatalogService.cs<br>public interface ICatalogService<br>{<br>    Task&lt;ProductDto&gt; GetProductAsync(int productId);<br>    Task&lt;bool&gt; UpdateStockAsync(int productId, int quantity);<br>}<br><br>// Catalog.Contracts/ProductDto.cs<br>public record ProductDto(<br>    int Id,<br>    string Name,<br>    decimal Price,<br>    int StockQuantity<br>);</pre><p>That’s it. Other modules don’t need to know about your repositories, your database, or your business logic. They just need to know what you can do for them.</p><h4>Step 5: Implement Core Business Logic</h4><p>The Core project contains your business logic, entities, and domain services — all private to the module. Other modules can’t access these directly, and that’s the point.</p><p>The entities here are your domain objects. They contain business logic and enforce business rules. They raise domain events when important things happen. They’re completely unaware of infrastructure.</p><h4>Step 6: Implement Infrastructure</h4><p>The Infrastructure project handles data access, external service integrations, and caching. It implements the interfaces defined in the Core project.</p><p>The important thing here: the Core project doesn’t reference Infrastructure. The Infrastructure project references Core. This keeps your business logic free of infrastructure concerns and makes testing easier.</p><h4>Step 7: Wire Up the API</h4><p>The Api project contains controllers that expose module functionality via HTTP endpoints. These controllers orchestrate calls to the Core layer and handle HTTP concerns — serialization, validation, status codes.</p><h4>Step 8: Configure Dependency Injection</h4><p>In your host’s Program.cs, register each module:</p><pre>builder.Services<br>    .AddCatalogModule()<br>    .AddOrdersModule()<br>    .AddInventoryModule();</pre><p>Each module registers its own services, its own DbContext, and its own event handlers. This keeps the host clean and makes it clear what modules your application includes.</p><h4>Step 9: Enforce Module Boundaries</h4><p>This is where the rubber meets the road. Use architecture tests to ensure developers don’t violate module boundaries:</p><pre>[Test]<br>public void CatalogModule_Should_NotReference_OrdersModule_Internals()<br>{<br>    // This test fails if someone accidentally references Orders.Core from Catalog.Core<br>}</pre><p>Run these tests in CI. If a developer tries to bypass the architecture, the build fails. This prevents the gradual erosion of boundaries that kills most modular monolith implementations.</p><h3>Best Practices</h3><h4>1. Start with Modular Monolith as Default</h4><p>For new projects, default to a modular monolith. As Martin Fowler observed, all successful microservice architectures he’s seen emerged from monolithic systems — not the other way around. Starting with a modular monolith gives you time to understand your domain before distributing it.</p><h4>2. Define Bounded Contexts Carefully</h4><p>Use Domain-Driven Design to identify bounded contexts before writing code. These boundaries should reflect business capabilities, not technical concerns. The wrong boundaries lead to constant cross-module communication, which defeats the purpose.</p><h4>3. Enforce Module Boundaries Religiously</h4><p>Use separate project assemblies for each module. Implement architecture tests that fail the build if boundaries are violated. Make it painful to bypass the architecture. This is the only way to prevent the gradual erosion of boundaries.</p><h4>4. Keep Contracts Minimal and Stable</h4><p>Module contracts should be minimal and stable. When you change a contract, all dependent modules may need updates. This is the same as microservices — contract stability is crucial for independent evolution.</p><h4>5. Use Explicit Dependencies</h4><p>Each module should explicitly declare its dependencies on other modules via Contracts projects. No implicit dependencies. No depending on implementation details. Make the dependencies visible and enforced.</p><h4>6. Consider Event-Driven Communication</h4><p>Use events for cross-module communication to reduce coupling. An in-memory event bus works well within a modular monolith. You get the decoupling benefits of asynchronous communication without the operational complexity.</p><h4>7. Implement Shared Infrastructure Carefully</h4><p>Cross-cutting concerns like authentication, logging, caching, and configuration should live in shared infrastructure projects. Keep business logic separate. The shared kernel should be small and stable.</p><h3>Common Mistakes</h3><h4>1. Creating “Modules” by Technical Layer</h4><p>Organizing modules by technical layer (e.g., “DataAccess” module, “Services” module) defeats the purpose. Modules should be organized by business capability. If you can’t explain to a business person what your module does, your boundaries are wrong.</p><h4>2. Allowing Direct Database Access Across Modules</h4><p>Modules should not directly access each other’s database tables. This creates hidden coupling. If the Orders module queries the Products table directly, you’ve defeated the purpose of module boundaries.</p><h4>3. Sharing Domain Entities Across Modules</h4><p>Each module should own its domain entities. Sharing entities across modules creates tight coupling. The Orders module’s concept of a product should be separate from the Catalog module’s concept.</p><h4>4. Starting with Microservices Too Early</h4><p>Starting with microservices before you understand your domain boundaries or have the operational maturity to support them leads to failure. Start with a modular monolith. Extract services only when scale justifies the complexity.</p><h4>5. Ignoring Database Isolation</h4><p>Even in a modular monolith, each module should have clear database ownership. Use separate schemas or separate databases within the same server. This maintains the option of extracting services later.</p><h3>Performance Considerations</h3><h4>In-Process Communication</h4><p>One of the biggest advantages of modular monoliths is in-process communication. Cross-module calls happen as method calls, not network requests. This can reduce request processing time by hundreds of milliseconds compared to microservices.</p><h4>Database Performance</h4><p>Modules can share database connections and leverage transaction boundaries for optimal performance. Query optimization across module boundaries is possible when needed. You’re not limited by network latency.</p><h4>Caching</h4><p>Data can be cached at the application level and shared across modules. Cache invalidation strategies are simpler without distributed cache consistency concerns. In-memory caches work well within a modular monolith.</p><h4>Scaling Considerations</h4><p>A modular monolith scales vertically more efficiently than horizontal scaling. You can scale your modular monolith to handle significant load before needing to extract services. Most applications never need to go further.</p><h3>Conclusion</h3><p>The architecture wars are finally over. The modular monolith has emerged as the pragmatic middle ground — offering the clean boundaries and team autonomy of microservices without the crippling operational complexity.</p><p>For most teams and most projects, this is the sweet spot. It gives you the discipline to build maintainable, testable systems while keeping deployment simple. It lets you evolve to distributed services when — and only when — the scale justifies the complexity.</p><p>Your next project deserves a modular monolith.</p><p>Start with strong boundaries from day one. Use Domain-Driven Design to identify your bounded contexts. Structure your .NET 8 solution with clear module separation. Enforce boundaries with architecture tests. Then, when your system is running and your team is growing, you can extract modules selectively — based on real operational needs, not on hype.</p><p>The pattern is proven. The tools are mature. The choice is clear.</p><p>Build better systems. Start simpler. Evolve smarter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3e8726d347e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>