<?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 Shrihari (Harry) on Medium]]></title>
        <description><![CDATA[Stories by Shrihari (Harry) on Medium]]></description>
        <link>https://medium.com/@mr.shrihari212?source=rss-534e115afa2a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-N7oTmVClH69stJK</url>
            <title>Stories by Shrihari (Harry) on Medium</title>
            <link>https://medium.com/@mr.shrihari212?source=rss-534e115afa2a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:22:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mr.shrihari212/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[How a Tiny API Logging Feature Became a Production Bottleneck]]></title>
            <link>https://medium.com/@mr.shrihari212/how-a-tiny-api-logging-feature-became-a-production-bottleneck-14c7b1b32a7d?source=rss-534e115afa2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/14c7b1b32a7d</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Shrihari (Harry)]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 08:05:21 GMT</pubDate>
            <atom:updated>2026-09-19T08:15:02.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4CAf85_r7BvVRtDQPpJLQ.png" /></figure><h3>It started with a simple requirement.</h3><blockquote><em>“We need API logs for two APIs.”</em></blockquote><p>Simple enough.</p><p>Add logging. Store the request and response details. Done.</p><p>Except… developers discovered the logging utility.</p><p>And like every useful utility in a codebase, it started getting reused.</p><p>Then reused again.</p><p>And again.</p><p>Soon, something designed for <strong>two APIs</strong> had quietly become part of the request lifecycle across multiple services.</p><p>That’s when things got interesting.</p><h3>The innocent-looking code</h3><p>The pattern looked harmless:</p><pre>async function handleRequest(req, res) {<br>  const result = await doBusinessWork(req.body);<br><br>  // Response is sent to the client<br>  res.json(result);<br><br>  // But the async handler is still running<br>  try {<br>    await logApiRequest({<br>      request: req.body,<br>      response: result<br>    });<br>  } catch (error) {<br>    console.error(&quot;Logging failed:&quot;, error);<br>  }<br>}</pre><p>At first glance, you might think:</p><blockquote><em>“The response is already sent. So what’s the problem?”</em></blockquote><p>And that’s exactly where the trap was.</p><p>res.json() had already sent the response to the client.</p><p>The client wasn’t sitting there waiting for the database logging operation.</p><p>But the <strong>async request handler itself was still alive</strong>.</p><p>Why?</p><p>Because of this:</p><pre>await logApiRequest(...)</pre><p>The handler’s Promise could not finish until the logging operation finished.</p><p>So we had effectively created:</p><pre>Business request<br>      ↓<br>Response sent<br>      ↓<br>&quot;Okay, we&#39;re done!&quot;<br>      ↓<br>...not actually done<br>      ↓<br>Wait for PostgreSQL logging<br>      ↓<br>Finally finish the handler</pre><p>The client had moved on.</p><p>The server hadn’t.</p><h3>Then PostgreSQL entered the picture</h3><p>The logging utility wasn’t just writing a quick statement.</p><p>The logging path checked out a PostgreSQL connection and performed a transaction:</p><pre>pool.connect()<br>     ↓<br>BEGIN<br>     ↓<br>INSERT<br>     ↓<br>COMMIT<br>     ↓<br>client.release()</pre><p>The API-log pool had a maximum of <strong>10 connections</strong>.</p><p>Under normal traffic, everything looked perfectly fine.</p><p>A log write might take only a few milliseconds.</p><p>So the same 10 connections could serve a lot of requests.</p><p>But production systems rarely fail during the happy path.</p><p>They fail when something gets slow.</p><h3>The domino effect</h3><p>Imagine PostgreSQL suddenly takes a few seconds longer than usual.</p><p>Maybe there is database contention.</p><p>Maybe there is a traffic spike.</p><p>Maybe I/O is slower.</p><p>It doesn’t really matter.</p><p>The important part is:</p><pre>5 ms DB operation<br>        ↓<br>becomes<br>5 seconds</pre><p>Now those 10 connections aren’t cycling quickly anymore.</p><p>They are occupied.</p><pre>Connection 1 → logging<br>Connection 2 → logging<br>Connection 3 → logging<br>...<br>Connection 10 → logging</pre><p>And then request number 11 arrives.</p><p>It asks:</p><pre>pool.connect()</pre><p>But there is no connection available.</p><p>So it waits.</p><p>Now request 12 waits.</p><p>Request 13 waits.</p><p>And so on.</p><p>The connection pool has effectively become a queue.</p><h3>The really nasty part</h3><p>Remember that await in the controller?</p><p>Those requests are still sitting inside their async handlers.</p><p>So we now have:</p><pre>Incoming traffic<br>       ↓<br>API request<br>       ↓<br>Response sent<br>       ↓<br>Await logging<br>       ↓<br>Waiting for DB connection<br>       ↓<br>Waiting...<br>       ↓<br>Waiting...</pre><p>The user may already have received their response.</p><p>But the application is accumulating unfinished work behind the scenes.</p><p>And that unfinished work still has references to request-related objects, snapshots, timers, context, and other state.</p><p>So the problem is no longer simply:</p><blockquote><em>“The logging query is slow.”</em></blockquote><p>It becomes:</p><blockquote><strong><em>“The application is accumulating work that shouldn’t still exist.”</em></strong></blockquote><h3>And then scale does what scale does</h3><p>At low traffic:</p><pre>100 requests<br>→ 100 logs<br>→ DB handles it<br>→ nobody notices</pre><p>At high traffic:</p><pre>1,000,000 requests<br>        ↓<br>1,000,000 logging operations<br>        ↓<br>transactions<br>        ↓<br>connection pool<br>        ↓<br>waiting<br>        ↓<br>more pending handlers<br>        ↓<br>more memory pressure<br>        ↓<br>more database pressure</pre><p>The logging feature had become part of the application’s critical resource path.</p><p>Something that was originally meant to <strong>observe the application</strong> was now capable of <strong>putting pressure on the application</strong>.</p><p>That’s the irony.</p><h3>The API that nobody thought was expensive</h3><p>This is probably the most dangerous type of production issue.</p><p>There wasn’t necessarily one obviously terrible query.</p><p>There wasn’t an infinite loop.</p><p>There wasn’t a CPU-heavy algorithm.</p><p>There was just a small utility:</p><pre>await logApiRequest(...)</pre><p>It looked harmless.</p><p>And because it was useful, developers reused it.</p><p>That’s good engineering behavior in isolation.</p><p>The problem was that the utility carried hidden infrastructure assumptions:</p><ul><li>PostgreSQL connection usage</li><li>transactions</li><li>connection-pool limits</li><li>request lifecycle coupling</li><li>database latency</li><li>memory retention while awaiting</li><li>traffic volume</li></ul><p>The abstraction hid the cost.</p><p>And once the abstraction became popular, its cost multiplied with every caller.</p><h3>The real lesson</h3><p>The scary part wasn’t that API logging existed.</p><p>The scary part was that <strong>a feature originally designed for two APIs gradually became infrastructure used by many APIs without anyone realizing that every call carried a database operation into the request lifecycle.</strong></p><p>At small scale:</p><blockquote><em>“It’s just one log insert.”</em></blockquote><p>At large scale:</p><blockquote><em>“It’s one database transaction for every request.”</em></blockquote><p>Those are very different statements.</p><p>And production traffic has a funny way of making the difference obvious.</p><h3>The final failure mode</h3><p>Eventually the chain looked like this:</p><pre>More traffic<br>    ↓<br>More API logging<br>    ↓<br>More DB transactions<br>    ↓<br>Connections occupied longer<br>    ↓<br>10-connection pool exhausted<br>    ↓<br>New logging operations wait<br>    ↓<br>More async handlers remain pending<br>    ↓<br>More server-side resources retained<br>    ↓<br>More DB/application pressure<br>    ↓<br>Peak traffic<br>    ↓<br>Catastrophic slowdown</pre><p>The original requirement was:</p><blockquote><strong><em>“Log two APIs.”</em></strong></blockquote><p>The system eventually behaved more like:</p><blockquote><strong><em>“Every request participates in a database logging workflow.”</em></strong></blockquote><p>And that’s the lesson worth remembering:</p><p><strong>The cost of a reusable utility isn’t just the code inside it.<br>It’s the infrastructure cost multiplied by every place you reuse it.</strong></p><p>A five-line helper can be harmless at 100 requests.</p><p>At a million requests, those same five lines might be your incident report.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14c7b1b32a7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rebuilding the System You’re Not Supposed to Touch]]></title>
            <link>https://medium.com/@mr.shrihari212/rebuilding-the-system-youre-not-supposed-to-touch-15416824d3d0?source=rss-534e115afa2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/15416824d3d0</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[data-stream-processing]]></category>
            <category><![CDATA[instagram-automation]]></category>
            <category><![CDATA[aws-kinesis]]></category>
            <dc:creator><![CDATA[Shrihari (Harry)]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 14:56:26 GMT</pubDate>
            <atom:updated>2026-03-21T15:02:06.304Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ih-n7aWV4bNBnA8iaIqDFg.png" /></figure><p>Every engineering team eventually inherits a system with an unspoken rule: “Don’t touch it. It works.”</p><p>Nobody can clearly explain <em>how</em> it works.<br>Nobody wants to take ownership of it.<br>But everyone knows one thing — if you try to fix anything, something unrelated will break.</p><p>This article is about rebuilding such a system. Not improving it. Not refactoring it. Rebuilding it — because that was the only sane option left.</p><p>The focus here is the <strong>Instagram automation pipeline</strong>: typing indicators, comment replies, and DM responses. A narrow slice of the system, but one that made the problems impossible to ignore.</p><h3>The Problem With “Working” Systems</h3><p>The old implementation technically worked.</p><p>It received webhooks, processed events, sent replies, and returned HTTP 200. From the outside, everything looked fine.</p><p>From the inside, it was something else entirely.</p><h3>What “working” actually meant</h3><ul><li>Fixing one bug introduced two new ones</li><li>Changes had unpredictable side effects</li><li>The same event could be processed multiple times</li><li>Some events silently failed and were never retried</li><li>Debugging required guesswork more than logs</li></ul><p>The system wasn’t stable — it was fragile in a way that looked stable.</p><p>And that’s worse.</p><p>Because it creates a false sense of safety while accumulating risk.</p><h3>Why Refactoring Wasn’t an Option</h3><p>In theory, you could improve the system incrementally:</p><ul><li>Add idempotency</li><li>Improve error handling</li><li>Clean up transformation logic</li><li>Fix routing</li></ul><p>In practice, every small change triggered unexpected breakage.</p><p>Not because the code was “bad” in isolation, but because:</p><ul><li>Logic was tightly coupled</li><li>Responsibilities were unclear</li><li>Control flow depended on side effects</li><li>There were hidden assumptions everywhere</li></ul><p>The system had no clear boundaries. So there was no safe place to start.</p><p>At some point, you stop asking “how do we fix this?” and start asking:</p><p><strong>“What if we don’t?”</strong></p><h3>The Decision: Build a Parallel System</h3><p>Instead of modifying the old pipeline, a new one was built alongside it.</p><p>Same inputs. Same outputs. Completely different execution model.</p><p>The idea was simple:</p><ul><li>Don’t fight the existing system</li><li>Don’t risk breaking production</li><li>Don’t rely on undocumented behavior</li></ul><p>Just replace it.</p><h3>Step 1: Remove Intelligence From the Webhook</h3><p>The first change was also the most important:</p><p>The webhook stopped doing any real work.</p><p>Instead of:</p><p>Webhook → process → respond</p><p>It became:</p><p>Webhook → enqueue → respond</p><p>All business logic moved to an asynchronous consumer.</p><h3>Why this mattered</h3><ul><li>Webhooks became fast and predictable</li><li>Timeouts stopped causing duplicate events</li><li>Failures became retryable</li><li>Processing became observable</li></ul><p>This single change removed an entire class of problems.</p><h3>Step 2: Assume Every Event Is a Duplicate</h3><p>The old system treated duplicates as rare.</p><p>The new system treats them as inevitable.</p><h3>Idempotency at two levels</h3><h3>Consumer level</h3><p>Before processing:</p><ul><li>Extract keys from events (comment IDs, message IDs)</li><li>Attempt to insert them into storage</li><li>If any key already exists → skip the record</li></ul><h3>Flow level</h3><p>Before sending replies:</p><ul><li>Check if the specific action was already processed</li><li>Only proceed if it wasn’t</li><li>Mark as processed after success</li></ul><h3>Why both?</h3><p>Because preventing duplicate processing is not enough.</p><p>You also need to prevent duplicate <strong>side effects</strong>.</p><h3>Step 3: Make “Doing Nothing” a Valid Outcome</h3><p>One of the biggest flaws in the old system was this assumption:</p><p><strong>Every event should produce an action.</strong></p><p>That’s not true.</p><p>In the new system, many events intentionally result in no action:</p><ul><li>Bot is inactive</li><li>Bot is soft-deleted</li><li>No matching intent</li><li>Missing required data</li><li>Page-generated events</li><li>Duplicate events</li></ul><p>And importantly, each of these cases is:</p><ul><li>Explicitly handled</li><li>Logged with a reason</li></ul><p>Silence is no longer ambiguous — it’s explainable.</p><h3>Step 4: Separate Comment and DM Logic Properly</h3><p>The old system blurred the distinction between comments and messages.</p><p>The new system treats them as separate flows:</p><h3>Comment flow</h3><ul><li>Public reply</li><li>Optional private DM</li><li>Post-level bot selection</li><li>Trigger mode handling</li></ul><h3>DM flow</h3><ul><li>Payload-based replies</li><li>Intent-based replies</li><li>Default fallback behavior</li></ul><p>Each flow:</p><ul><li>Validates its own inputs</li><li>Applies its own idempotency</li><li>Resolves its own bot</li><li>Handles its own failures</li></ul><p>This isolation prevents cross-impact between unrelated behaviors.</p><h3>Step 5: Handle Edge Cases Explicitly</h3><p>The old system failed unpredictably because edge cases were implicit.</p><p>The new system surfaces them:</p><ul><li>Page commenting on its own post → skip</li><li>Page-generated messages → skip</li><li>Missing identifiers → skip</li><li>Unknown payloads → fallback or skip</li><li>Bot not eligible → skip</li></ul><p>Each case is:</p><ul><li>Detected early</li><li>Handled deliberately</li><li>Logged clearly</li></ul><p>Nothing “just happens” anymore.</p><h3>Step 6: Add Observability Where It Actually Matters</h3><p>In the old system, logs existed — but they weren’t useful.</p><p>In the new system, logs are tied to decisions:</p><ul><li>Event received</li><li>Idempotency skip</li><li>Bot resolution result</li><li>Flow skipped (with reason)</li><li>Reply sent</li><li>Reply failed</li></ul><p>This makes it possible to answer questions like:</p><ul><li>Why didn’t this user get a reply?</li><li>Was this event processed already?</li><li>Which bot handled this message?</li></ul><p>Without reading the entire codebase.</p><h3>What Didn’t Change</h3><p>Interestingly, the hardest part wasn’t building the new system.</p><p>It was <strong>not touching the old one</strong>.</p><p>The old pipeline continued running until the new one proved stable.</p><p>No risky migrations.<br>No big-bang switch.<br>No assumptions.</p><p>Just gradual replacement.</p><h3>Lessons From Rebuilding Instead of Fixing</h3><h3>1. “Working” is not the same as “safe”</h3><p>A system that works under normal conditions but fails unpredictably is not reliable.</p><h3>2. Some systems can’t be refactored safely</h3><p>When logic is too entangled, rebuilding is often less risky than incremental fixes.</p><h3>3. Idempotency is not optional</h3><p>If your system processes external events, duplicates are guaranteed.</p><p>Design for it from the start.</p><h3>4. Silence must be intentional</h3><p>If nothing happens, you should know exactly why.</p><h3>5. Webhooks should be dumb</h3><p>The moment you add business logic to a webhook, you start accumulating failure modes.</p><h3>Final Thoughts</h3><p>There’s a certain irony in all of this.</p><p>The old system wasn’t broken enough to justify replacing it quickly.<br>But it was broken enough to make improving it impossible.</p><p>So it stayed in that uncomfortable middle ground — working, but untouchable.</p><p>Until the only practical solution was to stop touching it entirely.</p><p>And build something new next to it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15416824d3d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Really Happens When You Run serverless deploy]]></title>
            <link>https://medium.com/@mr.shrihari212/what-really-happens-when-you-run-serverless-deploy-8bc19d55e4a7?source=rss-534e115afa2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bc19d55e4a7</guid>
            <category><![CDATA[cloud-architecture]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Shrihari (Harry)]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 02:08:47 GMT</pubDate>
            <atom:updated>2026-02-21T06:29:41.180Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rbfwHl7Y6B7MCvLUwIpOw.png" /></figure><p><em>A Practical Deep Dive into Infrastructure-as-Code !</em></p><p>Let’s start with this.</p><p>At some point, we’ve all typed:</p><pre>serverless deploy</pre><p>Watched logs scroll by.<br>Seen “Stack update successful.”<br>Nodded confidently.</p><p>And had absolutely no idea what just happened.</p><p>This article fixes that.</p><p>No buzzwords. No “cloud magic.” Just the real mechanics behind Infrastructure-as-Code (IaC) and the Serverless Framework — explained like an engineer who has broken production more than once.</p><h3>Infrastructure-as-Code (IaC): Not Just “YAML in Git”</h3><p>Infrastructure-as-Code means defining cloud infrastructure in code instead of clicking buttons in a console like it’s 2013.</p><p>Instead of manually creating:</p><ul><li>Lambda functions</li><li>API Gateways</li><li>IAM roles</li><li>DynamoDB tables</li><li>S3 buckets</li></ul><p>You define desired state declaratively in a file (e.g., serverless.yml), commit it, and deploy it.</p><p>Two important layers of versioning exist:</p><h3>1. Git Versioning</h3><p>Your infrastructure definitions live in Git.<br>You can review changes, roll back commits, and track who changed what.</p><p>No more “who deleted the production table?” mystery meetings.</p><h3>2. Cloud Stack Versioning</h3><p>On AWS, deployments are handled by <strong>AWS CloudFormation</strong>, which maintains stack history, supports rollbacks, and tracks resource state internally.</p><p>IaC is not just “config in code.”<br>It is reproducible, versioned, state-aware infrastructure management.</p><h3>So What Is the Serverless Framework Actually Doing?</h3><p>The Serverless Framework is a Node.js CLI tool that acts as an abstraction layer over AWS CloudFormation.</p><p>It is not:</p><ul><li>A backend framework</li><li>A Lambda runtime</li><li>A magical server eraser</li></ul><p>It is a deployment orchestrator.</p><p>When you run:</p><pre>serverless deploy</pre><p>This happens:</p><ol><li>It parses your serverless.yml</li><li>It converts that YAML into a CloudFormation template (JSON)</li><li>It packages your Lambda code into a zip</li><li>It uploads artifacts to S3</li><li>It calls CloudFormation APIs (CreateStack or UpdateStack)</li><li>CloudFormation takes over</li><li>AWS services are provisioned</li></ol><p>The full chain looks like this:</p><p>Infrastructure definition (serverless.yml)<br>→ Serverless CLI<br>→ CloudFormation<br>→ AWS service APIs<br>→ Resources created</p><p>The CLI does not create Lambda directly.<br>CloudFormation does.</p><p>There is no magic. Just layered abstraction.</p><h3>What Is a CloudFormation Stack?</h3><p>A CloudFormation stack is a logical grouping of AWS resources managed as a single unit.</p><p>If your service defines:</p><ul><li>3 Lambda functions</li><li>1 SQS queue</li><li>1 DynamoDB table</li><li>1 IAM role</li></ul><p>They belong to one stack.</p><p>You don’t deploy “a Lambda.”<br>You deploy a stack.</p><p>You don’t update “an API.”<br>You update a stack.</p><p>You don’t delete “a function.”<br>You delete a stack.</p><p>Stack = infrastructure boundary.</p><p>Understanding this concept is essential. Most engineers ignore it. Those engineers eventually debug stack rollbacks at 2 a.m.</p><h3>Event-Driven Architecture: The Real Foundation</h3><p>Serverless systems are typically event-driven.</p><p>Instead of:</p><p>Client → Server → Database</p><p>You design:</p><p>Event → Reaction</p><p>Examples:</p><ul><li>File uploaded → Lambda triggered</li><li>Order placed → Payment service reacts</li><li>Payment succeeded → Email service reacts</li></ul><p>Systems become loosely coupled and asynchronous.</p><p>That is the architectural model you’re building — not “just a Lambda.”</p><h3>IAM: The Part Everyone Underestimates</h3><p>IAM defines who can do what.</p><p>Every Lambda runs with an IAM role.</p><p>That role determines:</p><ul><li>What S3 buckets it can read</li><li>What DynamoDB tables it can write</li><li>Whether it can publish to SNS</li></ul><p>Too restrictive → runtime errors.<br>Too permissive → security risk.</p><p>Over-permissioning in production is not “just for now.”<br>It becomes permanent.</p><p>Senior engineers treat IAM as architecture, not inconvenience.</p><h3>Environment Separation: Dev Is Not Prod</h3><p>Using:</p><pre>serverless deploy --stage prod</pre><p>Creates a separate stack.</p><p>Environment separation must include:</p><ul><li>Separate databases</li><li>Separate queues</li><li>Separate secrets</li><li>Separate domains</li></ul><p>If your dev and prod share infrastructure, that is not efficiency. That is risk.</p><h3>Cold Starts: The Latency Tax</h3><p>Lambda functions are not always running.</p><p>If idle, AWS shuts down the container.</p><p>The next request triggers:</p><ul><li>Runtime initialization</li><li>Dependency loading</li><li>Code bootstrapping</li></ul><p>That delay is called a cold start.</p><p>Cold start impact depends on:</p><ul><li>Runtime choice</li><li>Bundle size</li><li>Initialization logic</li><li>VPC configuration</li></ul><p>Serverless reduces operational overhead, but it does not eliminate performance trade-offs.</p><h3>Cost Awareness: Pay-Per-Use Is Not Automatically Cheap</h3><p>Serverless pricing is usage-based.</p><p>Costs include:</p><ul><li>Invocation count</li><li>Execution duration</li><li>Memory allocation</li><li>API Gateway requests</li><li>Database capacity</li><li>Data transfer</li></ul><p>Chatty microservices increase cost.<br>High memory allocations increase cost.<br>Uncontrolled event storms increase cost.</p><p>Architecture decisions directly affect billing.</p><p>Serverless is efficient when designed well. Expensive when designed casually.</p><h3>What Infrastructure-as-Code Also Includes (Beyond YAML)</h3><p>Senior-level IaC knowledge includes:</p><ul><li>State management</li><li>Idempotent deployments</li><li>Drift detection (console changes vs code definition)</li><li>Secret management</li><li>Resource lifecycle protection (retain policies)</li><li>Observability as code (logs, alarms, metrics)</li><li>Tagging strategy for cost governance</li><li>Stack limits and modularization</li></ul><p>IaC is not just “write config and deploy.”</p><p>It is system governance encoded.</p><h3>What You Actually Need to Master</h3><p>You do not need to memorize every CLI flag.</p><p>You must understand:</p><ul><li>How CloudFormation manages state</li><li>How stacks are structured</li><li>How IAM affects runtime behavior</li><li>How event-driven systems flow</li><li>How environments are isolated</li><li>How cost and latency trade-offs work</li><li>How deployments fail and roll back</li></ul><p>Tool syntax can be Googled.</p><p>Architectural clarity cannot.</p><h3>Final Thought</h3><p>When you run:</p><pre>serverless deploy</pre><p>You are not deploying a function.</p><p>You are:</p><ul><li>Defining desired infrastructure state</li><li>Converting it into a declarative template</li><li>Handing it to a cloud orchestration engine</li><li>Updating distributed resources atomically</li></ul><p>That is real system engineering.</p><p>The YAML is just the entry point.</p><p>Understanding the layers behind it is what separates someone who uses serverless from someone who designs with it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bc19d55e4a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Kinesis Deep Dive (With Focus on Kinesis Data Streams)]]></title>
            <link>https://medium.com/@mr.shrihari212/aws-kinesis-deep-dive-with-focus-on-kinesis-data-streams-1d439a1f472f?source=rss-534e115afa2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d439a1f472f</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[kinesis-data-stream]]></category>
            <category><![CDATA[aws-kinesis]]></category>
            <dc:creator><![CDATA[Shrihari (Harry)]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 03:09:26 GMT</pubDate>
            <atom:updated>2026-02-20T03:09:26.591Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dZ5kR05Cz7DYNG2uIH5E2A.png" /></figure><h3>What AWS Kinesis Is</h3><p>Amazon Kinesis is a fully managed streaming data platform from Amazon Web Services designed for real-time data ingestion, processing, and analysis at scale.</p><p>Think of it as AWS’s native answer to “I have a firehose of events and I need to do something intelligent with them before my system melts.”</p><p>It is built for:</p><ul><li>Continuous data ingestion</li><li>Real-time or near-real-time processing</li><li>Horizontally scalable event pipelines</li><li>Managed infrastructure (so you don’t babysit brokers at 2 AM)</li></ul><h3>Why It Is Used</h3><p>Kinesis exists for one reason: <strong>real-time streaming at scale without infrastructure management overhead.</strong></p><p>It is used when:</p><ul><li>You cannot afford batch delays (e.g., fraud detection).</li><li>You have high-velocity event streams (millions per second).</li><li>You want managed scaling instead of running Kafka clusters yourself.</li><li>You are deeply invested in the AWS ecosystem.</li></ul><h3>Real-World Streaming Use Cases</h3><ol><li><strong>Clickstream Analytics</strong><br>Capture user activity events and process in near real time.</li><li><strong>Fraud Detection</strong><br>Process payment events instantly and run anomaly detection.</li><li><strong>IoT Telemetry</strong><br>Ingest sensor data continuously from thousands of devices.</li><li><strong>Log Aggregation</strong><br>Stream application logs for monitoring and alerting.</li><li><strong>Real-Time Personalization</strong><br>Update recommendations instantly as user behavior changes.</li></ol><p>If your system is event-driven and latency-sensitive, Kinesis is a serious contender.</p><h3>Overview of Kinesis Services</h3><p>AWS Kinesis is actually a family of services:</p><h3>1. Kinesis Data Streams (KDS) — Primary Focus</h3><p>Core streaming service for building custom real-time data pipelines.</p><h3>2. Kinesis Data Firehose</h3><p>Managed delivery service that loads streaming data into S3, Redshift, OpenSearch with minimal configuration.</p><h3>3. Kinesis Data Analytics</h3><p>Run SQL or Apache Flink on streaming data.</p><h3>4. Kinesis Video Streams</h3><p>Stream video data for processing or storage.</p><p>The rest of this article focuses primarily on <strong>Kinesis Data Streams</strong>, because that’s where the architectural nuance lives.</p><h3>Kinesis vs Kafka vs MSK</h3><h3>Apache Kafka</h3><p>Apache Kafka is an open-source distributed event streaming platform.</p><p>You manage:</p><ul><li>Brokers</li><li>Zookeeper (or KRaft in newer versions)</li><li>Scaling</li><li>Patching</li><li>Monitoring</li><li>Capacity planning</li></ul><p>Full flexibility. Full responsibility.</p><h3>Amazon Kinesis</h3><p>Managed streaming service.</p><p>You manage:</p><ul><li>Shard count (provisioned mode)</li><li>Scaling decisions (unless on-demand)</li><li>Consumer logic</li></ul><p>AWS manages:</p><ul><li>Infrastructure</li><li>Replication</li><li>Availability</li><li>Durability</li></ul><h3>Amazon MSK</h3><p>Amazon MSK is AWS-managed Kafka.</p><p>You get:</p><ul><li>Native Kafka APIs</li><li>Kafka ecosystem compatibility</li><li>Managed brokers</li></ul><p>You still manage:</p><ul><li>Topic configs</li><li>Partition counts</li><li>Scaling strategy</li></ul><h3>Detailed Comparison</h3><h3>Architecture</h3><p>FeatureKafkaKinesisMSKStorage ModelPartitioned logSharded streamPartitioned logOrderingPer partitionPer shardPer partitionInfra ManagementSelf-managedFully managedManaged Kafka</p><h3>Operational Model</h3><ul><li><strong>Kafka</strong>: Full control, full ops burden.</li><li><strong>Kinesis</strong>: No broker management.</li><li><strong>MSK</strong>: Kafka APIs, AWS-managed cluster.</li></ul><p>If you want zero broker ops, Kinesis wins.</p><h3>Performance</h3><ul><li>Kafka can push extremely high throughput depending on hardware.</li><li>Kinesis shard has strict throughput limits.</li><li>MSK performance depends on instance types and partition count.</li></ul><h3>Throughput Limits</h3><p>Kinesis (Provisioned Mode):</p><ul><li>1 MB/sec write per shard</li><li>1000 records/sec write per shard</li><li>2 MB/sec read per shard</li></ul><p>Kafka:</p><ul><li>Depends on cluster size and partitions.</li><li>No hard per-partition cap enforced by platform.</li></ul><h3>Cost Model</h3><ul><li>Kafka (self-managed): infra + ops cost.</li><li>MSK: broker-hour + storage cost.</li><li>Kinesis: shard-hour (provisioned) OR per-GB (on-demand).</li></ul><p>Kinesis is simple but can get expensive if you overprovision shards.</p><h3>Scaling Model</h3><ul><li>Kafka/MSK: Add partitions manually.</li><li>Kinesis: Reshard (split/merge shards).</li><li>Kinesis On-Demand: Auto scales.</li></ul><h3>Retention</h3><ul><li>Kafka: Configurable, can retain indefinitely.</li><li>Kinesis: 24 hours default, up to 365 days (extended retention).</li></ul><h3>Deployment Flexibility</h3><ul><li>Kafka: Anywhere (on-prem, cloud).</li><li>MSK: AWS only.</li><li>Kinesis: AWS only.</li></ul><h3>Deep Dive: Kinesis Data Streams Architecture</h3><h3>Core Components</h3><h3>1. Shards</h3><p>A shard is the fundamental unit of:</p><ul><li>Throughput</li><li>Scaling</li><li>Ordering</li><li>Parallelism</li></ul><p>Everything revolves around shards.</p><p>If you have 5 shards, you get:</p><ul><li>5 units of parallel read</li><li>5 independent ordering guarantees</li></ul><h3>2. Producers</h3><p>Applications that push records into the stream.</p><p>Common producers:</p><ul><li>EC2 apps</li><li>Containers</li><li>Lambda</li><li>KPL (Kinesis Producer Library)</li></ul><p>Each record must include:</p><ul><li>Data</li><li>Partition key</li></ul><h3>3. Partition Keys</h3><p>Partition key determines:</p><ul><li>Which shard the record goes to</li><li>Ordering boundaries</li></ul><p>Hash(partitionKey) → maps to shard</p><p>All records with same partition key:</p><ul><li>Go to same shard</li><li>Maintain strict ordering</li></ul><p>If you choose a terrible partition key (e.g., constant string), congratulations — you just throttled yourself.</p><h3>4. Consumers</h3><p>Applications that read from shards.</p><p>Options:</p><ul><li>KCL (Kinesis Client Library)</li><li>Lambda</li><li>Custom polling</li><li>Enhanced fan-out</li></ul><h3>5. Ordering Guarantees</h3><p>Ordering is guaranteed:</p><ul><li>Within a shard</li><li>For records sharing the same partition key</li></ul><p>No ordering guarantee across shards.</p><h3>6. Retention</h3><ul><li>Default: 24 hours</li><li>Extendable: up to 365 days</li><li>Records remain until retention expires</li></ul><h3>Lambda + Kinesis Integration</h3><p>This is where things get interesting.</p><h3>Starting Position</h3><p>Two options:</p><ul><li>TRIM_HORIZON<br>Start from oldest available record.</li><li>LATEST<br>Start from new records only.</li></ul><p>Use case:</p><ul><li>Replay pipeline → TRIM_HORIZON</li><li>Real-time processing only → LATEST</li></ul><h3>batchSize</h3><p>Range:</p><ul><li>1 to 10,000 records</li></ul><p>Impact:</p><ul><li>Larger batchSize → fewer Lambda invocations</li><li>Lower invocation cost</li><li>Higher per-batch failure impact</li></ul><p>If one batch has 1000 records, and 1 fails… things get fun. (We’ll get there.)</p><h3>maximumBatchingWindowInSeconds (batch window)</h3><p>Range:</p><ul><li>0 to 300 seconds</li></ul><p>Lambda waits up to this duration to accumulate records before invoking.</p><p>Impact:</p><ul><li>Larger window → higher batch density</li><li>Lower invocation frequency</li><li>Increased latency</li></ul><p>Latency-sensitive? Keep it low.<br>Cost-sensitive? Increase it.</p><h3>Batch Failure Handling</h3><h3>What Happens If One Record Fails?</h3><p>Default behavior:</p><ul><li>Entire batch fails</li><li>Entire batch retried</li></ul><p>Yes, even if 999 out of 1000 succeeded.</p><h3>Does Whole Batch Retry?</h3><p>Yes.</p><p>Lambda retries until:</p><ul><li>Success</li><li>Record expires</li><li>Maximum retry attempts exceeded (if configured)</li></ul><h3>Can It Cause Duplicate Processing?</h3><p>Absolutely.</p><p>Records that previously succeeded in the batch:</p><ul><li>Will be reprocessed.</li></ul><p>You must build idempotency.</p><h3>Can a Failing Record Block a Shard?</h3><p>Yes.</p><p>Because ordering is per shard, Lambda cannot move past a failed record.</p><p>That shard remains blocked until:</p><ul><li>Record succeeds</li><li>It expires</li></ul><p>This is known as a shard-level processing stall.</p><h3>Lambda Partial Batch Response</h3><p>To fix the “all-or-nothing” nightmare:</p><p>Enable:</p><p>reportBatchItemFailures</p><p>Lambda can now return:</p><ul><li>List of failed record IDs</li></ul><p>Result:</p><ul><li>Only failed records are retried</li><li>Successful records are checkpointed</li></ul><p>Benefits:</p><ul><li>Reduced retry blast radius</li><li>Reduced duplicate processing</li><li>Less shard blocking</li></ul><p>Still not magic:</p><ul><li>A permanently failing record will continue retrying.</li><li>But it no longer replays successful siblings.</li></ul><h3>Retry Behavior</h3><p>Lambda retry strategy:</p><ul><li>Exponential backoff</li><li>Retries until success or expiration</li><li>Entire shard pauses until failure resolved (unless partial batch response enabled)</li></ul><p>With partial batch:</p><ul><li>Only failed records retried</li><li>Checkpoint advances past successful ones</li></ul><h3>Scaling Mechanics</h3><h3>Why Lambda Does Not Autoscale Beyond Shard Count</h3><p>Parallelism in Kinesis is shard-bound.</p><p>1 shard = 1 concurrent Lambda invocation.</p><p>If you have:</p><ul><li>3 shards → max 3 concurrent Lambdas</li></ul><p>You cannot exceed shard count parallelism.</p><p>Shards are the concurrency ceiling.</p><h3>Resharding</h3><p>Two operations:</p><ul><li>Split shard → increase capacity</li><li>Merge shards → reduce capacity</li></ul><p>Resharding changes:</p><ul><li>Throughput</li><li>Parallelism</li><li>Cost</li></ul><p>But does not affect historical data.</p><h3>Provisioned vs On-Demand</h3><p>Provisioned:</p><ul><li>You define shard count.</li><li>Predictable cost.</li><li>Manual scaling.</li></ul><p>On-Demand:</p><ul><li>Auto scales with traffic.</li><li>Charged per GB ingested.</li><li>Simpler, more expensive at scale.</li></ul><h3>Cost Optimization</h3><h3>Why Increasing batchSize Reduces Invocation Cost</h3><p>Lambda cost:</p><ul><li>Per invocation</li><li>Plus execution duration</li></ul><p>Larger batch:</p><ul><li>Fewer invocations</li><li>Lower per-record overhead</li></ul><p>Example:</p><p>1000 records:</p><ul><li>batchSize 1 → 1000 invocations</li><li>batchSize 100 → 10 invocations</li></ul><p>That is not a subtle difference.</p><h3>Retry Blast Radius</h3><p>“Retry blast radius” means:</p><p>How much successfully processed data gets retried when a failure happens?</p><p>Large batch:</p><ul><li>Large blast radius</li></ul><p>Small batch:</p><ul><li>Small blast radius</li></ul><p>Trade-off:</p><ul><li>Larger batch → cheaper, higher duplicate risk</li><li>Smaller batch → more expensive, safer retries</li></ul><h3>Redeployment Behavior</h3><p>Redeploying infrastructure (CloudFormation, CDK, Terraform):</p><p>Does NOT create a new stream unless:</p><ul><li>Stream name changes</li><li>Logical resource replaced</li><li>Configuration forces replacement</li></ul><p>If resource definition remains stable:</p><ul><li>Same stream</li><li>Same data</li><li>Same shards</li></ul><p>No surprise duplication unless you deliberately change resource identity.</p><h3>Final Observations</h3><p>Kinesis Data Streams is:</p><ul><li>Deterministic in scaling (shard-driven)</li><li>Strict in ordering (per shard)</li><li>Sensitive to partition key design</li><li>Cost-sensitive to batch size configuration</li><li>Extremely powerful when integrated correctly with Lambda</li></ul><p>If you understand:</p><ul><li>Shards control parallelism</li><li>Partition keys control ordering</li><li>Batch size controls cost</li><li>Partial batch response controls retry scope</li></ul><p>Then you understand Kinesis at a senior level.</p><p>Everything else is implementation detail.</p><p>And if your shard is blocked because of one malformed record in production, welcome to streaming systems. Build idempotency, monitor aggressively, and choose partition keys like your throughput depends on it — because it does.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d439a1f472f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Execution Order: How Queries Really Run]]></title>
            <link>https://medium.com/@mr.shrihari212/sql-execution-order-how-queries-really-run-4e3b228ec0c0?source=rss-534e115afa2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e3b228ec0c0</guid>
            <category><![CDATA[query-execution-order]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Shrihari (Harry)]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 11:56:36 GMT</pubDate>
            <atom:updated>2026-02-14T11:56:36.507Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YbIVlav9DKOVapetOrL0aA.png" /></figure><p>If you write SQL like this:</p><pre>SELECT ...<br>FROM ...<br>WHERE ...<br>GROUP BY ...<br>HAVING ...<br>ORDER BY ...<br>LIMIT ...</pre><p>…it’s tempting to assume the database executes it in that top-to-bottom order. It doesn’t. That’s why WHERE COUNT(*) &gt; 5 fails, why HAVING exists, and why GROUP BY errors keep surprising developers at 2AM.</p><p>Understanding the <strong>logical execution order</strong> of SQL is the difference between guessing your queries will work and knowing they will work — every single time.</p><h3>Syntax Order vs Logical Execution Order</h3><p>There are two distinct concepts:</p><ul><li><strong>Syntax order:</strong> how you write a query so the parser can understand it.</li><li><strong>Logical execution order:</strong> the sequence in which the database engine processes rows internally.</li></ul><p>Confusing the two is the root of most SQL confusion. Logical execution is about <strong>how the engine actually transforms data</strong>, not how you type your query.</p><h3>The Complete Logical Execution Pipeline</h3><p>Here’s the full pipeline:</p><pre>1. WITH / CTEs                 -- define temporary result sets<br>2. FROM                        -- select base tables<br>3. LATERAL / CROSS APPLY       -- row-level dependent sources<br>4. JOIN / ON                   -- combine tables<br>5. WHERE                       -- filter raw rows<br>6. GROUP BY                    -- form groups<br>7. Aggregate functions         -- compute per group<br>8. HAVING                      -- filter aggregated groups<br>9. WINDOW functions            -- compute row-level analytics<br>10. SELECT                     -- project final columns<br>11. DISTINCT                   -- remove duplicates<br>12. Subqueries                 -- execute as required<br>13. UNION / INTERSECT / EXCEPT -- combine result sets<br>14. ORDER BY                   -- sort results<br>15. LIMIT / OFFSET / FETCH     -- trim rows</pre><p>This is the <strong>complete, precise logical execution order</strong>, not a simplified or partial version. It ensures predictable behavior, prevents mistakes, and builds a solid mental model of how SQL processes data.</p><h3>Step-by-Step Breakdown</h3><h3>1. WITH / CTEs</h3><p>Common Table Expressions define temporary result sets. They are logically executed before the main query. Modern optimizers may inline them, but conceptually, they are “first in line.”</p><pre>WITH TopOrders AS (<br>  SELECT * FROM Orders WHERE amount &gt; 100<br>)<br>SELECT * FROM TopOrders;</pre><p>CTEs are particularly useful for breaking complex queries into readable parts.</p><h3>2. FROM</h3><p>The database engine identifies the base table(s) and starts building the working row set. At this stage, no filters or transformations are applied — it’s raw data selection.</p><h3>3. LATERAL / CROSS APPLY</h3><p>These constructs allow subqueries or functions in the FROM clause to reference columns from preceding tables. They are evaluated per row from the left table, which is why they behave like controlled correlated subqueries.</p><h3>4. JOIN / ON</h3><p>Join operations combine multiple tables based on conditions. Only rows satisfying the join predicate survive.</p><ul><li><strong>INNER JOIN:</strong> keeps only matching rows</li><li><strong>LEFT/RIGHT/FULL OUTER JOIN:</strong> retains unmatched rows from one or both sides</li></ul><p>Logical execution ensures joins are applied <strong>before</strong> row-level filtering with WHERE.</p><h3>5. WHERE</h3><p>Filters individual rows from the joined dataset. At this stage:</p><ul><li>Aggregates do <strong>not exist</strong></li><li>Grouping has <strong>not happened</strong></li><li>Window functions have <strong>not been applied</strong></li></ul><p>Example:</p><pre>WHERE amount &gt; 100</pre><p>This explains why writing WHERE COUNT(*) &gt; 5 fails: the engine hasn’t created any group yet.</p><h3>6. GROUP BY</h3><p>Rows are partitioned into groups based on one or more columns. Each group will eventually produce <strong>one output row per unique combination</strong>.</p><p>Grouping is what makes aggregation meaningful. Without it, SUM() or COUNT() would compute over the entire dataset, not per group.</p><h3>7. Aggregate Functions</h3><p>Functions like COUNT(), SUM(), AVG(), MIN(), and MAX() are computed <strong>after grouping</strong>, per group.</p><ul><li>These functions collapse rows into a summary value.</li><li>They only exist once grouping is complete.</li></ul><h3>8. HAVING</h3><p>Filters groups <strong>after aggregation</strong>. It’s like WHERE, but for grouped data:</p><pre>HAVING COUNT(*) &gt; 10</pre><p>WHERE filters rows.<br>HAVING filters groups.</p><h3>9. WINDOW Functions</h3><p>Analytic functions like ROW_NUMBER(), RANK(), or SUM() OVER(PARTITION BY ...) run <strong>after grouping but before final projection</strong>.</p><ul><li>They do not collapse rows.</li><li>They allow computations across partitions of the result set.</li></ul><h3>10. SELECT</h3><p>Projects the final columns and expressions. This is where aliases are assigned and calculations are evaluated.</p><p>Key point: SELECT executes <strong>after aggregates exist</strong>, which is why:</p><pre>SELECT alias_name FROM table<br>ORDER BY alias_name</pre><p>works, but you cannot reference an alias in WHERE.</p><h3>11. DISTINCT</h3><p>Removes duplicates <strong>after projection</strong> but before sorting or limiting.</p><ul><li>Think of it as a “deduplication pass” on the selected columns.</li><li>DISTINCT is often misunderstood; it runs <strong>after SELECT</strong>, not during aggregation.</li></ul><h3>12. Subqueries</h3><p>Executed according to their placement:</p><ul><li>FROM subquery: acts as a derived table, executed first</li><li>WHERE subquery: evaluated during row filtering</li><li>Correlated subquery: executed once per outer row</li></ul><p>Understanding subquery execution is critical for both correctness and performance.</p><h3>13. UNION / INTERSECT / EXCEPT</h3><p>Combine multiple SELECT statements. Each SELECT runs <strong>fully through its own pipeline</strong>, then the set operator merges the results.</p><p>Sorting and limiting happen after the combination.</p><h3>14. ORDER BY</h3><p>Sorts the final result set based on columns, expressions, or aliases.</p><ul><li>Available only after SELECT, aggregates, and window functions</li><li>Explains why ORDER BY can reference a SELECT alias</li></ul><h3>15. LIMIT / OFFSET / FETCH</h3><p>Finally, the database restricts the number of rows returned.</p><ul><li>Applied <strong>after sorting</strong></li><li>Ensures pagination behaves predictably</li></ul><h3>The Mental Model That Makes SQL Predictable</h3><p>Think of SQL as a <strong>data transformation pipeline</strong>:</p><ol><li>Build data (FROM / JOIN / LATERAL / CTEs)</li><li>Filter rows (WHERE)</li><li>Group rows (GROUP BY)</li><li>Compute aggregates (Aggregate Functions)</li><li>Filter groups (HAVING)</li><li>Compute analytics (WINDOW Functions)</li><li>Project output (SELECT)</li><li>Remove duplicates (DISTINCT)</li><li>Execute subqueries (as required)</li><li>Combine result sets (UNION / INTERSECT / EXCEPT)</li><li>Sort results (ORDER BY)</li><li>Limit rows (LIMIT / OFFSET / FETCH)</li></ol><p>Internalize this pipeline and SQL stops being mysterious.</p><h3>Final Takeaway</h3><p>SQL is declarative, but its logical execution model is structured and predictable.</p><p>Subqueries, CTEs, aggregates, window functions, and set operations all fit into this ordered pipeline. Subqueries execute at different stages depending on where they appear in the query.</p><p>Understanding <strong>where each clause executes — and why — </strong>eliminates confusion, prevents errors, and makes query performance predictable.</p><p>Once you internalize this mental model — including subqueries and CTEs — SQL becomes logical instead of surprising.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e3b228ec0c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Styles Explained (Why Everyone Confuses Them, and How to Never Do It Again)]]></title>
            <link>https://medium.com/@mr.shrihari212/api-styles-explained-why-everyone-confuses-them-and-how-to-never-do-it-again-f07c99680c4b?source=rss-534e115afa2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f07c99680c4b</guid>
            <dc:creator><![CDATA[Shrihari (Harry)]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 13:24:57 GMT</pubDate>
            <atom:updated>2026-02-08T13:24:57.840Z</atom:updated>
            <content:encoded><![CDATA[<p>APIs are one of the most talked-about topics in software development — and also one of the most confidently misunderstood. We casually throw around terms like REST, GraphQL, gRPC, SOAP, WebSockets, and Webhooks as if they’re interchangeable “API styles,” even though they solve completely different problems at completely different layers.</p><p>This article clears that up — by separating architecture from transport, behavior from data, and real design decisions from terminology people repeat because it sounds correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yr9d8Gi83IVyGpLQVnlX9Q.png" /></figure><p>If you’ve ever seen a list like this:</p><ul><li>REST</li><li>SOAP</li><li>GraphQL</li><li>gRPC</li><li>WebSockets</li><li>Webhooks</li></ul><p>…and thought, <em>“Okay cool, these are API styles”</em> — congratulations, you’ve been gently lied to by the internet.</p><p>Not maliciously. Just… confidently wrong.</p><p>The problem is simple:<br>people mix <strong>architecture</strong>, <strong>transport</strong>, and <strong>communication patterns</strong> into one bucket and call it <em>API styles</em>.<br>That’s how WebSockets end up sitting next to REST like they belong to the same species.</p><p>They do not.</p><p>This article fixes that — cleanly, permanently, and with zero buzzwords.</p><h3>What an “API Style” Actually Is</h3><p>An <strong>API architectural style</strong> answers one core question:</p><blockquote>What is the fundamental interaction model between client and server?</blockquote><p>In other words:</p><ul><li>Are we transferring state?</li><li>Are we executing commands?</li><li>Are we shaping data?</li><li>Are we reacting to events?</li></ul><p>If a technology does <strong>not</strong> answer that question, it is <strong>not</strong> an API style — no matter how popular it is.</p><p>Keep that definition in your head. We’ll use it like a weapon.</p><h3>REST: State Transfer, Not Function Calls</h3><p>REST (Representational State Transfer) is about <strong>resources and state</strong>, not behavior.</p><p>You don’t “do things” in REST.<br>You <strong>transfer representations of state</strong>.</p><ul><li>Resources are identified by URLs</li><li>HTTP verbs define intent (GET, POST, PUT, DELETE)</li><li>The server exposes <em>what exists</em>, not <em>what it can do</em></li></ul><p>Example:</p><pre>GET /users/123<br>DELETE /users/123</pre><p>Not:</p><pre>POST /deleteUserById</pre><p>REST says:</p><blockquote><em>“Here is the state of a resource. Modify or delete it using standard semantics.”</em></blockquote><p>This is why REST scales well, caches well, and survives the real world.</p><h3>RPC: Behavior Execution Over the Network</h3><p>RPC (Remote Procedure Call) is the opposite philosophy.</p><p>RPC says:</p><blockquote><em>“I don’t care about resources. I want to call a function on another machine.”</em></blockquote><p>So APIs look like:</p><pre>createUser()<br>deleteUser(id)<br>fetchOpportunityWithQuestionFilter()</pre><p>This is <strong>behavior-first</strong>, not resource-first.</p><p>RPC is:</p><ul><li>Direct</li><li>Explicit</li><li>Easy to reason about</li><li>Tightly coupled to server behavior</li></ul><p>Modern gRPC is just <strong>high-performance RPC</strong>:</p><ul><li>Binary payloads</li><li>HTTP/2</li><li>Strong contracts</li><li>Streaming support</li></ul><p>It’s excellent for <strong>internal service-to-service communication</strong>.</p><p>It is not REST.<br>And that’s fine.</p><h3>SOAP: RPC With a Suit, a Tie, and 47 Pages of XML</h3><p>SOAP belongs right here — <strong>after RPC</strong> — because that’s exactly what it is.</p><p>SOAP is:</p><blockquote><em>RPC with a suit, a tie, and 47 pages of XML.</em></blockquote><p>It is:</p><ul><li>Behavior-oriented</li><li>Contract-first (WSDL)</li><li>Extremely strict</li><li>Painfully verbose</li><li>Still alive in banks because auditors sleep better at night</li></ul><p>SOAP defines:</p><ul><li>Message structure</li><li>Operation contracts</li><li>Error handling</li><li>Security extensions</li></ul><p>That makes it a <strong>true API architectural style</strong>, even if developers avoid it like unpaid overtime.</p><p>SOAP didn’t die because it was wrong.<br>It died because it was exhausting.</p><h3>GraphQL: Client-Driven Data Shaping</h3><p>GraphQL is neither REST nor RPC.</p><p>GraphQL says:</p><blockquote><em>“The client decides the shape of the data.”</em></blockquote><ul><li>Single endpoint</li><li>Strong schema</li><li>Precise data fetching</li><li>No over-fetching</li><li>No under-fetching</li></ul><p>Example:</p><pre>query {<br>  user(id: 123) {<br>    name<br>    posts {<br>      title<br>    }<br>  }<br>}</pre><p>GraphQL is about <strong>data composition</strong>, not resources or behaviors.</p><p>It shines when:</p><ul><li>Clients vary wildly (web, mobile, dashboards)</li><li>Data relationships are complex</li><li>Over-fetching hurts performance</li></ul><p>It trades simplicity for flexibility — intentionally.</p><h3>Event-Driven APIs: Reaction, Not Requests</h3><p>Event-driven APIs flip the model entirely.</p><p>Instead of:</p><blockquote><em>“Client asks → Server responds”</em></blockquote><p>It’s:</p><blockquote><em>“Something happened → Interested systems react”</em></blockquote><p>Examples:</p><ul><li>UserCreated</li><li>PaymentFailed</li><li>OrderShipped</li></ul><p>Consumers don’t control timing.<br>They <strong>subscribe</strong>.</p><p>This is how systems scale without becoming tightly coupled.</p><p>Event-driven APIs are about <strong>reaction</strong>, not control.</p><h3>Why WebSockets Are Included (and Why This Is Where People Screw Up)</h3><p>WebSocket is <strong>not an API style</strong>.</p><p>Read that again. Slowly.</p><p>WebSocket does <strong>not</strong> define:</p><ul><li>Resource modeling</li><li>State transfer</li><li>Behavior semantics</li><li>Data ownership</li></ul><p>WebSocket only answers:</p><blockquote><em>“How do we keep a persistent, two-way connection open?”</em></blockquote><p>That’s it.</p><p>You can run:</p><ul><li>REST over WebSockets</li><li>RPC over WebSockets</li><li>Event streams over WebSockets</li><li>Absolute chaos over WebSockets</li></ul><p>WebSocket is a <strong>transport</strong>, not an architecture.</p><p>It’s a pipe.<br>Not a philosophy.</p><p>People include it because it’s used for real-time systems — and then forget to think any further.</p><h3>Why Webhooks Are Also Misplaced</h3><p>Webhooks are <strong>not an API style</strong>.<br> They are an <strong>integration pattern</strong>.</p><p>A webhook is simply:</p><ul><li>An <strong>HTTP callback</strong></li><li>Triggered by an <strong>event</strong></li><li>Sent to a <strong>client-defined URL</strong></li></ul><p>That’s it. No more, no less.</p><p>What webhooks <strong>do not define</strong>:</p><ul><li>No resource model</li><li>No interaction semantics</li><li>No schema evolution rules</li><li>No API structure or contract beyond “we POST something to you”</li></ul><p>Webhooks answer <strong>when</strong> data is pushed — not <strong>how</strong> an API is designed.</p><h3>“But Aren’t Webhooks Event-Driven APIs?”</h3><p>This is where people mess it up.</p><p><strong>Event-driven architecture</strong> is a system design model:</p><ul><li>Events are first-class citizens</li><li>Events have schemas</li><li>Producers and consumers are decoupled</li><li>Events flow through brokers (Kafka, Pulsar, SNS, etc.)</li><li>Multiple consumers can independently react</li></ul><p>A <strong>webhook is just one delivery mechanism</strong> for events — and a limited one.</p><p>Key differences:</p><ul><li>Webhooks are <strong>point-to-point</strong></li><li>Event-driven systems are <strong>fan-out</strong></li><li>Webhooks push events via <strong>HTTP</strong></li><li>Event-driven systems use <strong>message brokers</strong></li><li>Webhooks assume the receiver is online</li><li>Event systems handle retries, replay, ordering, and durability</li></ul><p>In other words:</p><blockquote><strong><em>Webhooks are to event-driven systems what </em></strong><strong><em>curl is to distributed messaging.</em></strong></blockquote><p>Useful. Practical. Absolutely not the architecture itself.</p><h3>The Correct Framing</h3><ul><li><strong>Event-driven API</strong> → architectural style</li><li><strong>Webhooks</strong> → one way to notify someone that an event happened</li></ul><p>That’s why webhooks show up everywhere — and why they don’t belong in lists of “API styles.”</p><p>They are a tool, not a philosophy.</p><h3>The Real Reason People Mix All of This Up</h3><p>Because they conflate <strong>three different layers</strong>.</p><h3>1. API Architectural Style (the philosophy)</h3><ul><li>REST</li><li>RPC / gRPC</li><li>SOAP</li><li>GraphQL</li><li>Event-driven APIs</li></ul><h3>2. Transport (the pipe)</h3><ul><li>HTTP</li><li>HTTP/2</li><li>WebSocket</li><li>TCP</li></ul><h3>3. Interaction Pattern (the behavior)</h3><ul><li>Request–response</li><li>Streaming</li><li>Pub/Sub</li><li>Webhooks</li></ul><p>Once you separate these, <strong>API discussions stop being confusing instantly</strong>.</p><h3>The Clean, Correct Mental Model (Tattoo This)</h3><ul><li>REST → state transfer</li><li>RPC / SOAP → behavior execution</li><li>GraphQL → client-defined data shape</li><li>Event-driven → reaction to events</li></ul><p>And separately:</p><ul><li>WebSocket → transport</li><li>Webhooks → delivery pattern</li></ul><p>If something doesn’t define <em>how clients conceptually interact with servers</em>, it is not an API style.</p><h3>Final Takeaway</h3><p>Most confusion around APIs doesn’t come from complexity — it comes from sloppy categorization.</p><p>REST, RPC, SOAP, GraphQL, and event-driven APIs are <strong>architectural philosophies</strong>.<br>WebSockets and Webhooks are <strong>tools used inside those philosophies</strong>.</p><p>Once you stop mixing layers, you stop arguing semantics and start designing systems that actually make sense.</p><p>And yes — <br>if your URL reads like a function name, you’ve built RPC over HTTP.<br>Own it. Just don’t call it REST ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f07c99680c4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalability in System Design]]></title>
            <link>https://medium.com/@mr.shrihari212/scalability-in-system-design-08979eaff115?source=rss-534e115afa2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/08979eaff115</guid>
            <dc:creator><![CDATA[Shrihari (Harry)]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 08:38:41 GMT</pubDate>
            <atom:updated>2026-02-08T08:38:41.569Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fkt4_usAiI7ASChYCQJccg.png" /></figure><p>Most people talk about scalability as if it’s just:</p><blockquote><em>“Add more servers and pray.”</em></blockquote><p>And yes — that works.<br>Right up until it doesn’t.</p><p>Then your database melts, your queues explode, latency graphs look like heart attacks, and someone confidently suggests:</p><blockquote><em>“Let’s just increase the timeout.”</em></blockquote><p>That suggestion is not a solution.<br>It is a cry for help.</p><p>Scalability is not a single feature.<br>It is not a cloud checkbox.<br>And it is absolutely <strong>not</strong> something you bolt on after launch.</p><p>Scalability is a <strong>sequence of architectural constraints</strong> that determines how a system behaves as load grows. If those constraints are wrong, no amount of hardware will save you.</p><p>This article explains scalability the way real systems experience it — <strong>step by step, failure by failure</strong>.</p><h3>What Scalability Actually Means (And What It Doesn’t)</h3><p>Scalability is the ability of a system to handle <strong>increasing load</strong> by adding resources in a <strong>predictable and cost-effective</strong> way.</p><p>Predictable is the key word.</p><p>A system that handles 10× traffic today but collapses at 12× tomorrow is <strong>not scalable</strong>.<br>A scalable system degrades <strong>gradually</strong>, not catastrophically.</p><p>Scalability is not about peak performance.<br>It’s about <strong>controlled growth under pressure</strong>.</p><h3>The Only Two Ways to Scale (Yes, Only Two)</h3><p>There are exactly <strong>two</strong> ways to scale a system.</p><p>Anyone claiming a third is selling buzzwords.</p><h3>1. Vertical Scaling (Scale Up)</h3><p>You make <strong>one machine stronger</strong>:</p><ul><li>More CPU cores</li><li>More RAM</li><li>Faster disks (SSD → NVMe)</li></ul><p>Teams start here because it’s simple and mostly invisible to the codebase.</p><p>But it fails long-term because:</p><ul><li>Hardware has physical limits</li><li>Upgrades often require downtime</li><li>One machine becomes a massive single point of failure</li></ul><p>Vertical scaling <strong>delays</strong> the problem.<br>It never eliminates it.</p><h3>2. Horizontal Scaling (Scale Out)</h3><p>You add <strong>more machines</strong> and distribute the load.</p><p>This is where real scalability begins — and where naïve designs go to die.</p><p>The moment you scale horizontally, you inherit new questions:</p><ul><li>Which server handles which request?</li><li>Where does user state live?</li><li>How do machines stay consistent?</li></ul><p>These questions define everything that follows.</p><h3>Part 1: Load Balancers and Cloned Application Servers</h3><p>Once you scale horizontally, traffic must be distributed.<br>That’s the job of a <strong>load balancer</strong>.</p><p>The load balancer sits in front of your application servers and routes requests using strategies like:</p><ul><li>Round robin (simple, often wrong)</li><li>Least connections</li><li>Weighted routing</li></ul><p>But the load balancer introduces a brutal truth:</p><blockquote><strong><em>A user can hit a different server on every request.</em></strong></blockquote><p>If that sentence scares you — good. You’re paying attention.</p><h3>The Golden Rule of Scalability</h3><blockquote><strong><em>Application servers must be stateless and identical.</em></strong></blockquote><p>This is not a suggestion.<br>This is not “best practice.”<br>This is a law.</p><p>Stateless means:</p><ul><li>No sessions in local memory</li><li>No user data on local disk</li><li>No server-specific logic</li></ul><p>Any request → any server → same result.</p><p>The moment a server’s identity matters, horizontal scaling breaks.</p><h3>Session Management: Where Beginners Accidentally Kill Scalability</h3><p>Sticky sessions try to route the same user to the same server.</p><p>It sounds convenient.<br>It is also fragile.</p><p>If that server dies, the session dies.<br>Congratulations — you just reintroduced a single point of failure.</p><p>The fix is simple and unavoidable:</p><blockquote><strong><em>Sessions must live outside the application servers.</em></strong></blockquote><p>Typically in Redis.</p><p>Why Redis?</p><ul><li>Shared across all servers</li><li>Extremely fast (in-memory)</li><li>Supports persistence if needed</li></ul><p><strong>Key rule:</strong><br>External storage means <strong>not on the app server</strong>. Ever.</p><h3>Immutable Infrastructure: How You Prevent Server Snowflakes</h3><p>Once you have many servers, a new problem appears:</p><blockquote><em>“How do we ensure every server runs the same code and configuration?”</em></blockquote><p>Manual setup fails immediately.<br>SSH-based fixes fail quietly.<br>Environment drift becomes your silent killer.</p><p>The solution is <strong>immutable infrastructure</strong>.</p><p>You build a golden image (for example, an AMI) containing:</p><ul><li>OS</li><li>Dependencies</li><li>Configuration</li><li>Application code</li></ul><p>Every server is a clone of that image.</p><p>No patching.<br>No fixing live servers.<br>Deployments mean <strong>replace, not modify</strong>.</p><p>This is how horizontal scaling stays predictable.</p><h3>Part 2: The Database — Where Scalability Gets Real</h3><p>Application servers scale easily.</p><p>Databases do not.</p><p>As traffic grows:</p><ul><li>Reads increase</li><li>Writes increase</li><li>Locks appear</li><li>Latency spikes</li></ul><p>Eventually, the database becomes the bottleneck — <strong>every single time</strong>.</p><h3>First Response: Replication</h3><p>The classic approach:</p><ul><li>Writes go to a primary</li><li>Reads go to replicas</li></ul><p>This improves <strong>read throughput</strong>.</p><p>It does <strong>nothing</strong> for write scalability.</p><p>The primary remains a choke point.</p><h3>Second Response: Denormalization</h3><p>Joins are expensive at scale.</p><p>So you remove them.</p><ul><li>Duplicate data intentionally</li><li>Push joins into application code</li><li>Accept weaker consistency for better performance</li></ul><p>Denormalization is not bad design.<br>It is a <strong>scalability trade-off</strong>.</p><h3>The Inevitable Endgame: Sharding</h3><p>When write throughput exceeds a single machine, sharding becomes unavoidable.</p><p>You partition data across nodes:</p><ul><li>By user ID</li><li>By region</li><li>By hash</li></ul><p>Sharding shifts complexity into the application layer — routing, rebalancing, and cross-shard queries.</p><p>But once you reach large scale:</p><blockquote><strong><em>Sharding is not optional. It is inevitable.</em></strong></blockquote><h3>Part 3: Cache — The Mandatory Accelerator</h3><p>Even a well-scaled database is too slow for high-volume reads.</p><ul><li>Disk I/O is expensive</li><li>Network hops add latency</li><li>Repeated reads waste resources</li></ul><p>So we introduce <strong>cache</strong>.</p><h3>Cache as a Buffer Layer</h3><pre>Application → Cache → Database</pre><ul><li>Database = source of truth</li><li>Cache = disposable accelerator</li></ul><p>This is not optional at scale.<br>It’s survival.</p><h3>What You Cache Matters More Than How You Cache</h3><h4>Bad Pattern: Caching Raw Database Queries</h4><ul><li>Cache SQL results</li><li>Keys tied to query strings</li><li>Invalidation is painful</li><li>Schema changes break everything</li></ul><p>This pattern does not age well.</p><h4>Correct Pattern: Object-Level Caching</h4><p>You cache <strong>fully assembled domain objects</strong>.</p><p>Examples:</p><ul><li>user:123</li><li>product:456</li></ul><p>The application builds the object once, stores it, and serves it directly.</p><p>Why this works:</p><ul><li>Stable keys</li><li>Simple invalidation</li><li>Decoupled from schema</li><li>Matches application logic</li></ul><p>Production systems cache <strong>objects</strong>, not rows.</p><h3>Cache Behavior: Cache-Aside</h3><p>The application explicitly controls the cache:</p><ul><li>Read from cache</li><li>On miss, read DB and populate cache</li><li>Invalidate when data changes</li></ul><p>If the cache dies, the system still works — just slower.</p><p>That’s exactly what you want.</p><h3>Part 4: Asynchronism — Stop Blocking the Request Path</h3><p>Scalability collapses when slow work blocks user requests.</p><p>If something is slow, it should <strong>not</strong> be synchronous.</p><p>There are two fundamental async models.</p><h3>1. Precomputation</h3><p>You do work <strong>before users ask for it</strong>:</p><ul><li>Pre-render pages</li><li>Precompute aggregates</li><li>Serve via CDN</li></ul><p>This shifts computation from runtime to background time and enables massive read scalability.</p><h3>2. Queue-Based Asynchronous Processing</h3><p>For unpredictable or user-specific work:</p><ul><li>Accept request</li><li>Enqueue job</li><li>Respond immediately</li><li>Process in background</li></ul><p>Queues protect the system under load and allow horizontal scaling via workers.</p><p>If it’s slow, unreliable, or expensive — it belongs in a queue.</p><h3>The Correct Mental Model</h3><p>Scalability is about predictable growth.<br>Predictable growth requires horizontal scaling.<br>Horizontal scaling introduces distribution.<br>Distribution introduces state problems.<br>State problems require caching and asynchronism.<br>Growth eventually forces data partitioning.</p><p>Everything else exists to keep the system alive after that.</p><h3>Final Takeaway: What Scalability Really Demands</h3><p>Scalability is not a tool you install, a framework you adopt, or a cloud feature you enable.</p><p>It is a <strong>long chain of architectural decisions</strong> that starts earlier than most teams expect and becomes brutally expensive to change later.</p><p>Scalable systems begin with <strong>stateless application servers</strong>, which force you to confront where state lives.<br>That leads naturally to <strong>externalized state</strong>, which creates pressure on databases.<br>Databases hit limits, which forces <strong>caching</strong>, <strong>asynchronous processing</strong>, and eventually <strong>data partitioning</strong>.</p><p>None of these steps are optional at scale.<br>They are not trends. They are consequences.</p><p>Designing for scalability early is not about optimizing for traffic you don’t have.<br>It’s about <strong>avoiding architectural choices that make growth impossible</strong>.</p><p>You don’t build scalability by predicting the future.<br>You build it by choosing structures that <strong>don’t collapse when the future arrives</strong>.</p><p>That is the difference between a system that grows calmly under load — and one that panics, fragments, and fails the moment success shows up.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08979eaff115" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your React SPA Might Look Like a Ghost Town After Deploying to S3 + CloudFront and How to Fix…]]></title>
            <link>https://medium.com/@mr.shrihari212/why-your-react-spa-might-look-like-a-ghost-town-after-deploying-to-s3-cloudfront-and-how-to-fix-fc98712fc81e?source=rss-534e115afa2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc98712fc81e</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[react-app-deployment]]></category>
            <category><![CDATA[static-hosting]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[single-page-applications]]></category>
            <dc:creator><![CDATA[Shrihari (Harry)]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 05:02:56 GMT</pubDate>
            <atom:updated>2025-12-11T06:09:06.295Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Your React SPA Might Look Like a Ghost Town After Deploying to S3 + CloudFront and How to Fix It Like a Pro</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*aGCl3BPRYC40Hwa8muWKOQ.png" /></figure><p>If you’ve ever deployed your React app to S3 + CloudFront, only to refresh the page and see… nothing, welcome to the club. You’ve just experienced the infamous <em>blank page after deploy</em> syndrome. Don’t worry, you’re not cursed; you’re just missing a few deployment best practices that every industry developer swears by. Let’s dig in with some honesty, and zero fluff.</p><h3>1. The Problem in Plain English</h3><p>Your SPA is special. It’s modern. It’s client-side. It’s React. That’s all great — until your browser, CloudFront, or some overzealous caching decides to mess things up.</p><p>Here’s the scenario:</p><ol><li>You deploy v10 of your app. CloudFront caches the old index.html somewhere across the globe.</li><li>You delete old JS/CSS assets in S3 to be “clean and efficient.”</li><li>A user hits your site before caches refresh.</li><li>CloudFront serves stale index.html, which references JS/CSS that no longer exist.</li><li>Blank page. Panic. Tears.</li></ol><p>Welcome to SPA deployment hell. This isn’t a React bug. It’s a feature. Well, a feature in the universe conspiring against first-time visitors.</p><h3>2. Why Hashing Alone Isn’t Enough</h3><p>You might think, “Ah! If I just hash my JS/CSS filenames, I’m golden.”</p><p>Not quite. Hashed assets help <strong>cache-busting</strong>, yes, but if you delete old hashed files too early, your freshly minted index.html can’t find them. That’s exactly what causes the blank page problem.</p><p>Industry wisdom: <strong>Don’t delete old build files immediately.</strong> Ever seen those Reddit threads where people lose their minds over --delete in aws s3 sync? Yeah, that.</p><h3>3. The Industry-Approved Fix: Service Workers + Versioned Builds + No-Cache index.html</h3><p>Here’s where we stop crying and start engineering.</p><h3>Step 1: Versioned Folders for Builds</h3><p>Every build gets its own timestamped folder in S3:</p><pre>/builds/2025-12-11-09-00-abc123/<br>/builds/2025-12-11-14-30-def456/</pre><p>index.html references <strong>only the newest build folder</strong>. This is automatic — your build tool (Vite, Webpack, etc.) injects the correct paths during build. CloudFront serves index.html and suddenly, magic: latest assets everywhere.</p><h3>Step 2: No-Cache Policy for index.html</h3><p>Set <strong>Cache-Control: no-cache</strong> for index.html. This ensures CloudFront always fetches the latest version instead of serving a stale copy from edge caches. Trust me, this tiny step avoids a lot of tears and late-night panics.</p><h3>Step 3: Service Worker Update Flow</h3><p>Install a service worker to handle <strong>asset caching</strong> and <strong>update notifications</strong>. When a new deployment is live, the service worker can prompt users:</p><blockquote><em>“Hey buddy, there’s a shiny new version. Click update or live in your legacy world.”</em></blockquote><p>This prevents blank screens for returning users and avoids the “why is everything gray” panic.</p><h3>Step 4: Retain a Few Old Builds</h3><p>Instead of blindly deleting old builds after 24 hours (which could break the first-time visitors), keep the <strong>last 3–5 builds</strong>. Old users can still fetch their assets, new users get the latest. Automation via CI/CD scripts is the cleanest approach. S3 lifecycle rules alone can’t do this intelligently.</p><h3>Step 5: CloudFront Invalidations</h3><p>Invalidate only index.html (or relevant files) so that all edges serve the newest build reference. Don’t invalidate every JS file — that’s overkill and expensive.</p><h3>4. Enter Artifactory (Yes, Big Tech Actually Uses This)</h3><p>Curious about how companies like Netflix, Amazon, and Shopify avoid deployment chaos at scale? Meet <strong>Artifactory</strong>. It’s basically a highly organized warehouse for all your build artifacts — your JS/CSS bundles, Docker images, or any static assets.</p><ul><li><strong>Version control for builds:</strong> No more guessing which folder is live.</li><li><strong>Immutable storage:</strong> Once uploaded, artifacts don’t change. Perfect for reproducibility.</li><li><strong>CDN-ready distribution:</strong> Artifactory + S3/CloudFront allows serving builds reliably across global users.</li></ul><p>Hint: even if you’re just doing SPA hosting on S3 today, thinking about versioned builds and artifact repositories is how pros scale deployments without pain.</p><h3>5. Why This Works</h3><ol><li><strong>New builds live in their own folder</strong> → no overwriting, no accidental deletion.</li><li><strong>Index.html always points to the newest folder</strong> → CloudFront edge caches are happy.</li><li><strong>Old builds still exist</strong> → first-time visitors never hit 404s.</li><li><strong>Service Worker handles updates for returning users</strong> → seamless experience.</li><li><strong>No-cache index.html</strong> → CloudFront never serves stale references.</li></ol><p>In short: nobody gets a blank screen, and your sanity remains intact.</p><h3>6. TL;DR</h3><ul><li>SPAs + static hosting = caching + deploy pain.</li><li>Don’t delete old hashed JS/CSS immediately.</li><li>Use <strong>versioned build folders</strong> for S3 deployments.</li><li>Apply <strong>no-cache</strong> to index.html.</li><li>Service workers manage updates and keep users from staring at blank screens.</li><li>Keep the last 3–5 builds. Automate cleanup in CI/CD.</li><li>Invalidate index.html only, not everything.</li><li>Consider Artifactory for scalable artifact management.</li></ul><p>Follow this, and your React SPA deployment will be smoother than a freshly brewed espresso — no ghost pages, no panicked Slack messages at 2 AM, just happy users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc98712fc81e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clear Thinking: A Fast, Clear, and Useful Summary for Everyday Decisions]]></title>
            <link>https://medium.com/@mr.shrihari212/clear-thinking-a-fast-clear-and-useful-summary-for-everyday-decisions-b43a70ef6092?source=rss-534e115afa2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b43a70ef6092</guid>
            <category><![CDATA[book-summary]]></category>
            <category><![CDATA[clear-thinking]]></category>
            <category><![CDATA[shane-parrish]]></category>
            <dc:creator><![CDATA[Shrihari (Harry)]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 10:01:03 GMT</pubDate>
            <atom:updated>2025-12-02T11:06:21.419Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Clear Thinking by Shane Parrish" src="https://cdn-images-1.medium.com/max/993/1*ccTfPxK6JHO_ym9hj6RJdw.jpeg" /></figure><p><em>Based on the book </em><strong><em>Clear Thinking</em></strong><em> by Shane Parrish</em></p><p>Let’s be honest: most of us <em>intend</em> to read life-changing books, but then life changes our plans. Meetings happen. Slack pings. Instagram wins. And suddenly that 289-page book you planned to get through… slips into the background of your screen.</p><p>This article exists to save you from that fate.</p><p>What follows is a clean, practical summary of <strong>Clear Thinking</strong> — built from direct lines and ideas inside the book, so even if you don’t have the time to read every chapter, you still walk away with the core principles intact.</p><h3>Why Clear Thinking Matters</h3><p>The biggest idea in the book is simple:<br> <strong>Winning isn’t about brilliance — it’s about avoiding stupidity.</strong></p><p>“While the rest of us are chasing victory, the best in the world know they must avoid losing before they can win.”</p><p>Clear thinking begins by creating <em>space</em> — space in your thoughts, feelings, and actions — and then using that space deliberately. Because “all the successful execution in the world is worthless if it’s not in service of the right outcome.”</p><p>And what determines your future?<br> Not the big, dramatic moments — but the ordinary ones.<br> “Each moment puts you in a better or worse position to handle the future.”</p><h3>The Enemies of Clear Thinking</h3><h3>1. Ego: The Master Saboteur</h3><p>Ego convinces us we’re smarter, safer, and more prepared than we are.</p><p>“Our ego tempts us into thinking we’re more than we are.”<br> It turns confidence into overconfidence and overconfidence into arrogance.<br> It whispers, <em>“You’ve read two articles on this… you’re basically an expert.”</em></p><p>Unearned knowledge rushes us to judgment.<br> We become obsessed with looking great instead of being great.</p><p>And when criticized?<br> “No thoughts, just pure animal instinct.”</p><p>If you find yourself constantly trying to prove you’re right, struggling to say “I don’t know,” or feeling wounded by minor slights — ego is driving.</p><h3>2. The Social Default</h3><p>We hate looking bad. Lou Brock said it best:<br> “Show me a guy who’s afraid to look bad, and I’ll show you a guy you can beat every time.”</p><p>When you fear disappointing people, fear being an outsider, or dread social scorn — the social default is in charge.</p><h3>3. The Inertia Default</h3><p>Starting is hard. Stopping is hard. Staying average is easy.</p><p>“Inertia keeps us in jobs we hate and in relationships that don’t make us happy.”<br> We stay because the pain isn’t enough to force action — the “zone of average.”</p><p>And over time, we become what we’re near.<br> “You unconsciously adopt the habits of the people you spend time with.”</p><p>Which means environment beats willpower, every time.</p><h3>Building the Foundation: The Four Internal Strengths</h3><p>Parrish focuses heavily on four strengths you must develop:</p><ol><li><strong>Self-accountability</strong> — “Complaining is not a strategy.” You control your response, not the world.</li><li><strong>Self-knowledge</strong> — know your strengths, your weaknesses, and what you’re actually capable of.</li><li><strong>Self-control</strong> — treat emotions “as if they were inanimate objects.”</li><li><strong>Self-confidence</strong> — the courage to focus on what’s right instead of who’s right.</li></ol><p>Confidence isn’t loud. Confidence is the willingness to look stupid temporarily in pursuit of improvement.</p><h3>Your Environment Is Your Destiny</h3><p>We absorb the attitudes, standards, and habits around us.<br> “If you work for a jerk, sooner or later you’ll become one.”</p><p>This is why the book emphasizes exemplars:<br> “Show me your role models and I’ll show you your future.”</p><p>Greatness comes from choosing the right models, studying them, and imitating the tiny things they do well.</p><p>“Champions don’t create the standard of excellence. The standard of excellence creates champions.”</p><h3>Better Decisions: Process Over Ego</h3><p>A major theme of <strong>Clear Thinking</strong> is that most of us don’t know how to make real decisions.</p><p>We confuse <em>choices</em> with <em>decisions</em>.</p><ul><li>A <strong>choice</strong> is casual.</li><li>A <strong>decision</strong> is “a judgment that a certain option is the best one,” built from a process:</li></ul><ol><li>Define the problem</li><li>Explore solutions</li><li>Evaluate options</li><li>Execute</li></ol><p>If you skip the process, you didn’t decide — you just reacted.</p><h3>Good decisions come from writing things down</h3><p>“When you write out the problem, you make the invisible visible.”</p><p>If your explanation is full of jargon, you don’t understand it well enough to decide on it.</p><h3>Avoiding Bad Decisions</h3><ul><li>Use second-level thinking: “And then what?”</li><li>Force yourself to find <strong>three</strong> solutions (the 3+ principle)</li><li>Consider opportunity costs through three lenses:</li><li>Compared with what?</li><li>And then what?</li><li>At the expense of what?</li></ul><h3>Outcome ≠ Quality</h3><p>“Resulting” — judging decisions by their outcomes — is a mental trap.</p><p>“One bad outcome doesn’t make you a poor decision-maker any more than one good outcome makes you a genius.”</p><p>The goal is consistent <em>process</em>, not constant perfection.</p><h3>Handling Mistakes the Right Way</h3><p>Most people fail not because of the first mistake, but the second one — the cover-up.</p><p>There are four steps to dealing with mistakes:</p><ol><li>Accept responsibility</li><li>Learn from the mistake</li><li>Commit to doing better</li><li>Repair the damage</li></ol><p>“Mistakes turn into anchors if you don’t accept them.”</p><p>The inner story you tell yourself becomes either your freedom or your prison.</p><h3>Action: Where Clear Thinking Actually Comes Alive</h3><p>Knowing what to do isn’t enough.</p><p>“There is no purpose to knowing what you should do and not doing it.”</p><p>Fear is the biggest blocker: fear of consequences and fear of being wrong.</p><p>Use these principles:</p><ul><li><strong>ASAP principle:</strong> if it’s easy to undo, act fast.</li><li><strong>ALAP principle:</strong> if it’s costly to undo, act as late as possible.</li><li><strong>STOP/FLOP/KNOW:</strong> stop when no new info comes, when you miss your first opportunity, or when you realize what’s right.</li></ul><p>And remember the power of optionality:<br> Sometimes the smartest person is the one who <em>waits</em>, even if everyone thinks they’re foolish.</p><h3>Margin of Safety: Protect Your Future Self</h3><p>A margin of safety is “a buffer between what you expect to happen and what could happen.”</p><p>As a rule of thumb:<br> Prepare to withstand <strong>double</strong> your worst-case scenario.</p><p>It feels wasteful when life is good — but priceless when life isn’t.</p><h3>What Actually Makes Life Worth Living</h3><p>The book closes with a shift from decision-making to meaning.</p><p>We spend life chasing money, status, and recognition — and we end up unhappy.</p><p>“Comparison is the thief of joy.”</p><p>Happiness isn’t conditional. It’s a choice.<br> A choice to prioritize what matters.</p><p>The best advice from elders?</p><ul><li>Say what you need to say <em>now</em>.</li><li>Spend time with your children.</li><li>Savor daily pleasures.</li><li>Work a job you love.</li><li>Choose your partner carefully.</li></ul><p>The small, ordinary moments matter more than the big wins.</p><p>As Steve Jobs famously put it:<br> “Remembering that you are going to die is the best way I know to avoid the trap of thinking that you have something to lose.”</p><p>When you imagine your older self looking back, clarity appears.<br> Wisdom is “turning your future hindsight into your current foresight.”</p><h3>Final Thoughts</h3><p>Clear Thinking isn’t a book about getting smarter — it’s a book about getting out of your own way.</p><ul><li>Remove ego</li><li>Resist defaults</li><li>Build strong habits</li><li>Choose exemplars</li><li>Follow a decision-making process</li><li>Take action</li><li>Build a margin of safety</li><li>And above all, decide <em>what actually matters</em> in your life</li></ul><p>Because “you can’t win if you don’t survive,” and you can’t live a meaningful life if you’re busy chasing things that don’t matter.</p><p>If you’re short on time, think of this article as the essentials.<br>If you can spare the time, the full book is absolutely worth reading — your future self will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b43a70ef6092" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying React in 2025: Developer’s Guide to Not Ruining Production]]></title>
            <link>https://medium.com/@mr.shrihari212/deploying-a-react-application-safely-from-rookie-mistakes-to-best-practices-3abee0f4a8ce?source=rss-534e115afa2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3abee0f4a8ce</guid>
            <category><![CDATA[deployement]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[frontend-development]]></category>
            <dc:creator><![CDATA[Shrihari (Harry)]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 12:25:19 GMT</pubDate>
            <atom:updated>2025-11-28T17:11:14.737Z</atom:updated>
            <content:encoded><![CDATA[<p>Note: This article focuses on deploying React applications using static hosting setups like S3 + CDN. Other platforms may differ in caching, security, and deployment behavior. Those will be covered in a separate article.</p><p>Let’s talk about React deployments. Not the “drag-and-drop my build folder somewhere and hope the CDN is in a good mood today” style. The real, reproducible, secured, battle-tested kind that prevents embarrassing outages, leaked tokens, and frantic coffee-fueled debugging at 3 AM.</p><h3>Why This Topic Matters: A Short History of Real Attacks</h3><p>If you think modern frontend deployments are immune to supply-chain attacks, the last two years should have convinced you otherwise. A few reminders:</p><h3>Shai-Hulud 2.0</h3><p>A highly automated npm supply-chain attack that weaponized preinstall and postinstall scripts across compromised packages. Anyone installing an affected dependency unknowingly executed malicious code. The payload didn’t just run locally; it attempted to steal access tokens, CI secrets, and environment variables. Even secrets stored securely inside GitHub Actions were exfiltrated once the workflow executed an infected package. It spread absurdly fast because every downstream project that installed the tainted package became a new infection point.</p><h3>The September 2025 npm Maintainer Compromise</h3><p>Attackers phished a crypto-related library maintainer, pushed backdoored versions, and poisoned updates used by millions of downloads per week. Though the payload targeted browser-based transactions, the underlying mechanism was the same: trust a compromised dependency, run malicious install scripts, and watch the dominoes fall.</p><p>These aren’t theoretical risks. They are real-world incidents that required nothing more than installing an npm package the wrong day of the week.</p><h3>What Senior Developers Actually Do: A Proper Deployment Strategy</h3><p>Below is a complete set of best practices covering build pipelines, supply-chain safety, hosting, caching, observability, and defensive configuration. This is how you deploy a React application without gambling your production environment away.</p><h3>1. Dependency and Build Hardening</h3><ul><li>Always use npm ci and not justnpm installin CI/CD to ensure deterministic installs. No version drift, no silent dependency surprises.</li><li>Disable all lifecycle scripts during CI builds. Malicious preinstall or postinstall scripts are a common attack vector. Your .npmrc in CI should include:</li></ul><pre>ignore-scripts=true <br>registry=https://registry.npmjs.org/ <br>strict-ssl=true</pre><ul><li>Pull only from the official npm registry. Do not trust mirrors or custom registries unless strictly audited.</li><li>Avoid floating versions. Pin your dependencies or at least review updates before applying them.</li></ul><h3>2. Secrets and Credential Safety</h3><ul><li>Never store API keys, tokens, or credentials inside frontend bundles. DevTools exists. People use it.</li><li>Use GitHub Actions secrets, AWS Parameter Store, HashiCorp Vault, or any managed secrets service.</li><li>Ensure CI logs do not accidentally leak environment variables.</li><li>Rotate sensitive tokens regularly and immediately on any suspicious activity.</li></ul><h3>3. CI/CD Workflow Quality</h3><ul><li>Run automated tests before deployment: unit tests, integration tests, and even E2E if your stack supports it.</li><li>Use build caching to speed up pipelines, but still rebuild dependencies cleanly.</li><li>Store versioned build artifacts. If someone asks “what exactly shipped last Thursday,” you should have an answer.</li><li>Implement automatic rollback mechanisms. Bad builds happen. Good pipelines recover quickly.</li></ul><h3>4. Static Hosting and CDN Deployment</h3><ul><li>Use hashed filenames to avoid stale asset caching. Files like main.a1b2c3.js ensure browsers pick up new builds automatically.</li><li>Invalidate CDN caches or use versioned paths on deployment. Without this, half your users will run the old build and half the new one.</li><li>Enable Brotli or Gzip compression for smaller bundle delivery.</li><li>Ensure content types and cache headers are correctly configured, especially with S3-style hosting.</li></ul><h3>5. Performance and Observability</h3><ul><li>Use code splitting and lazy loading to reduce initial load time.</li><li>Apply route-based chunking where appropriate.</li><li>Integrate client-side error tracking, such as Sentry or LogRocket, to catch issues immediately after release.</li><li>Monitor key metrics such as TTFB, asset load times, and JavaScript execution overhead.</li><li>Log client-side errors centrally for debugging.</li></ul><h3>6. Security Headers and Browser Safety</h3><ul><li>Enforce HTTPS for all traffic, including redirects.</li><li>Enable HSTS to force secure connections.</li><li>Add Content Security Policy (CSP) headers to prevent XSS and malicious script injection.</li><li>Set proper caching rules, CORS configurations, and MIME type protections.</li></ul><h3>7. Dependency Audits and Ongoing Monitoring</h3><ul><li>Run npm audit, Dependabot, or Snyk regularly. Do not allow critical vulnerabilities to pile up.</li><li>Check the health of new dependencies: commit frequency, maintainer activity, number of maintainers, package age, and audit history.</li><li>Remove unused dependencies. Every extra package is one more potential liability.</li></ul><h3>8. Reproducibility and Traceability</h3><ul><li>Always build in CI. Never ship builds compiled on a developer laptop.</li><li>Never manually modify node_modules. If you need a patch, use patch-package or fork responsibly.</li><li>Keep deployment logs, commit references, and version tags traceable.</li><li>Ensure all build and deployment steps are codified and not tribal knowledge inside someone’s head.</li></ul><h3>Why None of This Is Optional</h3><p>React deployments today sit at the intersection of frontend engineering, DevOps, and supply-chain security. Your bundle may be static, but the ecosystem around it is not. One compromised dependency update, one misconfigured CDN cache, or one careless secret leak is all it takes for a production incident.</p><p>Doing this right means:</p><ul><li>deterministically building,</li><li>preventing script execution,</li><li>isolating secrets,</li><li>properly caching and versioning assets,</li><li>and continuously monitoring for vulnerabilities.</li></ul><p>This is the difference between a stable, secure, reproducible deployment pipeline and a “works on my machine, explodes on everyone else’s machine” scenario.</p><h3>Closing Thoughts</h3><p>A React app running on S3 + CDN can be incredibly reliable and cost-efficient, but only if you deploy it with discipline. Follow the practices above and you’ll avoid the rookie mistakes that keep resurfacing in production teams everywhere.</p><p>In a follow-up article, I’ll cover alternatives such as containerized deployments, SSR pipelines, multi-environment CI/CD strategies, and advanced caching patterns for larger applications.</p><p>If you want that version, just say the word.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3abee0f4a8ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>