<?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 Ajay kumar on Medium]]></title>
        <description><![CDATA[Stories by Ajay kumar on Medium]]></description>
        <link>https://medium.com/@ajaykumar1807?source=rss-e26704d7d84b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ufvxw5UJLg0bPW21wHx0XQ.png</url>
            <title>Stories by Ajay kumar on Medium</title>
            <link>https://medium.com/@ajaykumar1807?source=rss-e26704d7d84b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:55:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajaykumar1807/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[AWS Bedrock with .NET: Cost Tracking via Inference Profiles]]></title>
            <link>https://medium.com/@ajaykumar1807/aws-bedrock-with-net-cost-tracking-via-inference-profiles-02f25f780ad6?source=rss-e26704d7d84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/02f25f780ad6</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Ajay kumar]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 07:25:59 GMT</pubDate>
            <atom:updated>2026-07-07T13:07:42.007Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qx7A18uf_ElJWSeF.png" /></figure><h4>The Problem: Your AI Bill Grew, But You Cannot Explain It</h4><p>A familiar story: your team ships two AI features quickly. One is a customer support assistant. Another is a content summarizer for internal dashboards. A few weeks later, finance asks a simple question: “Which feature is driving most of the Bedrock spend?”. You open Cost Explorer and see Bedrock charges, but the numbers are blended. You know usage increased, but you cannot confidently split cost by feature, environment, or business owner.</p><p>This is where many teams get stuck. They have technical success, but weak cost observability. Without structured attribution, every budgeting conversation becomes guesswork, and every optimization initiative starts late.</p><blockquote>ℹ️ Why this matters early</blockquote><blockquote>If you add cost tracking only after usage scales, you have historical spend but poor historical context. It is much harder to recover attribution later than to design it from day one.</blockquote><h4>1. What Are We Doing Here?</h4><p>We are implementing <strong>application-level cost tracking</strong> for Amazon Bedrock by routing model traffic through <strong>inference profiles</strong> and attaching meaningful <strong>tags</strong>. Inference profiles are not just routing identifiers. They are a practical control point to separate usage across products, tenants, or environments.</p><p>Think of it like setting up dedicated electricity meters in a building. The total power bill may be one number, but separate meters for each floor tell you exactly where energy is consumed. Inference profiles play a similar role for model invocation paths.</p><p>In this article, our target outcome is:</p><ul><li>Create one or more inference profiles per workload segment (for example, support-bot-prod, support-bot-staging).</li><li>Tag those profiles with cost allocation dimensions (team, product, environment, cost-center).</li><li>Invoke Bedrock using the inference profile identifier from .NET so usage maps cleanly to business context.</li><li>Use those tags in billing and reporting workflows.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KeJxi9-4nqg6I6GB.png" /><figcaption><em>Architecture showing .NET services invoking Bedrock through dedicated inference profiles with cost tracking</em></figcaption></figure><h4>2. When and Why Are We Doing This? (Application-Level Cost Tracking)</h4><p><strong>When to adopt this pattern:</strong></p><ul><li>When multiple AI features share the same Bedrock account and region.</li><li>When teams need showback or chargeback between business units.</li><li>When you run separate environments (dev, staging, prod) and want clean spend boundaries.</li><li>When your product managers need usage-to-value comparisons per feature, not just total AI spend.</li><li>When finance requires auditable allocation using tags and cost reports.</li></ul><h4>Why this is application-level, not only account-level</h4><p>Account-level reporting is useful for cloud governance, but product teams optimize at the application level. If one feature uses verbose prompts, long outputs, and high-cost models, you need to see that feature directly. Otherwise, optimization efforts are broad and ineffective.</p><p><strong>Application-level tracking gives you practical decisions:</strong></p><ul><li>Should this feature move from a larger model to a smaller model?</li><li>Should we cap output tokens in this workflow?</li><li>Which prompt templates are expensive relative to user value?</li><li>Which environment leaked unexpected traffic?</li></ul><blockquote>💡 Simple governance rule</blockquote><blockquote>If a feature can be independently prioritized by product and budget, it should have its own inference profile and tagging policy.</blockquote><h4>3. How Are We Doing It?</h4><p>We will implement this in three layers: profile creation, profile tagging, and profile-based invocation from .NET. You can create profiles manually for quick setup or through CloudFormation for repeatable infrastructure.</p><h4>Approach A: Manual Inference Profile Creation (Console + CLI)</h4><p>This is the fastest way to validate your design. Use it first when you are proving naming conventions and tag strategy with stakeholders.</p><ol><li>Open AWS Console and navigate to Bedrock inference profile management.</li><li>Create a profile with a clear workload-oriented name.</li><li>Select the model routing target as required by your workload.</li><li>Attach standard tags during creation.</li><li>Copy the generated profile identifier for app configuration.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4qshlLRJpakGIs4V.png" /><figcaption><em>AWS Bedrock console showing the inference profile creation form</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o6HqD0kLHdW7HBIF.png" /><figcaption><em>Bedrock console showing inference profile details with attached cost allocation tags</em></figcaption></figure><p>You can also do a similar operation with CLI for scripted experimentation:</p><pre># Code Sample #1 : Example CLI flow to create and tag an inference profile (illustrative)<br><br>aws bedrock create-inference-profile \<br>  --inference-profile-name support-bot-prod \<br>  --description &quot;Inference profile for support assistant in production&quot; \<br>  --model-source copyFrom=arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-haiku-20240307-v1:0<br><br>aws bedrock tag-resource \<br>  --resource-arn arn:aws:bedrock:us-east-1:123456789012:inference-profile/support-bot-prod \<br>  --tags key=environment,value=prod key=application,value=support-bot key=cost-center,value=cc-410</pre><blockquote>ℹ️ CLI note</blockquote><blockquote>CLI parameters evolve over time. Validate the latest command shape in official AWS Bedrock documentation before running in production automation.</blockquote><h4>Approach B: Creation via CloudFormation (recommended for production)</h4><p>Manual creation is useful for discovery. Production systems should move to Infrastructure as Code so profile names, tags, and routing definitions stay consistent across environments and accounts.</p><p>A typical CloudFormation template captures:</p><ul><li>Profile logical name and human-readable name.</li><li>Model source or routing reference.</li><li>Environment-aware tags.</li><li>Outputs for profile identifiers consumed by application configuration pipelines.</li></ul><pre># Code Sample #2 : CloudFormation template for application inference profile with cost allocation tags (guardrails excluded)<br><br># yaml-language-server: $schema=https://s3.amazonaws.com/cfn-resource-specifications-us-east-1-prod/schemas/2.15.0/all-spec.json<br>AWSTemplateFormatVersion: &quot;2010-09-09&quot;<br>Description: &gt;<br>    Creates an AWS Bedrock Application Inference Profile by copying from a<br>    foundation model or system-defined cross-region inference profile.<br>    Deploy once per environment; the output ARN can be dropped straight into<br>    AwsBedrockConverse as the modelId argument.<br><br>Parameters:<br>    InferenceProfileName:<br>        Type: String<br>        Description: &gt;<br>            Display name for the application inference profile.<br>            Allowed characters: alphanumeric, space, hyphen, underscore.<br>            Max 64 characters.<br>        Default: AwsBedrockConverse-ChatBot-Inference-Profile-CF<br>        AllowedPattern: &quot;^([0-9a-zA-Z][ _-]?)+$&quot;<br>        MinLength: 1<br>        MaxLength: 64<br><br>    InferenceProfileDescription:<br>        Type: String<br>        Description: Human-readable description of what this profile is used for.<br>        Default: Application inference profile for the AwsBedrockConverse chat-loop demo. Created via CloudFormation template.<br>        AllowedPattern: &quot;^([0-9a-zA-Z:.][ _-]?)+$&quot;<br>        MinLength: 1<br>        MaxLength: 200<br><br>    CopyFromArn:<br>        Type: String<br>        Description: &gt;<br>            ARN of the foundation model or system-defined cross-region inference<br>            profile to copy into this application profile.<br>        Default: &quot;arn:aws:bedrock:us-west-2:XXXXXXXXXX:inference-profile/us.meta.llama3-1-8b-instruct-v1:0&quot;<br><br>    Environment:<br>        Type: String<br>        Description: Deployment environment label (used in resource tags).<br>        Default: dev<br>        AllowedValues: [dev, staging, prod]<br><br>    BillingServiceName:<br>        Type: String<br>        Description: Billing cost-allocation tag value.<br>        Default: Default-App-Billing-Service<br><br>    TeamName:<br>        Type: String<br>        Description: Team or squad that owns this resource.<br>        Default: PoC-Team<br><br>Resources:<br>    BedrockApplicationInferenceProfile:<br>        Type: AWS::Bedrock::ApplicationInferenceProfile<br>        Properties:<br>            InferenceProfileName: !Ref InferenceProfileName<br>            Description: !Ref InferenceProfileDescription<br>            ModelSource:<br>                CopyFrom: !Ref CopyFromArn<br>            Tags:<br>                - Key: environment<br>                    Value: !Ref Environment<br>                - Key: SV:billing:service-name<br>                    Value: !Ref BillingServiceName<br>                - Key: team<br>                    Value: !Ref TeamName<br>                - Key: feature<br>                    Value: chat-loop<br>                - Key: managed-by<br>                    Value: cloudformation<br>                - Key: project<br>                    Value: aws-experiments<br>                - Key: AppName<br>                    Value: SampleBedrockAppUsingAIPUsingCloudFormation<br><br>Outputs:<br>    InferenceProfileId:<br>        Description: Unique identifier of the created application inference profile.<br>        Value: !GetAtt BedrockApplicationInferenceProfile.InferenceProfileId<br>        Export:<br>            Name: !Sub &quot;${AWS::StackName}-InferenceProfileId&quot;<br><br>    InferenceProfileArn:<br>        Description: &gt;<br>            Full ARN of the inference profile.<br>        Value: !GetAtt BedrockApplicationInferenceProfile.InferenceProfileArn<br>        Export:<br>            Name: !Sub &quot;${AWS::StackName}-InferenceProfileArn&quot;<br><br>    InferenceProfileStatus:<br>        Description: Status of the inference profile (ACTIVE once ready).<br>        Value: !GetAtt BedrockApplicationInferenceProfile.Status<br><br>    CreatedAt:<br>        Description: Timestamp when the inference profile was created.<br>        Value: !GetAtt BedrockApplicationInferenceProfile.CreatedAt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BvtDjMFQ32EnAKVp.png" /></figure><blockquote>💡 Why CloudFormation wins long-term</blockquote><blockquote>It gives repeatability, code review visibility, and drift control. Most importantly, it prevents accidental tag omissions that break cost allocation reports.</blockquote><h4>Tagging Strategy for Cost Attribution</h4><p>Tags are the bridge between technical usage and financial reporting. A profile without tags is like a transaction without metadata: it happened, but you cannot classify it reliably.</p><p>The screenshot shows both the tags you define and the tags CloudFormation adds automatically. Start with a small, mandatory taxonomy for the tags you control:</p><ul><li><strong>environment</strong>: dev.</li><li><strong>SV:billing:service-name</strong>: Default-App-Billing-Service.</li><li><strong>team</strong>: PoC-Team.</li><li><strong>feature</strong>: chat-loop.</li><li><strong>managed-by</strong>: cloudformation.</li><li><strong>project</strong>: aws-experiments.</li><li><strong>AppName</strong>: SampleBedrockAppUsingAIPUsingCloudFormation.</li></ul><p>CloudFormation also injects the resource lineage tags you see in the console, such as <strong>aws:cloudformation:stack-name</strong>, <strong>aws:cloudformation:stack-id</strong>, and <strong>aws:cloudformation:logical-id</strong>. Keep the user-defined values stable and lowercase where possible.</p><pre># Code Sample #3 : Suggested tag policy contract for inference profiles<br><br>{<br>  &quot;requiredTags&quot;: [<br>    &quot;environment&quot;,<br>    &quot;SV:billing:service-name&quot;,<br>    &quot;team&quot;,<br>    &quot;feature&quot;,<br>    &quot;managed-by&quot;,<br>    &quot;project&quot;,<br>    &quot;AppName&quot;<br>  ],<br>    &quot;allowedEnvironments&quot;: [&quot;dev&quot;, &quot;staging&quot;, &quot;prod&quot;],<br>    &quot;notes&quot;: [<br>        &quot;AppName matches the screenshot and can stay in PascalCase.&quot;,<br>        &quot;CloudFormation adds aws:cloudformation:* tags automatically.&quot;<br>    ]<br>}</pre><h4>Using the Inference Profile in .NET</h4><p>Creation and tagging are only half the story. To make attribution real, your application must invoke Bedrock through the profile identifier, not by directly coupling to a model identifier in each feature.</p><pre># Code Sample #4 : Converse request in .NET using inference profile ID<br><br>using Amazon.BedrockRuntime;<br>using Amazon.BedrockRuntime.Model;<br><br>var client = new AmazonBedrockRuntimeClient(Amazon.RegionEndpoint.USEast1);<br><br>string inferenceProfileId = configuration[&quot;Bedrock:InferenceProfileId&quot;]<br>    ?? throw new InvalidOperationException(&quot;Bedrock:InferenceProfileId is not configured.&quot;);<br><br>var request = new ConverseRequest<br>{<br>    ModelId = inferenceProfileId,<br>    Messages = new List&lt;Message&gt;<br>    {<br>        new()<br>        {<br>            Role = &quot;user&quot;,<br>            Content = new List&lt;ContentBlock&gt;<br>            {<br>                new() { Text = &quot;Summarize this support ticket in 3 bullet points.&quot; }<br>            }<br>        }<br>    },<br>    InferenceConfig = new InferenceConfiguration<br>    {<br>        MaxTokens = 300,<br>        Temperature = 0.2f<br>    }<br>};<br><br>var response = await client.ConverseAsync(request);<br>string output = response.Output.Message.Content.FirstOrDefault(c =&gt; c.Text != null)?.Text ?? string.Empty;var client = new AmazonBedrockRuntimeClient(Amazon.RegionEndpoint.USEast1);</pre><blockquote>ℹ️ Avoid hidden direct model IDs</blockquote><blockquote>If one code path still invokes a raw model ID, that traffic can bypass your cost allocation design. Enforce profile ID usage through shared abstractions and code review checks.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wxtK3aMzk25vxXbZ.png" /></figure><h4>Operational Checklist</h4><ul><li>Create separate profiles for each environment at minimum.</li><li>Require tags at creation time and block untagged resources in CI validation.</li><li>Store profile IDs in configuration per environment, not hardcoded in source.</li><li>Track token usage metrics and correlate with tag-based cost reports weekly.</li><li>Review top-cost profiles monthly and optimize prompt length, output caps, or model class.</li></ul><h4>Finally, track costs in cost explorer</h4><p>Once this setup is in place, validate attribution in Cost Explorer by filtering with the same <strong>AppName</strong> tag value used on the inference profile. This closes the loop between runtime invocation traffic and finance reporting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ULfZSG3AvJBcoCNX.png" /><figcaption><em>AWS Cost Explorer showing Bedrock costs filtered by AppName tag value from the inference profile</em></figcaption></figure><h4>Summary</h4><p>Application-level Bedrock cost tracking becomes much clearer when you standardize on inference profiles and tags. You are not just creating a billing view; you are building a feedback loop for product decisions.</p><ul><li><strong>What we did:</strong> Designed cost attribution through inference profiles for foundation model traffic.</li><li><strong>When and why:</strong> Used this pattern whenever multiple AI workloads need clean ownership and optimization accountability.</li><li><strong>How we did it:</strong> Covered manual profile creation, CloudFormation-based provisioning, and mandatory tagging strategy, plus .NET invocation through profile IDs.</li></ul><p>With this setup, the next time finance asks “where did the spend come from?”, your answer is not a guess. It is a report.</p><h4>References &amp; Further Reading</h4><ul><li><a href="https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles.html">Amazon Bedrock Inference Profiles</a></li><li><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html">AWS CloudFormation User Guide</a></li><li><a href="https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html">AWS Cost Allocation Tags</a></li></ul><p>Thanks for reading through. Please share feedback, if any, in comments or on my email <a href="/service/mailto:ajay.a338@gmail.com">ajay.a338@gmail.com</a></p><p><em>Originally published at </em><a href="https://devcodex.in/blog/ai/bedrock/inference-profile-cost-tracking/"><em>https://devcodex.in</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02f25f780ad6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streaming APIs in .NET: What, When, and How]]></title>
            <link>https://medium.com/@ajaykumar1807/streaming-apis-in-net-what-when-and-how-876565f900d7?source=rss-e26704d7d84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/876565f900d7</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Ajay kumar]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 17:15:53 GMT</pubDate>
            <atom:updated>2026-07-14T16:21:13.190Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E1jYykOf9sZf62US.png" /></figure><h4>🚰 What If Your API Could Talk While It Thinks?</h4><p>Picture this: you click <strong>Generate Report</strong> in your application, and then… nothing. The spinner keeps spinning. You start wondering whether the server is working, whether the request got stuck, or whether you should refresh the page and risk making it worse.</p><p>Most APIs are like that quiet restaurant kitchen where you place an order and hear absolutely nothing until the dish either arrives or never does.</p><p>But what if the API could behave more like a chef cooking at an open counter? First you hear, “<em>Order received.</em>” Then, “<em>Vegetables chopped.</em>” Then, “Sauce is ready.” Then finally, “Dish is served.” Suddenly the wait feels shorter because you can <strong>see progress happening in real time</strong>.</p><p>That is the core idea behind <strong>streaming APIs</strong>. Instead of making the client wait for one giant response at the end, the server sends useful pieces of data as they become available. For chat applications, that might be words appearing one by one. For dashboards, it might be live updates. For long-running jobs, it might be progress events.</p><p>Streaming is not only about speed. It is about <strong>perceived responsiveness</strong>. Even when total processing time stays the same, the user experience feels dramatically better when the client starts receiving data immediately.</p><blockquote>ℹ️ Why this matters</blockquote><blockquote>Streaming is not only about speed. It is about <strong>perceived responsiveness</strong>. Even when total processing time stays the same, the user experience feels dramatically better when the client starts receiving data immediately.</blockquote><h4>🌊 What Is a Streaming API?</h4><p>A <strong>streaming API</strong> is an API that sends data in multiple chunks over time instead of returning the complete response in one go. Think of a normal API response as getting an entire book delivered in a sealed box. A streaming API feels more like reading a newspaper being printed line by line as the presses run.</p><p>In a traditional request-response flow, the client sends one request, the server does all the work, and only then sends back the full payload. With streaming, the connection stays open and the server keeps pushing small messages while work is in progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LkkjELLjl5LKv61M2Nk2UA.png" /><figcaption>Streaming API — Concept</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7efsooBPJTM1hWYfcxIzw.png" /><figcaption>Traditional API vs Streaming API</figcaption></figure><h4><strong>The Common Shapes of Streaming</strong></h4><p>Not every streaming API looks the same. The three most common approaches are:</p><ul><li><strong>Server-Sent Events (SSE):</strong> Great when the server only needs to push updates to the client over regular HTTP.</li><li><strong>WebSockets:</strong> Best when both client and server need full two-way, low-latency communication.</li><li><strong>gRPC streaming:</strong> Common in service-to-service systems where performance and typed contracts matter.</li></ul><p>The demo in this article uses <strong>Server-Sent Events</strong> because it is the easiest way to explain the concept. It keeps the mental model simple: the server writes messages, and the client reads them as they arrive.</p><h4>🎯 When Should You Use Streaming APIs?</h4><p>Streaming is useful when the user benefits from receiving <strong>partial results early</strong>. If the final answer is expensive to compute, if updates keep changing, or if the client needs progress rather than silence, streaming is usually a better fit than a single buffered response.</p><p><strong>Real-World Cases Where Streaming Shines</strong></p><ul><li><strong>AI chat APIs:</strong> OpenAI, Anthropic, and AWS Bedrock stream generated text token by token so the answer starts appearing before the full model output is ready.</li><li><strong>Code assistants:</strong> Tools like GitHub Copilot feel responsive because suggestions can be produced progressively instead of waiting for one large completion payload.</li><li><strong>Market data APIs:</strong> Stock and crypto platforms stream price ticks because sending a fresh full response every second would be wasteful and slow.</li><li><strong>Infrastructure watch APIs:</strong> Kubernetes watch endpoints stream resource changes so clients can observe pod or deployment updates in near real time.</li><li><strong>Build and deployment logs:</strong> CI/CD systems often stream log output so you can watch a build fail at step 3 instead of waiting five minutes for a giant error dump.</li><li><strong>Progress-heavy business workflows:</strong> Video processing, report generation, file imports, and ETL jobs can stream milestones like queued, validating, transforming, and completed.</li></ul><h4>When Streaming Is Overkill</h4><p>Streaming is powerful, but it is not a default choice for every endpoint. If your API returns a small object in 50 milliseconds, there is no benefit in keeping the connection open and delivering the object in pieces.</p><h4>🛠️ How Does a Streaming API Work?</h4><p>Let us walk through the simplest mental model possible. Our in-house demo has two parts: a server that sends messages one at a time, and a client that reads those messages one at a time. That is enough to understand the entire pattern.</p><p><strong>Step 1: </strong>The Server Keeps the Connection Open</p><p>Instead of calculating everything and returning once, the server marks the response as text/event-stream. Then it writes small lines of text, flushes them, waits a bit, and repeats. Each flush pushes data to the client immediately.</p><pre>// Code Sample #1 : Server sending chunks using Server-Sent Events<br>private async Task HandleRequest(HttpListenerContext context)<br>{<br>    var response = context.Response;<br>    response.ContentType = &quot;text/event-stream&quot;;<br>    response.Headers.Add(&quot;Cache-Control&quot;, &quot;no-cache&quot;);<br>    response.Headers.Add(&quot;Connection&quot;, &quot;keep-alive&quot;);<br><br>    using var writer = new StreamWriter(response.OutputStream, Encoding.UTF8, leaveOpen: true);<br><br>    var messages = new[]<br>    {<br>        &quot;Starting data transmission&quot;,<br>        &quot;Chunk 1: Processing request&quot;,<br>        &quot;Chunk 2: Analyzing input&quot;,<br>        &quot;Chunk 3: Generating response&quot;,<br>        &quot;Chunk 4: Almost done&quot;,<br>        &quot;Chunk 5: Complete!&quot;<br>    };<br><br>    foreach (var msg in messages)<br>    {<br>        await writer.WriteLineAsync($&quot;data: {msg}&quot;);<br>        await writer.WriteLineAsync();<br>        await writer.FlushAsync();<br>        await Task.Delay(1500);<br>    }<br><br>    await writer.WriteLineAsync(&quot;data: [DONE]&quot;);<br>    await writer.FlushAsync();<br>    response.Close();<br>}</pre><p>There are two important details here. First, each message is prefixed with data:, which is the standard SSE format. Second, FlushAsync() is what makes the data visible to the client right away. Without flushing, the server may buffer the output and the client would not feel the stream.</p><p><strong>Step 2: </strong>The Client Starts Reading Before the Server Finishes</p><p>On the client side, the key is to read the response as a stream, not as one finished string. That is why the demo uses HttpCompletionOption.ResponseHeadersRead. It tells HttpClient: &quot;<em>Give me the response as soon as headers arrive. I will read the body myself as it comes in.</em>&quot;</p><pre>// Code Sample #2 : Client reading streaming data line by line<br>public static async Task ConsumerAsync()<br>{<br>    using var client = new HttpClient();<br><br>    using var response = await client.GetAsync(&quot;http://localhost:8080/stream&quot;,<br>        HttpCompletionOption.ResponseHeadersRead);<br><br>    using var stream = await response.Content.ReadAsStreamAsync();<br>    using var reader = new StreamReader(stream);<br><br>    while (!reader.EndOfStream)<br>    {<br>        var line = await reader.ReadLineAsync();<br>        if (string.IsNullOrWhiteSpace(line)) continue;<br><br>        if (line.StartsWith(&quot;data: &quot;))<br>        {<br>            var data = line.Substring(&quot;data: &quot;.Length);<br>            if (data == &quot;[DONE]&quot;)<br>            {<br>                break;<br>            }<br><br>            Console.WriteLine($&quot;Received: {data}&quot;);<br>        }<br>    }<br>}</pre><p>This is the moment streaming becomes real. The client is no longer waiting for the last byte of the response. It is reacting chunk by chunk. That same pattern powers AI typing effects, live dashboards, and log viewers.</p><p><strong>Step 3:</strong> A Minimal End-to-End Example</p><pre>// Code Sample #3 : Final bootstrap step for the already-defined streaming server and client<br>public static async Task Main(string[] args)<br>{<br>    var server = new StreamingServer();<br><br>    var serverTask = server.StartAsync();<br>    await Task.Delay(1000);<br><br>    try<br>    {<br>        await ConsumerAsync();<br>    }<br>    finally<br>    {<br>        server.Stop();<br>    }<br>}</pre><p>The snippet below is the final bootstrap step, assuming the server and consumer methods shown earlier are already defined.</p><h4>🧭 Choosing the Right Streaming Style</h4><p>Once the concept clicks, the next question is usually: <strong>Which transport should I pick?</strong> A good rule of thumb is to match the tool to the communication pattern.</p><ul><li><strong>Use SSE</strong> when the server needs to push a steady stream of updates to a browser or client and the client mostly listens.</li><li><strong>Use WebSockets</strong> when both sides need to send messages freely, like chat rooms, multiplayer games, or collaborative editing.</li><li><strong>Use gRPC streaming</strong> when services talk to services and you want strong contracts, binary efficiency, and high throughput.</li></ul><p>One simple way to remember the difference is this: <strong>SSE is one-way</strong>, from server to client, while <strong>WebSockets are two-way</strong>, allowing both sides to send messages whenever they need to.</p><p>In other words, SSE is like a radio broadcast, WebSockets are like a phone call, and gRPC streaming is like a private fiber line between two offices.</p><h4>✅ Summary</h4><p>Streaming APIs solve a very human problem: <strong>waiting in silence feels slow and uncertain</strong>. By sending data progressively, they make applications feel alive, responsive, and trustworthy.</p><ul><li><strong>What:</strong> A streaming API delivers multiple chunks over time instead of one final payload.</li><li><strong>When:</strong> Use it for AI responses, logs, market feeds, progress-heavy jobs, and live state updates.</li><li><strong>How:</strong> Keep the connection open, flush chunks from the server, and read them incrementally on the client.</li></ul><p>If you remember one thing from this article, let it be this: a streaming API is not magic. It is just a polite API that does not wait until the very end to start talking.</p><p><em>Originally published at </em><a href="https://devcodex.in/blog/software-practices/streaming-apis-explained"><em>https://devcodex.in</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=876565f900d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Bedrock with .NET: Guardrails for Safe AI Applications]]></title>
            <link>https://medium.com/@ajaykumar1807/aws-bedrock-with-net-guardrails-for-safe-ai-applications-39600e9d6881?source=rss-e26704d7d84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/39600e9d6881</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Ajay kumar]]></dc:creator>
            <pubDate>Sun, 17 May 2026 18:35:47 GMT</pubDate>
            <atom:updated>2026-05-17T18:35:47.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ettIPzFw91crZQ5BU2ahxA.png" /></figure><h4>The Problem: An AI With No Boundaries</h4><p>Picture this: your team ships a customer support chatbot powered by AWS Bedrock. Within a week, you get a support ticket — a user tricked the bot into writing Python code, another coaxed it into sharing someone else’s email address from a previous response, and one sent a barrage of hateful messages that the model cheerfully responded to.</p><p>You didn’t build a bad AI. You built one with no guardrails.</p><p>In the real world, AI models are powerful but they don’t know where the boundaries are — unless you tell them. That’s exactly what <strong>AWS Bedrock Guardrails</strong> are for.</p><blockquote>ℹ️ Part of the Bedrock Series</blockquote><blockquote>This is the fourth article in the AWS Bedrock with .NET series. We’ve previously covered <a href="https://medium.com/@ajaykumar1807/aws-bedrock-with-net-getting-started-8169027d6746">Getting Started with AWS Bedrock</a>, the <a href="https://medium.com/@ajaykumar1807/aws-bedrock-with-net-conversational-ai-converse-api-3ca658806415">Converse API</a>, and <a href="https://medium.com/@ajaykumar1807/aws-bedrock-with-net-converse-api-with-tools-da6fae30efd9">Converse API with Tools</a>. This article builds on the same setup.</blockquote><h4>🛡️ What Are AWS Bedrock Guardrails?</h4><p>AWS Bedrock Guardrails are a configurable safety layer you attach to your AI model calls. Think of them as a strict — but invisible — security guard standing between your users and the model.</p><p>Before the user’s message even reaches the model, the guardrail inspects it. After the model responds, the guardrail checks the output too. If anything violates your policy — hateful language, off-topic requests, personally identifiable information — the guardrail either blocks the message entirely or silently redacts the sensitive parts.</p><p>Guardrails give you three distinct safety capabilities:</p><ul><li><strong>Content Filters:</strong> Block hate speech, violence, insults, sexual content, and prompt injection attacks at configurable sensitivity levels (LOW, MEDIUM, HIGH).</li><li><strong>Topic Denial:</strong> Define topics the model must refuse to engage with — like coding help or entertainment requests in a customer support context.</li><li><strong>PII Redaction:</strong> Automatically anonymise personally identifiable information like names, emails, phone numbers, and IP addresses in both input and output.</li></ul><p>Guardrails are defined independently of your model. You create one, publish it as a versioned snapshot, then attach it to any Converse API call. Swap models, keep the same guardrail — your safety policy travels with the application, not the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SaOjS33FWgz7RMR6.png" /><figcaption><em>Figure 1 : AWS Bedrock Guardrails Architecture: Input assessment, model processing, and output assessment flow</em></figcaption></figure><h4>🎯 When Should You Use Guardrails?</h4><p>Guardrails are not optional for production AI applications. Here are the scenarios where they become essential:</p><ul><li><strong>Customer-facing chatbots:</strong> Any bot a real user can interact with needs content filters to prevent abuse and hateful prompts from getting through.</li><li><strong>Scoped assistants:</strong> A billing assistant should only answer billing questions. Topic denial lets you enforce that boundary deterministically — no matter how cleverly a user phrases their request.</li><li><strong>Regulated industries:</strong> Healthcare, finance, and legal applications must not leak PII. PII redaction handles this transparently before the model ever sees the data.</li><li><strong>Multi-tenant systems:</strong> Different guardrail versions per tenant means you can dial up or down the strictness for different customer tiers.</li></ul><blockquote>💡 Guardrails are versioned</blockquote><blockquote>Think of guardrail versions like Git commits — each version is a snapshot. When you publish version 2 with stricter rules, your production bot stays on version 1 until you explicitly tell it to upgrade. This prevents accidental policy changes from breaking production.</blockquote><h4>🏗️ How: Building a Guardrailed Customer Support Bot</h4><p>Now that you understand what guardrails are and when to use them, let’s build a complete, production-ready example. We’ll create a customer support bot with all three safety mechanisms: content filtering, topic denial, and PII redaction. The implementation follows a three-stage flow: create the guardrail, publish a version, and attach it to your Converse API calls.</p><h4><strong>Prerequisites</strong></h4><ul><li>An AWS account with Bedrock access enabled in us-east-1</li><li>AWS credentials configured (see the <a href="https://devcodex.in/blog/ai/bedrock">Getting Started article</a>)</li><li>.NET 9 SDK installed</li><li>The following NuGet packages:</li></ul><pre>// Code Sample #1 : Install the required AWS SDK packages<br>dotnet add package AWSSDK.Bedrock<br>dotnet add package AWSSDK.BedrockRuntime</pre><p><strong>Step 1 — Resolve the Namespace Conflict</strong></p><p>Both AWSSDK.Bedrock and AWSSDK.BedrockRuntime define types with similar names. To keep things clean, alias the ambiguous types at the top of your service file.</p><pre>// Code Sample #2 : Namespace aliases to resolve type conflicts<br>// Alias to keep both namespaces usable side-by-side<br>using BedrockGuardrailConfiguration =<br>    Amazon.BedrockRuntime.Model.GuardrailConfiguration;<br>using BedrockContentFilterType =<br>    Amazon.Bedrock.GuardrailContentFilterType;</pre><p><strong>Step 2 — Create a Guardrail with Content Filters</strong></p><p>Creating a guardrail is a one-time provisioning step — you describe your safety policy and Bedrock stores it. Here we configure content filters to block hate, insults, misconduct, and prompt injection attempts:</p><pre>// Code Sample #3 : Create a guardrail with content filters<br>var createRequest = new CreateGuardrailRequest<br>{<br>    Name        = $&quot;customer-support-guardrail-{DateTime.UtcNow:yyyyMMddHHmmss}&quot;,<br>    Description = &quot;Content filters + topic denial + PII redaction for a customer support chatbot&quot;,<br><br>    ContentPolicyConfig = new GuardrailContentPolicyConfig<br>    {<br>        FiltersConfig = new List&lt;GuardrailContentFilterConfig&gt;<br>        {<br>            new() { Type = BedrockContentFilterType.HATE,<br>                    InputStrength  = GuardrailFilterStrength.HIGH,<br>                    OutputStrength = GuardrailFilterStrength.HIGH },<br>            new() { Type = BedrockContentFilterType.SEXUAL,<br>                    InputStrength  = GuardrailFilterStrength.HIGH,<br>                    OutputStrength = GuardrailFilterStrength.HIGH },<br>            new() { Type = BedrockContentFilterType.VIOLENCE,<br>                    InputStrength  = GuardrailFilterStrength.MEDIUM,<br>                    OutputStrength = GuardrailFilterStrength.MEDIUM },<br>            new() { Type = BedrockContentFilterType.INSULTS,<br>                    InputStrength  = GuardrailFilterStrength.MEDIUM,<br>                    OutputStrength = GuardrailFilterStrength.MEDIUM },<br>            new() { Type = BedrockContentFilterType.MISCONDUCT,<br>                    InputStrength  = GuardrailFilterStrength.HIGH,<br>                    OutputStrength = GuardrailFilterStrength.HIGH },<br>            new() { Type = BedrockContentFilterType.PROMPT_ATTACK,<br>                    InputStrength  = GuardrailFilterStrength.MEDIUM,<br>                    OutputStrength = GuardrailFilterStrength.NONE },<br>        }<br>    },<br><br>    BlockedInputMessaging   = &quot;[BLOCKED] Your message was blocked by the content policy.&quot;,<br>    BlockedOutputsMessaging = &quot;[BLOCKED] The response was blocked by the content policy.&quot;<br>};<br><br>var createResponse = await _bedrockClient.CreateGuardrailAsync(createRequest);<br>string guardrailId = createResponse.GuardrailId;</pre><p>Each filter has an InputStrength (what comes from the user) and an OutputStrength (what the model sends back). You can tune them independently — for instance, be strict on hate speech in both directions but only inspect inputs for prompt injection.</p><p><strong>Step 3 — Add Topic Denial</strong></p><p>Content filters handle <em>how</em> something is said. Topic denial handles <em>what</em> is asked. For a customer support bot that should only handle orders, billing, and shipping — everything else gets denied:</p><pre>// Code Sample #4 : Configure topic denial policy<br>TopicPolicyConfig = new GuardrailTopicPolicyConfig<br>{<br>    TopicsConfig = new List&lt;GuardrailTopicConfig&gt;<br>    {<br>        new()<br>        {<br>            Name       = &quot;off-topic-requests&quot;,<br>            Definition = &quot;Requests asking for entertainment, general knowledge, &quot; +<br>                         &quot;recipes, coding help, jokes, or trivia unrelated to &quot; +<br>                         &quot;customer support operations.&quot;,<br>            Examples   = new List&lt;string&gt;<br>            {<br>                &quot;Tell me a joke&quot;,<br>                &quot;What is the capital of France?&quot;,<br>                &quot;How do I write Python code?&quot;,<br>                &quot;Give me a recipe for pasta&quot;,<br>                &quot;What&#39;s the weather today?&quot;<br>            },<br>            Type = GuardrailTopicType.DENY<br>        }<br>    }<br>}</pre><p>Code Sample #4 : Configure topic denial policy</p><p>Bedrock uses the definition and examples to understand the intent of a denied topic. The more precise your definition, the more reliably it catches real-world variations of the same request.</p><p><strong>Step 4 — Enable PII Redaction</strong></p><p>PII redaction happens silently. Before your prompt reaches the model, Bedrock anonymises detected PII — replacing a real name, email, or phone number with a placeholder. The model never sees the raw data:</p><pre>// Code Sample #5 : Configure PII anonymisation<br>SensitiveInformationPolicyConfig = new GuardrailSensitiveInformationPolicyConfig<br>{<br>    PiiEntitiesConfig =<br>    [<br>        new() { Type   = GuardrailPiiEntityType.EMAIL,<br>                Action = GuardrailSensitiveInformationAction.ANONYMIZE },<br>        new() { Type   = GuardrailPiiEntityType.PHONE,<br>                Action = GuardrailSensitiveInformationAction.ANONYMIZE },<br>        new() { Type   = GuardrailPiiEntityType.NAME,<br>                Action = GuardrailSensitiveInformationAction.ANONYMIZE },<br>        new() { Type   = GuardrailPiiEntityType.IP_ADDRESS,<br>                Action = GuardrailSensitiveInformationAction.ANONYMIZE },<br>    ]<br>}</pre><blockquote>ℹ️ PII redaction is transparent</blockquote><blockquote>Because redaction happens before the model processes input, the model never sees the real name or email — it only sees the anonymised token (e.g., [NAME]). This means PII redaction won&#39;t appear in the guardrail trace as a policy violation — it simply happens silently.</blockquote><p><strong>Step 5 — Publish a Version</strong></p><p>After creation, a guardrail lives in DRAFT state. You publish a numbered version to lock it down for use in production:</p><pre>// Code Sample #6 : Publish a versioned guardrail snapshot<br>var versionResponse = await _bedrockClient.CreateGuardrailVersionAsync(<br>    new CreateGuardrailVersionRequest<br>    {<br>        GuardrailIdentifier = guardrailId,<br>        Description         = &quot;Initial production version&quot;<br>    });<br><br>string version = versionResponse.Version;<br>Console.WriteLine($&quot;Guardrail published as version: {version}&quot;);</pre><p><strong>Step 6 — Attach the Guardrail to a Converse API Call</strong></p><p>With the guardrail provisioned and versioned, attaching it to a model call is a single property on the ConverseRequest. Everything else stays identical to a standard Converse call:</p><pre>// Code Sample #7 : Attach guardrail to a Converse API request<br>var request = new ConverseRequest<br>{<br>    ModelId = &quot;openai.gpt-oss-20b-1:0&quot;,<br>    System  = new List&lt;SystemContentBlock&gt;<br>    {<br>        new() { Text = &quot;You are a helpful customer support assistant. &quot; +<br>                       &quot;Help customers with order tracking, billing questions, &quot; +<br>                       &quot;shipping issues, and technical support. Be professional, &quot; +<br>                       &quot;empathetic, and courteous. Keep your answers concise.&quot; }<br>    },<br>    Messages = new List&lt;Message&gt;<br>    {<br>        new()<br>        {<br>            Role    = &quot;user&quot;,<br>            Content = new List&lt;ContentBlock&gt; { new() { Text = userInput } }<br>        }<br>    },<br>    GuardrailConfig = new BedrockGuardrailConfiguration<br>    {<br>        GuardrailIdentifier = guardrailId,<br>        GuardrailVersion    = version,<br>        Trace               = GuardrailTrace.Enabled   // see which policies fire<br>    }<br>};<br><br>var response    = await _runtimeClient.ConverseAsync(request);<br>bool intervened = response.StopReason == StopReason.Guardrail_intervened;<br>string output   = response.Output?.Message?.Content<br>    .FirstOrDefault(c =&gt; c.Text != null)?.Text<br>    ?? &quot;[no text content]&quot;;<br><br>Console.WriteLine(intervened ? &quot;⚠️  GUARDRAIL INTERVENED&quot; : &quot;✅ PASSED&quot;);<br>Console.WriteLine(output);var response    = await _runtimeClient.ConverseAsync(request);<br>bool intervened = response.StopReason == StopReason.Guardrail_intervened;<br>string output   = response.Output?.Message?.Content<br>    .FirstOrDefault(c =&gt; c.Text != null)?.Text<br>    ?? &quot;[no text content]&quot;;</pre><p>When StopReason is Guardrail_intervened, the output text will contain your configured BlockedOutputsMessaging rather than a model response. Your application code should check this flag and handle it gracefully — show a friendly message rather than a raw blocked string.</p><p><strong>Step 7 — Read the Guardrail Trace</strong></p><p>Enabling Trace = GuardrailTrace.Enabled gives you detailed visibility into which policies fired and why. This is invaluable during development and for audit logging in production:</p><pre>// Code Sample #8 : Helper method to extract policy violations from the guardrail trace<br>private static string GetViolatedPolicy(GuardrailTraceAssessment trace)<br>{<br>    var violations = new List&lt;string&gt;();<br><br>    // Check input assessments<br>    if (trace.InputAssessment != null)<br>    {<br>        foreach (var (_, assessment) in trace.InputAssessment)<br>        {<br>            if (assessment.ContentPolicy?.Filters?.Count &gt; 0)<br>                violations.Add(&quot;Content Filter&quot;);<br>            if (assessment.TopicPolicy?.Topics?.Count &gt; 0)<br>            {<br>                var topicNames = assessment.TopicPolicy.Topics<br>                    .Where(t =&gt; !string.IsNullOrEmpty(t.Name))<br>                    .Select(t =&gt; t.Name)<br>                    .Distinct();<br>                violations.Add($&quot;Topic Policy: {string.Join(&quot;, &quot;, topicNames)}&quot;);<br>            }<br>            if (assessment.SensitiveInformationPolicy?.PiiEntities?.Count &gt; 0)<br>                violations.Add(&quot;PII&quot;);<br>        }<br>    }<br><br>    // Check output assessments<br>    if (trace.OutputAssessments != null)<br>    {<br>        foreach (var (_, assessments) in trace.OutputAssessments)<br>        {<br>            foreach (var assessment in assessments)<br>            {<br>                if (assessment.ContentPolicy?.Filters?.Count &gt; 0)<br>                    violations.Add(&quot;Content Filter&quot;);<br>                if (assessment.TopicPolicy?.Topics?.Count &gt; 0)<br>                {<br>                    var topicNames = assessment.TopicPolicy.Topics<br>                        .Where(t =&gt; !string.IsNullOrEmpty(t.Name))<br>                        .Select(t =&gt; t.Name)<br>                        .Distinct();<br>                    violations.Add($&quot;Topic Policy: {string.Join(&quot;, &quot;, topicNames)}&quot;);<br>                }<br>                if (assessment.SensitiveInformationPolicy?.PiiEntities?.Count &gt; 0)<br>                    violations.Add(&quot;PII&quot;);<br>            }<br>        }<br>    }<br><br>    return violations.Count &gt; 0 ? string.Join(&quot;, &quot;, violations.Distinct()) : &quot;Unknown Policy&quot;;<br>}    // Check input assessments<br>    if (trace.InputAssessment != null)<br>    {<br>        foreach (var (_, assessment) in trace.InputAssessment)<br>        {<br>            if (assessment.ContentPolicy?.Filters?.Count &gt; 0)<br>                violations.Add(&quot;Content Filter&quot;);<br>            if (assessment.TopicPolicy?.Topics?.Count &gt; 0)<br>            {<br>                var topicNames = assessment.TopicPolicy.Topics<br>                    .Where(t =&gt; !string.IsNullOrEmpty(t.Name))<br>                    .Select(t =&gt; t.Name)<br>                    .Distinct();<br>                violations.Add($&quot;Topic Policy: {string.Join(&quot;, &quot;, topicNames)}&quot;);<br>            }<br>            if (assessment.SensitiveInformationPolicy?.PiiEntities?.Count &gt; 0)<br>                violations.Add(&quot;PII&quot;);<br>        }<br>    }</pre><blockquote>💡 Try it yourself</blockquote><blockquote>The full working code with the GetViolatedPolicy helper is available at <a href="https://github.com/ajaysskumar/ai-playground/blob/main/AwsBedrockExamples/Services/BedrockGuardrailsDemoService.cs">ajaysskumar/ai-playground</a>. This helper extracts violations from both input and output assessments to give you a clear picture of what policies fired.</blockquote><p><strong>Testing the Guardrail — What to Expect</strong></p><p>Here’s what you’ll see when running the interactive demo with the guardrail configured. Each test case illustrates one of the three safety mechanisms in action:</p><pre># Code Sample #9 : Running the bedrock-guardrails demo and testing all four scenarios<br>dotnet run --project AwsBedrockExamples -- --demo bedrock-guardrails<br>Starting AI Demo: bedrock-guardrails</pre><pre>=== AWS Bedrock Guardrails Demo ===<br>This demo creates a Guardrail with content filters, topic denial, and PII redaction.<br>Test it interactively with custom questions.</pre><pre>&gt;&gt;&gt; Creating guardrail...<br>    Guardrail created  → ID: 5ygui4clw0sc  (status: DRAFT)<br>&gt;&gt;&gt; Publishing guardrail version...<br>    Version published  → 1</pre><pre>=== Interactive Mode: Test Custom Questions ===</pre><pre>Enter your questions to test against the guardrail.<br>Type &#39;exit&#39; to end the session.</pre><pre>Your question &gt; Where is my order ORD-001? Placed 3 days ago.</pre><pre>Stop Reason: end_turn<br>Status : PASSED<br>Model  : Hi there!  <br>I&#39;ve pulled up your order history and you&#39;re on track—ORD‑001 was processed and shipped out 3 days ago. Here are the details:</pre><pre>| Item | Status | Tracking # | Carrier | Estimated Delivery |<br>|------|--------|-----------|---------|---------------------|<br>| Your Purchase | Shipped | 34C89D5B00 | UPS | 4–5 business days (Fin** 30th)** |</pre><pre>You can also view the full tracking history by logging into your account and visiting the **Orders** section, or by clicking the link below:</pre><pre>🔗 [Track ORD-001 »](#)</pre><pre>If the package hasn&#39;t moved on the tracking system within the next 24 hours or you have any other concerns, just let me know and I&#39;ll investigate right away. Thanks for shopping with us!</pre><pre>Your question &gt; Tell me something funny to cheer me up</pre><pre>Stop Reason: guardrail_intervened<br>Status : GUARDRAIL INTERVENED - Topic Policy: off-topic-requests<br>Model  : [BLOCKED] Your message was blocked by the content policy.</pre><pre>Your question &gt; You&#39;re all useless idiots! I hate this company!</pre><pre>Stop Reason: guardrail_intervened<br>Status : GUARDRAIL INTERVENED - Content Filter<br>Model  : [BLOCKED] Your message was blocked by the content policy.</pre><pre>Your question &gt; Hi, I&#39;m John Smith. Email me at john@smith.com. Alternatively, can you send me your email to follow up as well?</pre><pre>Stop Reason: guardrail_intervened<br>Status : GUARDRAIL INTERVENED - PII<br>Model  : Hi {NAME},</pre><pre>Thanks for contacting us.  <br>You can reach our support team directly at **{EMAIL}**.  <br>If you&#39;d like to continue the conversation here, just let me know the details of your request and I&#39;ll help right away.</pre><pre>Feel free to reply to this email or use the chat window—whichever you prefer.</pre><pre>Best regards,  <br>[Your Name]  <br>Customer Support Team</pre><pre>Your question &gt; exit</pre><pre>Exiting interactive mode.</pre><p>Notice how each test case behaves exactly as predicted:</p><ul><li><strong>First prompt</strong> passes cleanly with a detailed model response.</li><li><strong>Second prompt</strong> triggers topic denial — the guardrail recognises the off-topic nature and responds with your configured blocked message.</li><li><strong>Third prompt</strong> is caught by the content filter for hateful language — regardless of domain.</li><li><strong>Fourth prompt</strong> shows PII redaction in action both ways: the model never sees the real name/email in input, and the output gets anonymised with template tokens.</li></ul><h4>📋 Key Takeaways</h4><p>AWS Bedrock Guardrails give you a production-grade safety layer that operates independently of your model choice. They’re not an afterthought — they’re a critical piece of any customer-facing AI application.</p><p><strong>What We Built</strong></p><p>In this article, we built a complete, guardrailed customer support bot. Here’s what you learned:</p><ul><li>How to <strong>configure content filters</strong> to block harmful language at configurable sensitivity levels (LOW, MEDIUM, HIGH)</li><li>How to enforce <strong>topic boundaries</strong> so a support bot stays focused on its scope and refuses off-topic requests</li><li>How to silently <strong>redact PII</strong> from both input and output before the model ever touches it — protecting customer privacy at the guardrail layer</li><li>How to <strong>version guardrails</strong> independently of models so you can iterate safety policy in staging without affecting production</li><li>How to <strong>attach and trace</strong> guardrails in live Converse API calls to monitor which policies fire and why</li></ul><p><strong>Why This Matters</strong></p><p>Guardrails aren’t a luxury feature. They’re the difference between a prototype and a production system. They give you:</p><ul><li><strong>Reduced risk:</strong> Content filters prevent abuse, hate, and prompt injection before it reaches your model</li><li><strong>Compliance coverage:</strong> PII redaction handles GDPR and HIPAA requirements automatically</li><li><strong>Predictable behavior:</strong> Topic denial enforces your bot’s scope deterministically — no surprises in production</li><li><strong>Audit trails:</strong> Guardrail traces give you visibility into what policies fired and when</li></ul><p><strong>Next Steps</strong></p><p>The full working code is available in the <a href="https://github.com/ajaysskumar/ai-playground">ajaysskumar/ai-playground</a> repository under AwsBedrockExamples/Services/BedrockGuardrailsDemoService.cs. Clone it, run the demo, and start adding guardrails to your own Bedrock workflows today.</p><p>If you haven’t read the previous articles in the Bedrock series, start with <a href="https://medium.com/@ajaykumar1807/aws-bedrock-with-net-getting-started-8169027d6746">Getting Started with AWS Bedrock</a> to understand the foundation.</p><p><strong>Related Resources:</strong></p><ul><li><a href="https://github.com/ajaysskumar/ai-playground/blob/main/AwsBedrockExamples/Services/BedrockGuardrailsDemoService.cs">BedrockGuardrailsDemoService.cs</a> — Complete guardrails implementation with trace parsing</li><li><a href="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html">AWS Bedrock Guardrails Documentation</a> — Official AWS reference for all guardrail features</li><li><a href="https://docs.aws.amazon.com/bedrock/latest/APIReference/API_GuardrailConfiguration.html">GuardrailConfiguration API Reference</a> — Complete API documentation</li></ul><blockquote>ℹ️ 🎓 Series Complete</blockquote><blockquote>Congratulations! You’ve mastered the complete AWS Bedrock lifecycle in .NET: from basics → production auth → conversational AI → structured outputs → safety guardrails. Ready to build production GenAI applications? <a href="https://github.com/ajaysskumar/ai-playground">Explore the full code examples on GitHub.</a></blockquote><p>For reference, the code repository being discussed is available at github: <a href="https://github.com/ajaysskumar/ai-playground">https://github.com/ajaysskumar/ai-playground</a></p><p>Thanks for reading through. Please share feedback, if any, in comments or on my email <a href="/service/mailto:ajay.a338@gmail.com">ajay.a338@gmail.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39600e9d6881" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Bedrock with .NET: Converse API with Tools]]></title>
            <link>https://medium.com/@ajaykumar1807/aws-bedrock-with-net-converse-api-with-tools-da6fae30efd9?source=rss-e26704d7d84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/da6fae30efd9</guid>
            <category><![CDATA[aws-bedrock]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Ajay kumar]]></dc:creator>
            <pubDate>Sun, 17 May 2026 15:07:12 GMT</pubDate>
            <atom:updated>2026-05-17T15:07:12.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2AW7W8qF2cdmlPLDyr2zPQ.png" /></figure><h4>The Problem: You Can’t Trust Plain Text</h4><p>You ask the AI for movie details. It responds with a beautifully written paragraph. Now your code needs to extract the title, the year, the director, and the rating from that paragraph. So you write a regex. It works — until the model rephrases something slightly differently, and suddenly your parser breaks silently in production.</p><p>This is the fragility of relying on plain text responses from AI models. The output looks right to a human, but it is unpredictable for a machine. Prompt engineering can nudge the model toward a format, but it cannot enforce one.</p><blockquote>ℹ️ The core problem</blockquote><blockquote>Without a contract between your code and the model’s output, every response is a gamble. One rephrase and your downstream logic breaks.</blockquote><h4>What is the Converse API with Tools?</h4><p>AWS Bedrock’s <strong>Converse API</strong> can be supercharged with <strong>tools</strong> — structured interfaces that let the model call functions, enforce output schemas, or interact with external systems. This enables developers to build AI agents that not only chat, but also return structured data, trigger workflows, or integrate with business logic.</p><p>In this article, you’ll learn how to use the Converse API with tools to guarantee structured, reliable responses from generative AI models. We’ll walk through a real-world example: extracting detailed movie information as JSON using a tool schema.</p><blockquote>ℹ️ Why Tools?</blockquote><blockquote>Tools let you move beyond plain text. They enable the model to return data in a format your application can consume directly — no more brittle prompt engineering or regex parsing!</blockquote><h4>When and Why to Use Tools with Converse API</h4><ul><li><strong>Structured Output:</strong> Enforce JSON schemas for reliable, machine-readable responses.</li><li><strong>Function Calling:</strong> Let the model trigger business logic, database queries, or API calls.</li><li><strong>Data Extraction:</strong> Extract entities, summaries, or analytics from unstructured text.</li><li><strong>Workflow Automation:</strong> Build agents that can take actions, not just answer questions.</li></ul><p>Use tools when you need more than just a chat — you want the AI to work as part of your system.</p><h4>How: Building a Movie Info Extractor with Converse Tools</h4><h4>Prerequisites</h4><ul><li>AWS account with Bedrock access enabled.</li><li>AWS credentials with permissions for Bedrock Converse API and tools.</li><li>.NET 8 or later SDK installed.</li><li>NuGet package: <strong>AWSSDK.BedrockRuntime</strong></li></ul><h4>Service Implementation Example</h4><p>This example is broken into smaller steps for clarity. Let’s walk through each part of the service.</p><p><strong>Step 1: Service Setup</strong></p><p>Define the service class with a Bedrock client and the model ID. The client is initialised with the target AWS region.</p><pre>using Amazon.BedrockRuntime;<br>using Amazon.BedrockRuntime.Model;<br>using Amazon.Runtime.Documents;<br>using System.Text.Json;<br><br>public class BedrockWithConverseToolsService<br>{<br>    private readonly AmazonBedrockRuntimeClient _client;<br>    private const string ModelId = &quot;anthropic.claude-3-haiku-20240307-v1:0&quot;;<br><br>    public BedrockWithConverseToolsService()<br>    {<br>        _client = new AmazonBedrockRuntimeClient(Amazon.RegionEndpoint.USEast1);<br>    }<br>}</pre><p><strong>Step 2: Sending the Request</strong></p><p>Build the user message with the movie query, attach the tool configuration, and send the request to Bedrock. After receiving the response, locate the tool use block that contains the structured output.</p><pre>public async Task&lt;string&gt; GetMovieDetailsAsJson(string movieQuery)<br>{<br>    // Build the tool configuration - this GUARANTEES the output structure<br>    var toolConfig = BuildToolConfiguration();<br><br>    var userMessage = new Message<br>    {<br>        Role = &quot;user&quot;,<br>        Content = new List&lt;ContentBlock&gt;<br>        {<br>            new ContentBlock<br>            {<br>                Text = $&quot;Provide detailed information about the movie &#39;{movieQuery}&#39;.&quot;<br>            }<br>        }<br>    };<br><br>    var converseRequest = new ConverseRequest<br>    {<br>        ModelId = ModelId,<br>        Messages = new List&lt;Message&gt; { userMessage },<br>        ToolConfig = toolConfig,<br>        System = new List&lt;SystemContentBlock&gt;<br>        {<br>            new SystemContentBlock { Text = &quot;You are a movie information expert&quot; }<br>        }<br>    };<br><br>    var response = await _client.ConverseAsync(converseRequest);<br><br>    if (response?.Output?.Message?.Content == null)<br>        return JsonSerializer.Serialize(new { error = &quot;Invalid response from Bedrock&quot; });<br><br>    // Find the tool use response - in v4 it&#39;s accessed via ToolUse property<br>    var toolUseBlock = response.Output.Message.Content<br>        .FirstOrDefault(c =&gt; c.ToolUse != null);<br><br>    if (toolUseBlock?.ToolUse == null)<br>        return JsonSerializer.Serialize(new { error = &quot;Model did not use the expected tool&quot; });<br><br>    // Extract the structured data from the tool input<br>    return ExtractMovieInfoAsJson(toolUseBlock.ToolUse.Input);<br>}</pre><p><strong>Step 3: Defining the Tool Schema</strong></p><p>The tool schema is the key piece — it tells the model exactly what shape the output must take. We define a movies array with required fields for each entry. Setting ToolChoice to the specific tool name forces the model to always use it.</p><pre>private ToolConfiguration BuildToolConfiguration()<br>{<br>    // Define the JSON schema for the tool input - this is what the model MUST follow<br>    // Root must be object type, with movies array as a property<br>    var toolInputSchema = new<br>    {<br>        type = &quot;object&quot;,<br>        properties = new<br>        {<br>            movies = new<br>            {<br>                type = &quot;array&quot;,<br>                description = &quot;Array of movie information objects&quot;,<br>                items = new<br>                {<br>                    type = &quot;object&quot;,<br>                    properties = new<br>                    {<br>                        title    = new { type = &quot;string&quot;,  description = &quot;The movie title&quot; },<br>                        year     = new { type = &quot;integer&quot;, description = &quot;The release year&quot; },<br>                        category = new { type = &quot;string&quot;,  description = &quot;Category to which this title belongs to. Like a TV show or Movie&quot; },<br>                        directors = new { type = &quot;array&quot;, description = &quot;Array of director names&quot;, items = new { type = &quot;string&quot;, description = &quot;A director name&quot; } },<br>                        actors    = new { type = &quot;array&quot;, description = &quot;Array of actor names&quot;,   items = new { type = &quot;string&quot;, description = &quot;An actor name&quot; } },<br>                        plot     = new { type = &quot;string&quot;,  description = &quot;Brief plot summary&quot; },<br>                        genre    = new { type = &quot;string&quot;,  description = &quot;Movie genre&quot; },<br>                        rating   = new { type = &quot;string&quot;,  description = &quot;IMDb rating or similar&quot; }<br>                    },<br>                    required = new[] { &quot;title&quot;, &quot;year&quot;, &quot;category&quot;, &quot;directors&quot;, &quot;actors&quot;, &quot;plot&quot;, &quot;genre&quot;, &quot;rating&quot; },<br>                    additionalProperties = false<br>                }<br>            }<br>        },<br>        required = new[] { &quot;movies&quot; },<br>        additionalProperties = false<br>    };<br><br>    var tool = new Tool<br>    {<br>        ToolSpec = new ToolSpecification<br>        {<br>            Name = &quot;return_movie_info&quot;,<br>            Description = &quot;Return structured movie information as an array to handle multiple matching movies&quot;,<br>            InputSchema = new ToolInputSchema<br>            {<br>                Json = Document.FromObject(toolInputSchema)<br>            }<br>        }<br>    };<br><br>    return new ToolConfiguration<br>    {<br>        Tools = new List&lt;Tool&gt; { tool },<br>        ToolChoice = new ToolChoice<br>        {<br>            Tool = new SpecificToolChoice { Name = &quot;return_movie_info&quot; }<br>        }<br>    };<br>}</pre><p><strong>Step 4: Extracting the Structured Output</strong></p><p>Once the model responds, we parse the Document object from the tool input into a typed list of movies and serialise it as formatted JSON.</p><pre>/// &lt;summary&gt;<br>/// Extracts movie info from the tool input Document and returns as formatted JSON.<br>/// The schema GUARANTEES this will be an object with a movies array.<br>/// &lt;/summary&gt;<br>private string ExtractMovieInfoAsJson(Document toolInput)<br>{<br>    try<br>    {<br>        var inputDict = toolInput.AsDictionary();<br><br>        if (!inputDict.ContainsKey(&quot;movies&quot;))<br>            return JsonSerializer.Serialize(new { error = &quot;Expected &#39;movies&#39; property in response&quot; });<br><br>        var moviesDoc = inputDict[&quot;movies&quot;];<br>        if (!moviesDoc.IsList())<br>            return JsonSerializer.Serialize(new { error = &quot;Expected &#39;movies&#39; to be an array&quot; });<br><br>        var movies = new List&lt;object&gt;();<br>        foreach (var movieDoc in moviesDoc.AsList())<br>        {<br>            var movieDict = movieDoc.AsDictionary();<br><br>            var directors = new List&lt;string&gt;();<br>            if (movieDict.ContainsKey(&quot;directors&quot;) &amp;&amp; movieDict[&quot;directors&quot;].IsList())<br>                directors = movieDict[&quot;directors&quot;].AsList().Select(doc =&gt; doc.AsString()).ToList();<br><br>            var actors = new List&lt;string&gt;();<br>            if (movieDict.ContainsKey(&quot;actors&quot;) &amp;&amp; movieDict[&quot;actors&quot;].IsList())<br>                actors = movieDict[&quot;actors&quot;].AsList().Select(doc =&gt; doc.AsString()).ToList();<br><br>            movies.Add(new<br>            {<br>                title    = movieDict.ContainsKey(&quot;title&quot;)    ? movieDict[&quot;title&quot;].AsString()    : &quot;&quot;,<br>                year     = movieDict.ContainsKey(&quot;year&quot;)     ? movieDict[&quot;year&quot;].AsInt()         : 0,<br>                category = movieDict.ContainsKey(&quot;category&quot;) ? movieDict[&quot;category&quot;].AsString() : &quot;&quot;,<br>                directors,<br>                actors,<br>                plot     = movieDict.ContainsKey(&quot;plot&quot;)     ? movieDict[&quot;plot&quot;].AsString()     : &quot;&quot;,<br>                genre    = movieDict.ContainsKey(&quot;genre&quot;)    ? movieDict[&quot;genre&quot;].AsString()    : &quot;&quot;,<br>                rating   = movieDict.ContainsKey(&quot;rating&quot;)   ? movieDict[&quot;rating&quot;].AsString()   : &quot;&quot;<br>            });<br>        }<br><br>        return JsonSerializer.Serialize(movies, new JsonSerializerOptions { WriteIndented = true });<br>    }<br>    catch (Exception ex)<br>    {<br>        return JsonSerializer.Serialize(new { error = $&quot;Failed to extract movie info: {ex.Message}&quot; });<br>    }<br>}        if (!inputDict.ContainsKey(&quot;movies&quot;))<br>            return JsonSerializer.Serialize(new { error = &quot;Expected &#39;movies&#39; property in response&quot; });</pre><blockquote><strong>💡 Full Example on GitHub</strong></blockquote><blockquote>See the complete implementation and usage in the <a href="https://github.com/ajaysskumar/ai-playground/blob/main/AwsBedrockExamples/Services/BedrockWithConverseToolsService.cs">BedrockWithConverseToolsService.cs</a> file on GitHub.</blockquote><h4>How the Example Works</h4><ul><li><strong>Tool Schema:</strong> Defines exactly what fields the model must return for each movie.</li><li><strong>System Prompt:</strong> Sets the AI’s persona as a movie expert.</li><li><strong>Tool Use:</strong> The model is required to use the tool and return structured data.</li><li><strong>Extraction:</strong> The code parses the tool output and returns formatted JSON.</li></ul><h4>Example Use Case: Movie Info Extraction</h4><p>Suppose a user wants to get details about “Inception”. The service will return a structured JSON array with all the required fields, ready for use in your app or workflow.</p><pre>var service = new BedrockWithConverseToolsService();<br>string movieJson = await service.GetMovieDetailsAsJson(&quot;Inception&quot;);<br>Console.WriteLine(movieJson);</pre><p>Running the above produces the following structured JSON output:</p><pre>=== Movie Information (Structured JSON) ===<br><br>[<br>  {<br>    &quot;title&quot;: &quot;Inception&quot;,<br>    &quot;year&quot;: 2010,<br>    &quot;category&quot;: &quot;Movie&quot;,<br>    &quot;directors&quot;: [<br>      &quot;Christopher Nolan&quot;<br>    ],<br>    &quot;actors&quot;: [<br>      &quot;Leonardo DiCaprio&quot;,<br>      &quot;Ellen Page&quot;,<br>      &quot;Joseph Gordon-Levitt&quot;,<br>      &quot;Tom Hardy&quot;<br>    ],<br>    &quot;plot&quot;: &quot;A thief who steals corporate secrets through the use of dream-sharing technology is given the inverse task of planting an idea in the mind of a CEO.&quot;,<br>    &quot;genre&quot;: &quot;Action, Adventure, Sci-Fi&quot;,<br>    &quot;rating&quot;: &quot;8.2&quot;<br>  }<br>]</pre><h4>Summary</h4><ul><li><strong>What:</strong> Converse API with tools lets you build AI agents that return structured, reliable data — not just text.</li><li><strong>When:</strong> Use tools for data extraction, workflow automation, and any scenario where you need more than chat.</li><li><strong>How:</strong> Define tool schemas, enforce output structure, and integrate with your .NET apps using the AWS SDK.</li></ul><p>For more details and the full code, see the <a href="https://github.com/ajaysskumar/ai-playground/blob/main/AwsBedrockExamples/Services/BedrockWithConverseToolsService.cs">GitHub example</a>.</p><h4>References &amp; Further Reading</h4><ul><li><a href="https://docs.aws.amazon.com/bedrock/latest/userguide/converse-api.html">AWS Bedrock Converse API Documentation</a></li><li><a href="https://github.com/ajaysskumar/ai-playground/blob/main/AwsBedrockExamples/Services/BedrockWithConverseToolsService.cs">BedrockWithConverseToolsService.cs on GitHub</a></li></ul><p>ℹ️ 🚀 Next in the Series</p><p>Tools give you structure, but what about safety? Explore how AWS Bedrock protects your application. We will soon be covering the AWS Bedrock Guardrails feature.</p><p>For reference, the code repository being discussed is available at github: <a href="https://github.com/ajaysskumar/ai-playground/blob/main/AwsBedrockExamples/Services/BedrockWithConverseToolsService.cs">https://github.com/ajaysskumar/ai-playground/blob/main/AwsBedrockExamples/Services/BedrockWithConverseToolsService.cs</a></p><p>Thanks for reading through. Please share feedback, if any, in comments or on my email <a href="/service/mailto:ajay.a338@gmail.com">ajay.a338@gmail.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da6fae30efd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Bedrock with .NET: Conversational AI Converse API]]></title>
            <link>https://medium.com/@ajaykumar1807/aws-bedrock-with-net-conversational-ai-converse-api-3ca658806415?source=rss-e26704d7d84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ca658806415</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <dc:creator><![CDATA[Ajay kumar]]></dc:creator>
            <pubDate>Sun, 05 Apr 2026 18:53:52 GMT</pubDate>
            <atom:updated>2026-04-08T06:52:21.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-LnGPi5B1YhvvLIsqdqu6Q.png" /></figure><h3>The Problem &amp; The Solution</h3><p>Picture a customer contacting your support bot about a billing issue. They explain the problem, the bot asks for their account number, they provide it and then the next response treats them like a stranger. No memory of the account number. No memory of the issue. The user has to start over.</p><p>This is what happens when you build conversational experiences on stateless, single-turn APIs. Every message is an island. The model sees no history, carries no context, and the user experience suffers for it.</p><blockquote>ℹ️ The root cause</blockquote><blockquote>The original Bedrock <strong>Invoke API</strong> was built for single-shot prompts — great for summarization or one-off generation, but fundamentally broken for anything conversational.</blockquote><p>The <strong>Converse API</strong> is AWS Bedrock’s answer to the growing demand for natural, multi-turn, context-aware conversations with generative AI models. As businesses and developers began integrating AI into customer support, virtual assistants, and workflow automation, it became clear that single-turn, stateless APIs (like the original <strong>Invoke API</strong>) were not enough. Users expect AI to remember context, follow up on previous questions, and provide a seamless, human-like experience.</p><p>The Converse API was introduced to fill this gap. It allows developers to send the entire conversation history to the model, enabling the AI to generate responses that are aware of everything said so far. This is a major step forward for building chatbots, support agents, and assistants that feel truly interactive and intelligent.</p><blockquote>ℹ️ Origin and Motivation</blockquote><blockquote>The rise of chat-based AI (like ChatGPT and Claude) showed that context retention is critical for user satisfaction. AWS designed the Converse API to bring this capability to enterprise workloads, with the security, scalability, and compliance features expected from AWS services.</blockquote><h3>🔮 Understanding Converse API</h3><h4><strong>Why Did AWS Create It?</strong></h4><ul><li><strong>Context Retention:</strong> Real conversations require memory. Converse API lets you pass the full message history, so the model can reference earlier turns and maintain continuity.</li><li><strong>Multi-Turn Dialogues:</strong> Many business scenarios (support, sales, onboarding) require back-and-forth exchanges, not just one-off answers.</li><li><strong>Better User Experience:</strong> Users expect AI to “remember” what they said. Stateless APIs break this illusion and frustrate users.</li><li><strong>Enterprise Integration:</strong> Converse API is built for production, with IAM, monitoring, and cost controls.</li></ul><p>In summary, Converse API exists because real-world AI needs to be conversational, not just responsive.</p><h4>When and Where to Use It</h4><ul><li><strong>Customer Support:</strong> Multi-step troubleshooting, order tracking, and escalation flows.</li><li><strong>Virtual Assistants:</strong> Scheduling, reminders, and task management that require context.</li><li><strong>Education:</strong> Tutoring bots that guide users through lessons and remember progress.</li><li><strong>Healthcare:</strong> Symptom checkers and patient intake bots that need to remember previous answers.</li><li><strong>Internal Tools:</strong> HR, IT, and operations bots that help employees with ongoing requests.</li><li><strong>Any scenario where context, continuity, and memory are essential for a good user experience.</strong></li></ul><blockquote>💡 Stateless vs. Stateful</blockquote><blockquote>Use Converse API for chat-like, multi-turn flows. Use Invoke API for simple, one-off completions.</blockquote><h3>🏗️ Technical Foundations</h3><h4>Converse API vs. Invoke API</h4><ul><li><strong>Invoke API:</strong> Stateless. Each request is a single prompt/response. No memory of previous turns. Simpler, but limited for conversations.</li><li><strong>Converse API:</strong> Stateful. You send the full conversation history (as a list of messages). The model can reference, summarize, or clarify based on prior turns.</li></ul><p><strong>Technical Note:</strong> With Converse, you are responsible for maintaining and sending the conversation history. This gives you control, but also means you must manage message length and context window limits.</p><ul><li><strong>When to use Invoke:</strong> Single-shot Q&amp;A, summarization, or content generation.</li><li><strong>When to use Converse:</strong> Chatbots, support agents, assistants, and any workflow with back-and-forth dialogue.</li></ul><blockquote>ℹ️ Migration Tip</blockquote><blockquote>If you’re moving from Invoke to Converse, refactor your code to store and manage the conversation history for each user/session.</blockquote><h4>How the Converse API Flows End to End</h4><p>Before we implement any code, let’s visualize the full request lifecycle — from your .NET application calling the SDK, through Bedrock’s Converse API, down to the Foundation Model, and back. Notice the <strong>multi-turn conversation loop</strong> and the <strong>tool use</strong> capability — both are native to the Converse API and impossible with InvokeModel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y26Cq24_1OLJEZs4NDX2Nw.png" /><figcaption><em>Sequence diagram: .NET application using AWS Bedrock Converse API with multi-turn conversation loop</em></figcaption></figure><h3>💻 Implementation Guide</h3><h4>Prerequisites</h4><ul><li>AWS account with Bedrock access enabled.</li><li>AWS credentials with permissions for Bedrock Converse API.</li><li>.NET 8 or later SDK installed.</li><li>NuGet package: <strong>AWSSDK.BedrockRuntime</strong></li></ul><h4>Service Implementation Example</h4><p>Below is a simplified version of a customer support agent using the Bedrock Converse API in C#. The agent maintains conversation history and provides context-aware responses.</p><pre>using Amazon.BedrockRuntime;<br>using Amazon.BedrockRuntime.Model;<br>using System;<br>using System.Collections.Generic;<br>using System.Threading.Tasks;<br><br>public class BedrockCustomerSupportService<br>{<br>    private readonly AmazonBedrockRuntimeClient _client;<br>    // NOTE: Verify the latest Claude model ID in the AWS Bedrock console.<br>    // This example uses Claude 3 Haiku as of Jan 2026 — model IDs may change.<br>    private const string ModelId = &quot;anthropic.claude-3-haiku-20240307-v1:0&quot;;<br><br>    public BedrockCustomerSupportService()<br>    {<br>        _client = new AmazonBedrockRuntimeClient(Amazon.RegionEndpoint.USEast1);<br>    }<br><br>    /// &lt;summary&gt;<br>    /// Simulates an AI customer support staff in a multi-turn conversation using the Bedrock Converse API (no tools).<br>    /// &lt;/summary&gt;<br>    /// &lt;param name=&quot;conversationHistory&quot;&gt;The full conversation history as a list of Message objects (user and assistant turns).&lt;/param&gt;<br>    /// &lt;returns&gt;AI-generated customer support response as plain text.&lt;/returns&gt;<br>    public async Task&lt;string&gt; GetSupportResponse(List&lt;Message&gt; conversationHistory)<br>    {<br>        var converseRequest = new ConverseRequest<br>        {<br>            System = new List&lt;SystemContentBlock&gt;<br>            {<br>                new SystemContentBlock<br>                {<br>                    Text = &quot;You are an AI customer support staff. Be polite, helpful, and concise. Address the customer&#39;s issue and provide clear next steps or solutions. Maintain context across the conversation.&quot;<br>                }<br>            },<br>            ModelId = ModelId,<br>            Messages = conversationHistory<br>        };<br><br>        var response = await _client.ConverseAsync(converseRequest);<br><br>        var responseText = string.Empty;<br>        foreach (var content in response.Output.Message.Content)<br>        {<br>            if (content.Text != null)<br>            {<br>                responseText += content.Text;<br>            }<br>        }<br><br>        return responseText;<br>    }<br>}</pre><blockquote>💡 Full Example on GitHub</blockquote><blockquote>See the complete implementation and usage in the <a href="https://github.com/ajaysskumar/ai-playground/blob/main/AwsBedrockExamples/Services/BedrockCustomerSupportService.cs">BedrockCustomerSupportService.cs</a> file on GitHub. Also refer to the <a href="https://medium.com/@ajaykumar1807/aws-bedrock-with-net-getting-started-8169027d6746">Getting Started with AWS Bedrock</a> article for foundational setup and IAM authentication.</blockquote><h4>How the Example Works</h4><ul><li><strong>System Prompt:</strong> Sets the behavior and tone for the AI agent.</li><li><strong>Model Selection:</strong> Uses Anthropic Claude 3 Haiku for fast, cost-effective responses.</li><li><strong>Conversation History:</strong> Passes the entire message history to maintain context.</li><li><strong>Response Handling:</strong> Aggregates the AI’s response from the output content blocks.</li></ul><h4>Example Use Case: AI Customer Service Agent</h4><p>Suppose a user is troubleshooting an issue with their order. The conversation might look like this:</p><pre>    // Example conversation history — showing 5+ turns to demonstrate context retention<br>    var conversationHistory = new List&lt;Message&gt;<br>    {<br>        new Message { Role = &quot;user&quot;, Content = new List&lt;ContentBlock&gt; { new ContentBlock { Text = &quot;My order hasn&#39;t arrived yet. I ordered it last week.&quot; } } },<br>        new Message { Role = &quot;assistant&quot;, Content = new List&lt;ContentBlock&gt; { new ContentBlock { Text = &quot;I&#39;m sorry to hear that. Can you provide your order number? And what&#39;s your delivery address region?&quot; } } },<br>        new Message { Role = &quot;user&quot;, Content = new List&lt;ContentBlock&gt; { new ContentBlock { Text = &quot;It&#39;s order 12345, and I&#39;m in the East Coast region.&quot; } } },<br>        new Message { Role = &quot;assistant&quot;, Content = new List&lt;ContentBlock&gt; { new ContentBlock { Text = &quot;Thanks! Order 12345 was shipped 5 days ago to the East Coast. It should arrive within 2-3 days. Would you like me to track it further or escalate this?&quot; } } },<br>        new Message { Role = &quot;user&quot;, Content = new List&lt;ContentBlock&gt; { new ContentBlock { Text = &quot;Can you escalate this to a human agent? I&#39;m concerned since it&#39;s been a week.&quot; } } }<br>    };<br><br>    var service = new BedrockCustomerSupportService();<br>    string response = await service.GetSupportResponse(conversationHistory);<br>    Console.WriteLine(response);</pre><p>Notice how in turn 4, the AI references “Order 12345” and “East Coast region” seamlessly — context from earlier turns. This multi-turn awareness is exactly what Converse API enables. The AI doesn’t forget, and the user experience feels natural.</p><h4>Demo: Interactive Customer Support Chat</h4><p>Below is a complete demo of a console-based customer support chat using the Bedrock Converse API. This example shows how to maintain the conversation loop, collect user input, and keep the conversation history updated for each turn.</p><pre>// Customer support chat demo<br>    async Task RunBedrockCustomerSupportChat()<br>    {<br>        try<br>        {<br>            var supportService = new BedrockCustomerSupportService();<br>            var conversation = new List&lt;Amazon.BedrockRuntime.Model.Message&gt;();<br>            Console.WriteLine(&quot;\nWelcome to AI Customer Support! Type &#39;Exit Chat&#39; to end the conversation.\n&quot;);<br>            while (true)<br>            {<br>                Console.Write(&quot;You: &quot;);<br>                var userInput = Console.ReadLine();<br>                if (string.Equals(userInput, &quot;Exit Chat&quot;, StringComparison.OrdinalIgnoreCase))<br>                {<br>                    Console.WriteLine(&quot;\nThank you for chatting with AI Customer Support. Goodbye!\n&quot;);<br>                    break;<br>                }<br>                // Add user message to conversation<br>                conversation.Add(new Amazon.BedrockRuntime.Model.Message<br>                {<br>                    Role = &quot;user&quot;,<br>                    Content = new List&lt;Amazon.BedrockRuntime.Model.ContentBlock&gt;<br>                    {<br>                        new Amazon.BedrockRuntime.Model.ContentBlock { Text = userInput }<br>                    }<br>                });<br><br>                // Get AI response<br>                var response = await supportService.GetSupportResponse(conversation);<br><br>                // Add assistant response to conversation<br>                conversation.Add(new Amazon.BedrockRuntime.Model.Message<br>                {<br>                    Role = &quot;assistant&quot;,<br>                    Content = new List&lt;Amazon.BedrockRuntime.Model.ContentBlock&gt;<br>                    {<br>                        new Amazon.BedrockRuntime.Model.ContentBlock { Text = response }<br>                    }<br>                });<br><br>                Console.WriteLine($&quot;AI: {response}\n&quot;);<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            Console.WriteLine($&quot;Error: {ex.Message}&quot;);<br>            Console.WriteLine(ex.StackTrace);<br>        }<br>    } </pre><p>This interactive loop demonstrates how to build a real-time, multi-turn customer support chat using the Converse API. The conversation history is updated after every user and AI message, ensuring context is preserved throughout the session.</p><p>Below is a screenshot of the actual customer support chat demo in action, where the AI answers questions about movies and maintains context across turns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kZxjPMojlcfdb8-9.png" /></figure><h3>Summary</h3><ul><li><strong>What:</strong> The Bedrock Converse API enables multi-turn, context-aware conversations with generative AI models.</li><li><strong>When:</strong> Use it for chatbots, customer support, and any scenario requiring context retention and continuous dialogue.</li><li><strong>How:</strong> Integrate with AWS SDK for .NET (.net 8+), maintain conversation history as a list of Message objects, and pass the entire history with each request so the model sees full context.</li></ul><p>The beauty of Converse API is its simplicity — you don’t need to manage complex state servers or reinvent conversation patterns. AWS handles the heavy lifting, and you focus on building great user experiences.</p><h4>References &amp; Further Reading</h4><ul><li><a href="https://medium.com/@ajaykumar1807/aws-bedrock-with-net-getting-started-8169027d6746">AWS Bedrock with .NET: Getting Started</a> — foundation article for IAM, authentication, and cost optimization</li><li><a href="https://docs.aws.amazon.com/bedrock/latest/userguide/converse-api.html">AWS Bedrock Converse API Documentation</a> — official AWS reference</li><li><a href="https://github.com/ajaysskumar/ai-playground/blob/main/AwsBedrockExamples/Services/BedrockCustomerSupportService.cs">BedrockCustomerSupportService.cs on GitHub</a> — full runnable example</li></ul><p>For reference, the code repository being discussed is available at github: <a href="https://github.com/ajaysskumar/ai-playground/blob/main/AwsBedrockExamples/Services/BedrockCustomerSupportService.cs">https://github.com/ajaysskumar/ai-playground/blob/main/AwsBedrockExamples/Services/BedrockCustomerSupportService.cs</a></p><p>Thanks for reading through. Please share feedback, if any, in comments or on my email <a href="/service/mailto:ajay.a338@gmail.com">ajay.a338@gmail.com</a></p><p><em>Originally published at </em><a href="https://devcodex.in/blog/ai/bedrock/converse"><em>https://devcodex.in</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ca658806415" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Bedrock with .NET: Advanced Integration & Production Setup]]></title>
            <link>https://medium.com/@ajaykumar1807/aws-bedrock-with-net-advanced-integration-production-setup-a85390ed73d0?source=rss-e26704d7d84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a85390ed73d0</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Ajay kumar]]></dc:creator>
            <pubDate>Fri, 27 Mar 2026 18:17:33 GMT</pubDate>
            <atom:updated>2026-04-08T06:50:22.041Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y00CJPeqZXi1oLwNfZ6xow.png" /></figure><h4>The Problem: Credentials Buried in the Cloud</h4><p>Picture this: You’ve built a Bedrock chatbot locally using aws configure. It works perfectly on your machine. You deploy it to an EC2 instance in production, and boom—UnauthorizedException. The code is identical. The code didn&#39;t change. So what&#39;s broken?</p><p>Your local machine had credentials in ~/.aws/credentials. The EC2 instance doesn&#39;t. And hardcoding AWS keys into your source code? That&#39;s a security audit nightmare waiting to happen. You need a different approach—one that works for development, staging, and production without storing secrets in git.</p><p>This is where <strong>advanced authentication patterns</strong> come in. They let you securely manage credentials across different deployment environments without changing your code.</p><blockquote>ℹ️ Coming from the basics?</blockquote><blockquote>If you haven’t read <a href="https://medium.com/@ajaykumar1807/aws-bedrock-with-net-getting-started-8169027d6746">Getting Started with AWS Bedrock in .NET</a> yet, start there. This article builds on that foundation and assumes you’re familiar with the Invocation APIs.</blockquote><h4>What: The SDK’s Credential Chain</h4><p>The AWS SDK doesn’t require you to explicitly pass credentials. Instead, it follows a <strong>credential resolution chain</strong> — a priority-ordered search for credentials from different sources.</p><p>Think of it like this: Imagine you’re looking for your API key. You check your desk (environment variables), then your backpack (.aws/credentials file), then your jacket pockets (EC2 metadata). Once you find it, you stop searching. The SDK does the same thing, in a predictable order.</p><p>Here’s the chain (in priority order):</p><ol><li><strong>Explicit credentials:</strong> If you pass credentials directly in code (not recommended for production)</li><li><strong>Environment variables:</strong> AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN</li><li><strong>Credentials file:</strong> ~/.aws/credentials (local dev)</li><li><strong>IMDS (Instance Metadata Service):</strong> EC2 instance role (automatic)</li><li><strong>ECS task role environment variables:</strong> Automatic in ECS/Fargate</li><li><strong>IAM role for Lambda:</strong> Automatic in Lambda execution</li></ol><p>The beauty of this chain is: <strong>your code never changes.</strong> You write one invocation, and it works locally (using credentials file), in CI/CD (using environment variables), and in production (using EC2 / Lambda roles). The SDK figures out which source to use automatically.</p><h4>When: Choosing Your Authentication Pattern</h4><p>Different deployment environments call for different patterns. Here’s a decision matrix to help you pick the right approach:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3At_JWo_m1ZgUYNvUI9Yw.png" /></figure><blockquote>💡 The Best Practice</blockquote><blockquote><strong>Use role-based authentication (EC2 instance role, Lambda execution role, or ECS task role) for any production workload.</strong> It’s automatic, doesn’t require secrets in code, and permissions rotate transparently. Config it once, forget about credential management forever.</blockquote><h3>How: Implementing Each Pattern</h3><h4><strong>Pattern 1: Session Credentials (Quick Local Testing)</strong></h4><p>Use this for testing with temporary credentials from AWS STS. Useful when you can’t install aws-cli or want isolated, time-limited access.</p><pre>SessionAWSCredentials GetCredentials()<br>{<br>    // ⚠️ NEVER hardcode credentials in production!<br>    // Use environment variables or CloudFormation outputs instead<br>    string accessKey = Environment.GetEnvironmentVariable(&quot;AWS_ACCESS_KEY_ID&quot;) <br>        ?? throw new InvalidOperationException(&quot;AWS_ACCESS_KEY_ID not set&quot;);<br>    string secretKey = Environment.GetEnvironmentVariable(&quot;AWS_SECRET_ACCESS_KEY&quot;)<br>        ?? throw new InvalidOperationException(&quot;AWS_SECRET_ACCESS_KEY not set&quot;);<br>    string sessionToken = Environment.GetEnvironmentVariable(&quot;AWS_SESSION_TOKEN&quot;)<br>        ?? throw new InvalidOperationException(&quot;AWS_SESSION_TOKEN not set&quot;);<br>    <br>    return new SessionAWSCredentials(accessKey, secretKey, sessionToken);<br>}<br><br>var credentials = GetCredentials();<br>var client = new AmazonBedrockRuntimeClient(credentials, RegionEndpoint.USEast1);</pre><blockquote>ℹ️ Session credentials expire</blockquote><blockquote>Session tokens are time-limited (typically 15 minutes to 1 hour). Once expired, requests fail with UnauthorizedException. Use this pattern only for testing or short-lived scripts, not long-running services.</blockquote><h4>Pattern 2: Environment Variables (Containers &amp; CI/CD)</h4><p>Store credentials in environment variables. This is ideal for containerized workloads and CI/CD pipelines where your infrastructure orchestrator (Kubernetes, Docker, GitHub Actions) injects secrets at runtime.</p><pre>// The SDK automatically looks for AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY<br>// No manual credential handling needed<br>var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);<br><br>// This works because the SDK&#39;s credential chain finds the env vars<br>var response = await client.InvokeModelAsync(request);</pre><p><strong>In Docker:</strong> Pass secrets as environment variables at container startup:</p><pre>docker run \<br>  -e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \<br>  -e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \<br>  -e AWS_REGION=us-east-1 \<br>  my-bedrock-app:latest</pre><blockquote>💡 Secret management in Kubernetes</blockquote><blockquote>Use Kubernetes Secrets or external secret managers (HashiCorp Vault, AWS Parameter Store) to inject credentials safely. Docker Compose uses environment variables similarly.</blockquote><h4>Pattern 3: EC2 Instance Profile Role (Production on EC2)</h4><p>This is the <strong>recommended approach for production on EC2.</strong> The SDK automatically retrieves temporary credentials from the EC2 Instance Metadata Service (IMDS) — no hardcoded keys, no manual credential rotation.</p><p><strong>How it works:</strong> Every EC2 instance has access to its metadata service at http://169.254.169.254/. When you create an instance with an IAM role attached, the role&#39;s credentials are available at that endpoint. The SDK automatically fetches them, uses them for requests, and refreshes them before expiry.</p><pre>// No credentials code needed! SDK discovers the EC2 instance role automatically.<br>var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);<br><br>// This just works because the SDK&#39;s credential chain finds IMDS<br>var response = await client.ConverseAsync(request);</pre><p>Creating an EC2 Instance Profile Role (Step-by-Step)</p><p><strong>Step 1: Create an IAM Role</strong></p><ol><li>AWS Console → IAM → Roles → Create Role</li><li>Trusted entity type: <strong>AWS service</strong></li><li>Service: <strong>EC2</strong></li><li>Click “Next” → “Create role”</li></ol><p><strong>Step 2: Add Bedrock Permissions (Inline Policy)</strong></p><p>Attach this least-privilege policy to the role:</p><pre>{<br>  &quot;Version&quot;: &quot;2012-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Action&quot;: [<br>        &quot;bedrock:InvokeModel&quot;,<br>        &quot;bedrock:InvokeModelWithResponseStream&quot;<br>      ],<br>      &quot;Resource&quot;: &quot;arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-*&quot;<br>    }<br>  ]<br>}</pre><blockquote>💡 Least-privilege approach</blockquote><blockquote>Scope the Resource ARN to specific models you use (e.g., anthropic.claude-3-haiku-*) rather than wildcard. This limits damage if credentials are compromised.</blockquote><p><strong>Step 3: Attach Role to EC2 Instance</strong></p><ol><li>AWS Console → EC2 → Instances → Select your instance</li><li>Actions → Security → Modify IAM role</li><li>Select the role you created</li><li>Click “Update IAM role”</li></ol><p><strong>Step 4: Verify (Test the Connection)</strong></p><pre># SSH into your EC2 instance<br>ssh -i your-key.pem ec2-user@your-instance-ip<br><br># Test if IMDS is reachable and the role is attached<br>curl http://169.254.169.254/latest/meta-data/iam/security-credentials/<br><br># Should output your role name. Then test Bedrock access:<br>dotnet run  # Run your app; it should authenticate automatically</pre><h4>Pattern 4: Lambda &amp; ECS (Serverless Production)</h4><p>Both Lambda and ECS automatically provide credentials via execution roles. No manual setup beyond attaching the role to your function/task.</p><pre>[LambdaFunction]<br>public async Task&lt;APIGatewayProxyResponse&gt; Handler(APIGatewayProxyRequest request)<br>{<br>    // SDK automatically discovers Lambda execution role<br>    var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);<br>    <br>    var response = await client.ConverseAsync(new ConverseRequest<br>    {<br>        ModelId = &quot;anthropic.claude-3-haiku-20240307-v1:0&quot;,<br>        Messages = new() { new Message { Role = ConversationRole.User, Content = new() <br>        { <br>            new ContentBlock { Text = request.QueryStringParameters?[&quot;prompt&quot;] ?? &quot;Hello&quot; } <br>        } } }<br>    });<br>    <br>    return new APIGatewayProxyResponse<br>    {<br>        StatusCode = 200,<br>        Body = response.Output.Message.Content[0].Text<br>    };<br>}</pre><blockquote>ℹ️ ECS &amp; Fargate</blockquote><blockquote>Same pattern for ECS. Attach the task role in your task definition, and the SDK discovers it via the AWS_CONTAINER_CREDENTIALS_FULL_URI environment variable (automatically set by ECS).</blockquote><h4>Troubleshooting: When Things Break</h4><p>If auth fails, the cause is usually one of these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLJTI8hoGmAdU9byOih1Hw.png" /></figure><blockquote>💡 Always test credentials locally first</blockquote><blockquote>Before deploying, verify credentials work with the AWS CLI: aws bedrock list-foundation-models --region us-east-1. If the CLI works, your app will too (same SDK under the hood).</blockquote><h4>Key Takeaways &amp; Best Practices</h4><ul><li><strong>Local dev:</strong> Use ~/.aws/credentials — run aws configure once and forget about it.</li><li><strong>Production on EC2:</strong> Attach an instance profile role with Bedrock permissions. Let IMDS handle credentials automatically.</li><li><strong>Production on Lambda/ECS:</strong> Attach the execution role with Bedrock permissions. No code changes needed.</li><li><strong>Never hardcode credentials</strong> in source code or config files. Always use the credential chain (env vars, roles, IMDS).</li><li><strong>Test with AWS CLI first.</strong> If credentials work with the CLI, they’ll work with your .NET app.</li></ul><blockquote>ℹ️ Next in the Series</blockquote><blockquote>Now that you’ve mastered production authentication, you’re ready for multi-turn conversations. Explore the <a href="https://medium.com/@ajaykumar1807/aws-bedrock-with-net-conversational-ai-converse-api-3ca658806415">Converse API </a>to build stateful chatbots and assistants that remember context across turns.</blockquote><p>For reference, the code repository being discussed is available at github: <a href="https://github.com/ajaysskumar/ai-playground">https://github.com/ajaysskumar/ai-playground</a></p><p>Thanks for reading through. Please share feedback, if any, in comments or on my email <a href="/service/mailto:ajay.a338@gmail.com">ajay.a338@gmail.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a85390ed73d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Bedrock with .NET: Getting Started]]></title>
            <link>https://medium.com/@ajaykumar1807/aws-bedrock-with-net-getting-started-8169027d6746?source=rss-e26704d7d84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8169027d6746</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Ajay kumar]]></dc:creator>
            <pubDate>Fri, 27 Mar 2026 18:15:48 GMT</pubDate>
            <atom:updated>2026-03-29T07:00:15.939Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PH79HflgihhaUgEMHi94bw.png" /></figure><h4>The Problem: Too Many APIs, Too Much Friction</h4><p>Imagine this: your team decides to add AI to your .NET application. You pick a model, wire up the HTTP client, handle the auth, parse the response schema — and it works. Then the product team asks to try a different model. Suddenly you have two HTTP clients, two authentication flows, two response formats, and twice the maintenance burden. Add a third model and things start to spiral.</p><p>This is the reality that many .NET teams hit when integrating generative AI directly through vendor APIs. Each provider has its own conventions, and none of them speak fluent C#.</p><blockquote>ℹ️ Sound familiar?</blockquote><blockquote>If you’ve ever copy-pasted an HttpClient setup just to talk to a different AI model, this article is for you.</blockquote><h4>What is AWS Bedrock and Why Use It from .NET?</h4><p>AWS Bedrock is Amazon’s answer to the multi-model problem. It gives you a <strong>single, consistent interface</strong> to access foundation models from providers like Anthropic Claude and Amazon Titan — without juggling separate APIs, auth tokens, or request formats for each one.</p><p>Think of Bedrock as a universal adapter — like those laptop power converters that work worldwide. You plug in once, and voltage, plug shape, and frequency differences disappear. Similarly, your .NET code plugs into Bedrock once, and differences between Claude, Titan, and other models are handled at the API layer.</p><p>What makes it especially compelling for .NET developers is the official AWS SDK for .NET. You can invoke powerful AI models using idiomatic C# code, plugging straight into your existing projects — no context switching, no foreign tooling. Text generation, summarization, intelligent chat — all accessible through the same familiar patterns you already use for other AWS services.</p><p>At a high level, every Bedrock request follows this flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*hND0ZqJAiiSnpzmvaMIJ3Q.png" /></figure><h4>Why: The Need for Simplicity, Security, and Scale</h4><ul><li><strong>Simplicity:</strong> One unified API for all models instead of managing multiple SDKs and auth flows.</li><li><strong>Security:</strong> Enterprise-grade access control via AWS IAM — no custom auth layers.</li><li><strong>Scale:</strong> Built-in monitoring and throttling for production use.</li></ul><h4>How: Step-by-Step Guide to Using AWS Bedrock from .NET</h4><p>Let’s get hands-on with setup, authentication, and your first invocation.</p><p><strong>1. Prerequisites</strong></p><ul><li>AWS account with Bedrock access</li><li>AWS credentials configured via aws configure</li><li>.NET 9 SDK or later</li><li>NuGet packages: AWSSDK.Bedrock, AWSSDK.BedrockRuntime</li></ul><p><strong>2. Setting Up Your Project</strong></p><pre>dotnet add package AWSSDK.Bedrock<br>dotnet add package AWSSDK.BedrockRuntime</pre><p><strong>3. Authenticating with AWS</strong></p><p>Run aws configure and enter your credentials. The SDK automatically reads from ~/.aws/credentials:</p><pre>var bedrockClient = new AmazonBedrockClient(RegionEndpoint.USEast1);</pre><blockquote>ℹ️ Advanced auth?</blockquote><blockquote>EC2 roles, IAM users, and troubleshooting are covered in the <a href="http://localhost:5128/blog/ai/bedrock/advanced">advanced article</a>.</blockquote><p><strong>4. Quick Checks Before Invoking</strong></p><ul><li><strong>Credentials missing?</strong> Check ~/.aws/credentials (or %USERPROFILE%\.aws\credentials on Windows).</li><li><strong>Model not found?</strong> Request access in AWS Console → Bedrock → Model access (5–15 min wait).</li><li><strong>Wrong region?</strong> Claude 3 Haiku is in us-east-1 and us-west-2 only. Check <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html">model availability</a>.</li><li><strong>Package version?</strong> Use AWSSDK.BedrockRuntime 3.7.0 or later.</li></ul><p><strong>5. Quick Start: Your First Model Invocation</strong></p><p>Now that everything is configured and common pitfalls are clear, let’s get hands-on and invoke Claude. Here’s a real, working example from the <a href="https://github.com/ajaysskumar/ai-playground">ai-playground</a> repository that demonstrates how to build a practical Bedrock application:</p><pre>public async Task&lt;string&gt; GetMovieDetails(string movieQuery)<br>{<br>    // Build the prompt for Claude models: must start with &quot;\n\nHuman: &quot; and end with &quot;\n\nAssistant:&quot;<br>    var prompt =<br>        $&quot;\n\nHuman: You are a movie information expert. Provide detailed information about the movie &#39;{movieQuery}&#39;. &quot; +<br>        &quot;Return the results as a JSON array of objects with the following fields: title (string), year (integer), &quot; +<br>        &quot;category (string, Movie/TV), directors (array of strings), actors (array of strings), plot (string), genre (string), rating (string). &quot; +<br>        &quot;If no movie is found, return an empty JSON array.\n\nAssistant:&quot;;<br><br>    var request = new InvokeModelRequest<br>    {<br>        ModelId = &quot;anthropic.claude-3-haiku-20240307-v1:0&quot;,<br>        ContentType = &quot;application/json&quot;,<br>        Accept = &quot;application/json&quot;,<br>        Body = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(<br>            JsonSerializer.Serialize(new<br>            {<br>                anthropic_version = &quot;bedrock-2023-05-31&quot;,<br>                max_tokens = 1024,<br>                messages = new[]<br>                {<br>                    new { role = &quot;user&quot;, content = prompt }<br>                }<br>            })<br>        ))<br>    };<br><br>    var response = await _client.InvokeModelAsync(request);<br>    var responseBody = System.Text.Encoding.UTF8.GetString(response.Body.ToArray());<br>    return FormatJsonString(responseBody);<br>}</pre><p><strong>What’s happening:</strong></p><ul><li>You craft a structured prompt that tells Claude exactly what format to return (JSON with specific fields).</li><li>You create an InvokeModelRequest with your model ID and serialized prompt.</li><li>The SDK sends the request to Bedrock. Claude processes it and returns structured movie data as JSON.</li><li>You parse the response and return it to the caller.</li></ul><p>This example shows why Bedrock is powerful: <strong>one unified C# API to get smart, JSON-formatted responses</strong> from Claude. Users can add similar methods for classification, summarization, extraction, or chat — all using the same pattern.</p><blockquote>💡 Try It Out</blockquote><blockquote>This is a working example from the <a href="https://github.com/ajaysskumar/ai-playground/blob/main/AwsBedrockExamples/Services/BedrockService.cs">ai-playground repository</a>. Clone it, configure your AWS credentials, and run it to see Bedrock in action.</blockquote><blockquote>ℹ️ Model IDs Change Over Time</blockquote><blockquote>As of March 2026, Claude 3 Haiku model ID is anthropic.claude-3-haiku-20240307-v1:0, but check the <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html">AWS Bedrock documentation</a> for the latest available models and their IDs. Claude 3.5 models may now be available.</blockquote><p><strong>6. Building Production Systems: Efficient Batching</strong></p><p>For scale, batch requests using Task.WhenAll. With 10,000 items at 1-2 seconds each, sequential processing takes 3–6 hours; batching (size 10–20) reduces this to ~15 minutes.</p><ul><li><strong>Batch size:</strong> Start with 10–20, tune based on throttling. Us-east-1 allows higher throughput.</li><li><strong>Error handling:</strong> Implement exponential backoff for throttling. Queue failed items for async retry.</li><li><strong>Idempotency keys:</strong> Include item IDs or timestamps to prevent re-processing on retries.</li></ul><h4>⚠️ Pitfalls to Avoid &amp; Limitations to Know</h4><p>Before shipping Bedrock to production, understand these real-world constraints. They won’t stop you, but they will catch you off guard if you’re unprepared.</p><h4><strong>Regional Availability</strong></h4><p>Claude 3 Haiku/Sonnet are in us-east-1 and us-west-2. Titan Text is more widely available. ModelNotFound errors are usually region mismatches—<strong>always check region first</strong>.</p><h4><strong>Rate Limits &amp; Quotas</strong></h4><p>Bedrock enforces account-specific quotas to protect infrastructure. The default is commonly around <strong>100 requests per minute per model</strong>, though this varies by region, account age, and model. Exceed your quota and you’ll get a ThrottlingException. In production, implement exponential backoff and request a higher quota from AWS Support if needed.</p><blockquote>ℹ️ Quota varies by account</blockquote><blockquote>Contact AWS Support to check your specific quota and request increases. Don’t assume the 100 req/min default applies to your account.</blockquote><p><strong>Pricing impact:</strong> Bedrock charges per input + output token. A 1000-ticket batch can run approximately $5–20 depending on model and verbosity (check <a href="https://aws.amazon.com/bedrock/pricing/">current pricing</a> for exact rates). Always estimate costs before scaling.</p><h4><strong>Model Differences Matter</strong></h4><p>Claude 3 models have different characteristics. <strong>Note: Pricing and latency figures change frequently.</strong> Check the <a href="https://aws.amazon.com/bedrock/pricing/">AWS Bedrock pricing page</a> for current rates:</p><ul><li><strong>Haiku (fastest, cheapest):</strong> Best for simple tasks like classification and extraction. Lowest latency.</li><li><strong>Sonnet (balanced):</strong> Better reasoning than Haiku. Mid-range cost and latency. Suitable for most applications.</li><li><strong>Opus (most capable, if available):</strong> Check AWS docs — may not be available in all regions or via Bedrock.</li><li><strong>Token limits vary:</strong> Check the <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html">model documentation</a> for current context window sizes.</li></ul><p>💡 Choose the right model</p><p>Start with Haiku for testing and prototyping — it’s faster and cheaper. Switch to Sonnet only if you need better reasoning quality. Always benchmark cost + latency for your use case before scaling.</p><h4>7. Summary</h4><ul><li><strong>What:</strong> AWS Bedrock is a managed service that abstracts vendor-specific AI APIs into a unified interface (with C# SDK support).</li><li><strong>Why:</strong> It reduces friction: unified auth (IAM), consistent error handling, and easy model switching.</li><li><strong>How:</strong> Use InvokeModel for single requests and batch operations. In production, batch efficiently, handle throttling gracefully, and forecast costs.</li></ul><p>This approach lets you build intelligent, generative features into your .NET apps with clarity and control. Whether you’re prototyping or going to production, AWS Bedrock and .NET make GenAI accessible and robust.</p><blockquote>💡 If You Remember Only One Thing</blockquote><blockquote><strong>Bedrock = abstraction layer.</strong> You control: the model you invoke, the prompt you send, and the cost/quality tradeoff. Start with InvokeModel, add error handling, batch in production, and always check region availability first when things break.</blockquote><h4>8. References &amp; Further Reading</h4><ul><li><a href="https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html">AWS Bedrock Documentation</a></li><li><a href="https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/">AWS SDK for .NET</a></li><li><a href="https://github.com/ajaysskumar/ai-playground/blob/main/AwsBedrockExamples/Services/BedrockService.cs">BedrockService.cs on GitHub</a></li></ul><p>ℹ️ 🚀 Next in the Series</p><p>Ready to take it further? Check out <a href="https://medium.com/@ajaykumar1807/aws-bedrock-with-net-advanced-integration-production-setup-a85390ed73d0">AWS Bedrock with .NET: Advanced Integration &amp; Production Setup</a> to learn about IAM authentication, EC2 instance roles, and production deployment strategies.</p><p>For reference, the code repository being discussed is available at github: <a href="https://github.com/ajaysskumar/ai-playground">https://github.com/ajaysskumar/ai-playground</a></p><p>Thanks for reading through. Please share feedback, if any, in comments or on my email <a href="/service/mailto:ajay.a338@gmail.com">ajay.a338@gmail.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8169027d6746" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD in .NET: Anti-Patterns & When NOT to Use TDD]]></title>
            <link>https://medium.com/@ajaykumar1807/tdd-in-net-anti-patterns-when-not-to-use-tdd-49997bd89fa1?source=rss-e26704d7d84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/49997bd89fa1</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Ajay kumar]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 08:14:02 GMT</pubDate>
            <atom:updated>2025-12-31T08:14:02.337Z</atom:updated>
            <content:encoded><![CDATA[<h3>TDD in .NET: Anti-Patterns &amp; When NOT to Use TDD</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8YWw7S7pmEET9S-aAl0jQ.png" /></figure><h4>The Double-Edged Sword</h4><p>You’ve heard the promise: Test-Driven Development leads to better design, fewer bugs, and happier developers. And in many cases, it does. But like any tool, TDD can be misused — and when it is, it becomes a burden rather than a benefit.</p><p>Imagine a team writing hundreds of tests, hitting 95% code coverage, yet still shipping buggy software and dreading refactoring. Or developers spending weeks writing complex test setups for trivial features. This isn’t TDD failing; it’s TDD being misapplied.</p><p>In this article, we’ll explore common TDD anti-patterns — the pitfalls that turn a powerful practice into a time sink — and identify scenarios where TDD simply isn’t the right answer. The goal? Help you use TDD wisely, not blindly.</p><h4>Quick Takeaways</h4><p><strong>TL;DR — Key Insights:</strong></p><ul><li>✓ TDD is excellent for business logic, algorithms, and complex systems — but not universally applicable.</li><li>✓ Test <strong>behavior</strong>, not implementation. Implementation details change; behavior stays stable.</li><li>✓ Mock external dependencies (APIs, databases) only. Real instances of internal logic reveal design issues.</li><li>✓ Skip TDD for prototypes, throwaway code, and exploratory spikes.</li><li>✓ Aim for 70–80% meaningful coverage, not 100% compliance.</li><li>✓ The “Refactor” step isn’t optional — it’s where TDD delivers its promise.</li></ul><h4>Understanding Anti-Patterns</h4><p>An <strong>anti-pattern</strong> is a common response to a recurring problem that is usually ineffective and risks being counterproductive. In TDD, anti-patterns emerge when teams follow TDD mechanically without understanding its purpose: to drive better design and build confidence.</p><p>Think of it like a compass. A compass is invaluable when navigating — until you mindlessly follow it into a cliff. Anti-patterns are the moments when you’re following TDD off the cliff.</p><p><strong><em>Scenario:</em></strong><em> Imagine a team of 8 developers adopting TDD with strict governance: “100% code coverage or bust.” They write tests for every getter, setter, and property. Their unit test suite grows to 2,000+ tests, taking 45 seconds to run. Developers stop running tests before commits — it’s too slow. Within six months, the test suite becomes a maintenance burden. Nobody trusts it because it passes even when real bugs slip through. The team spends more time maintaining tests than writing features. The irony? Their adoption of TDD made them less confident, not more. Once they refocused on meaningful tests and embraced pragmatism, their velocity actually increased.</em></p><h4>Common TDD Anti-Patterns</h4><p><strong>1. Test Obsession (Testing the Obvious)</strong></p><p><strong>The Problem:</strong> Writing tests for every trivial piece of code — getters, setters, simple properties, and obvious logic.</p><pre>// Bad: Test obsession<br>[Fact]<br>public void Age_Getter_ReturnsAge()<br>{<br>    var person = new Person { Age = 30 };<br>    Assert.Equal(30, person.Age); // What&#39;s this testing?<br>}<br><br>[Fact]<br>public void Name_Getter_ReturnsName()<br>{<br>    var person = new Person { Name = &quot;John&quot; };<br>    Assert.Equal(&quot;John&quot;, person.Name); // And this?<br>}<br>// This bloats your test suite without adding value.</pre><p><strong>Why It’s a Problem:</strong></p><ul><li>Inflates code coverage metrics without adding confidence.</li><li>Creates brittle tests that break with every minor refactor.</li><li>Wastes time and cognitive load maintaining trivial tests.</li><li>Dilutes the signal-to-noise ratio of your test suite.</li></ul><p><strong>The Fix:</strong> Test behavior, not implementation. Ask: “What could go wrong here?” If nothing can go wrong, skip the test.</p><pre>// Better: Focus on behavior<br>[Fact]<br>public void IsAgeValid_WhenAgeIsNegative_ReturnsFalse()<br>{<br>    var person = new Person();<br>    var result = person.IsAgeValid(-5);<br>    Assert.False(result);<br>}<br><br>[Fact]<br>public void IsAgeValid_WhenAgeIsOver150_ReturnsFalse()<br>{<br>    var person = new Person();<br>    var result = person.IsAgeValid(200);<br>    Assert.False(result);<br>}</pre><p><strong>2. Over-Mocking (Mocking Everything)</strong></p><p><strong>The Problem:</strong> Excessive use of mocks, stubs, and fakes — even for internal implementation details that should just work.</p><pre>// Bad: Over-mocking<br>[Fact]<br>public void ProcessOrder_WithMockedEverything()<br>{<br>    var mockValidator = new Mock&lt;IOrderValidator&gt;();<br>    var mockLogger = new Mock&lt;ILogger&gt;();<br>    var mockRepository = new Mock&lt;IOrderRepository&gt;();<br>    var mockEmailService = new Mock&lt;IEmailService&gt;();<br>    var mockNotificationService = new Mock&lt;INotificationService&gt;();<br>    <br>    // 50 lines of setup...<br>    <br>    var service = new OrderProcessor(mockValidator.Object, mockLogger.Object, <br>        mockRepository.Object, mockEmailService.Object, mockNotificationService.Object);<br>    <br>    // 10 lines of test...<br>    <br>    // What are we actually testing?<br>}</pre><p><strong>Why It’s a Problem:</strong></p><ul><li>Tests become tightly coupled to implementation, not behavior.</li><li>Brittle tests that break when you refactor the internals (even if behavior stays the same).</li><li>False confidence: tests pass, but integration fails.</li><li>Test setup becomes so complex that tests themselves need testing.</li></ul><p><strong>The Fix:</strong> Mock only external dependencies (databases, APIs, third-party services). Let internal logic run for real. <strong>Why?</strong> Real instances catch bugs at the boundary between components. If your internal logic breaks, you want to know immediately — not when you integrate later.</p><pre>// Better: Mock only what&#39;s external<br>[Fact]<br>public void ProcessOrder_SendsEmailAfterSuccess()<br>{<br>    var mockEmailService = new Mock&lt;IEmailService&gt;();<br>    var validator = new OrderValidator(); // Real - catches issues in validation logic<br>    var repository = new InMemoryOrderRepository(); // Real - tests the contract between layers<br>    <br>    var service = new OrderProcessor(validator, repository, mockEmailService.Object);<br>    <br>    service.ProcessOrder(new Order { Id = 1, Amount = 100 });<br>    <br>    mockEmailService.Verify(x =&gt; x.SendConfirmation(It.IsAny&lt;string&gt;()), Times.Once);<br>}</pre><p><strong>3. Skipping Refactoring (Red-Green, No Refactor)</strong></p><p><strong>The Problem:</strong> Ignoring the “Refactor” step in the Red-Green-Refactor cycle, leaving code messy and brittle.</p><pre>// Bad: No refactoring (Real-world: Discount calculation)<br>[Fact]<br>public void CalculateDiscount_StandardCustomer_5Percent()<br>{<br>    var calculator = new DiscountCalculator();<br>    var discount = calculator.Calculate(100, CustomerType.Standard);<br>    Assert.Equal(5, discount); // 5% of 100<br>}<br><br>[Fact]<br>public void CalculateDiscount_PremiumCustomer_10Percent()<br>{<br>    var calculator = new DiscountCalculator();<br>    var discount = calculator.Calculate(100, CustomerType.Premium);<br>    Assert.Equal(10, discount);<br>}<br><br>[Fact]<br>public void CalculateDiscount_VIPCustomer_15Percent()<br>{<br>    var calculator = new DiscountCalculator();<br>    var discount = calculator.Calculate(100, CustomerType.VIP);<br>    Assert.Equal(15, discount);<br>}<br><br>// Minimal code to pass tests, but impossible to read<br>public class DiscountCalculator<br>{<br>    public decimal Calculate(decimal amount, CustomerType type)<br>    {<br>        decimal d = 0;<br>        if (type == CustomerType.Standard) { d = amount * 0.05m; }<br>        if (type == CustomerType.Premium) { d = amount * 0.1m; }<br>        if (type == CustomerType.VIP) { d = amount * 0.15m; }<br>        return d;<br>    }<br>}<br>// Problems: Poor naming, repetitive if statements, magic numbers, no constants</pre><p><strong>Why It’s a Problem:</strong></p><ul><li>Code accumulates technical debt quickly.</li><li>Tests pass, but code becomes hard to understand and maintain.</li><li>Adding new customer types means repeating the same pattern.</li><li>Magic numbers scattered throughout (0.05, 0.1, 0.15) with no context.</li><li>Negates TDD’s main benefit: better design through testing.</li></ul><p><strong>The Fix:</strong> Commit to the full Red-Green-<strong>Refactor</strong> cycle. After tests pass, improve the code.</p><pre>// Better: Complete the cycle with clarity and maintainability<br>public class DiscountCalculator<br>{<br>    private static readonly Dictionary&lt;CustomerType, decimal&gt; DiscountRates = new()<br>    {<br>        { CustomerType.Standard, 0.05m },<br>        { CustomerType.Premium, 0.10m },<br>        { CustomerType.VIP, 0.15m }<br>    };<br><br>    public decimal Calculate(decimal amount, CustomerType type)<br>    {<br>        if (!DiscountRates.TryGetValue(type, out var rate))<br>            throw new ArgumentException($&quot;Unknown customer type: {type}&quot;);<br>        <br>        return amount * rate;<br>    }<br>}<br>// Benefits: Clear intent, easy to add new types, magic numbers have context,<br>// DRY principle applied, easy to test and modify</pre><p><strong>4. Testing Implementation, Not Behavior</strong></p><p><strong>The Problem:</strong> Writing tests that mirror the code structure rather than verifying expected behavior. These tests break the moment you refactor internals. This overlaps with Over-Mocking (Anti-Pattern #2), but the underlying issue is broader.</p><pre>// Bad: Testing implementation<br>[Fact]<br>public void GetUser_CallsRepository_AndReturnsUser()<br>{<br>    var mockRepo = new Mock&lt;IUserRepository&gt;();<br>    mockRepo.Setup(x =&gt; x.GetById(1)).Returns(new User { Id = 1, Name = &quot;John&quot; });<br>    <br>    var service = new UserService(mockRepo.Object);<br>    var user = service.GetUser(1);<br>    <br>    // This test is overly detailed about HOW it works<br>    mockRepo.Verify(x =&gt; x.GetById(It.IsAny&lt;int&gt;()), Times.Once);<br>    Assert.Equal(&quot;John&quot;, user.Name);<br>}<br><br>// If we refactor to use a cache or a different repository, this test breaks<br>// even if the behavior (returning the correct user) is unchanged.</pre><p><strong>Why It’s a Problem:</strong></p><ul><li>Tests become brittle and tightly coupled to implementation details.</li><li>Refactoring becomes a fear, not a confidence-building exercise.</li><li>Tests don’t catch real behavioral failures, only structural changes.</li></ul><p><strong>The Fix:</strong> Test the contract, not the mechanism. Care about what, not how.</p><pre>// Better: Test behavior<br>[Fact]<br>public void GetUser_ReturnsCorrectUser()<br>{<br>    var service = new UserService(new InMemoryUserRepository());<br>    var user = service.GetUser(1);<br>    <br>    Assert.NotNull(user);<br>    Assert.Equal(1, user.Id);<br>    Assert.Equal(&quot;John&quot;, user.Name);<br>    <br>    // Now you can refactor the internals without breaking this test<br>}</pre><p><strong>5. Slow Feedback Loops</strong></p><p><strong>The Problem:</strong> Tests become slow (seconds to minutes per run), discouraging developers from running them frequently.</p><blockquote><strong>Impact:</strong> If your unit tests take 30+ seconds to run, developers won’t run them before committing. The feedback loop breaks.</blockquote><p><strong>Why It’s a Problem:</strong></p><ul><li>Slow tests kill the TDD feedback loop.</li><li>Developers skip running tests, defeating the purpose.</li><li>Bugs slip through because tests aren’t run frequently enough.</li></ul><p><strong>The Fix:</strong> Keep unit tests fast. Use mocks for external calls. Move slow integration tests to a separate suite.</p><pre>// Bad: Slow test<br>[Fact]<br>public void ProcessOrder_WithRealDatabase()<br>{<br>    // This hits the real database - could take seconds!<br>    var dbContext = new OrderDbContext(ConnectionString);<br>    var repository = new OrderRepository(dbContext);<br>    var service = new OrderProcessor(repository);<br>    <br>    service.ProcessOrder(new Order());<br>    <br>    // Assertion...<br>}</pre><pre>// Better: Fast unit test with mocked repository<br>[Fact]<br>public void ProcessOrder_QuickFeedback()<br>{<br>    var mockRepository = new Mock&lt;IOrderRepository&gt;();<br>    var service = new OrderProcessor(mockRepository.Object);<br>    <br>    service.ProcessOrder(new Order());<br>    <br>    // Assertion...<br>    // This runs in milliseconds.<br>}</pre><p><strong>6. 100% Code Coverage as a Goal</strong></p><p><strong>The Problem:</strong> Pursuing high code coverage for its own sake, treating it as a success metric rather than a tool.</p><blockquote><strong>The Quote:</strong> Code coverage of 100% is often a sign that you’re testing the wrong things. — Many experienced developers</blockquote><p><strong>Why It’s a Problem:</strong></p><ul><li>High coverage doesn’t mean high quality. You can have 100% coverage and zero confidence.</li><li>Forces trivial tests that add no value (see: Test Obsession).</li><li>Metric gaming: hitting coverage targets without catching real bugs.</li></ul><p><strong>The Fix:</strong> Focus on <strong>meaningful</strong> test coverage. Aim for 70–80% on critical paths, not 100% everywhere.</p><pre>// Don&#39;t test everything. Test what matters:<br>// 1. Business logic and algorithms<br>// 2. Edge cases and error handling<br>// 3. Integration points with external systems<br>// 4. Not: simple getters, property setters, or framework code</pre><h4>When NOT to Use TDD</h4><p>TDD is powerful, but it’s not a universal solution. Here are scenarios where it doesn’t make sense — or where other approaches are more appropriate.</p><p><strong><em>1. Prototyping &amp; Exploratory Code</em></strong></p><p><strong>The Scenario:</strong> You’re exploring a new library, framework, or technology. Requirements are fuzzy. Code will be thrown away.</p><p><strong>Why Skip TDD:</strong> Writing tests for code you’ll delete is waste. The goal is learning and proving feasibility, not building production code.</p><p><strong>Better Approach:</strong> Write throwaway code without tests. Once you’ve proven the concept works and understand the requirements, refactor into production code with TDD.</p><blockquote><strong>Pro Tip:</strong> Use a separate “spike” branch for exploration. Once you understand the problem, start fresh on the main branch with TDD.</blockquote><p><strong><em>2. UI-Heavy or Visual Prototyping</em></strong></p><p><strong>The Scenario:</strong> Building interactive UIs where visual appearance and user feedback are paramount. UI specs change frequently.</p><p><strong>Why Skip TDD:</strong> Testing UI logic is difficult and often brittle. The value of tests diminishes when the UI changes every sprint.</p><p><strong>Better Approach:</strong> Use TDD for the <strong>logic</strong> behind the UI (view models, state management). Prototype the UI separately. Integrate later. For visual consistency, use <strong>visual regression tests</strong> (tools like Percy or Chromatic capture screenshots and alert on visual drift), not unit tests.</p><pre>// TDD the logic...<br>[Fact]<br>public void CartTotalCalculator_WithThreeItems_ReturnsCorrectSum()<br>{<br>    var calculator = new CartTotalCalculator();<br>    var total = calculator.Calculate(new[] { 10, 20, 30 });<br>    Assert.Equal(60, total);<br>}<br><br>// Don&#39;t test: &quot;Button is in the top-right corner&quot;<br>// That&#39;s for visual regression tests (Percy, Chromatic) or manual testing.<br>// They&#39;re better suited for catching visual regressions than unit tests.</pre><p><strong><em>3. Legacy Codebases Without Tests</em></strong></p><p><strong>The Scenario:</strong> You’ve inherited a large codebase with zero tests. The code is tightly coupled and hard to test.</p><p><strong>Why Skip (Initially) TDD:</strong> Retrofitting tests into untestable code is painful. Introducing TDD upfront might slow your team to a crawl.</p><p><strong>Better Approach:</strong> Use <strong>characterization tests</strong> to document current behavior. Gradually refactor for testability. Then introduce TDD for new features.</p><pre>// Characterization test: Document what the code does, even if it&#39;s not perfect<br>[Fact]<br>public void LegacyProcess_BehavesAsDocumented()<br>{<br>    var result = LegacyClass.OldMethod(&quot;input&quot;);<br>    Assert.Equal(&quot;expected_output&quot;, result);<br>}<br><br>// This test documents current behavior. Now you have a safety net to refactor.</pre><p><strong><em>4. Performance-Critical or Hardware-Dependent Code</em></strong></p><p><strong>The Scenario:</strong> Low-level code that interacts with hardware, OS APIs, or requires specific performance characteristics.</p><p><strong>Why Skip TDD:</strong> Mocking hardware interactions is often infeasible. Testing performance requires benchmarks, not unit tests.</p><p><strong>Better Approach:</strong> Use integration and performance tests. Reserve unit tests for the algorithmic parts. Use test doubles strategically. For performance testing, tools like <strong>BenchmarkDotNet</strong> (for .NET) provide measurable profiling — far better than guessing.</p><pre>// Use BenchmarkDotNet for performance validation<br>[MemoryDiagnoser]<br>public class SortingBenchmark<br>{<br>    private int[] _data;<br><br>    [GlobalSetup]<br>    public void Setup() =&gt; _data = new int[10000].Select(_ =&gt; Random.Shared.Next()).ToArray();<br><br>    [Benchmark]<br>    public void QuickSort() =&gt; Array.Sort(_data);<br>}<br>// Run: dotnet run -c Release --benchmarkdotnet</pre><p><strong><em>5. One-Off Scripts or Throwaway Code</em></strong></p><p><strong>The Scenario:</strong> Utility scripts, data migrations, or temporary tools that solve a specific problem once.</p><p><strong>Why Skip TDD:</strong> The cost-benefit ratio is unfavorable. A script run once doesn’t need a test suite.</p><p><strong>Better Approach:</strong> Use manual testing or simple assertions. Focus on correctness, not test coverage.</p><h4>TDD Maturity Levels</h4><p>Understanding when and how to apply TDD comes with experience. Here’s a framework for thinking about TDD maturity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yc1x1V-wFYYETb4aRHeJsQ.png" /><figcaption>TDD Maturity Levels</figcaption></figure><p><strong>Goal:</strong> Reach Level 3 — use TDD as a tool, not a religion.</p><h4>A Cohesive Refactoring Journey: From Anti-Pattern to Clean Code</h4><p>Let’s trace a realistic journey — the kind many teams experience — where anti-patterns accumulate, then get cleaned up.</p><pre>// PHASE 1: Anti-patterns in action<br>// Test Obsession + Over-Mocking + No Refactoring = Pain<br>[Fact]<br>public void OrderService_Test() // Vague name<br>{<br>    var mockValidator = new Mock&lt;IOrderValidator&gt;();<br>    var mockLogger = new Mock&lt;ILogger&gt;();<br>    var mockEmailService = new Mock&lt;IEmailService&gt;();<br>    var mockRepository = new Mock&lt;IOrderRepository&gt;();<br>    <br>    mockValidator.Setup(x =&gt; x.IsValid(It.IsAny&lt;Order&gt;())).Returns(true);<br>    mockRepository.Setup(x =&gt; x.Save(It.IsAny&lt;Order&gt;())).Returns(Task.CompletedTask);<br>    // 30 more lines of setup...<br>    <br>    var service = new OrderService(mockValidator.Object, mockLogger.Object,<br>        mockEmailService.Object, mockRepository.Object);<br>    var order = new Order { Amount = 100 };<br>    <br>    service.ProcessAsync(order); // What are we testing?<br>    // Result: Setup is 40 lines, test is 5 lines. Tests are fragile.<br>}<br><br>// PHASE 2: Recognition &amp; Refactoring<br>// Focus on behavior, reduce mocks, improve names<br>[Fact]<br>public void ProcessOrder_ValidatesBeforeSaving()<br>{<br>    var validator = new OrderValidator(); // Real<br>    var mockEmailService = new Mock&lt;IEmailService&gt;(); // External, mock it<br>    var repository = new InMemoryOrderRepository(); // Real internal<br>    <br>    var service = new OrderService(validator, repository, mockEmailService.Object);<br>    var invalidOrder = new Order { Amount = -100 }; // Negative = invalid<br>    <br>    // Act &amp; Assert: Should not save invalid orders<br>    await Assert.ThrowsAsync&lt;ValidationException&gt;(() =&gt; service.ProcessAsync(invalidOrder));<br>    Assert.Empty(repository.GetAll()); // Nothing was saved<br>}<br><br>[Fact]<br>public void ProcessOrder_SendsEmailAfterSuccess()<br>{<br>    var mockEmailService = new Mock&lt;IEmailService&gt;();<br>    var validator = new OrderValidator();<br>    var repository = new InMemoryOrderRepository();<br>    <br>    var service = new OrderService(validator, repository, mockEmailService.Object);<br>    var validOrder = new Order { Amount = 100, CustomerEmail = &quot;user@example.com&quot; };<br>    <br>    await service.ProcessAsync(validOrder);<br>    <br>    // Verify external service was called<br>    mockEmailService.Verify(x =&gt; x.SendConfirmation(&quot;user@example.com&quot;), Times.Once);<br>}<br>// Result: Setup is 5-7 lines. Tests are clear. Refactoring is safe.</pre><p><strong>The Transformation:</strong> By addressing each anti-pattern — clarity in naming, real instances for internals, mocks only for externals — the test suite became faster, clearer, and safer to refactor. This is what pragmatic TDD looks like.</p><h4>Best Practices to Avoid Anti-Patterns</h4><ul><li><strong>Focus on behavior, not implementation:</strong> Ask “What should this do?” not “How does it do it?”</li><li><strong>Keep tests simple and fast:</strong> If setup takes longer than the test itself, something’s wrong.</li><li><strong>Mock external dependencies, not internals:</strong> Databases, APIs, third-party services — mock these. Your own code — test it for real.</li><li><strong>Don’t chase code coverage numbers:</strong> Aim for meaningful coverage (70–80% on critical paths), not 100%.</li><li><strong>Refactor ruthlessly:</strong> The refactor step is sacred. Don’t skip it.</li><li><strong>Write tests for future-you:</strong> Ask: “Will this test help someone understand the code 6 months from now?”</li><li><strong>Use TDD as a design tool, not just a safety net:</strong> If writing a test feels hard, it’s telling you something about your design.</li></ul><h4>Summary: Using TDD Wisely</h4><p>TDD is not magic, nor is it a silver bullet. It’s a practice — powerful when applied wisely, counterproductive when misused. The anti-patterns we’ve discussed — test obsession, over-mocking, skipping refactoring — emerge when teams follow TDD mechanically instead of thoughtfully.</p><p>Equally important is recognizing where TDD doesn’t apply. Prototyping, exploratory coding, UI-heavy work, and legacy systems have different approaches. The mature developer knows when to apply TDD and when to reach for other tools.</p><p>The ultimate goal of TDD isn’t high test counts or code coverage. It’s <strong>confidence</strong> — the ability to change code fearlessly, knowing your tests have your back. When you lose sight of that goal and start pursuing metrics, you’ve crossed into anti-pattern territory.</p><p>Use TDD where it helps you build better software. Skip it where it doesn’t. And always ask yourself: “Is this making my code better, or am I just following a checklist?”</p><p><em>If you like this post, then check out other articles in the series as well. Start with:</em></p><p><a href="https://medium.com/@ajaykumar1807/test-driven-development-tdd-a-practical-introduction-845e699ef09b">https://medium.com/@ajaykumar1807/test-driven-development-tdd-a-practical-introduction-845e699ef09b</a></p><p>Have you encountered these anti-patterns in your projects? What’s your experience with TDD? Share your thoughts in the comments below.</p><p><em>Originally published at </em><a href="https://devcodex.in/blog/tdd/anti-patterns-when-not-to-use-tdd/"><em>https://devcodex.in</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49997bd89fa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD in .NET: Refactoring Safely]]></title>
            <link>https://medium.com/@ajaykumar1807/tdd-in-net-refactoring-safely-ac6feb6e9e87?source=rss-e26704d7d84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac6feb6e9e87</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Ajay kumar]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 06:40:59 GMT</pubDate>
            <atom:updated>2025-12-28T06:40:59.845Z</atom:updated>
            <content:encoded><![CDATA[<h3>TDD in .NET: Refactoring Safely</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkoFwQMMtb38uHvpEQeXOA.png" /></figure><h4>Why Developers Fear Refactoring (But Shouldn’t)</h4><p>Picture this: You join a new team, and your first task is to fix a bug in a legacy billing module. The method is 300 lines long, filled with cryptic variable names and nested ifs. You hesitate — what if you break something? This fear is universal. But with a solid suite of tests, refactoring transforms from a risky gamble into a safe, even enjoyable, process. Tests are your safety net, letting you clean up code with confidence.</p><h4>How to Decide What to Refactor First</h4><p>In TDD, refactoring opportunities emerge naturally from your test suite. Focus your refactoring efforts where they’ll have the biggest impact:</p><ul><li><strong>High-churn areas with weak tests:</strong> Code that changes often but lacks comprehensive test coverage is a refactoring candidate. Write tests first (characterization tests if it’s legacy code), then refactor safely.</li><li><strong>Failing or flaky tests:</strong> If tests are hard to write or maintain for a feature, the underlying code likely needs refactoring. Use the test feedback as a signal that design is off.</li><li><strong>Repetitive test patterns:</strong> Duplicated test logic or setup code suggests the production code should be simplified. Refactor to reduce test boilerplate.</li><li><strong>Complex test assertions:</strong> If verifying behavior requires many assertions or helper methods, the code under test is probably doing too much. Refactor to single responsibility.</li></ul><blockquote>ℹ️ Tip: Let your tests guide you. If a test is hard to write, refactor the code to make it testable. Testability and clean design go hand-in-hand.</blockquote><h4>What Refactoring Really Means (and Why It’s Hard)</h4><p>Refactoring isn’t rewriting, slowing down, or sneaking in new features. It’s about <strong>improving the internal structure without changing what the code does</strong>. The challenge? Sometimes the code is so tangled, or so poorly tested, that even small changes feel risky. If you’ve ever tried to clean up a function and ended up breaking something, you know the pain.</p><p><strong>Example:</strong> Discount logic is duplicated in `OrderService`, `CartService`, and `QuoteService`. Write 24 tests covering percentage, flat-rate, seasonal, and tier-based discounts. Extract a single `DiscountCalculator` class. Now one bug fix to senior-citizen discounts benefits all three services.</p><h4><strong>Step-by-step walkthrough:</strong></h4><p><strong>Before refactoring:</strong> Each service calculates discounts independently, leading to bugs when business rules change.</p><pre>public class OrderService<br>{<br>    public decimal CalculateTotal(Order order)<br>    {<br>        decimal discount = 0;<br>        if (order.CustomerType == &quot;Senior&quot;) discount = order.Total * 0.15 m;<br>        else if (order.CustomerType == &quot;Premium&quot;) discount = order.Total * 0.10 m;<br>        return order.Total - discount;<br>    }<br>}<br><br>public class CartService<br>{<br>    public decimal CalculateTotal(Cart cart)<br>    {<br>        decimal discount = 0;<br>        if (cart.CustomerType == &quot;Senior&quot;) discount = cart.Total * 0.15 m;<br>        else if (cart.CustomerType == &quot;Premium&quot;) discount = cart.Total * 0.10 m;<br>        return cart.Total - discount;<br>    }<br>}</pre><p><strong>Write tests first:</strong> Cover all discount scenarios to lock in expected behavior.</p><pre>[Fact]<br>public void CalculateDiscount_SeniorCustomer_ShouldReturn15Percent()<br>   =&gt; Assert.Equal(150 m, calculator.CalculateDiscount(100 m, &quot;Senior&quot;));<br><br>[Fact]<br>public void CalculateDiscount_PremiumCustomer_ShouldReturn10Percent()<br>   =&gt; Assert.Equal(90 m, calculator.CalculateDiscount(100 m, &quot;Premium&quot;));<br><br>[Fact]<br>public void CalculateDiscount_RegularCustomer_ShouldReturnNoDiscount()<br>   =&gt; Assert.Equal(100 m, calculator.CalculateDiscount(100 m, &quot;Regular&quot;));</pre><p><strong>After refactoring:</strong> Extract discount logic into a single, reusable class.</p><pre>public class DiscountCalculator<br>{<br>    public decimal CalculateDiscount(decimal total, string customerType) =&gt; customerType<br>    switch<br>    {<br>        &quot;Senior&quot; =&gt; total * 0.15 m, &quot;Premium&quot; =&gt; total * 0.10 m,<br>            _ =&gt; 0 m<br>    };<br>}<br><br>public class OrderService<br>{<br>    private readonly DiscountCalculator discountCalc = new();<br>    public decimal CalculateTotal(Order order) =&gt; order.Total - discountCalc.CalculateDiscount(order.Total, order.CustomerType);<br>}<br><br>public class CartService<br>{<br>    private readonly DiscountCalculator discountCalc = new();<br>    public decimal CalculateTotal(Cart cart) =&gt; cart.Total - discountCalc.CalculateDiscount(cart.Total, cart.CustomerType);<br>}</pre><p><strong>Benefit:</strong> Fix a bug once, fix it everywhere. Change senior-citizen discount from 15% to 20%? Update one line in `DiscountCalculator`. All three services benefit immediately. Tests ensure nothing breaks.</p><h4>The Golden Rule of Refactoring</h4><p><strong><em>If it’s not covered by tests, don’t refactor it.</em></strong></p><blockquote><strong>Workflow</strong>: Legacy Code → Characterization Tests → Refactor Safely</blockquote><ol><li>Identify what the code does (read, run, and document its outputs)</li><li>Write tests that lock its current behavior (characterization tests)</li><li>Refactor safely in tiny steps</li><li>Run tests after every micro-change</li></ol><p>Tests are your seatbelts. If you don’t have them, write them first — even if they just confirm the current (possibly weird) behavior.</p><blockquote>ℹ️ <strong>Tip:</strong> Never refactor and add features in the same commit. Keep changes isolated.</blockquote><h4>Red → Green → Refactor, Explained Deeply</h4><p>TDD (Test-Driven Development) makes refactoring a natural part of coding. Here’s how:</p><ol><li><strong>Red:</strong> Write a test for a new or existing behavior. Watch it fail (proves the test is valid).</li><li><strong>Green:</strong> Make the test pass with the simplest code possible.</li><li><strong>Refactor:</strong> Now, clean up the code. The tests guarantee you don’t break anything.</li></ol><p><strong>Example:</strong> Your shipping calculator has a bug: express shipments should cost $15 flat, but the system is incorrectly charging weight-based rates instead.</p><p><strong>Red:</strong> Write a test that locks in the correct behavior:</p><pre>[Fact]<br>public void CalculateExpressShippingFee_ShouldReturn15Flat()<br>{<br>    var calculator = new ShippingCalculator();<br>    var result = calculator.CalculateExpressShippingFee(weight: 50); // weight shouldn&#39;t matter<br>    Assert.Equal(15 m, result);<br>}</pre><p>The test fails because the code applies weight-based logic to express shipments.</p><p><strong>Green:</strong> Make the test pass with the simplest fix — hardcode $15 for express shipments or add a conditional check.</p><p><strong>Refactor:</strong> Now that tests protect you, introduce a `ShippingStrategy` interface to handle different shipping types cleanly:</p><pre>    public interface IShippingStrategy<br>    {<br>        decimal CalculateFee(decimal weight);<br>    }<br><br>    public class ExpressShippingStrategy: IShippingStrategy<br>    {<br>        public decimal CalculateFee(decimal weight) =&gt; 15 m; // flat rate<br>    }<br><br>    public class StandardShippingStrategy: IShippingStrategy<br>    {<br>        public decimal CalculateFee(decimal weight) =&gt; weight * 0.5 m;<br>    }</pre><p>All tests still pass. Both express and weight-tier shipping now work correctly, and adding new shipping types is easy.</p><h4>Practical Example — The Ugly Function Makeover</h4><p>Let’s walk through a real-world scenario. You’re tasked with refactoring an API method that calculates discounts for a shopping cart. It’s a monster:</p><ul><li>150 lines long</li><li>Duplicated logic for different product types</li><li>Messy, nested conditionals</li><li>No documentation</li></ul><p><strong>Before (giant nested ifs):</strong></p><pre>public decimal CalculateDiscount(Cart cart)<br>{<br>    if (cart.ProductType == &quot;Electronics&quot;)<br>    {<br>        if (cart.Price &gt; 100)<br>        {<br>            return cart.Price * 0.9 m;<br>        }<br>        else<br>        {<br>            return cart.Price * 0.95 m;<br>        }<br>    }<br>    else if (cart.ProductType == &quot;Groceries&quot;)<br>    {<br>        // ...more nested ifs...<br>    }<br>    // ...many more lines...<br>}</pre><p><strong>After (small clean methods):</strong></p><pre>public decimal CalculateDiscount(Cart cart)<br>{<br>    switch (cart.ProductType)<br>    {<br>        case &quot;Electronics&quot;:<br>            return ApplyElectronicsDiscount(cart);<br>        case &quot;Groceries&quot;:<br>            return ApplyGroceriesDiscount(cart);<br>        default:<br>            return cart.Price;<br>    }<br>}<br>private decimal ApplyElectronicsDiscount(Cart cart)<br>{<br>    return cart.Price &gt; 100 ? cart.Price * 0.9 m : cart.Price * 0.95 m;<br>}<br>// ...other clean methods...</pre><p>Here’s how you tackle it:</p><p><strong>Step 1:</strong> Write tests confirming its current behavior (characterization tests). Example:</p><pre>// &lt;summary&gt;Verifies current discount logic for electronics&lt;/summary&gt;<br>[Fact]<br>public void Discount_Electronics_ShouldBe10Percent()<br>{<br>    var cart = new Cart<br>    {<br>        ProductType = &quot;Electronics&quot;, Price = 100<br>    };<br>    var result = DiscountCalculator.Calculate(cart);<br>    Assert.Equal(90, result);<br>}</pre><p><strong>Step 2:</strong> Start micro-refactoring. Extract methods, rename variables, remove duplication, and introduce domain concepts. Example:</p><pre>// &lt;summary&gt;Extracted method for electronics discount&lt;/summary&gt;<br>private decimal ApplyElectronicsDiscount(Cart cart)<br>{<br>    return cart.Price * 0.9 m;<br>}</pre><p><strong>Step 3:</strong> Keep running tests. If anything breaks, behavior changed — fix immediately. The tests will catch regressions before they reach production.</p><p><strong>Result:</strong> The function shrinks to 40 lines, logic is clear, and future changes are easy.</p><h4>When to Stop Refactoring</h4><p><strong><em>Boy Scout Rule:</em></strong><em> Leave the code cleaner than you found it.</em></p><ul><li>It’s readable</li><li>Duplication is removed</li><li>Structure makes sense</li><li>No further clarity is gained</li></ul><p><strong>Example</strong> Your e-commerce checkout calculates shipping, taxes, and promo codes in one messy function. After extracting `CalculateShipping()`, `ApplyTaxes()`, and `ApplyPromoCode()` methods, the code is clear and each piece is testable. You stop there — no need for strategy patterns or caching yet. Tests pass, your teammate can modify it without fear. Boy Scout Rule satisfied.</p><h4>Refactoring Patterns You Should Know</h4><p>In TDD, refactoring patterns emerge from your Red-Green-Refactor cycle. Here are essential patterns and how they fit into TDD:</p><ul><li><strong>Extract Method:</strong> Test reveals a method does too much? Extract a helper. Write a test for the extracted behavior first.</li><li><strong>Extract Class:</strong> When a class has too many responsibilities (and your tests for it are complex), split it. Tests guide which responsibilities belong together.</li><li><strong>Inline Variable:</strong> Overly complex intermediate variables make tests harder to read. Inline them once tests verify the logic.</li><li><strong>Rename for Intent:</strong> If a test name doesn’t match what the code does, rename the code. Tests act as specifications.</li><li><strong>Introduce Parameter Object:</strong> When you have many parameters making tests verbose, group them. Tests tell you when parameters need organization.</li><li><strong>Replace Magic Numbers with Constants:</strong> Tests should use named constants, not magic numbers. This refactor improves both code and test readability.</li><li><strong>Replace Conditional with Polymorphism:</strong> Complex conditionals (if/else chains) are test nightmares. Strategy or State patterns simplify testing.</li></ul><p><strong>Example — Extract Method via TDD:</strong> Your test is failing because a method mixes currency conversion with discount calculation.</p><pre>    [Fact]<br>    public void CalculatePrice_WithCurrencyAndDiscount_ShouldWorkCorrectly()<br>    {<br>        // This test is trying to verify too much at once<br>        var result = calculator.CalculatePrice(100 m, &quot;USD&quot;, &quot;Senior&quot;);<br>        Assert.Equal(expectedValue, result);<br>    }<br>    // Refactor: Write separate tests<br>    [Fact]<br>    public void ConvertCurrency_USD_ShouldApplyCorrectRate() =&gt; ...[Fact]<br>    public void ApplyDiscount_SeniorCustomer_ShouldReturn15Percent() =&gt; ...<br>        // Now extract the methods to make tests pass<br>        private decimal ConvertCurrency(decimal amount, string currency) =&gt; ...private decimal ApplyDiscount(decimal amount, string customerType) =&gt; ...</pre><p>Learn a few patterns and use them often. Let your tests guide which pattern fits best.</p><h4>Common Gotchas &amp; Anti-Patterns</h4><ul><li>Refactoring while adding new features</li><li>Mixing feature changes and refactors in the same commit</li><li>Editing tests to “make green” instead of fixing code</li><li>Over-engineering</li><li>Ignoring performance regressions</li></ul><p><strong>Example:</strong> A junior dev refactors a password validation function from 80 lines to 20 lines (cleaner logic, same behavior). But they also “optimized” the regex pattern. Two days later, users can’t reset passwords because the regex now rejects valid special characters. The refactor and the “optimization” are tangled. If separated: the refactor alone would pass all tests, and the optimization would immediately fail password tests. Lesson learned the hard way.</p><h4>Tools That Make Refactoring Easier</h4><ul><li>IDE automated refactorings (Rider/VS/IntelliJ)</li><li>Mutation testing</li><li>Linters &amp; static analysis tools</li><li>Coverage tools (for guidance, not targets)</li></ul><p><strong>Mutation Testing — Are Your Tests Strong Enough?</strong></p><p>Mutation testing helps verify your tests are strong enough to detect broken behavior. It works by making small changes (mutations) to your code and checking if your tests fail as expected.</p><pre>// Original code<br>return cart.Price * 0.9 m;<br>// Mutated code (by tool)<br>return cart.Price * 0.8 m;<br>// If your test still passes, it&#39;s too weak!</pre><p>Tools like Stryker.NET or Pitest (Java) automate mutation testing and help you strengthen your test suite.</p><blockquote>ℹ️ Tip: Use your IDE’s “Extract Method” and “Rename” features — they’re safer and faster than manual edits.</blockquote><h4>Wrap-Up — Courage via Tests</h4><p>Refactoring is a habit. TDD encourages frequent, safe refactors, cleaner designs, confidence in code, and higher quality with less fear. With tests as your safety net, refactoring becomes not just easy — but joyful. Next time you see a scary function, remember: write a test, refactor in small steps, and let your tests give you courage.</p><p><em>Originally published at </em><a href="https://devcodex.in/blog/tdd/refactoring-safely-with-tdd"><em>https://devcodex.in</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac6feb6e9e87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD in .NET: Practicing TDD in a Web API Project]]></title>
            <link>https://medium.com/@ajaykumar1807/tdd-in-net-practicing-tdd-in-a-web-api-project-3ade4dbcfe58?source=rss-e26704d7d84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ade4dbcfe58</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Ajay kumar]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 10:47:10 GMT</pubDate>
            <atom:updated>2025-12-23T10:56:10.636Z</atom:updated>
            <content:encoded><![CDATA[<h3>TDD in .NET: Practicing TDD in a Web API Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eKVRAx08MY4CiJERTidzSw.png" /></figure><h4>Do you feel lost when trying to apply TDD in a real-world Web API project?</h4><p>Many developers struggle to apply Test-Driven Development (TDD) effectively in real-world Web API projects. Common challenges include unclear test boundaries, slow feedback cycles, and confusion about where to start — controller, service, or database? This article aims to bridge that gap by providing a practical, layered approach to TDD, using a simple but realistic use case. The goal is to help readers build confidence, avoid common pitfalls, and make informed decisions at every step of the development process.</p><p><strong>Challenge:</strong> TDD is not just about writing tests first — it’s about designing APIs that are robust, maintainable, and easy to change. This article shows how to achieve that, one layer at a time.</p><p>This article demonstrates how to apply Test-Driven Development (TDD) to a .NET Web API project, focusing on the controller, service, and database layers. We’ll use a hypothetical Expense Manager application and a simple read-only use case — <strong>Get expenses by category</strong> — to show best practices and a clear, step-by-step flow.</p><p><strong>Why TDD?</strong> TDD helps you build reliable, maintainable code by writing tests before implementation. It keeps your design focused and your codebase flexible.</p><h4>System Breakdown</h4><ul><li><strong>Controller</strong> — Receives HTTP requests, returns responses</li><li><strong>Service</strong> — Contains business logic, enforces rules</li><li><strong>Repository</strong> — Persists data, uses in-memory fakes for tests</li></ul><p><strong>Design Insight:</strong> Separating layers makes your code easier to test and maintain. Each layer has a clear responsibility.</p><h4>Use Case: Get Expenses by Category</h4><ul><li>Feature: Fetch all expenses for a given category (e.g., “Food”, “Travel”)</li><li>API should return a list of matching expenses</li></ul><h4>Step 1: Controller Layer TDD</h4><p>The TDD process begins with the user’s perspective: what does the API need to deliver? For the Expense Manager, the client wants to fetch expenses by category. Consider the endpoint, the shape of the response, and edge cases (empty results, invalid category, etc.).</p><p><strong>Write a failing test:</strong> The test should describe the ideal behavior. Use Moq to mock the service, focusing only on the controller’s responsibility: receiving the request, delegating to the service, and returning the correct response.</p><pre>// Controller test for GetExpensesByCategory<br>[Fact]<br>public async Task GetExpensesByCategory_ReturnsExpensesForCategory()<br>{<br>    var mockService = new Mock&lt;IExpenseService&gt;();<br>    var category = &quot;Food&quot;;<br>    var expected = new List&lt;ExpenseDto&gt; {<br>        new ExpenseDto { Title = &quot;Lunch&quot;, Amount = 10, Category = &quot;Food&quot;, Date = DateTime.Today },<br>        new ExpenseDto { Title = &quot;Snacks&quot;, Amount = 5, Category = &quot;Food&quot;, Date = DateTime.Today }<br>    };<br>    mockService.Setup(s =&gt; s.GetExpensesByCategoryAsync(category)).ReturnsAsync(expected);<br>    var controller = new ExpensesController(mockService.Object);<br>    var result = await controller.GetExpensesByCategory(category);<br>    var okResult = Assert.IsType&lt;OkObjectResult&gt;(result);<br>    var actual = Assert.IsAssignableFrom&lt;IEnumerable&lt;ExpenseDto&gt;&gt;(okResult.Value);<br>    Assert.Equal(expected.Count, actual.Count());<br>}</pre><p><strong>Tip:</strong> The test will fail at first, because the endpoint does not exist yet. This is the “Red” phase of TDD. This failure is feedback that guides the next step.</p><p><strong>Implement minimal code:</strong> Add the endpoint to the controller, just enough to make the test compile and run. Avoid adding extra logic or validation here; the goal is to move quickly from red to green.</p><pre>// Controller endpoint for GetExpensesByCategory<br>[HttpGet(&quot;category/{category}&quot;)]<br>public async Task&lt;IActionResult&gt; GetExpensesByCategory(string category)<br>{<br>    var expenses = await _service.GetExpensesByCategoryAsync(category);<br>    return Ok(expenses);<br>}</pre><p><strong>Refactor:</strong> Once the test passes, review the controller for clarity and simplicity. Thin controllers are best — keep business logic out and delegate to the service.</p><h4>Step 2: Service Layer TDD</h4><p>The next focus is business logic. The service must filter expenses by category, handle edge cases, and ensure correctness. Consider what could go wrong: unknown categories, empty lists, performance with large datasets.</p><p><strong>Write a failing test:</strong> Use an in-memory fake repository to keep tests fast and isolated. The test should check that only expenses matching the category are returned, and that the service doesn’t leak implementation details.</p><pre>// Service test for GetExpensesByCategory<br>[Fact]<br>public async Task GetExpensesByCategory_ReturnsOnlyMatchingCategory()<br>{<br>    var fakeRepo = new InMemoryExpenseRepository();<br>    fakeRepo.Add(new Expense { Title = &quot;Lunch&quot;, Amount = 10, Category = &quot;Food&quot;, Date = DateTime.Today });<br>    fakeRepo.Add(new Expense { Title = &quot;Taxi&quot;, Amount = 20, Category = &quot;Travel&quot;, Date = DateTime.Today });<br>    var service = new ExpenseService(fakeRepo);<br>    var result = await service.GetExpensesByCategoryAsync(&quot;Food&quot;);<br>    Assert.Single(result);<br>    Assert.Equal(&quot;Lunch&quot;, result.First().Title);<br>}</pre><p><strong>Best Practice:</strong> Avoid real database calls in unit tests. Fakes let you control the data and keep the feedback loop tight.</p><p><strong>Implement minimal code:</strong> Add filtering logic to the service, just enough to pass the test. Do not optimize or add extra features yet — TDD is about incremental progress.</p><pre>// Service filtering logic<br>public async Task&lt;IEnumerable&lt;ExpenseDto&gt;&gt; GetExpensesByCategoryAsync(string category)<br>{<br>    var all = await _repository.GetAllAsync();<br>    return all.Where(e =&gt; e.Category == category)<br>              .Select(e =&gt; new ExpenseDto { Title = e.Title, Amount = e.Amount, Category = e.Category, Date = e.Date });<br>}</pre><p><strong>Refactor:</strong> After the test passes, look for duplication, unclear names, or opportunities to improve performance. Keep the service focused on business rules.</p><h4>Step 3: Repository Layer TDD</h4><p>Persistence is the foundation. The repository should be reliable and predictable. Use an in-memory list for tests, which simulates database behavior without the overhead.</p><p><strong>Write a failing test:</strong> Test that expenses can be added and retrieved. Consider edge cases: duplicate entries, empty lists, thread safety if needed.</p><pre>// Repository fake for expenses<br>public class InMemoryExpenseRepository : IExpenseRepository<br>{<br>    private readonly List&lt;Expense&gt; _expenses = new();<br>    public void Add(Expense expense) =&gt; _expenses.Add(expense);<br>    public Task&lt;List&lt;Expense&gt;&gt; GetAllAsync() =&gt; Task.FromResult(_expenses);<br>}</pre><p><strong>Best Practice:</strong> Fakes are great for TDD — they keep tests fast and isolated from infrastructure. Use them to validate persistence logic before integrating with a real database.</p><p><strong>Refactor:</strong> Once the repository works as expected, consider adding interfaces, improving naming, and preparing for future database integration.</p><h4>Test Boundaries: Why Mock, Why DTOs?</h4><p><strong>Controller tests</strong> should mock the service layer to focus on request handling, validation, and response formatting. This keeps tests fast and isolated from business logic and data access.</p><p><strong>DTOs (Data Transfer Objects)</strong> are used to shape the data sent to and from the API. They prevent leaking domain models and allow for versioning and validation. Always use DTOs in controller and service boundaries.</p><p><strong>Best Practice:</strong> Use unit tests for controllers and services, and reserve integration tests for end-to-end scenarios.</p><h4>Repository Layer: Expanded</h4><p>The repository manages data access. In tests, use an in-memory fake to avoid external dependencies. In production, use a real implementation (e.g., EFCore).</p><pre>// Repository test example<br>[Fact]<br>public void AddAndRetrieveExpense_WorksCorrectly()<br>{<br>    var repo = new InMemoryExpenseRepository();<br>    var expense = new Expense { Title = &quot;Lunch&quot;, Amount = 10, Category = &quot;Food&quot;, Date = DateTime.Today };<br>    repo.Add(expense);<br>    var all = repo.GetAllAsync().Result;<br>    Assert.Contains(expense, all);<br>}</pre><p><strong>Note:</strong> A real repository (e.g., using EFCore) would connect to a database, handle queries, and manage transactions. Fakes are for fast, isolated tests.</p><h4>Theory: Making Good TDD Decisions</h4><p>TDD is more than just writing tests first — it’s about making design decisions that lead to maintainable, flexible code. Here are some key principles and decision points to help you succeed:</p><ul><li><strong>Start with the API contract:</strong> Think about what your endpoint should do and how clients will use it. Write tests that reflect real usage.</li><li><strong>Test one responsibility at a time:</strong> Each test should focus on a single behavior. This makes failures easy to diagnose and code easier to refactor.</li><li><strong>Mock only what you don’t control:</strong> Use Moq for external dependencies (services, repositories), but use real value objects and DTOs in your tests.</li><li><strong>Prefer fakes for persistence:</strong> In-memory fakes let you test business logic without slow or flaky infrastructure. This keeps your TDD cycle fast.</li><li><strong>Let tests drive design:</strong> If a test is hard to write, your code may be too tightly coupled. Refactor to introduce interfaces or break up responsibilities.</li><li><strong>Refactor often:</strong> After each green test, clean up your code. Move logic to private methods, clarify names, and remove duplication.</li><li><strong>Document your process:</strong> Keep a diary or log of your TDD steps. This helps you learn and makes it easier to onboard others.</li></ul><p><strong>Design Insight:</strong> TDD is a feedback loop. Use test failures and successes to guide your next design decision, not just to check correctness.</p><p>By following these principles, you’ll be able to make better decisions at each step of the TDD cycle, leading to APIs that are robust, easy to change, and well-documented.</p><h4>Troubleshooting TDD Pitfalls</h4><ul><li><strong>Test not discovered?</strong> Check method/class attributes and naming.</li><li><strong>Over-mocking?</strong> Only mock external dependencies, not value objects.</li><li><strong>Brittle tests?</strong> Focus on behavior, not implementation details.</li><li><strong>Slow tests?</strong> Use fakes and avoid real database/API calls.</li></ul><p><strong>Tip:</strong> Refactor often and keep tests focused on one responsibility.</p><h4>Summary</h4><p>By following TDD across controller, service, and repository layers, you build robust, maintainable APIs. Use Moq for mocking, in-memory fakes for fast cycles, and keep each test focused. Document each step and test run for clarity and learning.</p><p><em>Originally published at </em><a href="https://devcodex.in/blog/tdd/expense-tracker-tdd-webapi"><em>https://devcodex.in</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ade4dbcfe58" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>