<?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 Vahid Faraji on Medium]]></title>
        <description><![CDATA[Stories by Vahid Faraji on Medium]]></description>
        <link>https://medium.com/@vahid-faraji-dev?source=rss-f3079f487992------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xnISSbTTk38unUmhmlfYgA.png</url>
            <title>Stories by Vahid Faraji on Medium</title>
            <link>https://medium.com/@vahid-faraji-dev?source=rss-f3079f487992------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:28:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vahid-faraji-dev/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[Managing Secrets in Dockerized Applications: From GitHub Actions to Production]]></title>
            <link>https://blog.devops.dev/managing-secrets-with-docker-from-github-actions-to-the-production-server-99a5bc0cd53c?source=rss-f3079f487992------2</link>
            <guid isPermaLink="false">https://medium.com/p/99a5bc0cd53c</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[aspdotnetcore]]></category>
            <category><![CDATA[management-secrets]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Vahid Faraji]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 14:01:25 GMT</pubDate>
            <atom:updated>2026-11-16T13:25:59.829Z</atom:updated>
            <content:encoded><![CDATA[<p>In one of my projects developed with ASP.NET Core, I was using Docker to run the services and GitHub Actions to manage the CI/CD process.</p><p>The deployment process was automated: with every push to the main branch, tests were executed first, then a new Docker image was built and transferred to the VPS, and finally the previous container was replaced with the new version.</p><p>While reviewing this process, I decided to make the management of sensitive production information independent of the build and deployment lifecycle as well.</p><p>It wasn’t just about securing secrets; <strong>I wanted each part of the infrastructure to have a clearly defined responsibility.</strong> Source code would be stored in Git, the Docker image would be responsible for running the application, GitHub Actions would manage the deployment process, and sensitive information such as API keys, database connection strings, and client secrets would remain in the production environment.</p><p>My goal was to ensure that each deployment changed only the application version, not the way its sensitive information was managed.</p><p>I had several options to achieve this, from environment variables and GitHub Actions Secrets to dedicated secret management services such as <strong>Azure Key Vault, HashiCorp Vault, and AWS Secrets Manager</strong>. However, considering the project’s existing architecture, which ran on a VPS with multiple Docker containers, I preferred a simpler and more manageable approach.</p><p>In the end, I chose <strong>protected files on the VPS and read-only Docker bind mounts</strong> and implemented this structure with a few limited changes to Program.cs and the GitHub Actions workflow.</p><p>In the following sections, I’ll share my experience with this change, the technical decisions I made, and the lessons I learned during implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpNEydMcK_X2XUCnvnIetA.png" /></figure><h3>Step 1: Moving Secrets to the VPS</h3><p>The first thing I did was decide where to store sensitive information on the server.</p><p>I didn’t want to create separate, scattered paths for every secret. I preferred a clear structure that could also be reused for other projects in the future.</p><p>I eventually chose the following structure:</p><pre>/etc/app-secrets/<br>└── my-app/<br>    ├── external-api-key<br>    ├── database-password<br>    └── ...</pre><p>Each file contains only one sensitive value. This allows each secret to be managed and replaced independently of the others.</p><p>To create the directory and restrict access to it, I used the following commands:</p><pre>mkdir -p /etc/app-secrets/my-app<br>chmod 700 /etc/app-secrets/my-app</pre><p>I then created the required files and set their permissions to 600.</p><p>For example:</p><pre>chmod 600 /etc/app-secrets/my-app/external-api-key</pre><p>These settings restrict access to the directory and sensitive files.</p><p>At this point, the secrets were stored on the VPS, but the application still couldn’t access them directly because the services were running inside Docker containers.</p><h3>Step 2: Mounting Secrets into Docker Containers</h3><p>To make the files on the VPS accessible inside the containers, I used Docker bind mounts.</p><p>This feature allows a file or directory from the host to be made available at a specific path inside a container, without having to include it in the Docker image.</p><p>For example, the API key file was located on the VPS at:</p><pre>/etc/app-secrets/my-app/external-api-key</pre><p>I mounted it at the following path inside the container:</p><pre>/run/secrets/external-api-key</pre><p>The corresponding Docker option looked like this:</p><pre>--mount type=bind,source=/etc/app-secrets/my-app/external-api-key,target=/run/secrets/external-api-key,readonly</pre><p>The readonly option was important to me because the application only needed to read the secret, not modify it.</p><p>One of the key aspects of this design is that the files are independent of the container lifecycle.</p><p>Even if a container is removed and recreated, the original file remains on the VPS. Of course, the new container must be started with the same bind mount configuration.</p><p>My project had two independent containers: one for the UI and another for the API.</p><p>A shared API key was mounted into both containers, while information such as database connection details and credentials for external services was made available only to the API.</p><p>This separation ensured that each service had access only to the secrets it actually needed.</p><h3>Step 3: Integrating Docker Secrets into GitHub Actions</h3><p>By this point, the secret files were ready on the VPS, and I knew how to mount them into Docker. However, one important part was still missing: <strong>the automated deployment process</strong>.</p><p>In my project, GitHub Actions built a new Docker image after the tests passed and transferred it to the VPS.</p><p>The previous container was then stopped and removed, and a new container was started using docker run.</p><p>This meant that if I configured the bind mounts only manually on the server, those settings wouldn’t automatically be included when the next deployment created a new container.</p><p>To solve this, I updated the GitHub Actions workflow and added the new mounts directly to the docker run command.</p><p>A simplified example of the API configuration looks like this:</p><pre>docker run -d \<br>  --name app-api \<br>  --mount type=bind,source=/etc/app-secrets/my-app/external-api-key,target=/run/secrets/external-api-key,readonly \<br>  --mount type=bind,source=/etc/app-secrets/my-app/database-password,target=/run/secrets/database-password,readonly \<br>  my-app-api:latest</pre><p>This code snippet shows only the part related to secrets; the other mounts and service settings were preserved in the original workflow.</p><p>What I found interesting was that <strong>I didn’t need to change the CI/CD architecture; I only needed to extend how the new container was started.</strong></p><p>From that point on, whenever GitHub Actions deployed a new version of the application, the new container would start with access to the same secret files already stored on the VPS.</p><p>This allowed the deployment process to remain fully automated without placing sensitive values in the workflow or Docker image.</p><h3>Step 4: Reading Secrets in ASP.NET Core</h3><p>Now it was time to update the application.</p><p>I wanted to keep this change as small as possible and avoid rewriting the services that already relied on configuration values.</p><p>Fortunately, ASP.NET Core provides this flexibility through IConfiguration.</p><p>In Program.cs, for the Production environment, I read the secret values from the files inside the container and added them to the configuration.</p><p>For example, the following code is a simplified version of this approach:</p><pre>if (builder.Environment.IsProduction())<br>{<br>    builder.Configuration[&quot;ExternalApi:Key&quot;] =<br>        File.ReadAllText(&quot;/run/secrets/external-api-key&quot;)<br>            .TrimEnd(&#39;\r&#39;, &#39;\n&#39;);<br>    // ... other secrets<br>}</pre><p>With this approach, the rest of the application continued using the same configuration keys as before.</p><p>For example, a service using ExternalApi:Key didn&#39;t need to know whether the API key came from a JSON file or a file mounted inside Docker.</p><p>In the Development environment, I also used the built-in .NET User Secrets feature so that production-specific files were only required on the server.</p><p><strong>The result was that the configuration source changed, but the contract for accessing configuration values remained the same.</strong></p><p>This was exactly what I wanted from the beginning: a change in how the infrastructure was managed, with minimal impact on the application logic.</p><h3>Step 5: Testing and Validating the Changes</h3><p>After making the changes, it was time to verify that everything worked as expected.</p><p>I didn’t want to rely solely on the configuration looking correct. It was important to me to make sure the containers could actually access the secret files and that the application could run without issues.</p><p>First, I checked that the files existed on the VPS and verified their permissions. Then, using Docker, I confirmed that the mounted files were readable inside the container without having to display their sensitive values.</p><p>In the Development environment, I also moved the settings to .NET User Secrets and adjusted the integration tests using test values and replacement dependencies so that the tests wouldn&#39;t rely on real production credentials.</p><p>One important distinction I paid attention to during this stage was the difference between a successful pipeline and a healthy running application.</p><p><strong>A green GitHub Actions workflow doesn’t necessarily mean the application is running correctly in production.</strong></p><p>A Docker image may build successfully, and even the container creation command may execute without errors, while the application still fails during startup because a secret is missing, a mount path is incorrect, or the file cannot be accessed.</p><p>That’s why I considered checking the container status, application logs, and actual service behavior after deployment to be an important part of the validation process.</p><h3>Step 6: What I Learned from This Experience</h3><p>This change didn’t involve a large amount of code, but it made me pay closer attention to several aspects of the deployment architecture.</p><p><strong>First, keeping secrets independent of Docker images.</strong></p><p>A Docker image should be reusable across different environments without carrying sensitive information specific to any one environment. With this structure, the image stays the same, and each environment provides its own secrets.</p><p><strong>Second, restricting access.</strong></p><p>Using a bind mount alone isn’t enough. File permissions on the VPS, system user access, and which secrets each container can access are all important. The readonly option also helps prevent the application from modifying the mounted file.</p><p><strong>Third, the importance of backup and recovery.</strong></p><p>When secrets are stored outside the Docker image, there must also be a clear plan for preserving and recovering them.</p><p>If the server is lost, having the source code and Docker image isn’t enough to bring the system back online. The secret files, or a secure way to recreate the credentials, are also required.</p><p><strong>Fourth, managing secret changes.</strong></p><p>In my implementation, secret values are read during startup and added to IConfiguration. Therefore, if a file&#39;s value changes, the corresponding container must be restarted for the new value to take effect.</p><p>This may seem like a small detail, but it matters when designing a credential rotation process.</p><h3>Conclusion</h3><p>My goal with this change wasn’t to build a complex secret management system. I wanted a solution that was simple, manageable, and maintainable within the project’s existing architecture.</p><p>By using protected files on the VPS, read-only Docker bind mounts, and a few limited changes to ASP.NET Core and GitHub Actions, I was able to separate the management of sensitive production information from the Docker image and build lifecycle.</p><p>Of course, this approach doesn’t replace all the capabilities of a dedicated secret manager. Areas such as secure backups, access control, auditing, and credential rotation still require attention and ongoing management.</p><p>But the most important outcome of this experience for me was <strong>a clearer separation of responsibilities across the infrastructure</strong>.</p><p>Source code is managed in Git, build and deployment processes in GitHub Actions, application execution in Docker, and sensitive production information in the server environment.</p><p>Sometimes, improving an architecture doesn’t require adding new tools; it simply requires separating responsibilities more clearly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99a5bc0cd53c" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/managing-secrets-with-docker-from-github-actions-to-the-production-server-99a5bc0cd53c">Managing Secrets in Dockerized Applications: From GitHub Actions to Production</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From APIs and Function Calling to MCP: How I Discovered a New Standard in AI]]></title>
            <link>https://vahid-faraji-dev.medium.com/from-apis-and-function-calling-to-mcp-how-i-discovered-a-new-standard-in-ai-f7790fa9111c?source=rss-f3079f487992------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7790fa9111c</guid>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[calling-function]]></category>
            <category><![CDATA[mcps]]></category>
            <dc:creator><![CDATA[Vahid Faraji]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 09:20:07 GMT</pubDate>
            <atom:updated>2026-11-06T09:25:54.954Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Will MCP replace APIs? What is the difference between an MCP Server, an MCP Client, and Function Calling — and when should we use each?</em></p><p>I’ve recently been working on a software project where part of the functionality involves artificial intelligence interacting with the system’s internal capabilities. To implement this, I needed <strong>Function Calling</strong> — a capability that allows language models such as GPT to request the use of tools and functions we define in our applications.</p><p>While exploring implementation approaches and reading the technical documentation, I came across something called the <strong>Model Context Protocol (MCP)</strong>.</p><p>My first question was simple: if Function Calling already lets us make our tools available to a model, what problem does MCP actually solve? What exactly is an MCP Server? Is MCP supposed to replace APIs, or is it simply a new way of doing something we could already do?</p><p>The more I read, the clearer it became that although these concepts are related, they each play a different role in software architecture.</p><p>I decided to share what I learned in this article. Perhaps you’ve encountered the same questions while building an AI agent or connecting AI to an existing software system.</p><p>To keep things simple, we’ll start with APIs, move on to Function Calling, and then explore MCP Servers and MCP Clients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_mry_4Y4Z82E_Nvh-ut5A.png" /></figure><h3>1. What Is an API? The Starting Point for Communication Between Applications</h3><p>Before discussing artificial intelligence, it’s worth revisiting one of the fundamental concepts in software development.</p><p>API stands for <strong>Application Programming Interface</strong>.</p><p>Simply put, an API provides a defined interface through which software systems can communicate.</p><p>Imagine we have an online store that keeps information about products, customers, and orders in a database.</p><p>Now we want to build a mobile app for that store as well.</p><p>To display a customer’s order, the mobile app doesn’t need direct access to the database. Instead, it sends a request to the store’s API.</p><p>For example:</p><p>GET /api/orders/1042</p><p>This request essentially means: “Return the details for order 1042.”</p><p>After verifying the user’s identity and access permissions, the backend retrieves the order information and sends a response.</p><p>For example:</p><pre>{&quot;orderId&quot;:1042,&quot;status&quot;:&quot;Shipped&quot;}</pre><p>The mobile app receives the response and shows the customer that their order has been shipped.</p><h3>REST APIs and Common HTTP Methods</h3><p>One common approach to API design is REST.</p><p>In a REST API, we typically work with HTTP methods such as:</p><ul><li><strong>GET</strong> — Retrieves information from the server.</li><li><strong>POST</strong> — Creates a new resource.</li><li><strong>PUT</strong> — Replaces or updates an existing resource.</li><li><strong>PATCH</strong> — Partially updates an existing resource.</li><li><strong>DELETE</strong> — Removes a resource.</li></ul><p>Of course, APIs aren’t limited to REST. Other approaches and technologies include GraphQL and gRPC.</p><p>The important point is that <strong>APIs are not specific to artificial intelligence</strong>. Software systems have been communicating through APIs for years.</p><p>But when we want an AI model to use the capabilities exposed by an API, things work a little differently.</p><h3>2. What Is Function Calling, and What Problem Does It Solve?</h3><p>Let’s return to our online store.</p><p>This time, we want to add an AI assistant to the website so customers can ask questions about their orders in natural language.</p><p>For example, a customer writes:</p><p>“Hi, I’d like to know whether my order 1042 has been shipped yet.”</p><p>A language model such as GPT can easily understand the question.</p><p>But there’s a problem.</p><p>By default, GPT has no access to the store’s database and doesn’t know the actual status of the order.</p><p>So how can it provide an accurate answer?</p><p>This is where Function Calling comes in.</p><h3>Making Functions Available to the Model</h3><p>Suppose our application has the following function:</p><p>get_order_status(order_id)</p><p>Its job is to retrieve an order’s status from the store’s system.</p><p>With Function Calling, we can describe this function to the model, including its name, purpose, and input parameters.</p><p>In other words, we tell the model:</p><p>“There is a tool called get_order_status that checks the status of an order using its order number.&quot;</p><p>Now, when the customer asks about order 1042, the process looks like this:</p><ol><li>GPT analyzes the customer’s request.</li><li>It determines that the get_order_status tool is needed to answer the question.</li><li>It returns a tool-call request containing the tool name and the argument order_id = 1042.</li><li>Our application checks the relevant permissions and executes the function.</li><li>The function’s result is passed back to GPT.</li><li>GPT uses that real information to generate a response for the customer.</li></ol><p>For example:</p><p>“Yes, your order has been shipped.”</p><h3>An Important Point About Function Calling</h3><p>GPT does not directly connect to our database or execute our C#, Python, or JavaScript functions itself.</p><p><strong>The model indicates which tool should be used; our application is responsible for actually executing that tool.</strong></p><p>This distinction matters for both security and software architecture.</p><p>We still control which operations are allowed, which users have permission to perform them, and which information can be returned.</p><h3>How Function Calling Relates to AI Agents</h3><p>Now imagine the customer makes a more complex request:</p><p>“Check my order status, and if it hasn’t shipped yet, open a support ticket.”</p><p>This may require more than one tool:</p><p>get_order_status(order_id)</p><p>create_support_ticket(order_id, message)</p><p>An AI agent can use a language model to interpret the request, call the first tool, evaluate the result, and — if necessary and authorized — use the second tool.</p><p>Put simply, an agent isn’t just a language model. It’s a system that brings together the model, tools, and the logic that coordinates how tasks are carried out.</p><p>So far, <strong>everything we’ve discussed can be implemented without MCP</strong>.</p><p>And that’s exactly what led me to the central question:</p><p><strong>If Function Calling can already do all this, why do we need MCP?</strong></p><h3>3. What Is MCP, and Why Was It Created?</h3><p>MCP stands for <strong>Model Context Protocol</strong>.</p><p>MCP is an open standard that allows AI applications to connect to different tools and information sources through a common protocol.</p><p>To understand the idea, let’s go back to our online store.</p><p>Suppose our store has several tools:</p><ul><li>get_order_status to check an order&#39;s status</li><li>get_customer_invoices to retrieve invoices</li><li>create_support_ticket to open a support request</li></ul><p>With direct Function Calling, we can define these tools in our own agent application and connect them to the backend.</p><p>This is a perfectly valid approach, and it works well in many projects.</p><p>Now imagine that, in the future, we want to make the same tools available to several different AI applications.</p><p>For instance, we might have an AI agent built into our store, while a second AI application also needs access to the same capabilities.</p><p>At this point, you might be asking the same question I asked myself:</p><p><strong>Why not just give the second application access to the same functions and APIs?</strong></p><p>The answer is: <strong>we absolutely can. MCP is not required for that.</strong></p><p>If we’ve developed both agents ourselves, we can share the same business logic, functions, and APIs between them. We could even keep the tool definitions and backend integration code in a shared library, so we don’t have to duplicate them.</p><p>In other words, MCP does <strong>not</strong> solve the problem of making multiple agents use the same backend. That was already possible.</p><p>The distinction becomes more useful when we want to expose those tools to other AI applications — for example, an application we didn’t build ourselves, but one that supports MCP. Without a shared contract, we may need application-specific integrations or configurations to describe our tools, call them, and handle their results.</p><p><strong>MCP aims to simplify this part of the integration through a common standard.</strong> A compatible application can discover the tools a server exposes, read their descriptions and input specifications, and request their execution through a defined protocol.</p><p>Of course, MCP compatibility doesn’t eliminate every integration task. The host application still needs to support MCP, and the necessary configuration, permissions, and restrictions still have to be in place.</p><p>This is why MCP is sometimes compared to USB-C.</p><p>Just as USB-C provides a standardized interface for connecting different devices, MCP provides a shared contract for connecting AI applications with tools and information sources.</p><p>That analogy doesn’t mean every capability becomes identical or that all configuration work disappears.</p><h3>4. What Is an MCP Server?</h3><p>When I first came across the term <em>MCP Server</em>, I wondered whether it meant building a completely new backend — or even a separate AI service.</p><p>The idea is simpler than that.</p><p><strong>An MCP Server is an application or service that exposes a set of tools and capabilities to other applications through the MCP protocol.</strong></p><p>Let’s say we build an MCP Server for our online store.</p><p>It exposes these three tools:</p><p>get_order_status</p><p>get_customer_invoices</p><p>create_support_ticket</p><p>Each tool has a name, a description of what it does, and a specification of its input parameters.</p><p>An MCP-compatible application can connect to the server and retrieve the list of available tools.</p><p>If the application needs to check an order’s status, it sends a request to the MCP Server to invoke the appropriate tool.</p><p>The MCP Server receives the request, processes it, and returns the result.</p><p>Behind the scenes, the server might simply call the store’s existing API:</p><p>MCP Server → Store API → Backend → Database</p><p>So adopting MCP doesn’t mean we have to rewrite all the application’s business logic.</p><p>In many cases, an MCP Server simply adds a standardized integration layer on top of capabilities that already exist.</p><p>For example, the same order-status function could be called directly by the store’s internal agent and also exposed through an MCP Server to another compatible application. We don’t need two different implementations of the order-status logic.</p><p>The key point is that <strong>an MCP Server offers a standardized way to expose capabilities; it is not a prerequisite for reusing functions</strong>.</p><h3>Does an MCP Server Have to Run as a Separate Server?</h3><p>No.</p><p>The word <em>server</em> doesn’t necessarily imply a separate physical machine or VPS.</p><p>An MCP Server can be:</p><ul><li>A local application running on a computer</li><li>An independent network service</li><li>A component within a larger application</li></ul><p>What matters is that it supports the communication and operations defined by the MCP protocol.</p><h3>How Do We Implement an MCP Server?</h3><p>We don’t have to implement the protocol from scratch.</p><p>SDKs are available for different programming languages, handling much of the underlying communication for us.</p><p>For example, in the .NET ecosystem, we can use the ModelContextProtocol.AspNetCore package.</p><p>At a high level, a simple implementation involves:</p><ol><li>Adding MCP Server functionality to the application.</li><li>Defining and registering the tools we want to expose.</li><li>Configuring an MCP transport, such as HTTP.</li><li>Implementing authentication and access restrictions as needed.</li></ol><p>Once that’s done, compatible applications can communicate with the exposed tools through MCP.</p><p>What I found especially interesting was that an MCP Server doesn’t need to replace the existing backend. It can build on the capabilities the backend already provides.</p><h3>5. What Is an MCP Client?</h3><p>Now that we understand the MCP Server, the next question is:</p><p>Who connects to it and sends requests to execute its tools?</p><p>That’s where the MCP Client comes in.</p><p><strong>An MCP Client is the component of an application that manages communication with an MCP Server using the MCP protocol.</strong></p><p>Imagine we have an AI assistant that supports MCP.</p><p>The assistant uses a language model to understand user requests, while its host application includes an MCP Client.</p><p>The communication flow can be simplified as:</p><p>AI Agent → MCP Client → MCP Server → API</p><p>This is a simplified view. In practice, the MCP Client is usually a component within the application hosting the agent.</p><p>Importantly, <strong>an MCP Client is not the AI model itself</strong>, and having an MCP Client doesn’t mean the model directly connects to the MCP Server. The host application uses the client to discover tools, makes those tools available to the model, and manages requests to invoke the tool the model selects. This workflow can still use Function Calling.</p><h3>What Happens When a User Asks a Question?</h3><p>Suppose a customer writes:</p><p>“Show me my last three invoices.”</p><p>Here’s how a simplified workflow might look.</p><h4><strong>Step 1: Discovering the Tools</strong></h4><p>The MCP Client asks the MCP Server for its available tools.</p><p>MCP defines an operation called tools/list for this purpose.</p><p>The server returns the tool names, descriptions, and input specifications.</p><h4><strong>Step 2: The Model Chooses a Tool</strong></h4><p>The agent application makes the available tools known to the model.</p><p>The model determines that get_customer_invoices is suitable for answering the request.</p><h4><strong>Step 3: Requesting Execution</strong></h4><p>The application sends a tool invocation request to the MCP Server through its MCP Client.</p><p>In MCP, this operation is called tools/call.</p><h4><strong>Step 4: Executing the Operation</strong></h4><p>The MCP Server performs the necessary checks and executes the tool.</p><p>The tool might call an accounting API to retrieve the customer’s invoices.</p><h4><strong>Step 5: Generating the Answer</strong></h4><p>The result is returned to the agent application, and the model uses it to produce a clear response for the customer.</p><p>This makes it important to distinguish the roles involved:</p><ul><li><strong>Language model:</strong> Interprets the user’s request and selects an appropriate tool.</li><li><strong>Agent application:</strong> Coordinates the decision-making, tool execution, and response generation.</li><li><strong>MCP Client:</strong> Manages communication with the MCP Server.</li><li><strong>MCP Server:</strong> Exposes tools and processes requests to execute them.</li></ul><p>Understanding this separation of responsibilities was one of the things that helped MCP click for me.</p><h3>6. Is MCP Only About Calling Functions?</h3><p>No.</p><p>So far, we’ve focused mainly on tools because they’re the part of MCP most closely related to Function Calling.</p><p>But MCP supports other capabilities too.</p><p>Three important concepts exposed by an MCP Server are:</p><p><strong>Tools:</strong> Operations an AI application can invoke to perform tasks.</p><p><strong>Resources:</strong> Information and content that a server can make available, such as data or documentation.</p><p><strong>Prompts:</strong> Reusable prompt templates that an application can use for specific tasks.</p><p>So MCP is more than another way to call functions. It’s a broader standard for making capabilities and information available to AI applications.</p><h3>7. What Is the Difference Between Function Calling and MCP?</h3><p>For me, this was probably the most important takeaway from studying MCP.</p><p>At first, it may seem that Function Calling and MCP are competing approaches and that we have to choose one over the other.</p><p>But that’s not actually the case.</p><p><strong>Function Calling and MCP address different problems, and they can work together.</strong></p><p>Function Calling describes how a model requests the use of a tool and works with the result.</p><p>MCP defines a standard protocol through which applications can expose, discover, and invoke tools and resources.</p><p>Let’s compare two architectures.</p><h3>Architecture 1: Direct Function Calling</h3><p>Agent → Function → Backend</p><p>In this architecture, we define the tools directly in our agent application.</p><p>When the model requests a tool, our application executes the corresponding function.</p><p>This is a simple, practical approach for an internal agent with a known set of tools.</p><p>Even if we have two or more internal agents, we can keep using this approach: implement the shared functions and APIs once, then connect each agent to the same capabilities. <strong>The number of agents alone is not a sufficient reason to introduce MCP.</strong></p><h3>Architecture 2: Using MCP</h3><p>Agent → MCP Client → MCP Server → Backend</p><p>In this architecture, tools are exposed through an MCP Server.</p><p>The agent application can use its MCP Client to discover and invoke them.</p><p>The advantage becomes more apparent when we want to make the same set of tools available through <strong>a standardized contract</strong> to different, independent AI applications — especially those that already have MCP Clients and for which we don’t want to build custom integrations.</p><p>So the central difference isn’t whether functions can be shared. <strong>Both architectures allow that.</strong> The difference is <strong>how tools are exposed, discovered, and invoked through a common standard</strong>.</p><p>With direct integration, we typically decide how each agent gets access to tools and executes them. With MCP, we have a common protocol for that interaction. The model can still use Function Calling to select a tool, while the application remains responsible for carrying out the actual operation.</p><p>Of course, MCP doesn’t solve every integration problem on its own. We still need authentication, permission management, error handling, and sound API design. Supporting MCP also doesn’t guarantee automatic compatibility with every application or eliminate the need for configuration.</p><h3>8. When Should We Use APIs, Function Calling, or MCP?</h3><p>I don’t think we should choose a technology simply because it’s newer.</p><p>We should start with the actual problem our project needs to solve.</p><p><strong>If we want two software applications to communicate</strong>, an API is often the right solution.</p><p><strong>If we want an AI model to use a defined set of capabilities in our own application</strong>, direct Function Calling may be more than enough.</p><p>If we want to expose a system’s capabilities through a standardized interface to multiple AI applications, especially independent applications that support MCP, then MCP may offer real value.</p><p>Having an agent doesn’t automatically mean we need to build an MCP Server. Even having several agents doesn’t create that requirement by itself. We can share the same functions and APIs between them.</p><p>For many projects, especially in their early stages, direct Function Calling is simpler and avoids unnecessary complexity.</p><p>But when we need standardized tool exposure, discovery by other applications, or integration with independent AI software, MCP becomes a more attractive option.</p><p>The question I now ask when making this decision is:</p><p><strong>Do we genuinely need a standardized interface for different consumers, or does a direct, controlled integration already meet the project’s current needs?</strong></p><h3>9. Security: Something We Shouldn’t Overlook</h3><p>One principle applies to all these architectures:</p><p><strong>Just because an AI model selects a tool doesn’t mean it should be allowed to perform any operation it wants.</strong></p><p>Imagine an agent that can cancel orders or access customers’ financial information.</p><p>Whether we’re using direct Function Calling or MCP, our application must verify the user’s identity, access permissions, and relevant business rules before performing an operation.</p><p>Sensitive actions may also require explicit user confirmation.</p><p>MCP is a communication protocol, not a replacement for backend security or access control. Even if a tool can be discovered through a standardized interface, that alone doesn’t grant permission to execute it.</p><h3>10. Conclusion: Will MCP Replace APIs?</h3><p>The short answer is no.</p><p>APIs, Function Calling, and MCP each serve a distinct purpose.</p><ul><li><strong>APIs</strong> enable communication between software systems.</li><li><strong>Function Calling</strong> enables a language model to generate requests to use defined tools.</li><li><strong>MCP</strong> provides a common standard for exposing and consuming tools and information sources in AI applications.</li></ul><p>What became clear to me through this research is that MCP isn’t necessarily a replacement for an existing architecture.</p><p>If we already have a backend with well-defined APIs, we can implement Function Calling directly on top of those capabilities. The same functions and APIs can even be shared by multiple internal agents, without requiring an MCP Server.</p><p>If, later on, we need to expose those tools through a standard contract to other AI applications, we can add MCP to our architecture — without necessarily rewriting the underlying business logic.</p><p>So we shouldn’t adopt MCP simply because we have multiple agents. <strong>Its real value lies in standardizing how AI applications connect to tools and information sources.</strong></p><p>This distinction matters for the software project I’m currently developing as well: choosing an approach that fits today’s requirements while leaving room to grow in the future.</p><p>Perhaps the most important lesson I took from exploring MCP is this:</p><p><strong>In software architecture, newer doesn’t always mean better. The best choice is the one that solves the project’s actual problem with the least necessary complexity.</strong></p><p>I hope this article helps clarify the differences between APIs, Function Calling, and MCP.</p><p>If you’ve used MCP or Function Calling in your own projects, I’d love to hear about your experience in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7790fa9111c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can Blazor Server Scale to Thousands of SaaS Users? Lessons from a Real-World Architecture Review]]></title>
            <link>https://vahid-faraji-dev.medium.com/can-blazor-server-scale-to-thousands-of-saas-users-lessons-from-a-real-world-architecture-review-566f96e79773?source=rss-f3079f487992------2</link>
            <guid isPermaLink="false">https://medium.com/p/566f96e79773</guid>
            <category><![CDATA[blazor]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Vahid Faraji]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 10:47:36 GMT</pubDate>
            <atom:updated>2026-10-08T10:47:36.660Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why we’re preparing our .NET application for scale instead of rushing into a migration to React or Angular.</em></p><p>One of the most important questions in software development is: <strong>Will the technologies we choose today still support our product tomorrow?</strong></p><p>This becomes especially relevant when an application evolves from a relatively small internal system into a SaaS product intended to serve hundreds of organizations and thousands of users.</p><p>We’re currently developing a real-world application built on Microsoft’s .NET ecosystem:</p><p>· <strong>Frontend:</strong> Blazor Interactive Server</p><p>· <strong>Backend:</strong> ASP.NET Core Web API</p><p>· <strong>Database:</strong> MariaDB</p><p>· <strong>Containerization:</strong> Docker</p><p>· <strong>CI/CD:</strong> GitHub Actions</p><p>· <strong>Background processing:</strong> Hangfire, with PostgreSQL planned for job storage</p><p>As the product evolves, we’re evaluating how this architecture could serve a much larger audience. Our goal isn’t simply to handle more users. We want a system that remains secure, reliable, maintainable and cost-effective as the business grows.</p><p>This article explores the architectural questions we’re facing and why we’re not rushing into a frontend migration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WepONdwQ6SE2FYTOU2yLtw.png" /></figure><h3>1. Is Blazor Server the Wrong Choice for a Large SaaS Application?</h3><p>When developers discuss scalable SaaS applications, React, Angular and Vue often dominate the conversation. Blazor Server, meanwhile, is sometimes dismissed because it maintains a live connection between browser and server.</p><p>But does that automatically make it unsuitable? <strong>Not at all.</strong></p><p>Blazor Interactive Server executes interactive UI logic on the server and communicates with the browser using SignalR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*cAtrtlkqAg1gHB6e_9jsqA.png" /><figcaption><em>Figure 1 — In Interactive Server, UI events travel over SignalR while interactive state and C# execution remain on the server.</em></figcaption></figure><p>When a user clicks a button, the browser sends the event to the server, C# code executes there, Blazor computes the UI changes, and those changes return to the browser.</p><p>This brings genuine advantages: C# across the stack, natural ASP.NET Core integration, less custom JavaScript for many scenarios, shared models and validation, and productive development for form-heavy business applications.</p><p>There’s a cost, however: <strong>the server maintains interactive state for connected users.</strong> Blazor manages that state through a <em>Circuit</em>. Each Circuit can consume memory and other resources. As the number of concurrent connections grows, so can infrastructure requirements.</p><p>The real question isn’t simply whether Blazor Server scales. It’s whether the application has been designed to manage its Circuits, state and resources efficiently.</p><h3>2. What Does “Thousands of Users” Actually Mean?</h3><p>Registered users and concurrent users are not the same thing. Imagine 500 organizations with 20 users each: that’s 10,000 accounts, not necessarily 10,000 simultaneous connections.</p><p>Depending on work patterns, perhaps 1,000–2,000 users will be active during peak hours. And an open connection is not the same as an active workload: someone reading a dashboard is different from someone importing thousands of records.</p><p>Three metrics deserve separate attention:</p><p>· <strong>Concurrent connections:</strong> How many connections the application currently maintains.</p><p>· <strong>Active users:</strong> How many people perform operations in a defined time period.</p><p>· <strong>Requests per second:</strong> How much traffic the backend processes.</p><p>For Blazor Interactive Server, <strong>memory consumption per Circuit</strong> is a critical factor in scalability.</p><p>According to Microsoft’s official documentation, a minimal Hello World-style application consumes approximately <strong>250 KB per Circuit</strong>, with a baseline estimate of around <strong>1.3 GB of server memory for 5,000 concurrent users</strong>.</p><p>However, these figures represent a minimal application, not a production SaaS environment. Real-world memory consumption can be significantly higher depending on component complexity, retained state, dependency injection lifetimes, and disconnected Circuits.</p><p>Therefore, rather than relying on theoretical estimates, <strong>we plan to validate our application’s scalability through realistic load testing</strong>, measuring memory usage, CPU utilization, connection stability, and overall performance under increasing user loads.</p><p><strong>Before changing frameworks out of concern for future scale, we should measure the actual application.</strong></p><h3>3. Would Blazor WebAssembly Be Better?</h3><p>One option we’re evaluating is Blazor WebAssembly. The primary distinction is where UI logic executes.</p><p>Interactive Server runs that logic on the server. WebAssembly runs C# UI code inside the browser and calls backend APIs as needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*AdmKme3W9eB7D8YB38H0AQ.png" /><figcaption><em>Figure 2 — WebAssembly executes interactive C# UI code in the browser and accesses backend services through APIs.</em></figcaption></figure><p>WebAssembly doesn’t need a server-side Blazor Circuit for ordinary client-side interactions. That can reduce server memory pressure for UI state. But it brings other trade-offs: larger first downloads, client CPU and memory usage, a greater dependency on API design, and more care around browser-side authentication and security.</p><p>So should we move? <strong>We don’t believe a migration is justified yet.</strong> Rewriting a functioning frontend creates testing costs, maintenance risk, potential regressions and new architecture decisions.</p><p>A hybrid architecture remains possible: Interactive Server for internal administration, with WebAssembly for selected high-traffic customer features. A clean ASP.NET Core API makes that feasible without rewriting business logic.</p><h3>4. The More Important Challenge: Multi-Tenancy</h3><p>A larger architectural issue emerged during our review: <strong>How can hundreds of independent organizations use one application without exposing their data to one another?</strong></p><p>That’s the core of multi-tenancy. A <em>tenant</em> represents an independently governed customer boundary, potentially with its own users, permissions, settings and data.</p><p>If two organizations share a CRM platform, neither should be able to access the other’s contacts, reports or documents. This isolation must be enforced on the backend, not merely hidden in the interface.</p><p>A shared database with a tenant identifier is one common design:</p><p>SELECT *</p><p>FROM contacts</p><p>WHERE tenant_id = @TenantId;</p><p>But adding a WHERE clause isn’t sufficient. Authorization, write operations, file storage, cache keys, reporting pipelines and background jobs must all be tenant-aware. Tenant identity should come from authenticated and authorized server-side context, never just a browser-supplied identifier.</p><p>Our domain already contains organizational structures such as Holdings and Businesses. We need to decide whether Tenant should be a separate boundary or map to an existing concept. That depends on the commercial model and whether a user might belong to several organizations.</p><p><strong>Designing tenant isolation before onboarding independent customers is a more urgent priority than changing the frontend framework.</strong></p><h3>5. Scalability Is More Than a Frontend Problem</h3><p>Migrating to React or WebAssembly doesn’t magically solve backend bottlenecks. Thousands of users can still overload poorly designed database queries, APIs or long-running processes.</p><h3>Database efficiency</h3><p>We need suitable indexes, server-side pagination, connection pooling, short transactions, efficient queries and careful analysis of N+1 access patterns. In multi-tenant systems, indexes should match common tenant-scoped filtering and sorting patterns.</p><h3>A frontend-independent backend</h3><p>One architectural advantage we already have is an independent ASP.NET Core Web API. It means we can add another frontend or mobile client later without having to rewrite the core business logic.</p><h3>Background jobs</h3><p>Generating large reports, sending messages and importing records shouldn’t unnecessarily occupy interactive UI resources. We’re planning background processing with Hangfire, using PostgreSQL for its job storage. Workers can eventually be scaled independently from the API and UI.</p><h3>6. Docker and Horizontal Scaling</h3><p>We deploy with Docker and GitHub Actions. That’s a solid operational foundation, but containerization alone does not create scalability.</p><p>When a single application instance reaches capacity, we can run multiple API and UI replicas behind a reverse proxy or load balancer. Stateless APIs are usually easier to distribute.</p><p>Blazor Interactive Server needs additional planning because a user’s Circuit lives in the memory of a specific application instance. Multi-server deployments therefore require the right connection routing and session-affinity strategy. Shared Data Protection keys, WebSocket handling, reconnection behavior and health checks also matter.</p><p>Azure SignalR Service may help manage large numbers of connections, but it doesn’t eliminate the CPU and memory required by application Circuits. Likewise, adding Redis or a load balancer isn’t a substitute for understanding Circuit placement and lifecycle.</p><p>We also don’t need Kubernetes simply because we’re discussing SaaS. Docker and a carefully managed deployment architecture can remain appropriate until actual scale and operational demands justify more complexity.</p><h3>7. Why We’re Not Migrating Yet</h3><p>New frameworks can be tempting, but adopting a new technology does not automatically create business value.</p><p>A move from Blazor Server to React or Angular would require us to rebuild working features while introducing new testing, training and maintenance obligations.</p><p>Instead, we’ve prioritized four steps:</p><p>1. Design tenant boundaries, authorization and data isolation.</p><p>2. Reduce unnecessary memory retention and state inside Blazor Circuits.</p><p>3. Measure real workloads through load testing.</p><p>4. Expand infrastructure only when the evidence justifies it.</p><p>We’re considering test scenarios with 100, 500, 1,000 and 5,000 concurrent connections. Success won’t be measured by connection count alone; we’ll examine RAM, CPU, response latency, active Circuits, error rates and database performance.</p><p>These are <strong>planned tests</strong>, not previously completed benchmarks. We don’t yet claim a measured capacity figure.</p><h3>8. Conclusion: Architecture Matters More Than Framework Loyalty</h3><p>Our review has reinforced a straightforward lesson: <strong>Scalability doesn’t come automatically from choosing React, Angular, Blazor or Kubernetes.</strong></p><p>It comes from a set of good decisions about application state, data isolation, performance, security, background processing, monitoring and infrastructure.</p><p>Blazor Interactive Server has real costs, including live connections, Circuit memory and network sensitivity. It also offers valuable advantages for a .NET-focused team building complex business software.</p><p>For our real-world project, we’re retaining Blazor Server while preparing the system for future growth. That isn’t a permanent commitment. If production metrics eventually demonstrate that WebAssembly or another frontend architecture provides a measurable advantage, we’ll reconsider.</p><p><strong>Our goal isn’t to defend a framework. It’s to build a product that can grow without forcing us to rewrite everything at every stage.</strong></p><p>Before redesigning a system out of fear of tomorrow, we should establish exactly what limits its growth today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=566f96e79773" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI-Generated Code Is Not Automatically Correct or Optimized]]></title>
            <link>https://vahid-faraji-dev.medium.com/ai-generated-code-is-not-automatically-correct-or-optimized-044b3f161d1d?source=rss-f3079f487992------2</link>
            <guid isPermaLink="false">https://medium.com/p/044b3f161d1d</guid>
            <category><![CDATA[ai-generated-code]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database-query]]></category>
            <category><![CDATA[database-performance]]></category>
            <dc:creator><![CDATA[Vahid Faraji]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 09:48:47 GMT</pubDate>
            <atom:updated>2026-10-03T10:00:17.934Z</atom:updated>
            <content:encoded><![CDATA[<p>In one of my recent projects, I ran into an important lesson that I think is worth sharing:</p><p>AI can generate code quickly, suggest structures, and produce solutions that look perfectly reasonable at first glance. But that does not mean the generated solution is automatically the best one for a real production system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vq7Ji1GQgx7MjspxeSXtPA.png" /></figure><h3>A Real-World Example</h3><p>In one reporting component, I needed to calculate several different KPIs from a shared set of operational data.</p><p>An initial solution was to execute a separate database query for each KPI.</p><p>From a functional perspective, there was nothing wrong with that approach. Each query had a clear responsibility, the code was readable, and the results were correct.</p><p>But after looking at the problem more carefully, it became clear that most of those queries were working on almost the same underlying dataset.</p><p>That meant the application was repeatedly doing the same kind of work:</p><ul><li>accessing the database</li><li>executing another query</li><li>processing another result set</li><li>sending another result back to the application</li></ul><p>At that point, the issue was no longer correctness.</p><p>The issue was unnecessary database round trips.</p><h3>Changing the Approach</h3><p>Instead of executing multiple independent queries, I changed the design so that the required reporting data was loaded once with a single database query.</p><p>After that, calculations such as Count, GroupBy, distributions, percentages, and other KPIs were performed in application memory.</p><p>The overall flow became:</p><pre>Database<br>   ↓<br>One Query<br>   ↓<br>Required Report Data<br>   ↓<br>Application Memory<br>   ↓<br>Count / GroupBy / Percentage / KPI Calculations</pre><p>This had several advantages:</p><ul><li>fewer database round trips</li><li>multiple calculations could reuse the same dataset</li><li>reporting logic became more centralized and easier to understand</li><li>less unnecessary pressure on database connections</li><li>data that had already been loaded was not requested again</li></ul><p>This was a relatively small architectural change, but it made the data flow much cleaner.</p><h3>But Moving Data Into Memory Is Not Always Better</h3><p>This is where engineering judgment becomes important.</p><p>Loading data into application memory is not automatically the best solution either.</p><p>If the result set becomes very large, moving everything into RAM can introduce a different set of problems:</p><ul><li>higher memory consumption</li><li>increased network traffic</li><li>more work on the application server</li><li>reduced scalability</li></ul><p>So this approach only makes sense when the dataset is reasonably bounded and multiple calculations need to be performed on the same data.</p><p>For very large datasets, pushing aggregation back into the database may still be the better design.</p><p>The important point is not that one approach is universally better.</p><p>The important point is understanding the trade-off.</p><h3>Knowing About a Cache Is Not the Same as Using It Correctly</h3><p>There was another interesting part of this experience.</p><p>The reporting logic also needed several pieces of reference data: values such as categories, statuses, and other relatively static lookup information.</p><p>The system already had a cache-backed provider for this data.</p><p>AI was aware of that architecture.</p><p>Still, in several earlier suggestions, it continued to query those reference values directly from the database.</p><p>Technically, the code still worked.</p><p>Architecturally, however, it was the wrong path.</p><p>If a system intentionally has a caching layer for reference data, bypassing that layer and querying the database directly introduces unnecessary complexity.</p><p>It can lead to:</p><ul><li>unnecessary database queries</li><li>reduced benefit from the existing cache</li><li>multiple access paths for the same type of data</li><li>less predictable application behavior</li><li>harder maintenance over time</li></ul><p>That was an important reminder for me:</p><p><strong>Knowing the context is not the same as applying the context correctly.</strong></p><p>An AI model may already know that a cache exists, but that does not guarantee that every generated solution will consistently respect that architectural decision.</p><h3>Why This Matters</h3><p>Imagine a piece of reference data that changes rarely and is already available through a cache.</p><p>You effectively have two options:</p><pre>Option A<br><br>Application<br>   ↓<br>Cache<br>   ↓<br>Result</pre><pre>Option B<br><br>Application<br>   ↓<br>Database<br>   ↓<br>Query<br>   ↓<br>Result</pre><p>If the caching layer was specifically designed for this type of data, the second path is simply unnecessary.</p><p>One additional query may look insignificant in isolation.</p><p>But production systems are rarely affected by one isolated query.</p><p>They are affected by the accumulation of small decisions across hundreds or thousands of requests.</p><h3>Optimization Without Understanding the Domain Can Also Be Dangerous</h3><p>Another concern came up during the same work:</p><p>Could the joins in the reporting query generate duplicate rows and therefore produce incorrect statistics?</p><p>Looking only at the query itself, that is a reasonable concern.</p><p>But the query alone does not contain enough information to answer the question.</p><p>You also need to understand the database model, relationships, and constraints.</p><p>If the database guarantees uniqueness for the relevant relationships, adding an extra Distinct &quot;just to be safe&quot; may be completely unnecessary.</p><p>This is an important engineering lesson.</p><p>Even a suggestion that appears safer can add complexity when it is made without understanding the actual schema.</p><p>The correct answer depends on the system, not just on the visible query.</p><h3>A Production System Is More Than Its Code</h3><p>AI usually works with the information available in the prompt or context.</p><p>But production engineering decisions depend on much more than the code directly in front of us.</p><p>For example:</p><ul><li>actual data volume</li><li>indexes</li><li>unique constraints</li><li>relationship cardinality</li><li>number of concurrent users</li><li>query execution frequency</li><li>cache strategy</li><li>where aggregation should happen</li><li>cost of database round trips</li><li>application server capacity</li><li>future data growth</li></ul><p>Even when some of this information has already been provided to an AI system, it is still worth checking whether the proposed solution actually uses that information correctly.</p><p>This is especially important with performance-related decisions.</p><p>A piece of code can be syntactically correct, logically correct, and still be inefficient for the architecture it runs in.</p><h3>The Bigger Lesson</h3><p>I do not think the most useful question to ask AI during software development is:</p><blockquote><em>“What is the correct code?”</em></blockquote><p>A better question is:</p><blockquote><em>“Why are you recommending this solution, and what assumptions are you making?”</em></blockquote><p>Once those assumptions become visible, they can be compared against the real architecture.</p><p>That is where engineering judgment becomes valuable.</p><p>AI is an extremely powerful development tool. It can accelerate implementation, review alternatives, detect patterns, and reduce repetitive work.</p><p>But architecture, context, and final technical decisions still require human ownership.</p><p>Sometimes the best optimization is not writing more sophisticated code.</p><p>Sometimes it is simply understanding the system better and using the capabilities that already exist in the architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=044b3f161d1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async/Await Does Not Mean Background Processing: The Misconception Delaying Your APIs]]></title>
            <link>https://vahid-faraji-dev.medium.com/async-await-does-not-mean-background-processing-the-misconception-delaying-your-apis-3686e26662ab?source=rss-f3079f487992------2</link>
            <guid isPermaLink="false">https://medium.com/p/3686e26662ab</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[thread-pool]]></category>
            <category><![CDATA[background-processing]]></category>
            <category><![CDATA[run-task]]></category>
            <dc:creator><![CDATA[Vahid Faraji]]></dc:creator>
            <pubDate>Sun, 13 Sep 2026 12:35:21 GMT</pubDate>
            <atom:updated>2026-09-13T13:01:42.285Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most common misunderstandings in the world of backend development is confusing <strong>asynchronous I/O</strong> with <strong>Background Processing</strong>.</p><p>Some developers write heavy tasks such as calling AI, sending emails, or generating PDF files using async/await and expect the API to respond immediately while the task is performed in the background. However, when they test it, they see that the HTTP request still waits for several seconds!</p><p>Why does this happen? Doesn’t &quot;async&quot; mean asynchronous?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WElaz3HdYsRKZAvcqjxyyw.png" /></figure><h3>1. The Main Difference: Thread Liberation vs. Response Liberation</h3><p>To understand this, we need to separate two distinct concepts:</p><ol><li><strong>Server Resource Management (Thread Utilization)</strong></li><li><strong>User Request Execution Flow (Execution Flow)</strong></li></ol><p>When we write code like this:</p><pre>await aiService.AnalyzeMessageAsync(lead.Message);</pre><h4>A) From the Thread and CPU Perspective (Reducing Server Occupancy)</h4><p>The await keyword tells the system Runtime:</p><p><em>“I have started a network (I/O) operation with Azure OpenAI that takes 5 seconds. During these 5 seconds, do not keep the current thread waiting; release it so it can process requests from other users. When the network response comes back, bring another thread to continue executing the code.”</em></p><p>This is called <strong>non-blocking I/O</strong>. The purpose of this is <strong>increasing server throughput (scalability)</strong> so it can respond to more concurrent users, not reducing the waiting time for this particular user.</p><h4>B) From the User and Browser Perspective (Response)</h4><p>Although the server thread has been released, the code after the await will <strong>not execute</strong> until the Azure response comes back. As a result, the return OK() instruction is not executed, and the <strong>HTTP response does not reach the user/browser.</strong></p><p>The user still has to wait 5 seconds.</p><h3>2. The Restaurant Example (An Intuitive View)</h3><p>Imagine a restaurant operating in <strong>4 different modes</strong>:</p><ul><li><strong>Mode 1: Synchronous (Blocking)</strong></li></ul><p>The waiter takes your pizza order, goes to the kitchen, and stands in front of the oven for 15 minutes waiting for the pizza to bake. During this time, they do not serve any other customer.</p><p><em>(Very poor server efficiency).</em></p><ul><li><strong>Mode 2: Async with await (non-blocking)</strong></li></ul><p>The waiter gives the order to the kitchen and, during the 15 minutes while the pizza is baking, goes and serves 20 other customers. However, <strong>you are still sitting in your chair and cannot leave the restaurant until the pizza arrives at your table.</strong></p><p><em>(The server is managed very efficiently, but the user’s waiting time has not changed).</em></p><ul><li><strong>Mode 3: Task. Run / Fire-and-Forget</strong></li></ul><p>The waiter gives your order to the kitchen, immediately tells you that your pizza is ready to be prepared, and lets you leave. However, the waiter does not give the kitchen a reliable ticket or tracking system.</p><p>The waiter tells the kitchen to prepare your pizza and immediately lets you leave. However, there is no reliable system to make sure the order continues to be processed.</p><p>If the restaurant suddenly closes or the kitchen stops working, your order may simply disappear. You already left the restaurant believing that everything was handled successfully.</p><p><em>(Fast response, but unreliable background processing and possible data loss).</em></p><ul><li><strong>Mode 4: Background Task / Queue (True Background Processing)</strong></li></ul><p>You place your order, and the waiter immediately gives you a receipt and says, “Your<strong> order has been registered. You can leave. When it is ready, we will send it with a delivery driver.”</strong></p><p>You leave the restaurant in under 5 seconds (<strong>reduced user latency</strong>). The kitchen continues working in the background, and the order is tracked so that it can be retried or recovered if something goes wrong.</p><p>The difference from Mode 3 is that this time, the waiter does not simply tell the kitchen to prepare the pizza and then forget about it. The order is officially registered, so the restaurant knows that the pizza still needs to be prepared. If the kitchen has a problem, another worker can pick up the order and prepare it later.</p><p><em>(Fast response, reliable background processing, and proper failure handling).</em></p><h3>3. Example with C# / .NET — Code Review</h3><p>Suppose we want to register a new Lead in a CRM system and send its text to Azure OpenAI for sentiment analysis.</p><h3>Pattern One:</h3><pre>// Synchronous Blocking (Worst case for server Scalability)<br>[HttpPost]<br>public IActionResult CreateLead([FromBody] CreateLeadDto dto)<br>{<br>    var lead = new Lead { Message = dto.Message };<br>    // 1. Blocking the<br>    // Thread for saving to the database<br>    _dbContext.Leads.Add(lead);<br>    _dbContext.SaveChanges();<br>    // 2. ❌<br>    // Completely blocking the server Thread for 3 to<br>    // 10 seconds for AI<br>    // The method executes in Blocking mode<br>    // and the Thread waits doing nothing<br>    var aiResult = _aiService.Analyze(lead.Message);<br>    lead.Sentiment = aiResult.Sentiment;<br>    _dbContext.SaveChanges();<br>    return Ok(lead);<br>    // User waits + the server Thread was also locked!<br>}</pre><p>This is the most basic and vulnerable implementation approach in web programming. In this code, all methods such as SaveChanges() or Analyze() are called <strong>synchronously </strong>(without the await keyword). When the client sends a request to this API, the following happens:</p><h4>1. How the Server Thread Behaves (Complete Lock)</h4><p>When the HTTP request enters the server, the server’s <strong>thread pool assigns</strong> a dedicated thread (for example, Thread #12) to this request.</p><p>When the code reaches _aiService.Analyze(...), the network call to the AI service begins. This call takes, for example, 5 seconds.</p><p>During all of these 5 seconds, <strong>Thread #12 becomes completely locked (blocked),</strong> meaning this thread sits idle on the server waiting and <strong>cannot do anything else</strong>.</p><h4>2. What Happens to Server Scalability?</h4><p>The number of active Threads on each server is limited (for example, 100).</p><p>If 100 users simultaneously send requests to this endpoint, 100 server threads become locked.</p><p>If user 101 sends a simple request at the same moment (such as viewing a text page), the server no longer has a free thread to process their request!</p><p>A phenomenon called <strong>&quot;thread pool starvation&quot; </strong>occurs. The server starts rejecting requests and returns the <strong>HTTP 503 Service Unavailable</strong> error or completely <strong>crashes</strong>.</p><h3>Pattern Two: Async but Still Waiting (Slow Response)</h3><pre>[HttpPost]<br>public async Task&lt;IActionResult&gt; CreateLead([FromBody] CreateLeadDto dto)<br>{<br>    var lead = new Lead { Message = dto.Message };<br>    await _dbContext.Leads.AddAsync(lead);<br>    await _dbContext.SaveChangesAsync();<br>    // ❌ This line blocks the HTTP request for 3<br>    // to 10 seconds!<br>    var aiResult = await _aiService.AnalyzeAsync(lead.Message);<br>    lead.Sentiment = aiResult.Sentiment;<br>    await _dbContext.SaveChangesAsync();<br>    return Ok(lead); // User waits for the AI response!<br>}</pre><p><strong>Result:</strong> Response time = Database save (20 ms) + AI (4000 ms) = <strong>approximately 4 seconds of delay!</strong></p><h4>What is the difference between this code (sync) and the code in the pattern (async with await)?</h4><p>In both cases, <strong>the user waits 3 to 10 seconds.</strong> But the difference is what happens behind the scenes on the server:</p><ol><li><strong>In the Sync code above:</strong></li></ol><p>The server thread that received the request, for example, Thread #1, is completely <strong>blocked</strong> for 10 seconds and cannot process other requests during that time. If 100 users send requests simultaneously, 100 server threads become blocked, potentially leading to <strong>thread pool starvation</strong>. As a result, new requests may have to wait for an available thread and can eventually fail with a <strong>503 Service Unavailable</strong> error or a timeout.</p><p><strong>2. In the async code():</strong></p><p>Thread number 1 is released during those 10 seconds so that it can respond to other users. The server does not crash, and other users can continue working, but <strong>this particular user</strong> still has to wait the same 10 seconds for the response.</p><p>The thread handling the request is released during those 10 seconds, allowing it to process other requests. When the AI response arrives, a thread from the ThreadPool can resume the execution. The server can continue processing other users, but <strong>this particular user</strong> still has to wait the same 10 seconds for the response.</p><p><em>In ASP.NET Core / .NET, when execution reaches </em><em>await, the current thread is released. Once the I/O operation completes, the continuation of the method runs on a ThreadPool thread. This thread can be</em></p><ul><li><em>The </em><strong><em>same thread</em></strong><em> as before, or</em></li><li><em>A </em><strong><em>different thread</em></strong><em> from the ThreadPool.</em></li></ul><h3>Pattern Three: Dangerous Mistake — Task.Run (Fire-and-Forget)</h3><p>Some developers remove await to escape the high delay:</p><pre>// ❌ This is dangerous in Production!<br>[HttpPost]<br>public async Task&lt;IActionResult&gt; CreateLead([FromBody] CreateLeadDto dto)<br>{<br>    var lead = new Lead { Message = dto.Message };<br>    await _dbContext.Leads.AddAsync(lead);<br>    await _dbContext.SaveChangesAsync();<br>    // Uncontrolled execution<br>    // in the background<br>    Task.Run(async () =&gt; {<br>        var result = await _aiService.AnalyzeAsync(lead.Message);<br>        // Save result...<br>    });<br>    return Ok(lead); // Returns quickly, but...<br>}</pre><h4>Why is this not a good pattern?</h4><p>Task.Run starts the work in the background, but the application does not reliably manage that work. The HTTP request returns successfully while the task is still running.</p><p>If the API process restarts, or crashes, or the IIS app pool is recycled before the task finishes, the task is terminated and the remaining work is lost. There is <strong>no guaranteed retry, persistence, or reliable way to track whether the operation was completed successfully</strong></p><h4>Comparison of Pattern Two and Three:</h4><p><strong>(await directly in Controller):</strong></p><pre>var aiResult = await _aiService.AnalyzeAsync(lead.Message);</pre><p>In this case, the HTTP connection between the user and the server is <strong>open and alive</strong>.</p><ul><li><strong>If the server restarts or crashes:</strong> The user’s HTTP connection is terminated, and the browser immediately receives a <strong>502 Bad Gateway</strong> or <strong>504 Gateway Timeout</strong> or <strong>Connection Reset</strong> error.</li><li><strong>Result for the user:</strong> The user or client realizes that their request has <strong>failed</strong>. Therefore, the client can activate its <strong>auto-retry </strong>mechanism and resend the Lead creation request. “Client” does not necessarily mean the user. It refers to the software that sends the HTTP request to the API and receives the response.</li></ul><p><strong>(Task.Run / Fire-and-Forget):</strong></p><pre>Task.Run(async () =&gt; {<br>     var result = await _aiService.AnalyzeAsync(lead.Message);<br>     // ...<br>});<br>return Ok(lead); // 👈 This is where the problem is!</pre><p>In this case, the code <strong>immediately</strong> returns the 200 OK response to the user, and the HTTP connection is closed.</p><ul><li><strong>From the user’s perspective:</strong> The user receives the message “Lead registered successfully” (HTTP 200) and is reassured that everything went correctly.</li><li><strong>If the App Pool restarts 1 second later or an Unhandled Exception occurs:</strong> The processing inside Task.Run dies and is destroyed without sending any response!</li><li><strong>Result for the user:</strong> The user thinks the AI analysis will be performed, while the processing has evaporated from the server’s RAM! Nobody (neither the client nor the server) knows that this work was abandoned halfway because the server had already told the user, “Everything was OK!”</li></ul><h4>Summary of the Difference:</h4><ol><li><strong>(await):</strong> If the server crashes, a <strong>clear error is returned to the user</strong> (User/Client knows it failed).</li><li><strong>(Task.Run):</strong> The user is <strong>lied to</strong>; the server says the work was completed (200 OK), but later the background work is completely destroyed without the user having any idea about it (Silent Failure).</li></ol><h3>Pattern Four: Standard Architecture (Background Worker / Queue)</h3><p>The correct approach is to completely separate receiving the request from heavy processing:</p><pre>// 1. The API responds quickly (approximately 15<br>// milliseconds)<br>[HttpPost]<br>public async Task&lt;IActionResult&gt; CreateLead([FromBody] CreateLeadDto dto)<br>{<br>    var lead = new Lead { Message = dto.Message };<br>    await _dbContext.Leads.AddAsync(lead);<br>    await _dbContext.SaveChangesAsync();<br>    // Putting a<br>    // Job into the background queue (Channel or Queue)<br>    await _backgroundQueue.EnqueueAsync(new<br>    AnalyzeLeadJob(lead.Id));<br>    return Accepted(new { lead.Id, Status = &quot;Processing&quot; });<br>}</pre><pre><br>// 2. Processing is performed in a separate Background Service<br>public class LeadAiWorker : BackgroundService<br>{<br>    protected override async Task ExecuteAsync(CancellationToken<br>    stoppingToken)<br>    {<br>        await foreach (var jobId in<br>        _backgroundQueue.ReadAllAsync(stoppingToken))<br>        {<br>            // All<br>            // possible errors, Retry and the 3<br>            // to 10 second AI processing<br>            // are handled in the background<br>            // without making the user wait.<br>            await ProcessAiAnalysisAsync(jobId);<br>        }<br>    }<br>}</pre><p>The LeadAiWorker continuously waits for new jobs in the queue and processes them independently of the original HTTP request. The API can therefore return a response immediately, while the AI analysis continues in the background without keeping the user waiting.</p><h3>Comparison at a Glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQZs8Oa-Y2G7TSsvY9D8ow.png" /></figure><h3>Conclusion</h3><ol><li><strong>async/await is for optimizing server resources:</strong> This capability allows your server to respond to more users with fewer threads, but it does not make the method execution time zero.</li><li><strong>await prevents the response from being returned:</strong> Until an await completes, the response does not return.</li><li><strong>Move unnecessary heavy tasks to a queue:</strong> If the user does not need to see the result of the work (such as sending an email or performing AI analysis) immediately on the page, completely separate it from the HTTP request flow.</li></ol><p>I hope you found this topic interesting and useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3686e26662ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Burning Tokens: When Software Should Be Code, Not AI]]></title>
            <link>https://vahid-faraji-dev.medium.com/stop-burning-tokens-when-software-should-be-code-not-ai-fee72a935a63?source=rss-f3079f487992------2</link>
            <guid isPermaLink="false">https://medium.com/p/fee72a935a63</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[non-deterministic]]></category>
            <category><![CDATA[ai-token-usage]]></category>
            <category><![CDATA[deterministic]]></category>
            <dc:creator><![CDATA[Vahid Faraji]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 22:49:21 GMT</pubDate>
            <atom:updated>2026-09-11T22:49:21.719Z</atom:updated>
            <content:encoded><![CDATA[<p>These days, we almost have a ready-made answer for every problem:</p><p><strong>“Give it to AI.”</strong></p><p>Need to process some files? AI.</p><p>Need to analyze some data? AI.</p><p>Need to build a workflow? AI Agent.</p><p>Need to connect several APIs? Agentic Workflow.</p><p>Sometimes, even a task that could be solved with a simple script and a few lines of code gets turned into a prompt, an agent, several tools, and multiple calls to an LLM — and a lot of tokens get burned.</p><p>But there is an important question we should ask:</p><p><strong>Do we actually need AI for the scenario we are dealing with?</strong></p><p>Or are we just <strong>burning tokens and money?</strong></p><p>I have been thinking about where AI should be used and where it should not. Let’s look at a few examples and scenarios together.</p><p>Some of these examples may look similar. That is intentional. I deliberately repeat the same idea from different perspectives so that the distinction becomes clear and really sticks with us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*NlYWpPbnerM1XbN11t7LKA.png" /></figure><h3><strong>Before Using AI, Let’s Ask a Simple Question</strong></h3><p>In my opinion, before introducing AI into a workflow, we should ask ourselves two questions:</p><p><strong>Does the output of this decision need to be certain?</strong></p><p>And:</p><p><strong>Does that certainty matter to us?</strong></p><p>The answers can simplify many architectural decisions.</p><p>If a decision must always produce a specific result for a specific input, AI is probably not the right place for it.</p><p>If the output inherently requires interpretation, ambiguity, context, or judgment, AI can be extremely useful.</p><h3>Deterministic or Non-Deterministic?</h3><p>Imagine an online store has a simple business rule:</p><p>If a customer’s total purchase amount is greater than €1,000, the customer is considered a VIP.</p><p>This is a completely <strong>deterministic</strong> rule.</p><p>If the customer’s total purchase amount is €1,250, the answer should always be:</p><p>VIP = true</p><p>What do we actually need AI for here?</p><p>We can simply write:</p><pre>if (customer.TotalPurchase &gt; 1000)<br>{<br>    customer.IsVip = true;<br>}</pre><p>It is fast.</p><p>It is testable.</p><p>It is predictable.</p><p>Its execution cost is negligible.</p><p>And most importantly, the logic is deterministic.</p><p>Now imagine giving the same rule to an LLM:</p><blockquote><em>“Analyze the customer information and determine whether this customer should be considered VIP.”</em></blockquote><p>We have given a <strong>certain problem</strong> to a <strong>probabilistic system</strong>.</p><p>Even if the model is correct 99.9% of the time, the question is:</p><p><strong>Why introduce the possibility of an error into something we can execute with certainty using code?</strong></p><h3>A Small Error Can Become a Big Cost</h3><p>Someone might say:</p><blockquote><em>“Well, the model usually gives the correct answer.”</em></blockquote><p>The problem is the word <strong>usually</strong>.</p><p>In a real system, it does not matter only what happens once.</p><p>What matters is how many times the system runs.</p><p>Suppose a company processes 100,000 operations per day.</p><p>If an AI-based system has an error rate of only <strong>0.1%</strong>, that means approximately:</p><p><strong>100 errors per day.</strong></p><p>Now suppose each error requires only 30 minutes of human work to investigate and correct.</p><p>That becomes approximately:</p><p><strong>50 working hours.</strong></p><p>And that is only the cost of human effort.</p><p>An error could cause:</p><ul><li>The wrong workflow to execute</li><li>Incorrect data to be stored</li><li>An API to be called again unnecessarily</li><li>The wrong email to be sent</li><li>An order to be processed incorrectly</li><li>A task to be performed again</li><li>The team to spend time debugging</li><li>A customer to require support or correction</li></ul><p>So the cost of AI is not just <strong>token cost</strong>.</p><p>The real cost can also include <strong>time, infrastructure, latency, maintenance, support, and business errors</strong>.</p><h3>Deterministic Business Logic Should Be in Code</h3><p>In my opinion, this is one of the most important architectural principles when building AI-powered systems:</p><h4><strong>If business logic is deterministic, testable, and enforceable, it should be in code — not in a prompt or instructions.</strong></h4><p>Suppose a company’s rule is:</p><p>If an order has not been paid, it must not be shipped.</p><p>This should not exist only inside an agent’s prompt:</p><blockquote><em>If the order has not been paid,<br>do not allow shipping.</em></blockquote><p>That is a <strong>business rule</strong>.</p><p>Therefore, it should be enforced by the system:</p><pre>if (order.Status != OrderStatus.Paid)<br>{<br>    return ShippingResult.Blocked;<br>}</pre><p>A prompt can tell AI what to <strong>analyze</strong>.</p><p>But it should not replace business logic.</p><p>Because if a rule genuinely must be correct, it is better to enforce it with something we can test and control precisely.</p><h3>What Is AI Actually Good At?</h3><p>Now let’s change the scenario.</p><p>A customer writes:</p><blockquote><em>“I’ve bought from you several times and I’ve always been happy, but my last order was really disappointing. If this problem isn’t resolved, I probably won’t buy from you again.”</em></blockquote><p>Now ask:</p><p><strong>Is the customer dissatisfied?</strong></p><p><strong>Is the customer likely to churn?</strong></p><p><strong>What is their intent?</strong></p><p>We no longer have a simple if statement.</p><p>We are dealing with:</p><ul><li>Language</li><li>Context</li><li>Intent</li><li>Sentiment</li><li>Ambiguity</li><li>Interpretation</li></ul><p>This is where AI can provide real value.</p><p>For example, AI could produce a structured output like:</p><pre>{<br>  &quot;intent&quot;: &quot;complaint&quot;,<br>  &quot;sentiment&quot;: &quot;negative&quot;,<br>  &quot;churnRisk&quot;: 0.82<br>}</pre><p>Now there is an important point.</p><h4>AI does not necessarily need to make the final business decision.</h4><p>We can design the workflow like this:</p><pre>AI<br> ↓<br>Intent / Risk<br> ↓<br>Code<br> ↓<br>Business Rule<br> ↓<br>Action</pre><p>For example:</p><pre>if (result.ChurnRisk &gt;= 0.8)<br>{<br>    CreateHighPriorityTicket();<br>}</pre><p>Here, AI solves the <strong>non-deterministic</strong> part of the problem, while code handles the <strong>deterministic</strong> part.</p><p><strong>This distinction is very important.</strong></p><h3>Use AI for Ambiguity, Not Deterministic Rules</h3><p>The difference is important.</p><p>Suppose we ask the system:</p><blockquote><em>“Is this order paid?”</em></blockquote><p>And the database contains a clear value:</p><pre>OrderStatus = Paid</pre><p>We do not need AI.</p><p>But suppose we ask:</p><blockquote><em>“Does this customer message indicate that they intend to cancel their order?”</em></blockquote><p>Now AI can be useful.</p><p>In simple terms:</p><p><strong>If we already know the answer and can define it precisely, write code.</strong></p><p><strong>If reaching the answer requires understanding, interpretation, or analysis, bring AI into the process.</strong></p><h3>Token Burner</h3><p>This brings us to the concept of a <strong>Token Burner</strong>.</p><p>A Token Burner is a task that could have been solved once with code or a script, but instead we keep asking an LLM to understand and execute the same logic repeatedly.</p><p>For example, suppose we need to process 10,000 files every day.</p><p>The process is always:</p><ol><li>Find the file</li><li>Check the extension</li><li>Move it to a specific folder</li><li>Rename it</li></ol><p>Why should we ask AI every time:</p><blockquote><em>“Analyze this file and decide what should be done with it.”</em></blockquote><p>If the logic is completely defined, write a script.</p><p>We can even use AI to help us write that script <strong>once</strong>.</p><p>Then run the same script thousands of times.</p><h3>Use AI Once to Find the Solution</h3><p>I think there is a much better pattern here:</p><pre>Problem<br>   ↓<br>   AI<br>   ↓<br>Explore<br>   ↓<br>Find Solution<br>   ↓<br>Implement<br>   ↓<br>Define Contract<br>   ↓<br>Build Tool / Script / Service<br>   ↓<br>Reuse</pre><p>Instead of:</p><pre>Problem<br>   ↓<br>   AI<br>   ↓<br>Problem<br>   ↓<br>   AI<br>   ↓<br>Problem<br>   ↓<br>   AI</pre><p>Suppose we do not know how to design a complex process.</p><p>We ask AI for help.</p><p>We explore different scenarios.</p><p>We find a solution.</p><p>We can even ask AI to generate the initial code.</p><p>But once the solution is understood, if this process is going to be executed repeatedly, we should not ask AI to solve the same problem again every time.</p><p>We should turn the solution into:</p><ul><li>Function</li><li>Service</li><li>Script</li><li>API</li><li>Tool</li><li>Workflow</li></ul><p>And define a clear contract for it.</p><h3>Let AI Decide When to Use a Tool — Let Code Do the Work</h3><p>Suppose we have a customer information operation that is already implemented in code:</p><pre>GetCustomer(customerId)</pre><p>The operation has a clear and well-defined contract:</p><p><strong>Input:</strong></p><pre>customerId</pre><p><strong>Output:</strong></p><pre>Customer</pre><p>Now, when a user asks something that requires customer information, AI does not need to figure out how to retrieve that information from the database.</p><p>It only needs to recognize that the GetCustomer tool is required and provide the appropriate customerId.</p><p>The tool itself handles the actual operation deterministically.</p><p>The database query, validation, business rules, and data retrieval remain in code — not in the prompt.</p><p>In other words:</p><p><strong>AI decides. Code executes.</strong></p><h3>The LLM Should Be the Orchestrator, Not the Executor of Everything</h3><p>A healthy architecture could look something like this:</p><pre>User<br>  ↓<br> LLM<br>  ↓<br>Understand / Classify / Decide<br>  ↓<br> Tool<br>  ↓<br>Deterministic Code<br>  ↓<br>Database / API</pre><p>AI is placed where it provides value.</p><p>But the actual operations are performed by code and tools that we can test, restrict, and control.</p><p>This is much better than having an agent that is allowed to do almost everything by itself.</p><h3>Just Because AI Can Do Something Doesn’t Mean AI Should Do It</h3><p>This sentence may sound simple:</p><p><strong>Just because AI can do something doesn’t mean AI should do it.</strong></p><p>An LLM can add two numbers.</p><p>But a calculator is better.</p><p>An LLM can rename files.</p><p>But a script is better.</p><p>An LLM can evaluate a condition.</p><p>But if the condition is deterministic, code is better.</p><p>An LLM can generate and execute a database query.</p><p>But if the query is known and well-defined, a service or repository should execute it.</p><p>An LLM can analyze an order’s status.</p><p>But once the decision is clear, the business logic should be enforced in code.</p><p>The fact that AI <em>can</em> perform an operation is not, by itself, a reason to let AI perform it.</p><h3>Caching: Why Calculate the Same Thing Again?</h3><p>The same principle applies to caching.</p><p>If a question or result is repeated many times, why should we call the LLM every time?</p><p>Suppose the question is:</p><blockquote><em>“What is your return policy?”</em></blockquote><p>If the information has not changed, there is no need to send a new request to an LLM every time.</p><p>We can cache the result.</p><p>Even better:</p><p>If the answer is completely deterministic, perhaps we do not need an LLM at all.</p><h3>Keep the Blast Radius Small</h3><p>One of the problems with overly powerful agents is that they can have a large <strong>Blast Radius</strong>.</p><p>Imagine an agent has permission to:</p><ul><li>Modify the database</li><li>Modify orders</li><li>Send emails</li><li>Delete files</li><li>Call different APIs</li></ul><p>A single incorrect AI decision can have a large impact.</p><p>But if AI is only allowed to, for example, identify a customer’s intent, and then code decides what actions are permitted, the impact of an AI error becomes much smaller.</p><p>So:</p><p><strong>Keep AI within a controlled boundary whenever possible.</strong></p><p>AI does not need access to everything just because it is capable of using everything.</p><h3>The Goal Should Not Be Maximum AI</h3><p>Sometimes, when designing new systems, it can feel like the more AI we have, the more advanced the system is.</p><p>But that is not necessarily true.</p><p>A good system is not necessarily a system that contains the most AI.</p><p>A good system is one that is:</p><ul><li>Fast</li><li>Reliable</li><li>Testable</li><li>Maintainable</li><li>Reasonably priced</li><li>And uses AI only where it actually creates value</li></ul><p>In other words, the goal should not be:</p><p><strong>How much AI can we add?</strong></p><p>A better question is:</p><p><strong>Where does AI actually create value?</strong></p><h3>A Simple Test Before Every AI Call</h3><p>Before introducing AI into a workflow, we can ask ourselves a few simple questions:</p><h3>1. Does this decision need to be certain?</h3><p>If yes, it probably belongs in code.</p><p>If there is a clear rule that must always be followed, implement that rule instead of asking AI to make the decision.</p><h3>2. Should the same input always produce the same output?</h3><p>If yes, that is a strong indication that the problem is deterministic.</p><p>If it can be expressed as a simple, repeatable process, it may be better implemented as code or a script.</p><h3>3. Is an error costly, even if it happens only a small percentage of the time?</h3><p>If yes, we should not delegate the important decision to AI without proper validation and guardrails.</p><p>For critical logic, code gives us something AI cannot guarantee: the same input will produce the same result every time, making the behavior predictable and easier to test.</p><h3>4. Can I test this rule precisely with a unit test?</h3><p>If yes, why turn it into a prompt?</p><p>A rule that can be precisely tested, versioned, and maintained in code probably does not need AI.</p><h3>5. Does the problem require language, context, interpretation, classification, reasoning, or dealing with ambiguity?</h3><p>If yes, AI is probably valuable.</p><p>These are the kinds of problems where deterministic rules may not be enough and where AI can add real value.</p><h3>6. Is this task repeated frequently?</h3><p>If yes, perhaps the result of the AI work should eventually be turned into a tool, service, script, or another deterministic process.</p><p>This is especially important when AI helps us discover a solution. Once that solution becomes clear and repeatable, we should ask whether it still needs AI at runtime — or whether we can turn what we learned into code.</p><p>In other words:</p><p><strong>Use AI to discover and solve problems. Use code to repeat solutions that have become clear.</strong></p><h3>In the End, the Question Is Not “Can We Use AI?”</h3><p>For many tasks, we can.</p><p>The more important question is:</p><p><strong>Where should we use AI?</strong></p><p><strong>The goal is not to maximize AI usage.</strong></p><p><strong>The goal is to maximize value per AI call.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fee72a935a63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding Has Become Faster; The Role of Software Engineering Has Become More Important]]></title>
            <link>https://vahid-faraji-dev.medium.com/coding-has-become-faster-the-role-of-software-engineering-has-become-more-important-7dfb782db765?source=rss-f3079f487992------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dfb782db765</guid>
            <category><![CDATA[ai-assisted-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[business-value]]></category>
            <dc:creator><![CDATA[Vahid Faraji]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 11:23:04 GMT</pubDate>
            <atom:updated>2026-09-11T11:27:48.058Z</atom:updated>
            <content:encoded><![CDATA[<p>Artificial intelligence is significantly changing the way software is developed.</p><p>Today, with AI tools, we can produce something in a few minutes that previously might have taken hours or even days to write. AI is not only making code generation faster. It is also helping us investigate problems, understand unfamiliar code, find possible causes of bugs, explore different solutions, and resolve issues much faster than before. A feature, an API, tests, database queries, classes, and even architecture can be requested from AI, and in a very short time, we can reach an executable result.</p><p>This is fantastic.</p><p>But I think there is one point that receives less attention in all of this:</p><p><strong>AI has made coding faster and writing code easier; but this very fact makes the role of software engineering, problem solving, and architectural thinking more important than before.</strong></p><p>The issue is not that AI cannot provide good solutions. In fact, it can. The question is: <strong>Do we know what we should ask AI?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewDx6bknGf5njzQfH8DuUw.png" /></figure><h3>When Code Generation Is No Longer the Main Bottleneck</h3><p>Imagine we have an online store.</p><p>The product team says:</p><blockquote>“When the inventory of a product becomes low, we want to send a notification to customers who have previously purchased that product.”</blockquote><p>Today, we can give this problem to AI and get a solution very quickly.</p><p>AI can write a query for us, create a service, design a background job, add a queue, and even generate unit tests.</p><p>But before we write even a single line of code, there are important questions:</p><ul><li>Should someone who bought the product once three years ago also receive a notification? Or only a customer who is likely to need that product again?</li><li>What if we have 50,000 previous customers?</li><li>Are we going to send one large request to the notification system?</li><li>Should the processing be asynchronous?</li><li>What happens if the notification service becomes unavailable?</li><li>If the job runs again, will customers receive the message twice?</li><li>What happens if two instances of the application run the same job at the same time?</li><li>Should we have idempotency?</li><li>Should we have a domain event?</li></ul><p>These are no longer simply questions about <strong>“How do we write this code?”</strong></p><p>These are questions of <strong>software engineering and architecture.</strong></p><p>Of course, AI can point to these things and even provide very good solutions for them. But if we don’t ask the right questions, we may not address some of these areas.</p><h3>An Important Point: AI Certainly Has Answers for These Questions Too</h3><p>Here, I don’t want to say that AI cannot solve these problems. In fact, for each of these cases, it can suggest several solutions. Good solutions. It may also point out some of these issues.</p><p>We can ask AI:</p><blockquote>“How can we prevent duplicate notification delivery?”</blockquote><p>And AI can provide very good suggestions about idempotency, distributed locks, or queues.</p><p>We can ask:</p><blockquote>“What architecture would you suggest for processing 50,000 customers?”</blockquote><p>And AI can provide several different architectures.</p><p>We can ask it about trade-offs.</p><p>We can ask it to compare different solutions.</p><p>The point is that some areas may never be examined, and those overlooked areas can eventually create significant costs for both the software and the business.</p><p>In other words, if the developer has not thought about these topics at all, they may never ask AI about them.</p><h3>What Experience Teaches Us</h3><p>This is where the difference between an experienced developer and someone who simply uses AI to generate code can become very important.</p><p>An experienced developer may immediately say after seeing the requirement:</p><h4>“Wait. Before we write code, there are several things we need to clarify.”</h4><p>Maybe they have previously dealt with a broken notification system.</p><p>Maybe they have previously had a background job that processed information twice because it ran again.</p><p>Maybe they have previously seen a system that worked perfectly in Development but failed in Production as the amount of data increased.</p><p>Maybe they have previously faced a wrong architectural decision that became extremely expensive to change after several years.</p><p>This experience makes them ask <strong>questions that do not yet exist in the requirement.</strong></p><p>And this is exactly one of the most valuable roles of a software engineer in the age of AI.</p><h3>AI Can Solve the Problem You Give It; But Did You Give It the Right Problem?</h3><p>In my opinion, this is one of the most important changes that AI is bringing to Software Engineering.</p><p>The value of an engineer is not only in knowing the answer.</p><p>Perhaps in the future, knowing many of the answers will become less important, because AI can provide them to us.</p><p>The more important value is knowing:</p><h4>What question should we ask?</h4><h4>What assumption should we challenge?</h4><h4>What have we not seen yet?</h4><p>And most importantly:</p><h4>Is the problem we are solving really the main problem?</h4><p><strong>AI can help us investigate problems, explore solutions, and solve them much faster than before.</strong></p><p>But experience helps us understand <strong>which problems are worth bringing to AI, what questions we should ask, and what risks we should investigate.</strong></p><h3>The Real Risk: Accelerating the Production of Software That May Be Difficult to Maintain</h3><p>If an experienced engineer uses AI, they can free up a lot of time from repetitive work and use that time for better design, examining edge cases, testing, refactoring, and architectural decisions.</p><p>In such a situation, AI can actually improve software quality.</p><p>But there is another scenario.</p><p>Imagine a developer without sufficient understanding of architecture gives a requirement to AI, receives code, copy/pastes it, the build is green, and the feature is finished.</p><p>The next feature is the same.</p><p>And the next feature.</p><p>Production speed increases.</p><p>The number of lines of code increases.</p><p>The number of features increases.</p><p>And everyone is happy.</p><p>But something that may also be growing at the same time is <strong>complexity and technical debt</strong> — especially when we don’t ask the right questions, challenge our assumptions, look at the problem from different perspectives, <strong>and assume that the first answer we get is the best answer.</strong></p><h3>A Problem Today, a Cost in the Future</h3><p>The problem with technical debt is that it usually does not hurt at the exact moment it is created.</p><p>A simple decision might save only a few hours today.</p><p>But if the same decision is repeated across dozens of parts of the system, then a few years later, changing a simple feature may require examining many parts of the system.</p><p>A new developer may need to spend a lot of time understanding one part of the system.</p><p>Every small change may affect several different places.</p><p>The team may become afraid to refactor because of the risk of breaking other parts.</p><p>And ultimately, the cost is not only the developer’s time.</p><p>This cost can become a <strong>real financial cost for the business.</strong></p><h3>Maybe in the Future, We Won’t Have a Shortage of Software</h3><p>One of the things I find interesting about the future of Software Engineering is exactly this.</p><p>AI may make software production so fast and so cheap that the main problem will no longer be building software.</p><p>Companies may have more software in the future than they do today.</p><p>More applications.</p><p>More services.</p><p>More automations.</p><p>More features.</p><p>But the question is:</p><p><strong>Who will understand this software several years from now?</strong></p><p>Who knows why an architectural decision was made?</p><p>Who knows why a rule was placed in one service and not somewhere else?</p><p>Who knows why a queue was used?</p><p>Why was a separate database created?</p><p>Why was an asynchronous process designed?</p><p>And are these decisions still correct?</p><p>Of course, one answer is that AI has all these answers and can provide them. :)</p><p>Proper teamwork, good documentation, and knowledge sharing can also reduce many of these problems — but only if we consciously pay attention to them and make them part of the way we build software.</p><h3>AI Does Not Replace the Engineer; It Changes the Engineer’s Role</h3><p>For this reason, I don’t see the future of Software Engineering like this:</p><p><strong>AI → replaces the programmer.</strong></p><p>I think the more accurate picture is:</p><p><strong>AI → performs more of the mechanical and repetitive work.</strong></p><p>And as a result, the human role moves more toward:</p><ul><li>Problem Solving</li><li>Architecture</li><li>Critical Thinking</li><li>Reviewing</li><li>Validation</li><li>Understanding Business Requirements</li><li>Identifying Risks</li><li>Making Trade-offs</li></ul><p>A good engineer can ask AI to generate code.</p><p>But then asks:</p><blockquote>“Why this solution?”</blockquote><blockquote>“What alternatives do we have?”</blockquote><blockquote>“What assumptions are behind this solution?”</blockquote><blockquote>“What happens if the system becomes ten times larger?”</blockquote><blockquote>“What if this service goes down?”</blockquote><blockquote>“Do we really need this complexity?”</blockquote><p>And even:</p><p><strong>“Should we even build this feature this way?”</strong></p><h3>The Future Does Not Belong to Those Who Generate More Code</h3><p>AI will continue to improve.</p><p>Again:</p><p>It will generate better code.</p><p>It will understand more context.</p><p>It will analyze larger codebases.</p><p>It will suggest better architectures.</p><p>It will write better tests.</p><p>It will perform better refactoring.</p><p>And this is a very good thing.</p><p>But the better AI becomes at generating code, the more valuable one human ability becomes:</p><p><strong>The ability to see something beyond the code.</strong></p><p>Because Software Engineering is not just about building something that works today.</p><p>We build software so that tomorrow it can also be changed, extended, and maintained.</p><p>Therefore, I think AI is not the end of the importance of Software Engineering.</p><p><strong>On the contrary, AI can make the role of the Software Engineer, Architect, and Problem Solver more important than ever.</strong></p><p>Because in a world where anyone can generate a large amount of code in a few minutes, the real advantage is no longer simply the ability to produce code.</p><p>The real advantage is knowing <strong>what should be built, why it should be built, how it should be built, when we should stop building it, and most importantly, how we can create more business value.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dfb782db765" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Reduced Zapier Task Costs by Moving Part of the Automation to a .NET API]]></title>
            <link>https://vahid-faraji-dev.medium.com/how-i-reduced-zapier-task-costs-by-moving-part-of-the-automation-to-a-net-api-4680838cf559?source=rss-f3079f487992------2</link>
            <guid isPermaLink="false">https://medium.com/p/4680838cf559</guid>
            <category><![CDATA[microsoft-365]]></category>
            <category><![CDATA[zapier]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Vahid Faraji]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 14:47:59 GMT</pubDate>
            <atom:updated>2026-09-08T14:47:59.602Z</atom:updated>
            <content:encoded><![CDATA[<p>In one of the systems I was working on, part of the process for receiving and processing customer requests was handled with Zapier.</p><p>The overall structure of the system looked something like this:</p><pre>Incoming Email<br>      ↓<br>Zapier Trigger<br>      ↓<br>Webhook<br>      ↓<br>.NET API<br>      ↓<br>Internal Processing in .NET API<br>      ↓<br>Zapier Processes     </pre><p>Zapier was already part of the system and had been useful for me. Especially at the beginning of the project, being able to quickly build workflows without having to fully develop an independent automation system was a major advantage. (Of course, I’m aware that there are other tools such as Make and n8n, including AI-powered automation solutions. However, in this article, I don’t want to discuss or compare the advantages and disadvantages of those tools.)</p><p>But as the number of requests increased, one issue became more noticeable:</p><p><strong>The number of Zapier Tasks had increased.</strong></p><p>And the increase in Tasks directly affected the cost of the service.</p><p>While reviewing the Workflow, I realized that some of the things Zapier was doing were actually tasks that the Backend could easily handle.</p><p>For example, the API was already receiving the request, parsing the data, checking the customer information, and deciding how the process should continue. From there, the workflow continued in Zapier.</p><p>So a simple question came to mind:</p><blockquote>When the Backend has already completed the necessary checks, why should I send the result back to Zapier so that Zapier performs another operation and, for example, consumes an additional Task just to send an Email?</blockquote><p>That was when I decided to move part of the Automation out of Zapier and into the API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tOczboBPJNO5iLcPE36pog.png" /></figure><h3>The Goal: Not to Remove Zapier, but to Remove Unnecessary Tasks</h3><p>My goal was not to completely replace Zapier. Zapier is still useful for triggers and for quickly connecting different services.</p><p>The goal was to make Zapier do only what it was actually needed for.</p><p>The new Workflow became simpler:</p><pre>Incoming Email<br>      ↓<br>Zapier Trigger<br>      ↓<br>Webhook<br>      ↓<br>.NET API</pre><p>And after that, all decision-making happens inside the Backend.</p><p>For example:</p><pre>.NET API<br>   ↓<br>Parse Request<br>   ↓<br>Customer Exists?<br>   ├── Yes → Stop<br>   │<br>   └── No<br>        ↓<br>      Save Data<br>        ↓<br>      Send Email</pre><p>With this change alone, several Tasks were removed from each Workflow execution.</p><p>One of the parts I chose to move to the Backend was <strong>sending Email</strong>.</p><p>And this was exactly the part that led me into an interesting scenario with Microsoft 365.</p><h3>Sending Email from .NET; At First, It Looked Very Simple</h3><p>At first, the issue seemed very simple:</p><p>The API needed to send an Email.</p><p>.NET has had the following class for years:</p><pre>System.Net.Mail.SmtpClient</pre><p>So at first glance, it might seem that all I needed to do was enter:</p><pre>SMTP Host<br>Port<br>Username<br>Password</pre><p>and send the Email.</p><p>For simple SMTP Servers, this approach may still work. But the Mailbox used by the system was hosted on <strong>Microsoft 365 / Exchange Online</strong>, and this made things a little different.</p><h3>Why Didn’t I Use System.Net.Mail.SmtpClient?</h3><p>The important point is that it would not be correct to say that SmtpClient in .NET is absolutely incapable of sending Email.</p><p>The issue was that for a new implementation with requirements such as:</p><ul><li>Microsoft 365</li><li>OAuth2</li><li>Modern Authentication</li><li>Async operations</li><li>Testability</li><li>STARTTLS</li></ul><p>it was not a suitable option for my new architecture.</p><p>So instead, I used:</p><pre>MailKit</pre><p>MailKit provides a more modern API for SMTP, and working with OAuth2 in it feels much more natural.</p><p>The architecture ultimately looked like this:</p><pre>.NET API<br>   ↓<br>MailKit<br>   ↓<br>OAuth2<br>   ↓<br>Microsoft 365 SMTP<br>   ↓<br>Exchange Online</pre><h3>Why Microsoft 365 at All?</h3><p>I could have used another SMTP Server.</p><p>For example, if a regular SMTP Server had been available, the Configuration would probably have looked something like this:</p><pre>Host<br>Port<br>Username<br>Password<br>TLS</pre><p>But the system’s main Mailbox was already hosted on Microsoft 365.</p><p>So it made more sense to send Email through the same infrastructure.</p><p>That means:</p><pre>Application<br>      ↓<br>Microsoft Entra ID<br>      ↓<br>Exchange Online<br>      ↓<br>Microsoft 365 Mailbox</pre><p>As a result, the Sender remains the organization’s actual Mailbox.</p><h3>The Microsoft 365 SMTP Endpoint</h3><p>For SMTP Client Submission in Exchange Online, I used:</p><pre>smtp.office365.com</pre><p>Port:</p><pre>587</pre><p>and Connection Security:</p><pre>STARTTLS</pre><p>So:</p><pre>smtp.office365.com:587</pre><h3>But I Didn’t Want a Username and Password</h3><p>In a traditional SMTP setup, Authentication might look like this:</p><pre>Username<br>Password</pre><p>But in this project, I decided to use <strong>OAuth2 / Modern Authentication</strong>.</p><p>So the Application first needs to obtain an Access Token from Microsoft Entra.</p><p>That Token is then used for Authentication over SMTP.</p><p>Flow:</p><pre>.NET<br> ↓<br>Microsoft Entra<br> ↓<br>Access Token<br> ↓<br>MailKit<br> ↓<br>SMTP OAuth2<br> ↓<br>Exchange Online</pre><h3>Step One: Creating an App Registration in Microsoft Entra</h3><p>To allow the Application to obtain a Token without an interactive Login, I created an App Registration.</p><p>The general path:</p><pre>Microsoft Entra<br>→ App registrations<br>→ New registration</pre><p>A general name is chosen for the Application, for example:</p><pre>Automation Mail Service</pre><p>And because the Application belonged only to the same Organization:</p><pre>Accounts in this organizational directory only</pre><p>or:</p><pre>Single Tenant</pre><p>I selected that option.</p><p>After creating the App, we receive several important values:</p><pre>Application (Client) ID<br>Directory (Tenant) ID<br>App Registration Object ID</pre><p>These values are later used in the application Configuration.</p><h3>Step Two: Finding the Service Principal Object ID</h3><p>One part that can be confusing is that Microsoft has several types of IDs for an App.</p><p>Two important ones are:</p><pre>App Registration Object ID</pre><p>and:</p><pre>Enterprise Application / Service Principal Object ID</pre><p>These are not the same.</p><p>For part of the Exchange Online Configuration, I needed:</p><pre>Service Principal Object ID</pre><p>This value can be found under:</p><pre>Microsoft Entra<br>→ Enterprise applications<br>→ Application</pre><p>This distinction becomes very important later when running New-ServicePrincipal.</p><h3>Step Three: Creating a Client Secret</h3><p>For the Client Credentials Flow, we need to create a Client Secret.</p><p>Path:</p><pre>App Registration<br>→ Certificates &amp; secrets<br>→ Client secrets<br>→ New client secret</pre><p>Microsoft then displays two different values:</p><pre>Secret ID<br>Value</pre><p>Important point:</p><blockquote><em>What the Application needs is the </em><em>Value, not the </em><em>Secret ID.</em></blockquote><p>The application Configuration will later look something like this:</p><pre>TenantId<br>ClientId<br>ClientSecret</pre><h3>Step Four: Connecting PowerShell to Exchange Online</h3><p>To configure the Scope and Permission related to SMTP, we need to configure Exchange Online.</p><p>First, the relevant PowerShell Module:</p><pre>Install-Module ExchangeOnlineManagement -Scope CurrentUser</pre><p>If needed:</p><pre>Import-Module ExchangeOnlineManagement</pre><p>and then:</p><pre>Connect-ExchangeOnline</pre><p>After Authentication, Exchange Online commands can be executed.</p><p>If PowerShell does not allow the Module to run, for the current Session we can use:</p><pre>Set-ExecutionPolicy `<br>  -Scope Process `<br>  -ExecutionPolicy Bypass</pre><h3>Step Five: Registering the Service Principal in Exchange Online</h3><p>The App that exists in Entra also needs to be recognized by Exchange Online.</p><p>For this:</p><pre>New-ServicePrincipal `<br>  -AppId &quot;&lt;CLIENT-ID&gt;&quot; `<br>  -ObjectId &quot;&lt;SERVICE-PRINCIPAL-OBJECT-ID&gt;&quot; `<br>  -DisplayName &quot;Automation Mail Service&quot;</pre><p>An important point at this stage:</p><pre>ObjectId</pre><p>must be the Service Principal Object ID associated with the Enterprise Application.</p><p>Using the App Registration Object ID can cause an error.</p><h3>Step Six: Restricting Application Access</h3><p>One of my goals was to make sure the Application could not send Email from every Mailbox in the Tenant.</p><p>The Application should only have access to the system’s specific Mailbox.</p><p>For this, I created a Distribution Group for the Scope.</p><p>For example:</p><pre>New-DistributionGroup `<br>  -Name &quot;Automation SMTP RBAC&quot; `<br>  -Alias &quot;automation-smtp-rbac&quot;</pre><p>Then the required Mailbox:</p><pre>Add-DistributionGroupMember `<br>  -Identity &quot;Automation SMTP RBAC&quot; `<br>  -Member &quot;&lt;MAILBOX&gt;&quot;</pre><h3>Step Seven: Getting the Group’s Distinguished Name</h3><p>For the Management Scope, we need the group’s DN.</p><pre>Get-DistributionGroup `<br>  -Identity &quot;Automation SMTP RBAC&quot; |<br>  Format-List DistinguishedName</pre><p>The output looks something like this:</p><pre>CN=Automation SMTP RBAC,<br>OU=...,<br>OU=Microsoft Exchange Hosted Organizations,<br>DC=...,<br>DC=prod,<br>DC=outlook,<br>DC=com</pre><p>We keep this value for the next step.</p><h3>Step Eight: Enabling Organization Customization</h3><p>In some Tenants, before creating the Management Scope, it is necessary to run:</p><pre>Enable-OrganizationCustomization</pre><p>If it is already enabled, naturally no new change is required.</p><h3>Step Nine: Creating the Management Scope</h3><p>Now we create a Scope so that the Application only has access to Mailboxes that exist in the Distribution Group.</p><p>For example:</p><pre>New-ManagementScope `<br>  -Name &quot;Automation SMTP Scope&quot; `<br>  -RecipientRestrictionFilter &quot;MemberOfGroup -eq &#39;&lt;GROUP-DISTINGUISHED-NAME&gt;&#39;&quot;</pre><p>At this stage, the Permission structure looks approximately like this:</p><pre>Application<br>     ↓<br>Management Scope<br>     ↓<br>Distribution Group<br>     ↓<br>Specific Mailbox</pre><h3>Step Ten: Assigning SMTP.SendAsApp</h3><p>In the next step, we assign the SMTP Application Role to the Service Principal:</p><pre>New-ManagementRoleAssignment `<br>  -Name &quot;Automation SMTP SendAsApp&quot; `<br>  -Role &quot;Application SMTP.SendAsApp&quot; `<br>  -App &quot;&lt;SERVICE-PRINCIPAL-OBJECT-ID&gt;&quot; `<br>  -CustomResourceScope &quot;Automation SMTP Scope&quot;</pre><p>In some Tenants, to execute this command, the administrative Account must have the appropriate Exchange Role.</p><p>For example:</p><pre>Exchange Administrator</pre><p>If the Role has just been assigned, it is better to disconnect the current Connection and create it again:</p><pre>Disconnect-ExchangeOnline</pre><p>Then:</p><pre>Connect-ExchangeOnline</pre><h3>Step Eleven: Checking the Scope</h3><p>Before moving on to the Code, it is better to make sure the Permission is actually correct.</p><pre>Test-ServicePrincipalAuthorization `<br>  -Identity &quot;&lt;SERVICE-PRINCIPAL-OBJECT-ID&gt;&quot; `<br>  -Resource &quot;&lt;MAILBOX&gt;&quot;</pre><p>The expected output should show that the Application has:</p><pre>SMTP.SendAsApp</pre><p>and, more importantly:</p><pre>InScope = True</pre><p>If:</p><pre>InScope = True</pre><p>then the Service Principal is allowed to work with the specified Mailbox.</p><h3>The First Test and an Important Microsoft 365 Error</h3><p>After completing all the Configuration above, I ran the Integration Test.</p><p>The Connection to SMTP was established, but during Authentication I received the following error:</p><pre>535 5.7.139 Authentication unsuccessful<br>SmtpClientAuthentication is disabled for the Tenant</pre><p>There was a very important point here.</p><p>The Application Permissions were correct, and the OAuth Token was being obtained, but SMTP AUTH was disabled in Exchange Online.</p><h3>Checking SMTP AUTH at the Tenant Level</h3><p>I checked the status with the following command:</p><pre>Get-TransportConfig |<br>Format-List SmtpClientAuthenticationDisabled</pre><p>Output:</p><pre>SmtpClientAuthenticationDisabled : True</pre><p>This meant SMTP Client Authentication was disabled across the entire Tenant.</p><h3>Should I Enable SMTP AUTH for the Entire Tenant?</h3><p>I could have.</p><p>But there was no reason to open Authentication for every Mailbox in the Organization.</p><p>Only the Application and only one Mailbox needed it.</p><p>So I enabled SMTP AUTH at the level of that specific Mailbox:</p><pre>Set-CASMailbox `<br>  -Identity &quot;&lt;MAILBOX&gt;&quot; `<br>  -SmtpClientAuthenticationDisabled $false</pre><p>And then checked:</p><pre>Get-CASMailbox `<br>  -Identity &quot;&lt;MAILBOX&gt;&quot; |<br>  Format-List SmtpClientAuthenticationDisabled</pre><p>Expected output:</p><pre>SmtpClientAuthenticationDisabled : False</pre><p>As a result, I had:</p><pre>Tenant<br>SMTP AUTH Disabled</pre><p>but:</p><pre>Specific Mailbox<br>SMTP AUTH Enabled</pre><p>From a Security perspective, this made more sense for my needs.</p><h3>After This Step, the Email Was Actually Sent</h3><p>The Integration Test was run again.</p><p>This time:</p><pre>OAuth Token<br>✅</pre><pre>SMTP Connection<br>✅</pre><pre>SMTP Authentication<br>✅</pre><pre>Email Send<br>✅</pre><pre>Email Received<br>✅</pre><p>Final Flow:</p><pre>.NET Application<br>      ↓<br>Azure.Identity<br>      ↓<br>Microsoft Entra<br>      ↓<br>OAuth2 Access Token<br>      ↓<br>MailKit<br>      ↓<br>smtp.office365.com:587<br>      ↓<br>Exchange Online<br>      ↓<br>Recipient</pre><h3>Application Configuration</h3><p>In the Application Configuration, I had something along these lines:</p><pre>{<br>  &quot;Microsoft365Mail&quot;: {<br>    &quot;TenantId&quot;: &quot;&lt;TENANT-ID&gt;&quot;,<br>    &quot;ClientId&quot;: &quot;&lt;CLIENT-ID&gt;&quot;,<br>    &quot;ClientSecret&quot;: &quot;&lt;CLIENT-SECRET&gt;&quot;,<br>    &quot;Host&quot;: &quot;smtp.office365.com&quot;,<br>    &quot;Port&quot;: 587,<br>    &quot;FromEmail&quot;: &quot;&lt;MAILBOX&gt;&quot;,<br>    &quot;FromName&quot;: &quot;&lt;DISPLAY-NAME&gt;&quot;,<br>    &quot;UseStartTls&quot;: true<br>  }<br>}</pre><p>The actual Client Secret should naturally not be placed inside a public Repository.</p><p>For Production, it is better to retrieve the Secret from a Secret Store, Environment Variable, or an appropriate Secret Management solution.</p><h3>What Did I Do in the Code?</h3><p>In this article, I do not want to go into Source Code details, because the main issue is more about the architecture and Microsoft 365 Configuration.</p><p>In summary:</p><ul><li>I used MailKit for SMTP.</li><li>I used Azure.Identity to obtain the OAuth Token.</li><li>I managed ClientSecretCredential through Dependency Injection.</li><li>I kept the Credential in a way that allowed Token caching to be used.</li><li>I created an abstraction for the Email Service and Transport.</li><li>I separated the logic for creating the Subject and Body from the Use Case.</li><li>I wrote a real Integration Test for sending Email.</li><li>In the API Integration Tests, I replaced the real Email Service with a Fake so that running the Test would not cause a real Email to be sent.</li></ul><h3>The Main Result: Zapier Is Still There, but It Has Less Responsibility</h3><p>The interesting point about this project was that I did not remove Zapier.</p><p>Instead, I changed the boundaries of responsibility.</p><p>Before:</p><pre>Zapier<br>├── Trigger<br>├── Webhook<br>├── .NET API<br>├── Internal Processing in .NET API<br>├── Filter in Zapier<br>└── Send Email in Zapier</pre><p>After:</p><pre>Zapier<br>├── Trigger<br>└── Webhook</pre><p>And:</p><pre>.NET API<br>├── ...<br>├── Filter<br>└── Send Email</pre><p>This change reduced the number of Zapier Tasks consumed in each Workflow.</p><p>When a Workflow runs many times per day, removing even two Tasks from each execution can save a significant number of Tasks over the course of a month.</p><p>As a result, my Zapier cost actually decreased without requiring me to rewrite the entire Automation from scratch.</p><h3>What I Learned from This Experience</h3><p>For me, the most important point of this project was not that “Zapier is bad” or that “all Automations should be inside the Backend.”</p><p>Quite the opposite.</p><p>Zapier is a useful tool for quickly connecting systems.</p><p>But when a Backend already exists, it is worth reviewing the Workflows from time to time and asking:</p><blockquote><em>Does this Task really need to run on the Automation Platform, or can the Backend already handle it?</em></blockquote><p>In this project, the answer to that question was clear for Email sending.</p><p>Moving this responsibility to the .NET API not only reduced Zapier Tasks, but also gave me:</p><pre>More Control<br>Better Testability<br>Better Error Tracking<br>Lower Cost<br>Less Dependency on an External Workflow</pre><p>And perhaps most importantly, instead of removing a useful tool, I used it exactly where it created the most value for me. And perhaps most importantly, instead of removing a useful tool, I used it exactly where it created the most value for me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4680838cf559" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ChatGPT, Claude, Azure OpenAI, Anthropic API, Claude Code, and Cursor — What’s the Difference?]]></title>
            <link>https://vahid-faraji-dev.medium.com/chatgpt-claude-azure-openai-anthropic-api-claude-code-and-cursor-whats-the-difference-00f38771dded?source=rss-f3079f487992------2</link>
            <guid isPermaLink="false">https://medium.com/p/00f38771dded</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[business-agent]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Vahid Faraji]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 13:08:51 GMT</pubDate>
            <atom:updated>2026-08-31T14:27:11.181Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been working with AI for a while, but I haven’t really seen these concepts explained clearly in one place. So I decided to write an article and try to break them down in a simple way.</p><p>I hope it turned out well. If you like it, let me know if you’d like me to write more articles like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kjlmd-QMm-rdo6MSJmxSFA.png" /></figure><h3>First of all: Why are there so many different names?</h3><p>You’ve probably come across names like:</p><ul><li>ChatGPT</li><li>Claude</li><li>Gemini</li><li>OpenAI</li><li>Azure OpenAI</li><li>Anthropic API</li><li>Claude Code</li><li>Cursor</li><li>AI Agent</li><li>Business Agent</li><li>Function Calling</li><li>Tools</li></ul><p>The problem is that these are <strong>not all at the same level</strong>.</p><p>Some are <strong>products</strong>, some are <strong>AI models</strong>, some are <strong>APIs that allow developers to use AI models inside their applications</strong>, and some are <strong>AI-powered software development tools</strong>.</p><p>Once you understand this difference, everything becomes much easier.</p><p>I like to divide them into three main categories:</p><pre>                    AI<br>                     │<br>       ┌─────────────┼─────────────┐<br>       │             │             │<br>       ▼             ▼             ▼<br> AI Chat Products   AI APIs     AI Coding Tools<br>       │             │             │<br>       │             │             │<br> ChatGPT          Azure OpenAI   Claude Code<br> Claude           Anthropic API  Cursor<br> Gemini           Gemini API     ...</pre><p>Now let’s look at them one by one.</p><h3>1. What are ChatGPT, Claude, and Gemini?</h3><p>Let’s start with what most people already know.</p><p>When we open ChatGPT and start talking to it, we are using an <strong>AI product</strong>.</p><p>The same applies to Claude and Gemini.</p><p>For example:</p><pre>You<br> ↓<br>ChatGPT<br> ↓<br>AI Model<br> ↓<br>Response</pre><p>Or:</p><pre>You<br> ↓<br>Claude<br> ↓<br>AI Model<br> ↓<br>Response</pre><p>So here is an important point:</p><blockquote><strong><em>ChatGPT is not the same thing as a GPT model.</em></strong></blockquote><p>ChatGPT is a product/service that uses AI models behind the scenes.</p><p>In the same way:</p><blockquote><strong><em>Claude as a product is not the same thing as a Claude model.</em></strong></blockquote><p>This distinction becomes very important later.</p><h3>2. What is an AI Model?</h3><p>Now let’s go one level deeper.</p><p>An <strong>AI model</strong> is what actually processes the input, understands and analyzes it, reasons about it, and generates a response.</p><p>Different companies develop different AI models.</p><p>In a very simplified form:</p><pre>AI Company<br>     ↓<br>AI Model</pre><p>For example:</p><pre>Anthropic<br>    ↓<br>Claude Models</pre><p>Or:</p><pre>OpenAI<br>    ↓<br>GPT Models</pre><p>But as developers, we usually don’t want to work with the model directly.</p><p>We want to <strong>use the model inside our own software</strong>.</p><p>That’s where APIs come in.</p><h3>3. What is an API, and how is it different from an AI Model?</h3><p>Imagine I have a .NET application and I want to use an AI model.</p><p>I don’t necessarily install the model on my own server.</p><p>Instead, I use an API:</p><pre>My Application<br>      ↓<br>     API<br>      ↓<br>   AI Model<br>      ↓<br>    Result</pre><p>For example:</p><pre>.NET Application<br>      ↓<br>Azure OpenAI API<br>      ↓<br>AI Model<br>      ↓<br>Structured JSON</pre><p>Or:</p><pre>.NET Application<br>      ↓<br>Anthropic API<br>      ↓<br>Claude Model<br>      ↓<br>Response</pre><p>So:</p><blockquote><strong><em>An API is not an AI model itself.</em></strong></blockquote><p>An API is a way for our application to communicate with and use an AI model.</p><p>This is a common source of confusion.</p><p>For example, it is not technically accurate to say:</p><blockquote><em>“Anthropic API is an AI model.”</em></blockquote><p>A more accurate way to say it is:</p><blockquote><strong><em>Anthropic API provides a way for our application to access Anthropic’s AI models.</em></strong></blockquote><p>The same idea applies to Azure OpenAI.</p><h3>4. So where does a Business Agent fit into all of this?</h3><p>Now we get to the interesting part.</p><p>Imagine we have a <strong>Business Application</strong> that is supposed to handle some of the day-to-day tasks of a business intelligently.</p><p>For example, a user sends a request or message to the system:</p><blockquote><em>“I want to know the status of my request and whether I can make a change to it.”</em></blockquote><p>We want our system to be able to understand the message and, for example:</p><ol><li>Identify the type of request.</li><li>Extract the required information.</li><li>Find the user’s information in the system.</li><li>Check previous records if necessary.</li><li>Decide what action should be taken.</li><li>Perform the action itself if possible.</li><li>Or, if necessary, hand the task over to a human.</li></ol><p>At this point, we don’t just want a simple chatbot.</p><p>We want AI to be part of our <strong>Business Application</strong> and participate in real business processes within the boundaries we define.</p><p>For example, the overall architecture could look something like this:</p><pre>User<br>    ↓<br>Business Application<br>    ↓<br>.NET API<br>    ↓<br>AI Model<br>    ↓<br>Analysis / Decision<br>    ↓<br>Business Logic<br>    ↓<br>Tools / Functions<br>    ↓<br>CRM / Email / Database / Other Systems</pre><p>If the AI can use specific <strong>Tools</strong> and <strong>Functions</strong> alongside the model, and decide what the next step should be based on the result of each operation, the system can start to behave in an <strong>Agentic</strong> way.</p><p>In simple terms:</p><blockquote><strong><em>A Business Agent is an AI system that doesn’t just generate responses. Within a defined framework, it can use tools to achieve a goal and interact with real business systems.</em></strong></blockquote><h3>5. What are Tools and Function Calling?</h3><p>This is one of the most important concepts behind AI Agents.</p><p>Imagine that we have several Functions in our .NET Backend:</p><pre>getCustomer()<br>getCustomerHistory()<br>getPricing()<br>updateLead()<br>createSalesTask()<br>createEmailDraft()</pre><p>These Functions are written by us in .NET.</p><p>For example:</p><pre>public async Task&lt;CustomerHistory&gt; GetCustomerHistory(<br>    string email)<br>{<br>    // Query CRM / Database<br>}</pre><p>Now we tell the AI:</p><blockquote><em>“These Functions are available to you.”</em></blockquote><p>The AI can then decide which Function it needs to use based on the task it is trying to accomplish.</p><h3>6. What does “Choose Tool” mean?</h3><p>Suppose we have a new Lead and we tell the Agent:</p><blockquote><em>“Analyze this Lead.”</em></blockquote><p>The Agent has some initial information:</p><pre>{<br>  &quot;name&quot;: &quot;Max Miller&quot;,<br>  &quot;email&quot;: &quot;max@example.de&quot;,<br>  &quot;message&quot;: &quot;We need weekly office cleaning services.&quot;<br>}</pre><p>The Agent realizes that it needs to know whether this person has been a customer before.</p><p>So, from the Tools available to it, it chooses:</p><pre>Choose Tool<br>      ↓<br>getCustomerHistory()</pre><p>This simply means:</p><blockquote><strong><em>The Agent has decided which Function it needs to use to move closer to its goal.</em></strong></blockquote><h3>7. What does “Execute Tool” mean?</h3><p>There is an important detail here:</p><p><strong>The AI itself does not execute the Function.</strong></p><p>The AI simply says:</p><blockquote><em>“I want </em><em>getCustomerHistory to be executed.”</em></blockquote><p>Then our .NET application executes the Function.</p><pre>Agent<br>  ↓<br>getCustomerHistory()<br>  ↓<br>.NET<br>  ↓<br>CRM / Database<br>  ↓<br>Result</pre><p>For example, the result might be:</p><pre>{<br>  &quot;exists&quot;: true,<br>  &quot;customerId&quot;: 847,<br>  &quot;totalOrders&quot;: 8<br>}</pre><p>This result is then sent back to the Agent.</p><p>The Agent can analyze the result and decide what the next step should be.</p><h3>8. So how is an Agent different from a simple LLM?</h3><p>Before looking at Agents, it is important to understand what an <strong>LLM (Large Language Model)</strong> actually does.</p><p>An LLM is an AI model trained on large amounts of text to understand and generate human-like language. It can interpret input, reason over information, and generate different types of output, including text and structured data such as JSON.</p><p>A simple LLM interaction might look like this:</p><pre>Text<br> ↓<br>LLM<br> ↓<br>Response</pre><p>For example, in a lead qualification scenario, an LLM could analyze a customer’s message and return structured data:</p><pre>{<br>  &quot;category&quot;: &quot;commercial_service&quot;,<br>  &quot;location&quot;: &quot;Hamburg&quot;,<br>  &quot;frequency&quot;: &quot;weekly&quot;,<br>  &quot;score&quot;: 80<br>}</pre><p>In other words, <strong>an LLM can understand what we ask and generate an appropriate response.</strong></p><p>But an Agent goes a step further.</p><p>Instead of simply generating a response, an Agent can work toward a specific <strong>goal</strong>. It can decide what action to take, choose a tool when necessary, execute it, examine the result, and then decide what to do next.</p><p>A simplified Agent loop might look like this:</p><pre>Goal<br> ↓<br>Reason<br> ↓<br>Choose Tool<br> ↓<br>Execute Tool<br> ↓<br>Observe Result<br> ↓<br>Decide Next Action<br> ↓<br>Choose Another Tool<br> ↓<br>...<br> ↓<br>Final Decision</pre><p>For example:</p><pre>Analyze Lead<br>      ↓<br>Is this an existing customer?<br>      ↓<br>getCustomerHistory()<br>      ↓<br>Result<br>      ↓<br>Need more information?<br>      ↓<br>getCustomerDetails()<br>      ↓<br>Result<br>      ↓<br>Calculate qualification<br>      ↓<br>Create recommendation</pre><p>This is where the concept of an <strong>Agent</strong> starts to make sense.</p><p><strong>An LLM generates an answer. An Agent uses an LLM to reason about a goal, take actions, use tools, evaluate results, and continue until the task is completed.</strong></p><h3>9. But should we turn the entire system into an Agent?</h3><p>No.</p><p>This is one of the most important lessons when designing AI systems.</p><p>A better approach is often:</p><blockquote><strong><em>Let the Workflow control the overall process, and use an Agent in the parts that actually require reasoning and decision-making.</em></strong></blockquote><p>For example:</p><pre>Business Application<br>   ↓<br>.NET API<br>   ↓<br>Workflow<br>   ↓<br>Validate<br>   ↓<br>Save Lead<br>   ↓<br>Business Agent<br>   ↓<br>Azure OpenAI<br>   ↓<br>Tools<br>   ↓<br>Result<br>   ↓<br>.NET Business Rules<br>   ↓<br>CRM / Email</pre><p>In this architecture:</p><p><strong>Workflow = the skeleton of the system</strong></p><p><strong>Agent = the decision-making brain for complex parts</strong></p><p><strong>Tools = the Agent’s hands</strong></p><p><strong>AI Model = the intelligence engine</strong></p><h3>10. A real example with Email</h3><p>Suppose a customer sends:</p><blockquote><em>“Can I get a trial version of the software?”</em></blockquote><p>The AI can analyze the message:</p><pre>{<br>  &quot;intent&quot;: &quot;trial_request&quot;,<br>  &quot;product&quot;: &quot;software_trial&quot;<br>}</pre><p>Then .NET uses Business Rules to determine that this is a low-risk type of request.</p><p>In this case, the AI doesn’t even need to generate the entire email itself.</p><p>We can have a predefined template:</p><pre>SoftwareTrialRequest</pre><p>And the system can send the appropriate email automatically.</p><p>But what if the customer asks:</p><blockquote><em>“How much does the Enterprise version cost for 50 users, and can you give me a 30% discount?”</em></blockquote><p>Now the situation is more sensitive because the response may involve <strong>pricing, discounts, or a commercial commitment</strong>.</p><p>The system can decide:</p><pre>Pricing / Discount Request<br>          ↓<br>     Human Review<br>          ↓<br>    Create Email Draft<br>          ↓<br>     Human Approval<br>          ↓<br>          Send</pre><p>In this model, AI helps with understanding the request and preparing a response, but the final decision for sensitive matters remains under the control of <strong>Business Rules and a human</strong>.</p><h3>11. Can we trust the AI output?</h3><p>Not blindly.</p><p>For example, the customer asks:</p><blockquote><em>“How much does the Enterprise version cost for 50 users, and can you give me a 30% discount?”</em></blockquote><p>The AI might incorrectly analyze the message and return:</p><pre>{<br>  &quot;intent&quot;: &quot;general_question&quot;,<br>  &quot;requiresHumanReview&quot;: false<br>}</pre><p>Even though the request involves <strong>pricing and a discount</strong>, which could be a sensitive business decision.</p><p>This is where we should not allow AI to make the final decision on its own.</p><p>It is better to let AI handle <strong>understanding and analysis</strong>, while our Backend uses <strong>Business Rules</strong> to determine what action is actually allowed.</p><p>In other words:</p><pre>Customer Message<br>       ↓<br>      AI<br>       ↓<br>   Understand<br>       ↓<br> Structured Output<br>       ↓<br>      .NET<br>       ↓<br> Business Rules<br>       ↓<br>┌──────┼─────────┐<br>↓      ↓         ↓<br>Allow  Block   Human Review</pre><p>For example, even if the AI decides that a request is simple, the Backend can still say:</p><blockquote><em>“This request involves pricing or a discount, so automatic sending is not allowed.”</em></blockquote><p>The key principle is:</p><blockquote><strong><em>AI makes suggestions; the Backend controls execution.</em></strong></blockquote><p>This separation allows AI to provide intelligence and reasoning while keeping the final control over sensitive operations in the hands of the system and its business rules.</p><h3>12. So where do Claude Code and Cursor fit?</h3><p>So far, we have been talking about AI <strong>inside our application</strong>.</p><p>But there is another question:</p><blockquote><em>What if AI could also help the Developer build the software itself?</em></blockquote><p>This is where tools like <strong>Claude Code</strong> and <strong>Cursor</strong> come in.</p><p>We can put them in the category of:</p><blockquote><strong><em>AI Coding / Development Tools</em></strong></blockquote><h3>13. What is Claude Code?</h3><p>Claude Code can be thought of as a <strong>Coding Agent</strong>.</p><p>Instead of only asking:</p><blockquote><em>“Complete this Function.”</em></blockquote><p>You can give it a larger task:</p><blockquote><em>“Analyze the structure of this .NET project and implement a Lead Qualification system.”</em></blockquote><p>It can then work through a process such as:</p><pre>Repository<br>   ↓<br>Read files<br>   ↓<br>Understand codebase<br>   ↓<br>Plan<br>   ↓<br>Edit files<br>   ↓<br>Run commands<br>   ↓<br>Run tests<br>   ↓<br>Fix problems</pre><p>So Claude Code is more than simple autocomplete.</p><p>It can work with the codebase and perform multiple development tasks.</p><h3>14. What is Cursor?</h3><p>Cursor is an <strong>AI-powered IDE / Code Editor</strong> with Agentic Coding capabilities.</p><p>In other words, it combines:</p><pre>IDE<br> +<br>AI<br> +<br>Codebase Understanding<br> +<br>Agent Capabilities</pre><p>You can work with AI directly inside your development environment, ask it to analyze code, modify files, refactor parts of the project, and perform various development tasks.</p><p>So Claude Code and Cursor can be placed in the same general family:</p><pre>Development AI</pre><pre>Claude Code<br>Cursor<br>...</pre><p>But they are not the same thing as a Business Agent.</p><h3>15. Business Agent vs. Coding Agent</h3><p>This may be the most important distinction in the entire article.</p><p>Imagine I have an online business application.</p><h3>Business Agent</h3><p>It runs as part of the actual application:</p><pre>Customer<br>   ↓<br>Business Application<br>   ↓<br>Business Agent<br>   ↓<br>CRM<br>Email<br>Database<br>Orders</pre><p>Its job is to perform <strong>business tasks</strong>.</p><p>For example:</p><blockquote><em>“Analyze this Lead.”</em></blockquote><h3>Coding Agent</h3><p>It helps the Developer while building and maintaining the software:</p><pre>Developer<br>   ↓<br>Claude Code / Cursor<br>   ↓<br>Source Code<br>   ↓<br>Tests<br>   ↓<br>Application</pre><p>Its job is to help <strong>build and maintain software</strong>.</p><p>For example:</p><blockquote><em>“Implement this Feature in the .NET project.”</em></blockquote><p>So:</p><blockquote><strong><em>A Business Agent performs business-related tasks.</em></strong></blockquote><blockquote><strong><em>A Coding Agent helps the Developer build software.</em></strong></blockquote><h3>16. A complete picture of all these concepts</h3><p>If we put everything together into one diagram:</p><pre>                           AI<br>                            │<br>            ┌───────────────┼────────────────┐<br>            │               │                │<br>            ▼               ▼                ▼<br>      AI Chat Products   AI APIs        AI Coding Tools<br>            │               │                │<br>            │               │                │<br>        ChatGPT        Azure OpenAI      Claude Code<br>        Claude         Anthropic API     Cursor<br>        Gemini         Gemini API<br>                            │<br>                            ▼<br>                    Business Application<br>                            │<br>                          .NET<br>                            │<br>                         Agent<br>                            │<br>                   Tools / Functions<br>                            │<br>             ┌──────────────┼──────────────┐<br>             ▼              ▼              ▼<br>            CRM           Email         Database</pre><p>And if we think about it from a more practical perspective:</p><pre>                     CUSTOMER<br>                        │<br>                        ▼<br>                BUSINESS APPLICATION<br>                        │<br>                        ▼<br>                     .NET<br>                        │<br>                    Workflow<br>                        │<br>                        ▼<br>                Business Agent<br>                        │<br>                        ▼<br>                 Azure OpenAI<br>                        │<br>              Tool / Function Calling<br>                        │<br>          ┌─────────────┼─────────────┐<br>          ▼             ▼             ▼<br>         CRM          Email        Database</pre><p>On the other side, during development:</p><pre>                    DEVELOPER<br>                        │<br>                        ▼<br>                Claude Code / Cursor<br>                        │<br>                        ▼<br>                  .NET / Application<br>                        │<br>                        ▼<br>                   APPLICATION</pre><h3>17. So, if I had to summarize everything very simply</h3><h3>ChatGPT / Claude / Gemini</h3><p><strong>AI products for interacting directly with humans.</strong></p><pre>Human → AI Product → AI Model</pre><h3>Azure OpenAI / Anthropic API / Gemini API</h3><p><strong>Ways for our applications to use AI models.</strong></p><pre>Application → API → AI Model</pre><p>When we combine these models with <strong>Tools, Function Calling, Workflows, and Business Rules</strong>, we can build a <strong>Business Agent</strong>.</p><h3>Claude Code / Cursor</h3><p><strong>AI tools that help developers build software.</strong></p><pre>Developer → Coding AI → Source Code</pre><p>Some of them have Agentic capabilities, meaning they can do more than suggest code. They can work with the codebase, modify files, run tests, and follow a development task through multiple steps.</p><h3>18. The architecture I would choose for a real project</h3><p>If I were building a real <strong>Business Application</strong>, I could use an architecture like this:</p><pre>                 DEVELOPMENT<br>                     │<br>              Claude Code<br>                     │<br>                     ▼<br>              .NET Application<br>                     │<br>                     ▼<br>                  GitHub<br>                     │<br>                     ▼<br>                Production<br>                     │<br>                     ▼<br>                .NET Backend<br>                     │<br>              ┌──────┴──────┐<br>              │             │<br>          Workflow      Business Agent<br>                            │<br>                            ▼<br>                      Azure OpenAI<br>                            │<br>                     Tools / Functions<br>                            │<br>             ┌──────────────┼──────────────┐<br>             ▼              ▼              ▼<br>            CRM           Email         Database</pre><p>In this architecture, <strong>Claude Code</strong> helps the Developer during the development phase: building, modifying, testing, and maintaining the software.</p><p>During actual production, the <strong>Business Agent</strong> uses <strong>Azure OpenAI</strong> for analysis, decision-making, and interaction with Tools and Functions.</p><p>So there is absolutely no contradiction in using Claude Code for <strong>Development</strong> while using Azure OpenAI for the <strong>Business Agent</strong>.</p><p>They simply have different jobs:</p><blockquote><strong><em>Claude Code helps the Developer build the software; the Business Agent helps the software perform business tasks.</em></strong></blockquote><h3>Conclusion</h3><p>One of the reasons the AI world can feel confusing is that almost everything is simply called “AI”, even though these technologies can have completely different roles.</p><p>If we remember these three layers, a lot of the confusion disappears:</p><pre>1. AI Chat Product<br>   ↓<br>   ChatGPT / Claude / Gemini</pre><pre>2. AI Model + API<br>   ↓<br>   Azure OpenAI / Anthropic API / Gemini API<br>   ↓<br>   Bring AI capabilities into our applications<br>   ↓<br>   Agent + Tools + Workflow</pre><pre>3. AI Coding / Development Tool<br>   ↓<br>   Claude Code / Cursor<br>   ↓<br>   Help Developers build software</pre><p>And perhaps the simplest way to remember all of this is:</p><blockquote><strong><em>ChatGPT and Claude are products for interacting with AI.</em></strong></blockquote><blockquote><strong><em>Azure OpenAI and Anthropic API allow us to bring AI models into our own applications.</em></strong></blockquote><blockquote><strong><em>Claude Code and Cursor allow us to use AI as part of the software development process.</em></strong></blockquote><p>I hope this explanation helped make these concepts a little clearer.</p><p>If you’d like, let me know, and I can write more articles about <strong>AI Agents, Tools, Function Calling, Workflows, and the architecture of a real Business Agent with .NET</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00f38771dded" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mock It or Don’t? How to Decide What to Mock in Unit Tests]]></title>
            <link>https://vahid-faraji-dev.medium.com/mock-it-or-dont-how-to-decide-what-to-mock-in-unit-tests-d4858e7314d9?source=rss-f3079f487992------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4858e7314d9</guid>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Vahid Faraji]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 09:58:45 GMT</pubDate>
            <atom:updated>2026-08-31T09:28:09.973Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Featured in The .NET News Daily — Issue #527</strong></p><p>This article was selected and featured in The .NET News Daily, Issue #527, by DotNetNews.</p><p><a href="https://dotnetnews.co/archive/the-net-news-daily-issue-527/">View the issue →</a></p><p>When we start writing unit tests in .NET, we quickly run into an important question:</p><p><strong>Should we mock every dependency of our class?</strong></p><p>The short answer is:</p><p><strong>No.</strong></p><p>One of the most common misconceptions about unit testing is that <em>unit testing means mocking everything</em>. In reality, the right approach depends on the role of each dependency and what we need to control in the test.</p><p>Consider a component with these dependencies:</p><pre>private readonly IBookingApiClient _api;<br>private readonly IConfiguration _configuration;</pre><p>Both are dependencies, but they don’t necessarily need to be tested the same way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y0d4VdzaQ4aMQd1dm9uIfw.png" /></figure><h3>Mock External Boundaries</h3><p>Suppose IBookingApiClient communicates with an external API:</p><pre>public interface IBookingApiClient<br>{<br>    Task&lt;ScheduledEventsSummary&gt; GetScheduledEventsSummaryAsync(...);<br>}</pre><p>In a unit test, we don’t want to make real HTTP requests or depend on:</p><ul><li>Network availability</li><li>The external API being online</li><li>Real API responses</li><li>Timeouts or external failures</li></ul><p>This is where a mock is useful.</p><p>We can completely control the API’s behavior:</p><pre>_apiMock<br>    .Setup(x =&gt; x.GetScheduledEventsSummaryAsync(...))<br>    .ReturnsAsync(fakeData);</pre><p>We can also simulate failures:</p><pre>_apiMock<br>    .Setup(x =&gt; x.GetScheduledEventsSummaryAsync(...))<br>    .ThrowsAsync(new Exception(&quot;API Error&quot;));</pre><p>This allows the test to focus on our component’s behavior rather than the API.</p><h3>Mocks Can Also Verify Interactions</h3><p>Mocks aren’t only useful for controlling return values. They can also verify that a dependency was used correctly:</p><pre>_apiMock.Verify(<br>    x =&gt; x.GetScheduledEventsSummaryAsync(...),<br>    Times.Once);</pre><p>This is especially useful for dependencies that represent external boundaries, such as:</p><ul><li>API clients</li><li>Email senders</li><li>Payment gateways</li><li>Message publishers</li><li>External services</li></ul><p>For these kinds of dependencies, mocking is often a good choice.</p><h3>Don’t Mock Lightweight Dependencies Just Because They’re Interfaces</h3><p>Now consider IConfiguration.</p><p>Suppose our component reads a configuration value:</p><pre>var showDetails =<br>    Configuration[&quot;BookingDisplay:ShowDetailsButton&quot;];</pre><p>We could mock it:</p><pre>var configMock = new Mock&lt;IConfiguration&gt;();</pre><pre>configMock<br>    .Setup(x =&gt; x[&quot;BookingDisplay:ShowDetailsButton&quot;])<br>    .Returns(&quot;true&quot;);</pre><p>But do we really need a mock?</p><p>Usually, no.</p><p>.NET already provides a lightweight in-memory implementation:</p><pre>var configuration = new ConfigurationBuilder()<br>    .AddInMemoryCollection(new Dictionary&lt;string, string?&gt;<br>    {<br>        [&quot;BookingDisplay:ShowDetailsButton&quot;] = &quot;true&quot;<br>    })<br>    .Build();</pre><p>Now we’re using the real IConfiguration implementation without accessing files, environment variables, or external services.</p><p>This becomes even more useful if the implementation changes later.</p><p>For example, instead of:</p><pre>Configuration[&quot;BookingDisplay:ShowDetailsButton&quot;]</pre><p>we might use:</p><pre>Configuration<br>    .GetSection(&quot;BookingDisplay&quot;)<br>    .GetValue&lt;bool&gt;(&quot;ShowDetailsButton&quot;);</pre><p>A mock may require additional setups for these calls.</p><p>The in-memory configuration, however, already supports the real behavior.</p><p>So the test remains closer to how the application actually works.</p><h3>Mock, Stub, Fake, or Real Implementation?</h3><p>Mocking isn’t the only way to replace a dependency in a test.</p><h3>Mock</h3><p>Use a mock when you need to control behavior and/or verify interactions.</p><pre>apiMock<br>    .Setup(x =&gt; x.GetAsync())<br>    .ReturnsAsync(data);</pre><pre>apiMock.Verify(x =&gt; x.GetAsync(), Times.Once);</pre><h3>Stub</h3><p>Use a stub when you simply need to provide predefined data.</p><pre>var result = await service.GetAsync();</pre><p>The important part is that the dependency returns predictable data; interaction verification isn’t important.</p><h3>Fake</h3><p>A fake is a lightweight but functional implementation designed for testing.</p><p>For example, instead of using a real database, a fake repository might store data in an in-memory collection.</p><h3>Real Implementation</h3><p>Sometimes the best test dependency is simply the real implementation.</p><p>If it is:</p><ul><li>Lightweight</li><li>Fast</li><li>Deterministic</li><li>Easy to configure</li></ul><p>there may be no reason to mock it.</p><p>IConfiguration with AddInMemoryCollection() is a good example.</p><h3>A Practical Example</h3><p>Suppose our component has three dependencies:</p><pre>public BookingComponent(<br>    IBookingApiClient api,<br>    IConfiguration configuration,<br>    IEmailSender emailSender)<br>{<br>    ...<br>}</pre><p>Our test could use:</p><pre>var apiMock = new Mock&lt;IBookingApiClient&gt;();<br>var emailMock = new Mock&lt;IEmailSender&gt;();</pre><pre>var configuration = new ConfigurationBuilder()<br>    .AddInMemoryCollection(new Dictionary&lt;string, string?&gt;<br>    {<br>        [&quot;BookingDisplay:ShowDetailsButton&quot;] = &quot;true&quot;<br>    })<br>    .Build();</pre><pre>var component = new BookingComponent(<br>    apiMock.Object,<br>    configuration,<br>    emailMock.Object);</pre><p>Here:</p><ul><li>IBookingApiClient → <strong>Mock</strong></li><li>IEmailSender → <strong>Mock</strong></li><li>IConfiguration → <strong>Real in-memory implementation</strong></li></ul><p>The important point is that we’re making a decision for each dependency instead of blindly mocking everything.</p><h3>A Better Rule for Unit Testing</h3><p>Instead of asking:</p><blockquote><strong><em>“Is this dependency an interface?”</em></strong></blockquote><p>or:</p><blockquote><strong><em>“Should I mock every dependency?”</em></strong></blockquote><p>ask:</p><blockquote><strong><em>“What role does this dependency play in my test?”</em></strong></blockquote><p>Consider mocking when the dependency:</p><ul><li>Communicates with an external system</li><li>Performs I/O</li><li>Has behavior that needs to be controlled</li><li>Needs interaction verification</li><li>Is expensive or unsuitable for a unit test</li></ul><p>Consider using the real implementation when it is:</p><ul><li>Lightweight</li><li>Fast</li><li>Deterministic</li><li>Easy to configure</li><li>Already designed to work in memory</li></ul><p>A useful rule of thumb is:</p><blockquote><strong><em>Mock the boundaries. Use real lightweight implementations where they make sense.</em></strong></blockquote><p>Conceptually:</p><pre>Unit Under Test<br>                    │<br>          ┌─────────┴─────────┐<br>          │                   │<br>   External Boundary    Lightweight Dependency<br>          │                   │<br>        Mock              Real/In-Memory</pre><p>IBookingApiClient belongs on the first side.</p><p>IConfiguration belongs on the second.</p><h3>Why Over-Mocking Can Hurt</h3><p>Too much mocking can make tests tightly coupled to implementation details rather than actual behavior.</p><p>Consider a test where we mock every interaction with IConfiguration. Later, we refactor the production code and change how the configuration value is retrieved, while keeping the same externally observable behavior.</p><p>The application still works as expected, but the test may fail because the mock was configured for the old implementation.</p><p>For example, changing from:</p><pre>Configuration[&quot;BookingDisplay:ShowDetailsButton&quot;]</pre><p>to:</p><pre>Configuration<br>    .GetSection(&quot;BookingDisplay&quot;)<br>    .GetValue&lt;bool&gt;(&quot;ShowDetailsButton&quot;);</pre><p>shouldn’t necessarily require us to rewrite a test if the behavior we’re testing hasn’t changed.</p><p>This is one of the problems with <strong>over-mocking</strong>: the test can become coupled to <em>how</em> the code works instead of <em>what</em> the code does.</p><p>Good unit tests should focus on meaningful behavior and outcomes, rather than reproducing every internal implementation detail.</p><h3>The Takeaway</h3><p>Unit testing does <strong>not</strong> mean mocking every dependency.</p><p>In our example:</p><pre>IBookingApiClient<br>       ↓<br> External API<br>       ↓<br>     Mock</pre><p>We mock it because we want to control the external boundary, simulate different responses and failures, and potentially verify interactions.</p><p>But:</p><pre>IConfiguration<br>       ↓<br>In-Memory Configuration<br>       ↓<br> Real Implementation</pre><p>We can use the real implementation because it is lightweight, predictable, and easy to run in memory.</p><p>So instead of asking:</p><blockquote><strong><em>“How can I mock this dependency?”</em></strong></blockquote><p>ask:</p><blockquote><strong><em>“Do I actually need to mock this dependency?”</em></strong></blockquote><p>That small change in perspective can lead to tests that are simpler, more reliable, and less fragile.</p><p><strong>Good unit testing isn’t about mocking everything. It’s about knowing what should — and shouldn’t — be mocked.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4858e7314d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>