<?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 Rajkin Hossain on Medium]]></title>
        <description><![CDATA[Stories by Rajkin Hossain on Medium]]></description>
        <link>https://medium.com/@rajkin.hossain?source=rss-501f94b6baca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E8wolqYJ_zF7pmBH1-2jmg.jpeg</url>
            <title>Stories by Rajkin Hossain on Medium</title>
            <link>https://medium.com/@rajkin.hossain?source=rss-501f94b6baca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:32:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rajkin.hossain/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stop Removing await to Make Your API “Asynchronous” — Here’s the Proper Way to Do It]]></title>
            <link>https://medium.com/@rajkin.hossain/stop-removing-await-to-make-your-api-asynchronous-heres-the-proper-way-to-do-it-552406606ada?source=rss-501f94b6baca------2</link>
            <guid isPermaLink="false">https://medium.com/p/552406606ada</guid>
            <dc:creator><![CDATA[Rajkin Hossain]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 08:53:28 GMT</pubDate>
            <atom:updated>2026-02-15T08:53:28.400Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern backend applications aim to be fast, scalable, and responsive.</p><p>A common pattern developers try is this:</p><pre>GoAsync();<br>return Accepted();</pre><p>The idea seems logical:</p><blockquote><em>“If I don’t await the task, my API will return immediately and the server will be free.”</em></blockquote><p>Unfortunately, this is not real asynchronous architecture.<br> It’s unsafe fire-and-forget execution — and it can cause serious production issues.</p><p>Let’s break this down properly.</p><h3>The Problem with Removing await</h3><p>When you call an async method without awaiting it inside an ASP.NET request:</p><ul><li>The HTTP request finishes immediately</li><li>Scoped services (like DbContext) get disposed</li><li>Exceptions are not properly observed</li><li>There is no retry mechanism</li><li>If the application crashes, the task is lost</li><li>There is no visibility or monitoring</li></ul><p>In other words, you’ve created background work — without any background infrastructure.</p><p>This is not scalable. It’s risky.</p><h3>What Should We Do Instead?</h3><p>If we’re building a modular monolithic application, we still have proper architectural options — even without using a full message bus.</p><p>Let’s explore them.</p><h3>Option 1: Use Background Jobs (Recommended for Many Cases)</h3><p>Background job processors like:</p><ul><li>Hangfire</li><li>Quartz.NET</li><li>Custom BackgroundService workers</li></ul><p>are designed for this exact problem.</p><h3>Why Background Jobs Are Better</h3><p>They provide:</p><ul><li>Retry policies</li><li>Persistence (jobs survive app restart)</li><li>Error tracking</li><li>Monitoring dashboards</li><li>Scheduled &amp; delayed execution</li><li>Separation from HTTP lifecycle</li></ul><p>Example using Hangfire:</p><pre>BackgroundJob.Enqueue(() =&gt; ProcessEssayAsync(id));<br>return Accepted();</pre><p>Now:</p><ul><li>The API responds immediately</li><li>The job runs in the background</li><li>If it fails → it retries</li><li>If the server restarts → job persists</li><li>You can monitor job status</li></ul><p>This is real background processing</p><h3>Option 2: Use a Dedicated BackgroundService Queue (Lightweight Approach)</h3><p>If you don’t want external libraries, you can implement:</p><ul><li>Channel&lt;T&gt; or BlockingCollection&lt;T&gt;</li><li>A hosted BackgroundService</li><li>A controlled worker loop</li></ul><p>Example idea:</p><ul><li>Controller pushes command into in-memory queue</li><li>Background worker reads queue</li><li>Worker processes items safely</li></ul><p>This separates work from HTTP requests while staying inside your modular monolith.</p><p>However, note:</p><ul><li>In-memory queues are not durable</li><li>Restarting the app loses queued work</li></ul><p>So this works only if you accept that limitation.</p><h3>Option 3: Use Message-Based Architecture (Even in Modular Monolith)</h3><p>Even inside a modular monolith, you can:</p><ul><li>Introduce internal command dispatching</li><li>Implement durable local queues</li><li>Add retry policies</li><li>Persist messages in database</li></ul><p>This allows your monolith to behave like a distributed system — without splitting services.</p><p>This approach is especially useful if you plan future migration to microservices.</p><h3>When Should You Use Background Jobs?</h3><p>Use background processing when:</p><ul><li>The task is heavy (AI processing, file generation, reports)</li><li>You don’t need immediate response</li><li>The operation may take seconds or minutes</li><li>You want reliability &amp; retries</li><li>You need scheduled execution</li></ul><p>Examples:</p><ul><li>Essay AI evaluation</li><li>Email sending</li><li>Payment reconciliation</li><li>Cache rebuilding</li><li>Report generation</li></ul><p>Return <strong>202 Accepted</strong>, store status in database, and let the client poll for updates.</p><p>That’s scalable architecture.</p><h3>Key Architectural Principle</h3><p>Removing await only makes the request faster.<br> It does NOT make the system more scalable.</p><p>True scalability requires:</p><ul><li>Separation of concerns</li><li>Reliable execution pipeline</li><li>Retry strategies</li><li>State tracking</li><li>Durability</li></ul><p>Async without infrastructure is just unmanaged concurrency.</p><h3>Modular Monoliths Can Be Scalable</h3><p>You do not need microservices to achieve asynchronous processing.</p><p>A well-designed modular monolith can:</p><ul><li>Use background jobs</li><li>Implement internal queues</li><li>Maintain bounded contexts</li><li>Apply clean architecture principles</li><li>Return 202 instead of blocking requests</li></ul><p>The difference is architectural discipline.</p><h3>Final Thought</h3><p>If your goal is:</p><blockquote><em>“Let the API respond immediately and process work safely in the background.”</em></blockquote><p>Then don’t remove await.</p><p>Introduce proper background processing.</p><p>Scalability is not about making code asynchronous.<br> It’s about making work reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=552406606ada" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Outbox Pattern Is Not About Delay — It’s About Transactions]]></title>
            <link>https://medium.com/@rajkin.hossain/the-outbox-pattern-is-not-about-delay-its-about-transactions-e324692372a4?source=rss-501f94b6baca------2</link>
            <guid isPermaLink="false">https://medium.com/p/e324692372a4</guid>
            <dc:creator><![CDATA[Rajkin Hossain]]></dc:creator>
            <pubDate>Sat, 24 Jan 2026 20:57:51 GMT</pubDate>
            <atom:updated>2026-01-24T21:01:06.951Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Outbox Pattern Is Not About Delay — It’s About Transactions</h3><p>If you’ve ever implemented an event-driven system and thought:</p><blockquote><em>“I’m publishing events right after </em><em>SaveChanges(). Do I </em>really<em> need the Outbox pattern?”</em></blockquote><p>You’re not alone.</p><p>This question comes up all the time — especially when teams adopt DDD, CQRS, or message brokers like RabbitMQ or Kafka. And the short answer is:</p><blockquote><strong><em>Yes, you still need the Outbox pattern — even if you publish immediately.</em></strong></blockquote><p>Let’s break down <em>why</em>, and clear up a few very common misconceptions.</p><h3>The real problem Outbox solves (not what most people think)</h3><p>Many developers think the Outbox pattern exists because:</p><ul><li>Messages need to be published later</li><li>Background jobs are involved</li><li>Events are delayed by design</li></ul><p>That’s <strong>wrong</strong>.</p><p>The Outbox pattern has <em>one</em> purpose:</p><blockquote><strong><em>Guarantee atomicity between database state and message intent.</em></strong></blockquote><p>In simpler terms:</p><blockquote>Either both the data change and the event exist — or neither does.</blockquote><p>Timing has nothing to do with it.</p><h3>The naive approach: “Publish after SaveChanges”</h3><p>Most systems start like this:</p><pre>await dbContext.SaveChangesAsync();<br>await messageBus.Publish(orderCreatedEvent);</pre><p>At first glance, this looks reasonable.</p><p>But let’s walk through the failure scenarios.</p><h3>Failure scenario #1: DB succeeds, publish fails</h3><ol><li>Order is saved successfully</li><li>Application crashes / network fails / broker is down</li><li>Event is never published</li></ol><p>Result:</p><ul><li>Database says the order exists ✅</li><li>Other services never find out ❌</li></ul><p>You now have <strong>inconsistent system state</strong>.</p><h3>Failure scenario #2: Event published, DB rolled back</h3><p>This happens when:</p><ul><li>publishing is done before commit</li><li>or transaction rolls back after publish</li></ul><p>Result:</p><ul><li>Consumers react to an event for data that <strong>never existed</strong></li><li>This is worse than missing an event — it’s <strong>data corruption</strong></li></ul><h3>“But EF Core already wraps SaveChanges in a transaction?”</h3><p>Yes — but <strong>only the database operations</strong>.</p><p>EF Core cannot make your database and your message broker transactional together.<br>That would require a <strong>distributed transaction</strong>, which we intentionally avoid.</p><p>So this:</p><pre>SaveChanges();<br>PublishEvent();</pre><p>is <strong>two separate systems</strong>, two separate failure domains.</p><h3>Enter the Outbox Pattern</h3><p>The Outbox pattern changes <em>what</em> you make transactional.</p><p>Instead of:</p><blockquote><em>“Save data, then send event”</em></blockquote><p>You do this:</p><blockquote><em>“Save data + save intent to send event — atomically”</em></blockquote><h3>The only correct Outbox flow</h3><p>Inside <strong>one database transaction</strong>:</p><ol><li>Change domain state</li><li>Insert an Outbox record</li><li>Commit</li></ol><p>Then, <strong>outside</strong> the transaction:</p><ol><li>Read unprocessed outbox messages</li><li>Publish them</li><li>Mark them as processed</li></ol><p>Visually:</p><pre>[ TRANSACTION ]<br>- Update Order<br>- Insert OutboxMessage<br>[ COMMIT ]</pre><pre>[ ASYNC PROCESS ]<br>- Publish message<br>- Mark processed</pre><p>If publishing fails, the intent is still safely stored.</p><h3>Why the transaction is mandatory</h3><p>This is the non-negotiable rule:</p><blockquote><strong><em>If the outbox insert is not in the same transaction, you do not have the Outbox pattern.</em></strong></blockquote><p>Anything else is just “best effort messaging”.</p><h3>❌ Broken implementation</h3><pre>SaveChanges();<br>InsertOutboxMessage(); // separate operation</pre><p>Crash here → state exists, event lost.</p><h3>✅ Correct implementation</h3><pre>dbContext.Orders.Add(order);<br>dbContext.OutboxMessages.Add(outboxMessage);<br>await dbContext.SaveChangesAsync(); // one transaction</pre><p>This guarantees <strong>atomic durability</strong>.</p><p>Internally EF Core does something like: For general SQL database like PostGres/MySql, transaction is READ_COMITTED. Please also have a look on ACID Principles.</p><pre>BEGIN TRANSACTION<br>INSERT Orders<br>INSERT OutboxMessages<br>COMMIT</pre><p>You don’t see it, but it’s there.</p><h3>“Is Outbox only needed if messages are delayed?”</h3><p>No.</p><p>This is the biggest myth.</p><p>You can:</p><ul><li>publish immediately</li><li>publish after 20 seconds</li><li>publish via background worker</li><li>publish via cron job</li></ul><p>Outbox is <strong>not about delay</strong>.<br>It’s about <strong>never losing the intent to publish</strong>.</p><h3>Domain Events ≠ Outbox Events</h3><p>Another common confusion.</p><p>ConceptPurposeStoredDomain EventExpress business behavior❌ usually in memoryIntegration / Outbox EventCommunicate with other systems✅ persisted</p><p>Typical DDD flow:</p><pre>Aggregate raises DomainEvent<br>↓<br>Application layer handles it<br>↓<br>Integration event written to Outbox<br>↓<br>Dispatcher publishes it</pre><p>This separation keeps your domain clean and your system reliable.</p><h3>When can you skip the Outbox pattern?</h3><p>Very rarely.</p><p>You <em>might</em> skip it if <strong>all</strong> are true:</p><ul><li>Single monolith</li><li>No external consumers</li><li>Event loss is acceptable</li><li>No message broker</li></ul><p>The moment you introduce:</p><ul><li>RabbitMQ</li><li>Kafka</li><li>Another bounded context</li><li>Another service</li></ul><p>👉 <strong>Outbox becomes mandatory</strong></p><h3>MongoDB / NoSQL note</h3><p>Outbox still applies.</p><p>You must either:</p><ul><li>Use multi-document transactions</li><li>Or ensure both documents are written atomically</li></ul><p>If you can’t guarantee atomicity, you don’t have Outbox — just hope.</p><h3>Final takeaway</h3><p>If you remember only one sentence, remember this:</p><blockquote><strong><em>Outbox is not about sending messages — it’s about never losing the intent to send them.</em></strong></blockquote><p>And that intent <strong>must be transactionally durable</strong>.</p><p>Everything else — background workers, delays, retries — is just implementation detail.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e324692372a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Guide to AWS SSO: Ditch Your Access Keys Forever ]]></title>
            <link>https://medium.com/@rajkin.hossain/the-complete-guide-to-aws-sso-ditch-your-access-keys-forever-73d3e5f460a2?source=rss-501f94b6baca------2</link>
            <guid isPermaLink="false">https://medium.com/p/73d3e5f460a2</guid>
            <dc:creator><![CDATA[Rajkin Hossain]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 13:50:46 GMT</pubDate>
            <atom:updated>2025-12-24T13:50:46.902Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From authentication basics to advanced port forwarding — everything you need to securely access AWS resources</em></p><h3>Introduction</h3><p>Picture this: You’re a developer managing multiple AWS accounts. Your .aws/credentials file looks like a phone book, you’re constantly rotating access keys, and you live in fear of accidentally pushing secrets to GitHub.</p><p>Sound familiar?</p><p>There’s a better way. AWS IAM Identity Center (AWS SSO) eliminates static credentials entirely. In this comprehensive guide, I’ll walk you through:</p><ul><li>Why AWS SSO is superior to access keys</li><li>How SSO authentication actually works</li><li>Setting up multiple profiles with different permissions</li><li>Real-world port forwarding to private databases</li><li>Common pitfalls and how to avoid them</li></ul><p>Let’s dive in.</p><h3>Part 1: The Credential Problem</h3><p>Traditionally, accessing AWS required creating an IAM user and generating access keys:</p><pre># ~/.aws/credentials<br>[default]<br>aws_access_key_id = &lt;access_key&gt;<br>aws_secret_access_key = &lt;secret_access_key&gt;</pre><p>This approach has serious problems:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuiJNtUlj2CQo94IJMapIw.png" /></figure><h3>Do You Need Credentials File for SSO?</h3><p>No! This is the key insight:</p><p>&gt; With AWS SSO, you don’t need ANY static credentials in ~/.aws/credentials.</p><p>AWS SSO uses your corporate identity (via Okta, Azure AD, etc.) to generate temporary credentials on-demand. These credentials:</p><ul><li>Are cached locally in ~/.aws/sso/cache/</li><li>Auto-expire (typically 1–12 hours)</li><li>Are automatically refreshed when you re-authenticate</li></ul><p>Your .aws/credentials file can be completely empty — or not exist at all!</p><h3>Part 2: How AWS SSO Actually Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ucesclG4SzFqCpy-x0ltMw.png" /></figure><h3>Part 3: Setting Up AWS SSO</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8iSNr2xrDjwJP7JY2MrViA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dF-dFAmvDVKwY3vs-1MC3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WL0k_ZAz0JMpw1v7w1plkw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*zoT43rk0HFKwosoLZ8BoNg.png" /></figure><h3>Part 4: Port Forwarding — What, Why, and How</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6K9sH9tuOQIf0tAn7DmVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-p3PVkXL9viNMqlLFBgDqg.png" /></figure><h3>Part 5: Complete Port Forwarding Walkthrough</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEqsMjbElJAetEAVdG-EDw.png" /></figure><p>From the oputput, I’ll use &lt;i-unique_id&gt; (the SSM bastion).</p><pre>aws ssm start-session \<br>  --target &lt;i-unique_id&gt; \<br>  --document-name AWS-StartPortForwardingSessionToRemoteHost \<br>  --parameters &#39;{<br>    &quot;host&quot;: [&quot;my-database.cluster-abc123.ap-southeast-1.rds.amazonaws.com&quot;],<br>    &quot;portNumber&quot;: [&quot;5432&quot;],<br>    &quot;localPortNumber&quot;: [&quot;5431&quot;]<br>  }&#39; \<br>  --profile ssm-full \<br>  --region ap-southeast-1</pre><pre>Starting session with SessionId: user@company.com-abc123xyz<br>Port 5431 opened for sessionId user@company.com-abc123xyz<br>Waiting for connections...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NsaDRrKB_mlJfDVlHBe1MQ.png" /></figure><h3>Part 6: Common Issues &amp; Solutions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rG0hcADF4IfNBrJsyyWgqQ.png" /></figure><h3>Part 7: Quick Reference Commands</h3><pre># ========================================<br># LOGIN (do this once per session)<br># ========================================<br>aws sso login --sso-session company-sso<br><br># ========================================<br># ALL COMMANDS BELOW NEED --profile<br># (to specify which IAM role to use)<br># ========================================<br><br># Check who you are<br>aws sts get-caller-identity --profile dev-admin<br><br># List S3 buckets<br>aws s3 ls --profile s3-readonly<br><br># Describe EC2 instances<br>aws ec2 describe-instances --profile ec2-admin<br><br># Port forward to RDS<br>aws ssm start-session \<br>  --target i-INSTANCE_ID \<br>  --document-name AWS-StartPortForwardingSessionToRemoteHost \<br>  --parameters &#39;{&quot;host&quot;:[&quot;DB_ENDPOINT&quot;],&quot;portNumber&quot;:[&quot;5432&quot;],&quot;localPortNumber&quot;:[&quot;5431&quot;]}&#39; \<br>  --profile ssm-profile \<br>  --region REGION<br><br># Interactive shell on EC2 (no SSH needed!)<br>aws ssm start-session --target i-INSTANCE_ID --profile ssm-profile</pre><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxxISbwiYCBpg0_R54Axwg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73d3e5f460a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Building AI Agents in .NET]]></title>
            <link>https://medium.com/@rajkin.hossain/why-building-ai-agents-in-net-95177ab35f39?source=rss-501f94b6baca------2</link>
            <guid isPermaLink="false">https://medium.com/p/95177ab35f39</guid>
            <dc:creator><![CDATA[Rajkin Hossain]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 19:42:37 GMT</pubDate>
            <atom:updated>2025-12-02T19:58:03.560Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Building AI Agents in .NET Feels “Too Easy” — And What Most Developers Don’t Realize About How Gen-AI Evolved</h3><p>Over the past year, a surprising pattern has emerged in developer communities:<br>people who start building AI agents in <strong>.NET</strong> often feel like it’s <em>super smooth</em>… even “too simple” compared to Python examples floating around the internet.</p><p>You’ll see a Python agent that uses:</p><ul><li>loops</li><li>regex</li><li>manual message handling</li><li>“Action / Observation” patterns</li></ul><p>But then you write a .NET version using <strong>Microsoft.Extensions.AI</strong>, and suddenly everything collapses into:</p><pre>IChatClient client = new ChatClientBuilder(…)<br>    .UseFunctionInvocation()<br>    .Build();<br><br>var answer = await client.GetResponseAsync(messages, options);</pre><p>No loops.<br>No regex.<br>No ReAct scaffolding.<br>It just… works.</p><p>And that leads many people (including me initially) to wonder:</p><p>“Wait… why does Python need all this extra code, but .NET magically handles everything?”</p><p>The answer reveals a huge, under-discussed point:</p><p>🚀 Gen-AI Agents Evolved Extremely Fast</p><p>And most .NET developers only joined <strong>after</strong> the hard problems were already solved.</p><p>Let me explain.</p><h3>🏗️ Stage 1 (2022) — The “Manual Agent” Era: ReAct Loops</h3><p>Back when GPT-3.5 came out, the only way to give an LLM access to tools was:</p><ol><li>Tell the model:<br> “If you want to do something, say Action: followed by the operation.”</li><li>Parse that output manually using regex.</li><li>Run your Python function manually.</li><li>Feed the result back to the model as an “Observation”.</li><li>Repeat until the model says “Answer: …”.</li></ol><p>This was the <strong>true OG agent pattern</strong>, called <em>ReAct</em> (Reason + Act).</p><p>Typical code looked like:</p><pre>while True:<br>    response = llm(messages)<br>    if &quot;Action:&quot; in response:<br>        # parse text<br>        # run function<br>        # feed back observation<br>    else:<br>        break</pre><p>Lots of boilerplate.<br>Lots of brittle text parsing.<br>Lots of developer pain.</p><h3>🧬 Stage 2 (2023–2024) — Structured Tool Calling</h3><p>OpenAI introduced <strong>function calling</strong>, later renamed <strong>tools</strong>.<br> This changed everything.</p><p>Instead of relying on the LLM to say &quot;Action: xyz&quot;, the model now outputs:</p><pre>{<br>  &quot;tool_calls&quot;: [<br>    {<br>      &quot;function&quot;: {<br>         &quot;name&quot;: &quot;calculate&quot;,<br>         &quot;arguments&quot;: &quot;{ \&quot;expression\&quot;: \&quot;37 + 20\&quot; }&quot;<br>      }<br>    }<br>  ]<br>}</pre><p>This was the moment when <strong>manual ReAct loops became unnecessary</strong>.</p><p>BUT…</p><p>Python still required you to write at least a small loop:</p><ul><li>detect tool calls</li><li>run Python code</li><li>send tool result</li><li>ask the model again</li></ul><p>Frameworks like LangChain or Semantic Kernel added abstraction,<br>but raw Python clients still needed orchestration code.</p><h3>🌐 Stage 3 (2024–2025) — Enter .NET: Microsoft.Extensions.AI</h3><p>This is where .NET developers entered the scene.</p><p><strong>Microsoft Extensions for AI</strong> did something genius:</p><h3>✔ Automatically orchestrate tool calling</h3><h3>✔ Hide the internal loop</h3><h3>✔ Hide the message injection</h3><h3>✔ Hide the function mapping</h3><h3>✔ Return one final, natural-language answer</h3><p>This line is where the magic happens:</p><pre>.UseFunctionInvocation()</pre><pre>| Step                            | Who does it in .NET?    |<br>| ------------------------------- | ----------------------- |<br>| Detect tool calls               | Microsoft.Extensions.AI |<br>| Parse arguments                 | Microsoft.Extensions.AI |<br>| Run your C# function            | Microsoft.Extensions.AI |<br>| Add tool result to conversation | Microsoft.Extensions.AI |<br>| Send model a new message        | Microsoft.Extensions.AI |<br>| Repeat until final answer       | Microsoft.Extensions.AI |</pre><p>The developer only writes:</p><ul><li>Your tools (as C# methods)</li><li>One final GetResponseAsync call</li></ul><h3>🧩 The Big Insight Most .NET Developers Don’t Realize</h3><blockquote><strong><em>.NET devs are starting at Stage 3 of Gen-AI evolution…<br> without realizing the previous two stages even existed.</em></strong></blockquote><p>So when they see complicated Python ReAct loops online, they wonder:</p><blockquote><em>“Why did Python need loops, regex, and Observations?<br> Why is .NET so clean?”</em></blockquote><p>Because .NET came <em>after</em> the evolution,<br> and Microsoft built the modern orchestration layer into the framework.</p><p>Python devs lived through:</p><ul><li>Pre-function calling hacks</li><li>Manual loops</li><li>Prompt protocols</li><li>LangChain building agents by hand</li></ul><p>.NET devs joined at the point where:</p><ul><li>Function calling is standard</li><li>Orchestration is built-in</li><li>Agents are first-class</li><li>Conversation state management is solved</li></ul><p>That’s why building agents in .NET feels “effortlessly easy”.</p><h3>🧠 A Real Example: Python vs .NET</h3><h3>Old Python agent (manual ReAct loop)</h3><ul><li>Detect &quot;Action:&quot; with regex</li><li>Run function manually</li><li>Add &quot;Observation:&quot;</li><li>Loop again</li></ul><p>Modern .NET agent (one line handles it)</p><pre>.UseFunctionInvocation()</pre><p>The difference is not skill.<br>It’s <strong>timing</strong> and <strong>framework evolution</strong>.</p><h3>🎯 What This Means for .NET Developers</h3><h3>1️⃣ You’re using AI at a more mature stage</h3><p>The ecosystem already solved the hard problems.</p><h3>2️⃣ You get agent behavior “for free”</h3><p>No loops, no regex, no scaffolding.</p><h3>3️⃣ You are unconsciously using advanced concepts</h3><ul><li>Automated tool orchestration</li><li>Spec-compliant tool messages</li><li>Structured function calling</li><li>Multi-turn agent loops</li></ul><p>You may not see it, but the engine is doing A LOT.</p><h3>4️⃣ You can build production-grade agents with far less code</h3><p>This is a major advantage in enterprise settings.</p><h3>5️⃣ You are benefitting from the mistakes Python devs already made</h3><p>The .NET ecosystem is built on top of lessons learned over 2+ years of experimentation.</p><h3>🏁 Final Thoughts</h3><p>If you’re a .NET developer and building your first agent feels “too straightforward”…<br> that’s not a mistake.</p><p>It’s a sign that the <strong>Gen-AI ecosystem evolved</strong>,<br> and .NET arrived at the perfect moment.</p><p>You are building on the shoulders of:</p><ul><li>ReAct agents</li><li>LangChain</li><li>Semantic Kernel</li><li>GPT-3.5 tool-hacking</li><li>GPT-4 function calling</li><li>OpenAI tool schemas</li><li>Agent orchestration frameworks</li><li>And finally, Microsoft.Extensions.AI</li></ul><p>Which wraps all that complexity into one elegant, modern API.</p><p>This is why <strong>.NET agents feel simple</strong>…<br>because the Gen-AI world walked a long road so you don’t have to.</p><p>Python still leads in advanced runtime features like resumable LangGraph state, checkpointing, and DAG-based workflows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95177ab35f39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Highlighting LLM Feedback with Contextual Fragments Instead of Indexes]]></title>
            <link>https://medium.com/@rajkin.hossain/highlighting-llm-feedback-with-contextual-fragments-instead-of-indexes-af71f2644108?source=rss-501f94b6baca------2</link>
            <guid isPermaLink="false">https://medium.com/p/af71f2644108</guid>
            <category><![CDATA[edtech]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[writing]]></category>
            <dc:creator><![CDATA[Rajkin Hossain]]></dc:creator>
            <pubDate>Sat, 29 Nov 2025 09:54:07 GMT</pubDate>
            <atom:updated>2025-11-29T09:54:56.551Z</atom:updated>
            <content:encoded><![CDATA[<p>When building an LLM feedback checker for highlighting (for writing in my case), one common requirement is very simple:</p><p>Show the learner exactly where each grammar, spelling, or structure issue appears in their original essay.</p><p>A natural idea is to ask the model for character positions:</p><ul><li>startIndex</li><li>endIndex</li></ul><p>and then highlight that substring in the UI.</p><p>Another idea is to ask the model to return a fully formatted HTML version of the essay with &lt;span&gt; tags, colors, and tooltips already applied.</p><p>Both ideas look good in theory, but they become difficult in practice when you rely on large language models.</p><h3>Why raw indices can be unreliable</h3><p>Large language models don’t work with characters the way our code does. They operate on tokens and text patterns. Even with detailed instructions about:</p><ul><li>0-based indexing</li><li>inclusive/exclusive ranges</li><li>counting spaces, punctuation, and newlines</li></ul><p>it’s common to see occasional off-by-one errors or mismatched spans, especially in longer essays with:</p><ul><li>repeated words, extra spaces, multiple paragraphs</li></ul><p>The result is simple but frustrating: the model correctly identifies the error, but the wrong word or phrase gets highlighted. For learners, that is confusing and unhelpful.</p><p>So the question becomes: how can we make the contract between the model and the application simpler and more reliable?</p><h3>Why full HTML output is also NOT ideal</h3><p>It might seem easier to ask the model:</p><blockquote><em>“Please return the whole essay as HTML, with color-coded spans and tooltips already included.”</em></blockquote><p>That approach has some drawbacks:</p><ul><li><strong>Token usage and cost</strong><br> Returning the entire essay plus HTML tags and repeated attributes can produce very large responses. For frequent usage, this can significantly increase token consumption and cost.</li><li><strong>Layout control</strong><br>It becomes harder to control the exact styling from the frontend. Any small change in the design (colors, classes, tooltips) requires adjusting the prompt and hoping the model follows it consistently.</li></ul><p>Because of these issues, it can be simpler and cheaper to keep the model’s output more compact and let the frontend render HTML.</p><h3>Moving from indices to text fragments</h3><p>A more stable pattern is to stop asking the model for character offsets or full HTML and instead ask for <strong>text fragments</strong> taken directly from the essay.</p><p>Instead of:</p><ul><li>“Tell me the exact positions of the error”</li><li>or “Return the entire essay as HTML”</li></ul><p>we ask the model to return small pieces of information like:</p><pre>{<br>  &quot;fragment&quot;: &quot;communties&quot;,<br>  &quot;category&quot;: &quot;spelling&quot;,<br>  &quot;tooltip&quot;: &quot;SPELLING: correct spelling is &#39;communities&#39;.&quot;<br>}</pre><p>On the application side, the logic is:</p><ol><li>Keep the original essay text exactly as the user wrote it.</li><li>Search for fragment inside that text.</li><li>Use the match to compute indices and highlight in the UI.</li><li>Let the frontend (for example, Razor, Angular, etc.) decide how to render HTML, colors, and mouse-hover behavior.</li></ol><p>String search is something programming languages handle very reliably. This makes the “where to highlight” decision deterministic and easy to debug, while keeping the model’s response compact and token-efficient.</p><p>This already works well for spelling errors and unique words. However, grammar often involves very small function words, which leads to another challenge.</p><h3>The challenge with small words</h3><p>Many grammar issues are built around small words like:</p><ul><li>“a”, “the”, “in”, “on”, “to”</li><li>“it”, “they”, “is”, “are”, “was”, “were”</li></ul><p>These words appear many times in a typical essay.</p><p>Imagine a sentence like:</p><blockquote><em>He gave a advice to his friend.</em></blockquote><p>The model might correctly identify an article error and try to return:</p><pre>{<br>  &quot;fragment&quot;: &quot;a&quot;,<br>  &quot;category&quot;: &quot;grammar&quot;,<br>  &quot;tooltip&quot;: &quot;GRAMMAR – article error: use a different article here.&quot;<br>}</pre><p>But there might be several other “a”s in the same writing that are perfectly fine. The application cannot know which “a” is wrong just from that single character.</p><p>If we highlight the first “a” we find, we teach the wrong thing. If we highlight all of them, the feedback becomes noisy and unclear.</p><p>So simply switching from indices to bare fragments isn’t enough. We need to be a bit more specific in what we ask the model to return.</p><h3>Contextual, “unique-ish” fragments</h3><p>The improvement comes from changing the prompt so that the model returns <strong>contextual fragments</strong>, not just single small tokens.</p><p>The idea is:</p><ul><li>For <strong>content words</strong> (such as a misspelled noun or verb), the fragment can often be just that word, for example:</li><li>&quot;communties&quot;</li><li>For <strong>function words</strong> (articles, prepositions, auxiliaries, pronouns, etc.), the fragment should include nearby content words, so that it becomes more specific and easier to locate.</li></ul><p>In the system prompt, this can be expressed with rules like:</p><ul><li>Do not use a single function word such as “a”, “the”, or “in” as the only fragment if it appears multiple times in the essay.</li><li>Instead, include a small phrase that contains:</li><li>the function word plus its dependent word(s).</li></ul><p>Some examples:</p><ul><li>&quot;a advice&quot; – article + noun, showing an article error</li><li>&quot;in the other hand&quot; – a preposition/phrase error</li><li>&quot;a older people&quot; – article + adjective + noun</li><li>&quot;it help people&quot; – subject–verb agreement issue</li></ul><p>For punctuation and spacing errors, we can do something similar and include the nearby words and punctuation:</p><ul><li>&quot;However we&quot; – missing comma after “However”</li><li>&quot;word ,another&quot; – space before a comma</li><li>&quot;word.another&quot; – missing space after a full stop</li></ul><p>These fragments are still compact, but they are much more “unique-ish” inside the essay. This makes it easier for the application to find the correct place to highlight.</p><h3>A compact JSON structure instead of HTML</h3><p>Putting everything together, the model can return a structure like:</p><pre>{<br>  &quot;essay&quot;: {<br>    &quot;highlights&quot;: [<br>      {<br>        &quot;fragment&quot;: &quot;a advice&quot;,<br>        &quot;category&quot;: &quot;grammar&quot;,<br>        &quot;tooltip&quot;: &quot;GRAMMAR – article error: use &#39;an&#39; or remove the article for this noun.&quot;<br>      },<br>      {<br>        &quot;fragment&quot;: &quot;communties&quot;,<br>        &quot;category&quot;: &quot;spelling&quot;,<br>        &quot;tooltip&quot;: &quot;SPELLING: correct spelling is &#39;communities&#39;.&quot;<br>      }<br>    ]<br>  }<br>}</pre><p>Where:</p><ul><li>Each fragment is an exact substring of original essay.</li><li>category and tooltip describe the type of issue and guidance.</li></ul><p>On the backend and frontend side:</p><ol><li>The backend searches for each fragment inside original essay.</li><li>It finds the correct location and computes indices.</li><li>The UI layer uses those indices to render HTML, apply colors, and show tooltips on hover.</li></ol><p>This way:</p><ul><li>The <strong>model’s output stays small and token-efficient</strong> (plain text + metadata).</li><li>The <strong>frontend has full control</strong> over design and behavior.</li><li>The system remains easier to maintain and adjust.</li></ul><h3>Why this pattern helps</h3><p>This “contextual fragment” approach has a few practical advantages:</p><ol><li><strong>More reliable highlights</strong><br> The model doesn’t have to count characters or embed HTML. It returns small pieces of text that already exist in the essay. The application handles the exact positions and rendering.</li><li><strong>Lower token usage</strong><br> Instead of returning the full essay multiple times inside HTML, the model returns a compact JSON structure. This helps control response size and cost.</li><li><strong>Clearer feedback for learners</strong><br> Seeing a phrase like “a advice” or “in the other hand” highlighted, together with a short explanation, makes it easier for learners to understand what is wrong and how to fix it.</li><li><strong>Works across different models</strong><br> The pattern does not rely on any model-specific index behavior. As long as the model follows the prompt and returns exact fragments, the rest of the system remains stable.</li><li><strong>Simple backend and frontend logic</strong><br> The backend uses familiar string operations to locate fragments and compute indices. The frontend decides how to style and display highlights. Both sides are easy to test and adjust.</li></ol><h3>Summary</h3><p>When building a writer checker or any text feedback system that needs to highlight parts of the original text, it can be helpful to:</p><ul><li>Treat the user’s original text as the single source of truth.</li><li>Ask the model to return <strong>contextual fragments</strong> taken directly from that text, instead of character indices or full HTML.</li><li>Be explicit in the prompt:</li><li>Content words can often be highlighted on their own.</li><li>Function words (articles, prepositions, auxiliaries) should be returned as short, contextual phrases.</li><li>Use a compact JSON structure for feedback, and let your frontend render HTML and colors.</li><li>Let your application handle the exact positions and visual highlighting.</li></ul><p>This small change in the interface between the model and the application can make feedback more accurate, more understandable, more cost-efficient, and easier to maintain over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af71f2644108" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering ConfigureAwait(false) in ASP.NET: A Performance Boost for Asynchronous Programming]]></title>
            <link>https://medium.com/@rajkin.hossain/mastering-configureawait-false-in-asp-net-a-performance-boost-for-asynchronous-programming-22de531da7f6?source=rss-501f94b6baca------2</link>
            <guid isPermaLink="false">https://medium.com/p/22de531da7f6</guid>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[threading]]></category>
            <category><![CDATA[configureawait]]></category>
            <category><![CDATA[dot-net-framework]]></category>
            <dc:creator><![CDATA[Rajkin Hossain]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 15:20:13 GMT</pubDate>
            <atom:updated>2024-09-16T15:20:13.524Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern C# development, asynchronous programming is essential for creating efficient, scalable, and responsive applications. If you’re working with ASP.NET or ASP.NET Core, you’ve likely come across ConfigureAwait(false), but you may wonder why it’s so important. Used correctly, it can lead to better performance and resource utilization, particularly when making database calls or interacting with external systems.</p><p>In this article, we’ll break down how and when to use ConfigureAwait(false) in web applications, and we’ll also explore the cases where you should <strong>not</strong> use it, especially in desktop applications like WPF or WinForms.</p><h4>The Power of ConfigureAwait(false) in ASP.NET Applications</h4><p>When developing web applications, asynchronous methods are often used to handle time-consuming operations, such as calling a database or a remote API. One typical scenario is when you’re performing an async database operation, as shown below:</p><pre>var result = await databaseContext.SomeAsyncOperation()<br>                                  .ConfigureAwait(false);</pre><p>So, <strong>why</strong> do we use ConfigureAwait(false) here?</p><p>In a web application like ASP.NET or ASP.NET Core, there’s <strong>no need to return to the same thread</strong> that started the operation. When the await keyword is used, by default, the rest of the code (called a continuation) resumes on the same thread that initiated the asynchronous operation. This behavior is necessary in certain contexts, like updating a UI in desktop applications, but it&#39;s not needed in a web application where thread affinity isn&#39;t crucial.</p><p>By using ConfigureAwait(false), you&#39;re instructing the runtime that the continuation after the await can occur on <strong>any thread</strong>. This avoids the overhead of capturing and restoring the <strong>synchronization context</strong>, which in a web server environment can lead to <strong>improved performance and better resource utilization</strong>. Essentially, you free up server threads more efficiently, allowing your application to handle more concurrent requests.</p><p>This practice is especially important in high-performance, highly concurrent environments, like ASP.NET, where freeing up threads for other work is a key factor in scaling the application.</p><h4>When You Should Avoid ConfigureAwait(false)</h4><p>While ConfigureAwait(false) is a valuable tool in web applications, it’s not always the right choice—especially in desktop applications like <strong>WPF</strong> or <strong>WinForms</strong>. These applications have a single-threaded UI model, meaning that any updates to the UI must happen on the <strong>main thread</strong> (also called the UI thread).</p><p>If you use ConfigureAwait(false) in these environments, there&#39;s a risk that the code following the asynchronous operation will run on a background thread, which cannot update the UI. This can lead to threading errors or crashes.</p><pre>var data = await LoadDataAsync(); // Do not use ConfigureAwait(false)<br>UpdateUI(data); // Must run on the UI thread</pre><p>Here, if ConfigureAwait(false) were used, the UpdateUI(data) call might not run on the UI thread, causing exceptions or other unexpected behavior.</p><h4>Key Takeaways</h4><ol><li><strong>In ASP.NET or ASP.NET Core applications</strong>, use ConfigureAwait(false) in your async methods to prevent unnecessary thread blocking, improve performance, and increase scalability.</li><li><strong>In desktop applications (like WPF or WinForms)</strong>, avoid using ConfigureAwait(false) when the continuation involves updating the UI. You need the code to resume on the UI thread to safely interact with UI components.</li></ol><p>In summary, ConfigureAwait(false) is an essential part of writing efficient asynchronous code in C#. Understanding when and where to apply it can significantly improve the performance of your applications, particularly in server-side environments like ASP.NET. However, when building desktop applications, be cautious about using it, as it can lead to errors in UI management.</p><p>By mastering ConfigureAwait(false), you can make your applications more responsive, scalable, and ready to handle the demands of modern development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22de531da7f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Partial Updates in .NET Core Using JsonPatchDocument]]></title>
            <link>https://medium.com/@rajkin.hossain/improving-partial-updates-in-net-core-using-jsonpatchdocument-bf124de5b353?source=rss-501f94b6baca------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf124de5b353</guid>
            <dc:creator><![CDATA[Rajkin Hossain]]></dc:creator>
            <pubDate>Sat, 15 Jun 2024 16:13:22 GMT</pubDate>
            <atom:updated>2024-06-15T16:41:33.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>Improving Partial Updates in .NET Core Using JsonPatchDocument</h3><p>In modern web development, it’s common to use the HTTP PUT method for updating resources. However, this approach typically results in updating the entire resource, even when only a few properties need to be changed. This can negatively impact performance and lead to suboptimal design patterns. For more efficient and maintainable partial updates, .NET Core offers a robust solution using JsonPatchDocument.</p><h3>The Problem with Full Updates</h3><p>When using the PUT method for updates, you send the entire resource to the server, even if only a small part of it has changed. This approach has several drawbacks:</p><ol><li><strong>Increased Bandwidth Usage</strong>: Sending the whole object over the network can consume more bandwidth, especially for large objects.</li><li><strong>Higher Processing Overhead</strong>: Updating the entire object in the database can lead to unnecessary processing and resource consumption.</li><li><strong>Complex Code Maintenance</strong>: To perform partial updates, you might need to implement custom reflection-based logic or maintain a large number of SQL update queries for different operations (add, delete, replace, copy, etc.), increasing the risk of errors and code complexity.</li></ol><h3>The Solution: JsonPatchDocument</h3><p>.NET Core, with the help of Newtonsoft.Json, provides an elegant solution called JsonPatchDocument that simplifies partial updates. This utility allows you to specify only the properties you want to change, reducing the overhead and complexity associated with full updates.</p><h3>How JsonPatchDocument Works</h3><p>JsonPatchDocument enables you to define a series of operations (add, remove, replace, move, copy, test) that can be applied to an object. These operations are executed using the ApplyTo method, which updates the target object based on the specified changes.</p><h3>Example Controller with JsonPatchDocument</h3><p>Here’s a sample implementation of an ASP.NET Core controller that uses JsonPatchDocument for partial updates:</p><pre>using Microsoft.AspNetCore.JsonPatch;<br>using Microsoft.AspNetCore.Mvc;<br>using System.Collections.Generic;<br>using System.Linq;<br><br>namespace TestWebApi.Controllers<br>{<br>    [ApiController]<br>    [Route(&quot;api/[controller]&quot;)]<br>    public class ProductsController : ControllerBase<br>    {<br>        private static List&lt;Product&gt; _products = new List&lt;Product&gt;<br>        {<br>            new Product { Id = 1, Name = &quot;Product1&quot;, Price = 10.99m, Description = &quot;Sample product 1&quot; },<br>            new Product { Id = 2, Name = &quot;Product2&quot;, Price = 20.99m, Description = &quot;Sample product 2&quot; },<br>        };<br><br>        [HttpGet(&quot;{id}&quot;)]<br>        public IActionResult Get(int id)<br>        {<br>            var product = _products.FirstOrDefault(p =&gt; p.Id == id);<br><br>            if (product == null)<br>            {<br>                return NotFound();<br>            }<br><br>            return Ok(product);<br>        }<br><br>        [HttpPatch(&quot;{id}&quot;)]<br>        public IActionResult Update(int id, [FromBody] JsonPatchDocument&lt;Product&gt; patchDoc)<br>        {<br>            var product = _products.FirstOrDefault(p =&gt; p.Id == id);<br><br>            if (product == null)<br>            {<br>                return NotFound();<br>            }<br><br>            patchDoc.ApplyTo(product);<br><br>            if (!ModelState.IsValid)<br>            {<br>                return BadRequest(ModelState);<br>            }<br><br>            return Ok(product);<br>        }<br>    }<br>}</pre><pre>builder.Services.AddControllers().AddNewtonsoftJson();</pre><h3>Example JSON Patch Request</h3><p>To update the name and price properties of a product, you can send a JSON Patch request like this:</p><pre>[<br>  { &quot;op&quot;: &quot;add&quot;, &quot;path&quot;: &quot;/newField&quot;, &quot;value&quot;: &quot;New Value&quot; },<br>  { &quot;op&quot;: &quot;remove&quot;, &quot;path&quot;: &quot;/oldField&quot; },<br>  { &quot;op&quot;: &quot;replace&quot;, &quot;path&quot;: &quot;/existingField&quot;, &quot;value&quot;: &quot;Updated Value&quot; },<br>  { &quot;op&quot;: &quot;move&quot;, &quot;from&quot;: &quot;/tempField&quot;, &quot;path&quot;: &quot;/finalField&quot; },<br>  { &quot;op&quot;: &quot;copy&quot;, &quot;from&quot;: &quot;/sourceField&quot;, &quot;path&quot;: &quot;/destinationField&quot; },<br>  { &quot;op&quot;: &quot;test&quot;, &quot;path&quot;: &quot;/testField&quot;, &quot;value&quot;: &quot;Expected Value&quot; }<br>]</pre><h3>Benefits of Using JsonPatchDocument</h3><ol><li><strong>Efficiency</strong>: Only the changed properties are sent over the network, reducing bandwidth usage.</li><li><strong>Performance</strong>: Partial updates minimize the processing required on the server, improving performance. So internally the are doing UPDATE commands.</li><li><strong>Maintainability</strong>: The code is simpler and easier to maintain compared to custom reflection-based solutions or maintaining multiple SQL queries.</li></ol><h3>Conclusion</h3><p>Using JsonPatchDocument in .NET Core is a powerful way to handle partial updates efficiently. It reduces the overhead of updating entire objects and simplifies the maintenance of update logic. By leveraging this built-in feature, you can improve the performance and scalability of your applications.</p><p>In your projects, consider using JsonPatchDocument for scenarios where partial updates are frequent. It will not only enhance performance but also make your codebase cleaner and more maintainable.</p><p><a href="https://datatracker.ietf.org/doc/html/rfc6902">Reference: RFC 6902 — JavaScript Object Notation (JSON) Patch (ietf.org)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf124de5b353" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maintaining Idempotent Operations with Idempotency Key]]></title>
            <link>https://medium.com/@rajkin.hossain/maintaining-idempotent-operations-with-idempotency-keys-e3791b24e15a?source=rss-501f94b6baca------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3791b24e15a</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[idempotency]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Rajkin Hossain]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 16:19:12 GMT</pubDate>
            <atom:updated>2023-09-17T17:29:23.439Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction:</p><p>Storing an idempotency key is a critical component when working with APIs, especially in scenarios where you need to ensure that a request is processed only once, even if it’s retried. Idempotency keys help prevent duplicate actions and ensure data consistency.</p><p>Step 1: Setting Up the Database</p><p>In this step, we’ll create the necessary SQL tables (User and Account) to store user and account information. A well-structured database is crucial for any application that requires idempotent operations.</p><pre>CREATE TABLE Users (<br>    UserId INT PRIMARY KEY,<br>    Username VARCHAR(50) NOT NULL,<br>    Email VARCHAR(100) UNIQUE NOT NULL,<br>    -- Other user-related columns<br>);<br><br>CREATE TABLE Accounts (<br>    AccountId INT PRIMARY KEY,<br>    UserId INT REFERENCES Users(UserId),<br>    AccountNumber VARCHAR(20) NOT NULL UNIQUE,<br>    Balance DECIMAL(10, 2) DEFAULT 0.0,<br>    -- Other account-related columns<br>);</pre><p>Step 2: Implementing Idempotency Keys with Redis</p><p>Redis will be our choice for storing idempotency keys. We’ll walk through the installation and configuration of Redis and set up a Redis client in our .NET project to manage idempotency keys.</p><p>Step 3: Sample .NET Code</p><p>We’ll create a sample .NET API project (using ASP.NET Core) to demonstrate how to implement idempotent operations. This includes an endpoint for performing idempotent operations, integrating Redis for idempotency key management, and code samples for generating and validating idempotency keys.</p><pre>using StackExchange.Redis;<br><br>[AttributeUsage(AttributeTargets.Method)]<br>public class IdempotentAttribute : ActionFilterAttribute<br>{<br>    private ICacheManager RedisCacheManager { get; }<br><br>    public IdempotentAttribute(IConnectionMultiplexer connection)<br>    {<br>        RedisCacheManager = connection.GetCacheManager();<br>    }<br><br>    public override void OnActionExecuting(ActionExecutingContext context)<br>    {<br>        var idempotencyKey = context.HttpContext.Request.Headers[&quot;Idempotency-Key&quot;];<br><br>        if (string.IsNullOrEmpty(idempotencyKey))<br>        {<br>            context.Result = new BadRequestResult();<br>            return;<br>        }<br><br>        if (IsIdempotent(idempotencyKey))<br>        {<br>            context.Result = new ConflictResult();<br>        }<br>    }<br><br>    private bool IsIdempotent(string idempotencyKey)<br>    {<br>        return RedisCacheManager.KeyExists(idempotencyKey);<br>    }<br>}</pre><pre>using Microsoft.AspNetCore.Mvc;<br>using StackExchange.Redis;<br><br>[Route(&quot;api/accounts&quot;)]<br>[ApiController]<br>public class AccountController : ControllerBase<br>{<br>    private ICacheManager RedisCacheManager { get; }<br><br>    public AccountController(IConnectionMultiplexer connection)<br>    {<br>        RedisCacheManager = connection.GetCacheManager();<br>    }<br><br>    [HttpPost(&quot;deposit&quot;)]<br>    [Idempotent] // Apply the IdempotentAttribute to the action<br>    public IActionResult Deposit([FromBody] DepositRequest request)<br>    {<br>        // Process the deposit operation and update the account balance<br>        // ...<br><br>        // Mark the request as idempotent<br>        SetIdempotent(request.IdempotencyKey);<br><br>        return Ok(&quot;Deposit successful.&quot;);<br>    }<br><br>    private void SetIdempotent(string idempotencyKey)<br>    {<br>        // Store the idempotency key in Redis with an expiration time<br>        RedisCacheManager.StringSet(idempotencyKey, &quot;Processed&quot;, TimeSpan.FromHours(12));<br>    }<br>}</pre><p>Conclusion:</p><p>Having explored the preceding example, it becomes evident that mastering the idempotent technique is paramount when constructing a fault-tolerant API, particularly in contexts involving sensitive operations like payments.</p><p>This exposition should have provided you with a foundational grasp of idempotency and its application in ensuring the reliability of the POST or PATCH method. Stay tuned for further updates on related topics.</p><p>Thank you for reading!</p><p>Feedback and thoughts are always welcome in the comments section.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3791b24e15a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>