<?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 Sanjay Bhavikatti on Medium]]></title>
        <description><![CDATA[Stories by Sanjay Bhavikatti on Medium]]></description>
        <link>https://medium.com/@sanjay.bhavikatti.learn?source=rss-3cf6f1042ebd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*F7MpLd52t_iA_47-</url>
            <title>Stories by Sanjay Bhavikatti on Medium</title>
            <link>https://medium.com/@sanjay.bhavikatti.learn?source=rss-3cf6f1042ebd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:59:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sanjay.bhavikatti.learn/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[REST, GraphQL, and gRPC in One System: What We Learned Building It That Way]]></title>
            <link>https://medium.com/@sanjay.bhavikatti.learn/rest-graphql-and-grpc-in-one-system-what-we-learned-building-it-that-way-56a1113f424d?source=rss-3cf6f1042ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/56a1113f424d</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sanjay Bhavikatti]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 05:54:28 GMT</pubDate>
            <atom:updated>2026-09-15T05:54:28.210Z</atom:updated>
            <content:encoded><![CDATA[<p>Most articles comparing REST, GraphQL, and gRPC pick a winner. In practice, the more useful question usually isn’t “which one,” it’s “which one, where.” We built a complete Employee Management System deliberately using all three, REST for one layer, GraphQL for another, gRPC for a third, specifically to see where each one actually earns its place rather than taking anyone’s word for it. Here’s what that looked like, and what we’d tell someone about to make the same choice.</p><h2>Why Build It With All Three At Once</h2><p>The usual way people learn the trade-offs between these three is by reading comparison articles written by people who picked one for a project and rationalized it afterward. We wanted the opposite: put all three in the same system, talking to the same underlying data, and see where the seams actually show up under real use, not in theory.</p><p>The system: an Employee Management application with a handful of natural boundaries, employee CRUD operations, a reporting/search interface for HR staff, and internal service-to-service calls for things like payroll calculations pulling employee data. Three different consumption patterns, which turned out to map cleanly onto three different protocols.</p><h2>Where REST Did the Job</h2><p>REST handled the outward-facing CRUD operations: creating an employee record, updating a department, fetching a single employee by ID. This is REST’s home turf, and nothing about building this system changed that.</p><pre>POST   /api/employees<br>GET    /api/employees/{id}<br>PUT    /api/employees/{id}<br>DELETE /api/employees/{id}</pre><p>What stood out building it this way: REST’s simplicity is genuinely valuable when the consumer is unpredictable. Any client- a browser, a mobile app, a third-party integrator, a quick curl command while debugging- can talk to a REST endpoint without any special tooling or generated client code. That universality is easy to undervalue until you’re the one debugging a production issue at 11 pm and grateful you can just curl an endpoint directly.</p><p>The cost showed up on the reporting side, when HR staff wanted a view combining employee details, department info, and current project assignments in one screen. That meant either multiple REST round-trips from the frontend, or a bespoke aggregation endpoint that existed for exactly one UI screen and nothing else. Neither felt right, which is exactly the gap GraphQL was built to close.</p><h2>Where GraphQL Earned Its Place</h2><p>The HR reporting and search interface is where GraphQL made the clearest case for itself. A single query lets the frontend ask for exactly the shape of data a given screen needs:</p><pre>query EmployeeReport($departmentId: ID!) {<br>  department(id: $departmentId) {<br>    name<br>    employees {<br>      name<br>      title<br>      currentProjects {<br>        name<br>        status<br>      }<br>    }<br>  }<br>}</pre><p>One request, no over-fetching, no under-fetching, and no bespoke backend endpoint built for a single screen. As the reporting UI evolved and needed different fields on different screens, the frontend team adjusted queries without needing backend changes for every tweak, which was the single biggest velocity win of the whole exercise.</p><p>The trade-off: GraphQL’s flexibility pushes complexity into the resolver layer and makes performance easier to get wrong. A naive resolver structure produces the classic N+1 query problem: fetching one department is cheap, but fetching a department’s employees and each employee’s projects, naively resolved, can silently fan out into dozens of database calls per request. We only caught this because we specifically measured query performance under realistic report loads; it’s the kind of problem that doesn’t show up until real data volume hits it. Dataloader-style batching fixed it, but that’s additional infrastructure REST never asked us to think about.</p><h2>Where gRPC Was the Only Reasonable Choice</h2><p>The payroll service needed employee data from the core employee service, frequently, internally, and with clear expectations on the schema; both services were owned by the same team. This is gRPC’s exact use case: high-frequency, internal, service-to-service communication where both ends agree on a strict contract.</p><pre>service EmployeeService {<br>  rpc GetEmployee(EmployeeRequest) returns (EmployeeResponse);<br>  rpc StreamPayrollUpdates(PayrollFilter) returns (stream PayrollUpdate);<br>}</pre><p>Two things stood out here. First, the Protocol Buffers contract meant both services were working from a schema that couldn’t silently drift; a change to the .proto file is a change both sides have to acknowledge and regenerate against, which caught several would-be integration bugs at build time instead of at runtime. Second, the binary serialization and HTTP/2 transport made a measurable difference under the payroll service&#39;s batch-processing load, noticeably lower latency and payload size compared to the equivalent REST calls we benchmarked for comparison.</p><p>The cost: gRPC is a much harder sell for anything outward-facing. Browsers can’t natively speak gRPC without a proxy layer (grpc-web plus a translating gateway), and debugging binary payloads without proper tooling is far less pleasant than reading a JSON response in a browser dev tools tab. It’s a protocol you choose for internal, controlled communication, not general-purpose access.</p><h2>What This Actually Taught Us</h2><p>The comparison articles aren’t wrong about the individual trade-offs; they’re just missing the fact that these trade-offs are about where a protocol sits in your architecture, not which protocol is “best.” A few concrete takeaways from building all three side by side:</p><ul><li><strong>The decision axis isn’t protocol quality; it’s consumer predictability.</strong> REST for unpredictable, general-purpose clients. GraphQL for a frontend team that needs flexible, evolving queries against a stable backend. gRPC for two backend teams who both control their side of a high-frequency internal call.</li><li><strong>GraphQL moves complexity; it doesn’t remove it.</strong> The N+1 problem is REST’s over-fetching problem reborn on the backend instead of the network. It has to be solved deliberately, not assumed away.</li><li><strong>gRPC’s contract-first model catches bugs earlier, at the cost of tooling friction.</strong> Worth it for internal services owned by teams who can coordinate schema changes. A poor fit for anything with external or loosely coupled consumers.</li><li><strong>Running three protocols in one system is more operational overhead than picking one.</strong> Three sets of monitoring, three different debugging mental models, three onboarding curves for new engineers. This is a legitimate cost, and it’s worth being honest about before assuming a polyglot API layer is automatically the sophisticated choice.</li></ul><h2>The Takeaway</h2><p>There’s no universal winner between REST, GraphQL, and gRPC, and building a system that actually used all three made that a lot more concrete than any comparison chart could. The real skill isn’t picking a favorite protocol; it’s recognizing which consumption pattern you’re actually solving for at each boundary in your system, and being willing to accept the operational cost of more than one protocol when the boundaries genuinely call for it, rather than defaulting to one everywhere out of habit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56a1113f424d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Circuit Breaker Pattern: Stopping One Failure From Becoming Ten]]></title>
            <link>https://medium.com/@sanjay.bhavikatti.learn/the-circuit-breaker-pattern-stopping-one-failure-from-becoming-ten-712802c78495?source=rss-3cf6f1042ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/712802c78495</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Sanjay Bhavikatti]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 07:18:45 GMT</pubDate>
            <atom:updated>2026-09-11T07:18:45.662Z</atom:updated>
            <content:encoded><![CDATA[<p>If you read the last post about why microservices keep falling over, you already know the shape of the problem: one slow or failing service starts a chain reaction, threads pile up waiting on a dependency that isn’t responding, and within minutes a single downstream hiccup has taken the whole system down with it. This post is about the pattern built specifically to stop that chain reaction before it starts: the circuit breaker.</p><h2>The Failure Mode, Concretely</h2><p>Picture an order service calling a payment service. Under normal conditions, that call takes 50ms. Now the payment service starts struggling; maybe a database connection pool is exhausted, maybe a downstream bank API is timing out. Calls that used to take 50ms now take 10 seconds, or hang indefinitely.</p><p>The order service, having no idea anything is wrong, keeps calling it anyway. Every incoming order request spawns a thread that blocks waiting on the payment service. Within seconds, the order service’s own thread pool is exhausted, not because the order service itself is broken, but because it’s patiently queuing up behind a service that stopped answering. Now the order service looks down too, even though its own code hasn’t thrown a single exception.</p><p>This is the cascading failure. A local problem in one service becomes a system-wide outage, purely because nothing stopped the calling service from optimistically retrying a dependency that has already shown it’s unhealthy.</p><h2>What a Circuit Breaker Actually Does</h2><p>The pattern borrows its name and its logic directly from electrical circuit breakers: when current flow is dangerous, trip the circuit and stop it, rather than letting the wiring melt.</p><p>A software circuit breaker sits between your service and a downstream dependency, tracking the outcome of every call, and moves through three states:</p><p><strong>Closed</strong> — the normal state. Calls pass through to the dependency as usual. The breaker is quietly counting failures.</p><p><strong>Open</strong> — once failures cross a threshold (say, 50% of the last 20 calls failed), the breaker trips open. Every subsequent call fails immediately, without even attempting to reach the dependency. This is the critical part: instead of a caller waiting 10 seconds for a timeout, it fails in microseconds. No thread gets tied up. No queue backs up.</p><p><strong>Half-Open</strong> — after a cooldown period, the breaker allows a small number of test calls through. If they succeed, the breaker closes again and normal traffic resumes. If they fail, it snaps back to open and waits again.</p><p>That’s the whole mechanism. It’s not fixing the payment service. It’s protecting the order service from being dragged down by a dependency it can’t control, and it’s protecting the payment service from being hammered with traffic while it’s already struggling to recover.</p><h2>Circuit Breakers Alone Aren’t Enough</h2><p>A circuit breaker answers “should I even try this call,” but a resilient system usually needs it paired with a few adjacent patterns:</p><ul><li><strong>Timeouts.</strong> A circuit breaker can’t count a call as failed if that call is allowed to hang forever. Every downstream call needs an aggressive, explicit timeout, or the breaker never gets the signal it needs to trip.</li><li><strong>Retries with backoff.</strong> Once a breaker is half-open, retries should be spaced out, not hammered immediately, or you’ll trip it straight back to open.</li><li><strong>Bulkheads.</strong> Isolating thread pools or connection pools per dependency means a struggling payment service can’t starve resources meant for, say, the inventory service, even before the breaker trips.</li><li><strong>Fallbacks.</strong> When the breaker is open, what does the caller actually do? Return a cached value, queue the request for later, or degrade gracefully, rather than just surfacing a raw error to the end user.</li></ul><p>Circuit breakers are the most visible piece of this toolkit, but they work best as one layer in a deliberate resilience strategy, not a standalone fix.</p><h2>A Minimal Implementation Shape</h2><p>Most production systems reach for a library rather than hand-rolling this (Polly in .NET, resilience4j in Java, opossum in Node.js), but seeing the shape of it demystifies what those libraries are doing:</p><pre>class CircuitBreaker {<br>  constructor(fn, { failureThreshold = 5, cooldownMs = 30000 } = {}) {<br>    this.fn = fn;<br>    this.failureThreshold = failureThreshold;<br>    this.cooldownMs = cooldownMs;<br>    this.state = &quot;CLOSED&quot;;<br>    this.failureCount = 0;<br>    this.nextAttempt = 0;<br>  }<br> <br>  async call(...args) {<br>    if (this.state === &quot;OPEN&quot;) {<br>      if (Date.now() &lt; this.nextAttempt) {<br>        throw new Error(&quot;Circuit open: call rejected immediately&quot;);<br>      }<br>      this.state = &quot;HALF_OPEN&quot;;<br>    }<br> <br>    try {<br>      const result = await this.fn(...args);<br>      this.onSuccess();<br>      return result;<br>    } catch (err) {<br>      this.onFailure();<br>      throw err;<br>    }<br>  }<br> <br>  onSuccess() {<br>    this.failureCount = 0;<br>    this.state = &quot;CLOSED&quot;;<br>  }<br> <br>  onFailure() {<br>    this.failureCount++;<br>    if (this.failureCount &gt;= this.failureThreshold) {<br>      this.state = &quot;OPEN&quot;;<br>      this.nextAttempt = Date.now() + this.cooldownMs;<br>    }<br>  }<br>}</pre><p>Wrapped around any downstream call, this alone changes the failure profile of the whole system: instead of every caller timing out slowly and independently, the first handful fail fast, trip the breaker, and every call after that fails in microseconds until the dependency has had a chance to recover.</p><h2>Tuning It Without Guessing</h2><p>The two knobs that matter most, failure threshold and cooldown period, aren’t values to pick arbitrarily:</p><ul><li><strong>Threshold too low</strong> trips the breaker on ordinary transient blips, and you end up serving fallback responses for a dependency that was actually fine.</li><li><strong>Threshold too high</strong> delays protection until real damage (thread exhaustion, cascading timeouts) has already started.</li><li><strong>Cooldown too short</strong> means the breaker keeps flapping open and closed, hammering a still-recovering dependency with test traffic.</li><li><strong>Cooldown too long</strong> means you’re serving degraded responses well after the dependency has recovered.</li></ul><p>These values should come from actual latency and failure-rate baselines for each dependency, not a single default copy-pasted across every service in the system. A payment gateway and an internal cache have very different acceptable failure profiles.</p><h2>The Takeaway</h2><p>A circuit breaker doesn’t fix a broken dependency. What it does is stop a broken dependency from taking the rest of your system down with it, by failing fast instead of failing slow, and giving struggling services room to recover instead of being buried under retries from every caller that hasn’t noticed anything is wrong yet. If the last post left you wondering how to actually stop the cascade, this is the pattern that does it, and it’s usually the first resilience pattern worth adding once you’ve felt what a cascading failure looks like in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=712802c78495" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blazor Server vs Blazor WebAssembly vs Razor Pages: Picking the Right Rendering Model in .NET]]></title>
            <link>https://medium.com/@sanjay.bhavikatti.learn/blazor-server-vs-blazor-webassembly-vs-razor-pages-picking-the-right-rendering-model-in-net-08b4c0eeb94a?source=rss-3cf6f1042ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/08b4c0eeb94a</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[dot-net-developers]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[blazor]]></category>
            <dc:creator><![CDATA[Sanjay Bhavikatti]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 07:18:34 GMT</pubDate>
            <atom:updated>2026-09-11T07:18:34.049Z</atom:updated>
            <content:encoded><![CDATA[<p>Ask a .NET developer which rendering model to use for a new project, and you’ll often get three different answers depending on which team they last worked on. That’s not confusion for confusion’s sake; it reflects a real fact about the .NET ecosystem: there are genuinely three different rendering philosophies living under one framework, and each one optimizes for a different kind of application. This post breaks down what each one actually does, where it fits, and where teams tend to pick wrong.</p><h2>The Core Question Underneath All Three</h2><p>Every rendering model answer boils down to one question: where does the UI logic run, and how does it talk to the server? Once you frame it that way, the three options stop looking like arbitrary alternatives and start looking like points on a spectrum, from fully server-driven to fully client-driven.</p><h2>Razor Pages / MVC: Classic Server-Side Rendering</h2><p>This is the model most .NET developers cut their teeth on, and it’s still the right default for a large share of applications.</p><p>The mechanics are simple: every request hits the server, the server renders full HTML (via Razor syntax mixing C# and markup), and sends that complete HTML document back to the browser. Any interaction- submitting a form, navigating to a new page, clicking a link- triggers a fresh HTTP request and a fresh full-page render.</p><pre>public class EmployeeModel : PageModel<br>{<br>    public Employee Employee { get; set; }<br> <br>    public async Task OnGetAsync(int id)<br>    {<br>        Employee = await _employeeService.GetByIdAsync(id);<br>    }<br>}</pre><pre>@page &quot;{id:int}&quot;<br>@model EmployeeModel<br> <br>&lt;h1&gt;@Model.Employee.Name&lt;/h1&gt;<br>&lt;p&gt;@Model.Employee.Title&lt;/p&gt;</pre><p><strong>What this model gets right:</strong></p><ul><li><strong>Simplest mental model in the entire .NET rendering landscape.</strong> A request comes in, HTML goes out. No client-side state to reason about, no hydration step, no “why did this component not re-render” debugging session.</li><li><strong>Best SEO of the three, by default.</strong> Search engine crawlers receive fully-formed HTML on the very first response, no JavaScript execution required to see real content. This matters enormously for public-facing marketing pages, blogs, product listings, anything that needs to rank.</li><li><strong>Minimal client-side footprint.</strong> No large JS bundle to download, no WebAssembly runtime to boot. The page is usable the moment HTML arrives.</li><li><strong>Predictable, well-understood performance characteristics.</strong> Server load scales with requests, not with persistent connections, which makes capacity planning straightforward.</li></ul><p><strong>Where it costs you:</strong></p><ul><li><strong>Full page reloads on every interaction.</strong> Even a small UI update, say, marking one row as read, means a full round-trip and a full re-render unless you layer in something like partial views with AJAX or htmx-style progressive enhancement.</li><li><strong>No native rich interactivity.</strong> Anything resembling a modern SPA experience- drag-and-drop, live filtering without a page reload, real-time updates- requires bolting on JavaScript, which starts eroding the “it’s just C# and HTML” simplicity that makes this model attractive in the first place.</li><li><strong>State lives nowhere between requests</strong> unless you deliberately persist it (session, database, query string, hidden fields), which is by design, but it means anything stateful needs explicit handling.</li></ul><p><strong>Where it fits:</strong> content-heavy, SEO-sensitive, request-response shaped applications, public marketing sites, admin panels where full-page navigation is genuinely fine, most CRUD-heavy internal tools, and any team that wants to stay as close as possible to plain server-rendered HTML without taking on SPA complexity.</p><h2>Blazor Server: Interactivity Without Shipping a SPA</h2><p>Blazor Server keeps the actual UI logic running on the server, same as Razor Pages, but changes how updates reach the browser. Instead of full-page HTML responses per request, the server maintains a persistent connection (via SignalR) to each connected browser. User interactions- a button click, a keystroke- get sent up to the server over that connection; the server runs the relevant C# code and computes a UI diff, and only that diff gets pushed back down to update the DOM.</p><pre>@page &quot;/employees/{id:int}&quot;<br> <br>&lt;h1&gt;@employee.Name&lt;/h1&gt;<br>&lt;button @onclick=&quot;ToggleActive&quot;&gt;<br>    @(employee.IsActive ? &quot;Deactivate&quot; : &quot;Activate&quot;)<br>&lt;/button&gt;<br> <br>@code {<br>    private Employee employee;<br> <br>    protected override async Task OnInitializedAsync()<br>    {<br>        employee = await EmployeeService.GetByIdAsync(Id);<br>    }<br> <br>    private void ToggleActive()<br>    {<br>        employee.IsActive = !employee.IsActive;<br>    }<br>}</pre><p>No page reload happens when that button is clicked. The click event travels to the server, the server updates state and computes what changed, and only the changed DOM nodes update in the browser, all while the component’s C# code runs entirely server-side.</p><p><strong>What this model gets right:</strong></p><ul><li><strong>Rich interactivity while writing only C#.</strong> No separate JavaScript SPA framework to learn or maintain, no client-server API layer to build just to support the UI.</li><li><strong>Small initial download.</strong> The browser doesn’t need to download and boot a WebAssembly runtime, so first load is fast even on constrained connections.</li><li><strong>Server has direct access to everything.</strong> Database connections, internal services, secrets, all reachable directly from component code, no separate API layer required purely for UI purposes.</li></ul><p><strong>Where it costs you:</strong></p><ul><li><strong>Latency-sensitive by nature.</strong> Every interaction is a round-trip over the SignalR connection. On a good connection this feels instant; on a poor one, every click has a visible lag that a true client-side app wouldn’t have.</li><li><strong>Doesn’t survive connection loss gracefully.</strong> If the SignalR connection drops, the component’s state on the server can be lost, and the user typically sees a “reconnecting” overlay or has to reload the page entirely.</li><li><strong>Server-side memory and connection cost scale with concurrent users.</strong> Each connected browser holds an active circuit on the server. This is a fundamentally different scaling profile than stateless request-response rendering, and it needs to be planned for explicitly.</li></ul><p><strong>Where it fits:</strong> internal line-of-business applications on reliable internal networks, admin dashboards, data entry tools, anything where the team wants rich interactivity without standing up a separate frontend stack, and where users are on stable connections rather than flaky mobile networks.</p><h2>Blazor WebAssembly: The Actual SPA Model</h2><p>This is the model that finally moves execution into the browser. The C# application, compiled to WebAssembly, downloads to the browser and runs there directly, no persistent server connection required for the UI to function. It behaves like a genuine single-page application, similar in shape to a React or Angular SPA, except the component logic is C# instead of JavaScript.</p><pre>@page &quot;/employees/{id:int}&quot;<br>@inject HttpClient Http<br> <br>&lt;h1&gt;@employee?.Name&lt;/h1&gt;<br>&lt;button @onclick=&quot;ToggleActive&quot;&gt;<br>    @(employee.IsActive ? &quot;Deactivate&quot; : &quot;Activate&quot;)<br>&lt;/button&gt;<br> <br>@code {<br>    private Employee employee;<br> <br>    protected override async Task OnInitializedAsync()<br>    {<br>        employee = await Http.GetFromJsonAsync&lt;Employee&gt;($&quot;api/employees/{Id}&quot;);<br>    }<br> <br>    private async Task ToggleActive()<br>    {<br>        employee.IsActive = !employee.IsActive;<br>        await Http.PutAsJsonAsync($&quot;api/employees/{Id}&quot;, employee);<br>    }<br>}</pre><p>Notice the shift: there’s no direct database or service access here. The component calls a REST (or GraphQL, or gRPC-via-grpc-web) API, exactly the way a JavaScript SPA would, because the code genuinely runs client-side now, with no privileged server access of its own.</p><p><strong>What this model gets right:</strong></p><ul><li><strong>No server round-trip needed for UI logic.</strong> Once loaded, interactions are handled entirely in-browser, no network latency for anything that doesn’t need fresh server data.</li><li><strong>Works offline (with a service worker) and degrades gracefully on flaky connections</strong>, since the app itself is already running client-side.</li><li><strong>Scales server load differently.</strong> The server just serves a static app bundle plus API calls, rather than holding a persistent connection per user, which changes the scaling story substantially compared to Blazor Server.</li></ul><p><strong>Where it costs you:</strong></p><ul><li><strong>Large initial download.</strong> The WebAssembly runtime plus your compiled app adds real weight to first load; though this has improved significantly release over release, it’s still heavier than a server-rendered first paint.</li><li><strong>No direct server access from component code.</strong> You need a proper API layer (REST, GraphQL, gRPC-web) behind it, which is more architecture to build and maintain than either of the other two models.</li><li><strong>SEO requires extra work.</strong> Since the initial HTML shell is mostly empty until the WebAssembly app boots and renders, public-facing, crawler-sensitive pages need prerendering or server-side rendering assistance layered on top.</li></ul><p><strong>Where it fits:</strong> genuinely interactive, app-like experiences, internal tools used by mobile or remote workers on unreliable connections, and any scenario where you want the client-side SPA model but would rather write it in C# than JavaScript.</p><h2>A Decision Framework, Not a Ranking</h2><p>None of these three is “the best” in the abstract. The right question is which shape your application actually needs:</p><ul><li><strong>Public, content-heavy, SEO-critical</strong> → Razor Pages / MVC. Don’t reach for either Blazor model here unless you’re prepared to layer on prerendering just to get back what SSR gives you for free.</li><li><strong>Internal tool, rich interactivity, reliable network, team wants to stay in C# without building a separate API layer</strong> → Blazor Server.</li><li><strong>App-like experience, users on unreliable connections, or you already need (or want) a proper API layer behind the UI</strong> → Blazor WebAssembly.</li></ul><p>.NET 8 introduced render modes that let you mix these per-component within a single app, which softens this from a one-time architectural decision into something closer to a per-page or per-component choice. That flexibility is genuinely useful, but it doesn’t remove the need to understand what each mode actually costs; it just moves the decision to a finer grain.</p><h2>The Takeaway</h2><p>The three-way split in .NET’s rendering landscape isn’t accidental complexity; it reflects three real, different sets of trade-offs: where code executes, how state is held, and what a network hiccup does to the user’s experience. Razor Pages gives you the simplest mental model and the best SEO at the cost of full-page reloads. Blazor Server gives you rich C#-only interactivity at the cost of a persistent connection and latency sensitivity. Blazor WebAssembly gives you a genuine offline-capable SPA at the cost of a heavier first load and needing a real API layer behind it. Picking correctly starts with being honest about which of those costs your application and your users’ network conditions can actually absorb.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08b4c0eeb94a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing OIDC Authorization Code Flow with PKCE in ASP.NET (OWIN)]]></title>
            <link>https://medium.com/@sanjay.bhavikatti.learn/implementing-oidc-authorization-code-flow-with-pkce-in-asp-net-owin-9ab6dbb147a2?source=rss-3cf6f1042ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ab6dbb147a2</guid>
            <category><![CDATA[aspnet-mvc]]></category>
            <category><![CDATA[dot-net-framework]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[enterprise-software]]></category>
            <dc:creator><![CDATA[Sanjay Bhavikatti]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 06:48:14 GMT</pubDate>
            <atom:updated>2026-09-10T06:48:14.760Z</atom:updated>
            <content:encoded><![CDATA[<p>If you read the companion piece on SAML and OIDC, you already know the shape of the handshake: redirect to the identity provider, authenticate, come back with a code, exchange that code for tokens. This article goes one level deeper, implemented against classic ASP.NET (.NET Framework, MVC 5) using OWIN/Katana middleware rather than ASP.NET Core. A lot of enterprise codebases are still running on .NET Framework, and the OIDC story there looks noticeably different; PKCE in particular isn’t handled automatically the way it is in the newer stack, so we’re going to wire it up by hand.</p><h2>Why PKCE, Even for a Confidential Client</h2><p>PKCE (Proof Key for Code Exchange, pronounced “pixy”) was originally designed to protect public clients, mobile apps, and single-page apps that can’t safely store a client secret. But the guidance has shifted. Even confidential clients like a traditional ASP.NET MVC app, which does hold a secret server-side, benefit from PKCE because it protects against authorization code interception attacks regardless of client type. Most identity providers (Okta, Azure AD, Auth0, Keycloak included) now recommend PKCE universally.</p><p>The mechanism is simple:</p><ol><li>Before redirecting the user, the app generates a random code_verifier.</li><li>It hashes that verifier with SHA-256 to produce a code_challenge.</li><li>The code_challenge is sent in the initial authorization request.</li><li>When exchanging the authorization code for tokens later, the app sends the original code_verifier.</li><li>The identity provider hashes the verifier it receives and checks it matches the challenge from step 3.</li></ol><p>Unlike ASP.NET Core’s OIDC handler, the Microsoft.Owin.Security.OpenIdConnect middleware used in .NET Framework projects doesn&#39;t generate or attach PKCE parameters out of the box. We&#39;ll do it ourselves using the middleware&#39;s notification hooks.</p><h2>Project Setup</h2><pre>Install-Package Microsoft.Owin.Security.OpenIdConnect<br>Install-Package Microsoft.Owin.Security.Cookies<br>Install-Package Microsoft.Owin.Host.SystemWeb</pre><p>This assumes a standard ASP.NET MVC 5 project with OWIN startup already wired in via Startup.cs and [assembly: OwinStartup(typeof(OidcPkceDemo.Startup))].</p><h2>Configuring the OWIN Middleware</h2><p>Startup.cs:</p><pre>using System;<br>using System.IdentityModel.Tokens.Jwt;<br>using System.Security.Cryptography;<br>using System.Threading.Tasks;<br>using Microsoft.Owin;<br>using Microsoft.Owin.Security;<br>using Microsoft.Owin.Security.Cookies;<br>using Microsoft.Owin.Security.OpenIdConnect;<br>using Owin;<br> <br>[assembly: OwinStartup(typeof(OidcPkceDemo.Startup))]<br> <br>namespace OidcPkceDemo<br>{<br>    public class Startup<br>    {<br>        public void Configuration(IAppBuilder app)<br>        {<br>            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);<br> <br>            app.UseCookieAuthentication(new CookieAuthenticationOptions());<br> <br>            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions<br>            {<br>                Authority = &quot;https://your-idp-domain/oauth2/default&quot;,<br>                ClientId = &quot;your-client-id&quot;,<br>                ClientSecret = &quot;your-client-secret&quot;,<br>                RedirectUri = &quot;https://localhost:44300/signin-oidc&quot;,<br>                ResponseType = &quot;code&quot;,<br>                Scope = &quot;openid profile email&quot;,<br>                SignInAsAuthenticationType = CookieAuthenticationDefaults.AuthenticationType,<br> <br>                Notifications = new OpenIdConnectAuthenticationNotifications<br>                {<br>                    RedirectToIdentityProvider = OnRedirectToIdentityProvider,<br>                    AuthorizationCodeReceived = OnAuthorizationCodeReceived<br>                }<br>            });<br>        }<br> <br>        // Attach PKCE parameters before redirecting to the authorize endpoint<br>        private Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification&lt;OpenIdConnectMessage, OpenIdConnectAuthenticationOptions&gt; n)<br>        {<br>            if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)<br>            {<br>                var verifier = GenerateCodeVerifier();<br>                var challenge = GenerateCodeChallenge(verifier);<br> <br>                // Stash the verifier in a short-lived cookie so we can retrieve it<br>                // during the token exchange step later in this request lifecycle.<br>                n.OwinContext.Response.Cookies.Append(&quot;pkce_verifier&quot;, verifier, new Microsoft.Owin.CookieOptions<br>                {<br>                    HttpOnly = true,<br>                    Secure = true,<br>                    Expires = DateTime.UtcNow.AddMinutes(10)<br>                });<br> <br>                n.ProtocolMessage.SetParameter(&quot;code_challenge&quot;, challenge);<br>                n.ProtocolMessage.SetParameter(&quot;code_challenge_method&quot;, &quot;S256&quot;);<br>            }<br> <br>            return Task.CompletedTask;<br>        }<br> <br>        // Attach the verifier when exchanging the code for tokens<br>        private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification n)<br>        {<br>            var verifier = n.OwinContext.Request.Cookies[&quot;pkce_verifier&quot;];<br>            if (!string.IsNullOrEmpty(verifier))<br>            {<br>                n.TokenEndpointRequest.SetParameter(&quot;code_verifier&quot;, verifier);<br>            }<br> <br>            return Task.CompletedTask;<br>        }<br> <br>        private static string GenerateCodeVerifier()<br>        {<br>            var bytes = new byte[32];<br>            using (var rng = RandomNumberGenerator.Create())<br>            {<br>                rng.GetBytes(bytes);<br>            }<br>            return Base64UrlEncode(bytes);<br>        }<br> <br>        private static string GenerateCodeChallenge(string verifier)<br>        {<br>            using (var sha256 = SHA256.Create())<br>            {<br>                var hash = sha256.ComputeHash(System.Text.Encoding.ASCII.GetBytes(verifier));<br>                return Base64UrlEncode(hash);<br>            }<br>        }<br> <br>        private static string Base64UrlEncode(byte[] input)<br>        {<br>            return Convert.ToBase64String(input)<br>                .Replace(&quot;+&quot;, &quot;-&quot;)<br>                .Replace(&quot;/&quot;, &quot;_&quot;)<br>                .Replace(&quot;=&quot;, &quot;&quot;);<br>        }<br>    }<br>}</pre><h2>What Happens When You Hit [Authorize]</h2><p>Decorate any controller action with [Authorize]:</p><pre>using System.Web.Mvc;<br> <br>[Authorize]<br>public class DashboardController : Controller<br>{<br>    public ActionResult Index()<br>    {<br>        var name = User.Identity.Name;<br>        return View(model: name);<br>    }<br>}</pre><p>When an unauthenticated user hits this route, here’s the sequence:</p><ol><li>OnRedirectToIdentityProvider fires, generating the code_verifier, deriving the code_challenge, stashing the verifier in a short-lived HTTP-only cookie, and attaching the challenge to the outgoing request.</li><li>The OWIN middleware also generates a state parameter (CSRF protection) and a nonce (replay protection for the ID token) automatically.</li><li>The browser is redirected to the authorize endpoint:</li></ol><pre>GET /oauth2/default/v1/authorize?<br>  response_type=code<br>  &amp;client_id=your-client-id<br>  &amp;redirect_uri=https://localhost:44300/signin-oidc<br>  &amp;scope=openid profile email<br>  &amp;state=af0ifjsldkj<br>  &amp;nonce=n-0S6_WzA2Mj<br>  &amp;code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM<br>  &amp;code_challenge_method=S256</pre><ol><li>The user authenticates at the identity provider.</li><li>The provider redirects back to redirect_uri (/signin-oidc) with an authorization code and the same state value.</li><li>The middleware verifies the returned state, rejecting the response if it doesn&#39;t match. This is what stops CSRF-style injection of a forged authorization response.</li><li>OnAuthorizationCodeReceived fires, reading the pkce_verifier cookie and attaching it to the token exchange:</li></ol><pre>POST /oauth2/default/v1/token<br>Content-Type: application/x-www-form-urlencoded<br> <br>grant_type=authorization_code<br>&amp;code=P7q2Eu...<br>&amp;redirect_uri=https://localhost:44300/signin-oidc<br>&amp;client_id=your-client-id<br>&amp;client_secret=your-client-secret<br>&amp;code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk</pre><ol><li>The response contains an access_token, an id_token (a JWT), and optionally a refresh_token.</li><li>The middleware validates the ID token: signature against the provider’s JWKS, iss matches the configured authority, aud matches the client ID, exp hasn&#39;t passed, and nonce matches what was generated earlier.</li><li>Only after all of that passes does it construct the ClaimsPrincipal, sign in via the cookie middleware, and let the request continue to DashboardController.</li></ol><p>Steps 6 and 9 are the two checks worth internalizing, since they’re the ones that get skipped when developers hand-roll OIDC instead of trusting the maintained middleware. State validation stops forged callbacks. Nonce validation stops a captured ID token from being replayed in a different session.</p><h2>Manually Inspecting the ID Token</h2><p>Add this to any authenticated action to see the raw claims:</p><pre>using System.Linq;<br>using System.Web.Mvc;<br> <br>[Authorize]<br>public class DashboardController : Controller<br>{<br>    public JsonResult Claims()<br>    {<br>        var claims = ((System.Security.Claims.ClaimsIdentity)User.Identity)<br>            .Claims<br>            .Select(c =&gt; new { c.Type, c.Value });<br> <br>        return Json(claims, JsonRequestBehavior.AllowGet);<br>    }<br>}</pre><p>A decoded ID token payload typically looks like:</p><pre>{<br>  &quot;iss&quot;: &quot;https://your-idp-domain/oauth2/default&quot;,<br>  &quot;sub&quot;: &quot;00u1a2b3c4d5e6f7g8h9&quot;,<br>  &quot;aud&quot;: &quot;your-client-id&quot;,<br>  &quot;exp&quot;: 1893456000,<br>  &quot;iat&quot;: 1893452400,<br>  &quot;nonce&quot;: &quot;n-0S6_WzA2Mj&quot;,<br>  &quot;name&quot;: &quot;Jane Doe&quot;,<br>  &quot;email&quot;: &quot;jane.doe@example.com&quot;<br>}</pre><p>sub is the one claim you should treat as the durable, unique user identifier, never email, since email addresses can change or be reassigned.</p><h2>Refresh Tokens and Silent Renewal</h2><p>Access tokens are intentionally short-lived, often 5 to 60 minutes. Rather than forcing the user to log in again on every expiry, request the offline_access scope (if the provider supports it) to receive a refresh token, and handle renewal manually since the older OWIN middleware doesn&#39;t do this for you:</p><pre>using System.Collections.Generic;<br>using System.Net.Http;<br>using System.Threading.Tasks;<br> <br>public async Task&lt;string&gt; RefreshAccessTokenAsync(string refreshToken)<br>{<br>    using (var client = new HttpClient())<br>    {<br>        var content = new FormUrlEncodedContent(new Dictionary&lt;string, string&gt;<br>        {<br>            [&quot;grant_type&quot;] = &quot;refresh_token&quot;,<br>            [&quot;refresh_token&quot;] = refreshToken,<br>            [&quot;client_id&quot;] = &quot;your-client-id&quot;,<br>            [&quot;client_secret&quot;] = &quot;your-client-secret&quot;<br>        });<br> <br>        var response = await client.PostAsync(&quot;https://your-idp-domain/oauth2/default/v1/token&quot;, content);<br>        response.EnsureSuccessStatusCode();<br>        return await response.Content.ReadAsStringAsync();<br>    }<br>}</pre><p>Store refresh tokens server-side (encrypted, or in a secure token store, e.g. AuthenticationProperties persisted through the ticket, or a dedicated database table), never in client-accessible storage. A leaked refresh token is a long-lived credential, arguably more dangerous than a leaked access token precisely because it survives past the access token&#39;s short window.</p><h2>Common Pitfalls in .NET Framework Implementations</h2><ul><li><strong>Assuming PKCE is handled automatically.</strong> Unlike ASP.NET Core, the OWIN OpenIdConnectAuthenticationOptions has no UsePkce flag. Skipping the notification hooks above means you silently ship an OIDC integration without PKCE protection.</li><li><strong>Forgetting </strong><strong>RequireHttpsMetadata equivalents in production.</strong> Running the identity endpoints over plain HTTP in any non-local environment defeats the purpose of the token exchange.</li><li><strong>Not clearing or scoping </strong><strong>Scope correctly.</strong> The Scope property is a single space-delimited string here, not a collection, so a typo silently changes what claims come back.</li><li><strong>Relying on </strong><strong>email as a unique key.</strong> Use sub, paired with iss, as the actual identity key in your database.</li><li><strong>Storing the PKCE verifier insecurely.</strong> The cookie holding the code_verifier must be HttpOnly and Secure, and short-lived, since it&#39;s only needed for the few seconds between redirect and callback.</li><li><strong>Skipping token expiry handling.</strong> Without the manual refresh logic above, users get silently logged out mid-session with a confusing redirect loop back through the login flow.</li></ul><h2>Wrapping Up</h2><p>The OWIN OpenID Connect middleware gets you most of the way there: state and nonce validation, ID token signature checks, and the redirect/callback plumbing, but PKCE on .NET Framework is something you have to wire up yourself using the notification pipeline. Once it’s in place, the protocol is doing exactly what SAML and OIDC were built to do: proving identity once, at one trusted provider, and letting every downstream service simply check the proof, even on a codebase that predates ASP.NET Core.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ab6dbb147a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SAML, OIDC, and the Magic Behind “Sign in with Google”]]></title>
            <link>https://medium.com/@sanjay.bhavikatti.learn/saml-oidc-and-the-magic-behind-sign-in-with-google-3fdcbf303d04?source=rss-3cf6f1042ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fdcbf303d04</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sanjay Bhavikatti]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 06:33:26 GMT</pubDate>
            <atom:updated>2026-09-10T06:33:26.969Z</atom:updated>
            <content:encoded><![CDATA[<p>Every time you click “Sign in with Google” or “Sign in with Microsoft,” a small handshake happens behind the scenes that most developers never think about until it breaks. That handshake is what lets one identity provider vouch for you across dozens of unrelated applications, without you typing a password into each one. It’s called federated identity, and two protocols run the show: SAML and OIDC.</p><p>If you’ve ever debugged a “signature validation failed” error at 2 AM, or watched an enterprise procurement team veto a clean modern login flow because it “doesn’t support SAML,” this one’s for you.</p><h2>The Problem Federation Solves</h2><p>Before SSO, every application maintained its own password database. That meant:</p><ul><li>Users juggling dozens of credentials, reusing weak passwords across services</li><li>Every app becoming a target, since a breach anywhere exposed reusable passwords</li><li>No central place to revoke access when an employee left the company</li><li>Onboarding new tools meant provisioning a new identity from scratch</li></ul><p>Federation flips the model. Instead of every application knowing who you are, one trusted party (the Identity Provider, or IdP) vouches for you, and every other application (the Service Provider, or SP) simply trusts that vouching. Your company’s Okta, Azure AD, or Google Workspace becomes the single source of truth. Everything else just checks its ID.</p><h2>SAML: The Enterprise Veteran</h2><p>SAML (Security Assertion Markup Language) has been around since the early 2000s, and it still runs a huge share of enterprise logins today. It’s XML-based, which makes it verbose, but it’s also extremely well understood by enterprise IT teams, which is exactly why it refuses to die.</p><p>Here’s the core flow:</p><ol><li>A user tries to access a Service Provider (say, your internal HR portal).</li><li>The SP redirects the user to the IdP with an authentication request.</li><li>The user logs in at the IdP (username, password, maybe MFA).</li><li>The IdP builds a SAML assertion, an XML document declaring “this user is who they say they are, and here are their attributes,” and signs it with its private key.</li><li>The browser posts this assertion back to the SP.</li><li>The SP validates the signature against the IdP’s public certificate and, if valid, creates a session for the user.</li></ol><p>The assertion itself carries claims: the user’s identity, group memberships, sometimes role information. The SP never talks to the IdP directly during this flow; everything travels through the browser, which is why SAML is often called a browser-based, front-channel protocol.</p><p>SAML’s staying power comes from enterprise procurement. Large organizations already have SAML-based IdPs deeply wired into their access control and audit processes, and ripping that out is a much bigger project than most vendors want their customers to take on. If you’re building B2B software that sells into enterprises, expect a SAML SSO requirement eventually, even if your own stack is entirely modern.</p><h2>OIDC: OAuth2 With an Identity Layer</h2><p>OpenID Connect (OIDC) is newer, JSON-based, and built directly on top of OAuth2. If SAML feels like it belongs to the era of SOAP APIs, OIDC feels like it belongs to the era of REST and mobile apps, because it does.</p><p>OAuth2 alone was never designed for authentication. It was designed for authorization: letting an app access your data on another service without handing over your password. OIDC adds a thin identity layer on top, defining a standard way to also answer “who is this user.”</p><p>The most common flow, Authorization Code Flow, looks like this:</p><ol><li>The app redirects the user to the IdP’s authorization endpoint.</li><li>The user authenticates and consents.</li><li>The IdP redirects back to the app with a short-lived authorization code.</li><li>The app exchanges that code, server-to-server, for an access token and an ID token.</li><li>The ID token is a JWT (JSON Web Token) containing claims about the user: subject, issuer, expiry, and whatever profile fields were requested.</li><li>The app verifies the JWT’s signature and claims, then treats the user as authenticated.</li></ol><p>That server-to-server exchange in step 4 is the key architectural difference from SAML. It’s a back-channel step, which closes off a class of attacks that pure browser-based flows are exposed to. Combined with PKCE (Proof Key for Code Exchange), which protects the flow even for public clients like mobile apps and single-page apps, OIDC has become the default choice for anything built after roughly 2015.</p><h2>SAML vs OIDC: When Each One Wins</h2><p>Neither protocol is objectively better. They optimize for different worlds.</p><p><strong>Reach for SAML when:</strong></p><ul><li>You’re integrating with an enterprise IdP that only exposes SAML metadata</li><li>The buyer’s security team has a SAML-shaped checklist and won’t budge</li><li>You’re working with legacy on-prem systems that predate OAuth2 entirely</li></ul><p><strong>Reach for OIDC when:</strong></p><ul><li>You’re building anything mobile, single-page, or API-first</li><li>You want lightweight, JSON-based tokens instead of XML parsing</li><li>You need fine-grained, short-lived access tokens alongside identity, not just a login event</li></ul><p>A lot of modern IdPs (Okta, Auth0, Azure AD, Keycloak) simply speak both, acting as a bridge so your app can standardize on OIDC while the enterprise on the other side keeps using SAML. That bridging pattern is often the pragmatic answer rather than picking a permanent side.</p><h2>Where Federation Actually Breaks</h2><p>If you’re implementing either protocol, these are the failure modes that show up again and again in production:</p><ul><li><strong>Clock skew.</strong> SAML assertions and JWTs both carry validity windows. If the IdP and SP servers disagree on the time by more than a minute or two, valid tokens get rejected as expired or not-yet-valid.</li><li><strong>Audience mismatch.</strong> Tokens are scoped to a specific recipient (the aud claim in OIDC, the Audience restriction in SAML). Reusing a token meant for one app in another app fails validation, by design.</li><li><strong>Signature validation shortcuts.</strong> Skipping proper signature verification, or trusting the algorithm specified in the token itself, opens the door to forged tokens. Always pin the expected signing algorithm and key.</li><li><strong>Token replay.</strong> Without short expiry and one-time-use codes, a captured assertion or authorization code can be reused. Both protocols mitigate this, but only if implementations enforce it strictly.</li><li><strong>Overprivileged claims.</strong> It’s tempting to stuff every user attribute into the token. Bigger tokens mean bigger attack surface and more stale data floating around in caches.</li></ul><h2>The Takeaway</h2><p>SAML and OIDC solve the same underlying problem, letting one trusted identity provider vouch for a user across many applications, but they come from different eras and carry different assumptions. SAML is the XML-based veteran that enterprise procurement still demands. OIDC is the JSON-based, OAuth2-native standard that modern apps default to. Understanding both isn’t about picking a favorite; it’s about knowing which one the system in front of you actually needs, and where the handshake is likely to break when it does.</p><p>If your last read was about microservices falling over under their own complexity, think of this as the identity layer wiring all those services together, and one more place where a single misconfigured trust relationship can take down access for everyone at once.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fdcbf303d04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Microservices Keep Falling Over]]></title>
            <link>https://medium.com/@sanjay.bhavikatti.learn/why-your-microservices-keep-falling-over-2163ed365308?source=rss-3cf6f1042ebd------2</link>
            <guid isPermaLink="false">https://medium.com/p/2163ed365308</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Sanjay Bhavikatti]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 06:17:29 GMT</pubDate>
            <atom:updated>2026-09-08T06:38:06.495Z</atom:updated>
            <content:encoded><![CDATA[<h4>A field guide to the four failure patterns that take down distributed systems, and the four patterns that fix them</h4><p>Every team that moves to microservices eventually gets paged for the same reason. Not a bug in the code they wrote. A bug in the <em>space between</em> the code they wrote.</p><p>You split a monolith into ten services. Each one is simple, well tested, and easy to reason about in isolation. Then, one Tuesday afternoon, a database three hops away gets slow for eight seconds, and by the time anyone notices, your entire checkout flow is down. Nobody touched checkout. Checkout just happened to be standing in the blast radius.</p><p>This is the trade nobody tells you about when you draw the clean little boxes and arrows on the architecture diagram. Microservices do not remove complexity. They move it out of your codebase and into your network. Every function call you used to trust unconditionally now might time out, retry, duplicate, or fail halfway through. And if you have not designed for that, your system will teach you the hard way.</p><p>Here are four failure patterns that show up again and again in distributed systems, told as the incidents they actually cause, along with the patterns that prevent and cure each one.</p><h3>Before the horror stories: do you even need microservices?</h3><p>It is worth saying up front, because so many of these war stories start with a team that adopted microservices before they needed to.</p><p>Good reasons to split a monolith apart:</p><ul><li>Independent teams need to deploy independently, without blocking on each other</li><li>Different parts of the system have wildly different scaling needs, like image processing versus user authentication</li><li>A single codebase has grown so large that builds, tests, and onboarding have become genuinely painful</li><li>Fault isolation actually matters to your business: one feature failing should not take the whole product down</li></ul><p>Signs you should stay monolithic, or at least modular monolithic, a little longer:</p><ul><li>A small team, generally under eight to ten engineers</li><li>Domain boundaries that are still fuzzy, meaning you do not yet know where the seams should go</li><li>Low traffic with no real scaling pressure</li><li>No operational maturity yet for distributed tracing, service discovery, or on-call rotations spanning multiple services</li></ul><p>If none of the “good reasons” apply to you, the four failure modes below are optional reading. If they do apply, keep going, because you are going to need this.</p><h3>1. Cascading failures: the domino effect</h3><p><strong>The setup:</strong> Checkout calls Inventory. Inventory calls Pricing. On a normal day, the whole chain resolves in under a hundred milliseconds and nobody thinks about it twice.</p><p><strong>What goes wrong:</strong> Pricing’s database has a bad day. Maybe a slow migration, maybe a noisy neighbor on shared infrastructure. Response times jump from fifty milliseconds to eight seconds. Inventory is calling Pricing synchronously with no timeout configured, so its threads start piling up waiting. Its thread pool exhausts. Now Inventory cannot respond to anyone, including Checkout. Checkout’s threads pile up too. Within minutes, the entire checkout flow is down, and the root cause is a slow query in a service three hops away that almost nobody on the checkout team has ever heard of.</p><p><strong>Why it cascades:</strong> No timeouts on the remote call. No isolation between the thread pool handling Pricing calls and the pool handling everything else. No circuit breaker to stop calling a service that is clearly struggling.</p><p><strong>The fix: circuit breakers.</strong> A circuit breaker wraps a remote call and tracks its failure rate, moving through three states:</p><ul><li><strong>Closed: </strong>calls flow normally while the downstream service is healthy</li><li><strong>Open: </strong>once failures cross a threshold, the breaker trips and fails immediately, without even attempting the call, for a cooldown period.</li><li><strong>Half open</strong>: after the cooldown, a handful of test calls check whether the downstream has recovered before fully reopening the gate.</li></ul><p>The mental shift that matters here: failing fast is a feature, not a bug. Instead of Checkout hanging for eight seconds on a call that was never going to succeed, it gets an instant fallback, a cached price, a degraded response, or a polite “try again shortly,” and it stays healthy while Pricing gets a chance to recover.</p><p><strong>If it is already on fire:</strong> kill and restart the stuck thread pools, manually trip the breaker or flip an emergency bypass flag, scale the failing service if it is a capacity problem, or roll back if it is a bad deploy. Then go add the timeout and breaker that were missing, before the next repeat performance.</p><h3>2. Retry storms: the self-inflicted DDoS</h3><p><strong>The setup:</strong> Same chain as above, except now every service has been given “smart” retry logic. If a call fails, retry immediately, up to three times. Sounds responsible.</p><p><strong>What goes wrong:</strong> Pricing has a brief two-second blip during a routine deploy, nothing catastrophic. But every caller retries immediately, three times, with no backoff. Multiply that across every in-flight request from every running instance of every upstream service, and Pricing, already mid-recovery from a two-second hiccup, gets hit with three or four times its normal traffic in an instant. It falls over completely. The retries that were supposed to make the system more resilient just turned a minor blip into a full outage, faster than the original problem ever could have on its own.</p><p><strong>Why it cascades:</strong> Retries fire immediately with no backoff. No jitter, so every client’s retries land in the same synchronized burst. No retry budget capping total retry volume across the fleet. And, often, retrying operations that were not safe to retry in the first place (more on that below).</p><p><strong>The fix: backpressure, plus retry hygiene.</strong></p><p>Backpressure means a system explicitly signals “I am at capacity, slow down,” instead of silently absorbing every request until it collapses. In practice, that looks like bounded queues, load shedding (rejecting excess requests with a clear 429 or 503 instead of accepting them and dying anyway), and rate limiting at the edge.</p><p>Pair that with disciplined retries:</p><ul><li><strong>Exponential backoff: </strong>wait one second, then two, then four, instead of retrying instantly</li><li><strong>Jitter: </strong>randomize that wait slightly so thousands of clients do not all retry in perfect unison</li><li><strong>A retry budget: </strong>cap total retries fleet-wide, for example, no more than ten percent of traffic may be retries at any given moment</li><li><strong>Retry only when it is safe: </strong>which brings us to idempotency, in a minute</li></ul><p><strong>If it is already on fire:</strong> shed load immediately with aggressive rate limits at the edge, flip a kill switch to disable retries if you have one (this is exactly why that switch should exist before you need it), then scale the bottlenecked service if there is real headroom.</p><h3>3. Thundering herd: everyone wakes up at once</h3><p><strong>The setup:</strong> A price cache entry has a ten-minute TTL. Ten thousand requests per second are hitting that cache.</p><p><strong>What goes wrong:</strong> The entry expires. In the very next instant, all ten thousand requests in that second miss the cache simultaneously and go straight to the database to recompute the same value. A database built for steady, predictable read traffic suddenly receives ten thousand identical queries at once and falls over. Functionally, this is the same shape as a retry storm, a huge burst hitting an unprepared resource, but the trigger is different: it is a clock, or a cron job waking many workers at once, rather than an upstream failure.</p><p><strong>Why it cascades:</strong> Nothing prevents concurrent duplicate work on the same cache key. Every request that misses treats the miss the same way: recompute right now. And every cache entry expires on the same schedule, so misses cluster together instead of spreading out.</p><p><strong>The fix: request coalescing and jittered TTLs.</strong></p><ul><li><strong>Request coalescing, or single flight: </strong>only one of the ten thousand requests actually goes to the database; the other 9,999 wait for that single result and share it</li><li><strong>Jittered TTLs</strong>: instead of every entry expiring at exactly ten minutes, randomize slightly, say nine to eleven minutes, so expirations spread out over time instead of syncing up</li><li><strong>Stale while revalidate: </strong>serve the slightly stale cached value while one background request refreshes it, instead of making every caller wait</li></ul><p><strong>If it is already on fire:</strong> manually re-warm the cache before traffic resumes if it went fully cold, temporarily extend TTLs to stop repeat herds during recovery, and add read replicas as an immediate release valve. Then add coalescing so this specific trigger cannot recur.</p><h3>4. The twist: when your own fix bites you back</h3><p><strong>The setup:</strong> Checkout calls Payment: charge fifty dollars. The call times out on Checkout’s side. But the charge actually succeeded on Payment’s side; the response just got lost somewhere on the way back.</p><p><strong>What goes wrong:</strong> Checkout, dutifully following the retry hygiene from scenario two, retries the same charge. Payment has no way of knowing this is a retry of a request it already fulfilled, so it charges the customer again. This is the sting in the tail of every “just add retries” conversation: retries only help when the thing you are retrying is safe to repeat.</p><p><strong>Why it happened:</strong> The operation “charge fifty dollars” is not idempotent. Calling it twice has a different effect than calling it once.</p><p><strong>The fix: idempotency keys.</strong> The client generates a unique key per logical operation, a UUID representing “this specific checkout attempt,” and sends it along with every attempt, including retries. The server stores which keys it has already processed and what result they returned. When the same key shows up again, the server returns the stored result instead of re-executing the side effect. This is the pattern that makes circuit breakers, backpressure, and retries actually safe to combine, rather than three separate techniques that quietly undermine each other.</p><p><strong>If it is already on fire:</strong> reconcile directly against the source of truth, in this case the payment provider, rather than trusting either side’s local record, then refund any duplicate charges you find. Afterward, retrofit idempotency keys onto every operation your retry logic touches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DY3w8xlvnSssR5KbQqfyrQ.png" /></figure><p>Notice the shape of this table. The first three fixes are all, in one way or another, about not letting a burst of demand overwhelm a struggling resource. The fourth fix is the quiet prerequisite that makes the other three safe to use together. Add retries and backoff without idempotency, and you have just built a very disciplined way to double-charge your customers.</p><h3>The takeaway</h3><p>None of these four failures come from bad engineers writing bad code. They come from correct code making a reasonable assumption that a network call behaves like a function call, which will eventually be wrong. Distributed systems fail differently than single processes do: partially, unpredictably, and often in ways that only show up under real production load.</p><p>The fix is not to write more careful code. It is to assume the network will fail in exactly these ways, and to build the four guardrails- circuit breakers, backpressure, coalescing, and idempotency- before you need them rather than after the postmortem.</p><p>If you are running a system with more than two or three services talking to each other, it is worth a genuine audit this week: where is there a synchronous call with no timeout? Whose retry logic has backoff, has jitter, has a budget? Which of your write operations are actually safe to repeat? The answers are usually more interesting and more alarming than anyone expects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2163ed365308" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>