<?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 Sushil Maurya on Medium]]></title>
        <description><![CDATA[Stories by Sushil Maurya on Medium]]></description>
        <link>https://medium.com/@sushilm2011?source=rss-b21fc82d0b53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RQNpy0OLZKHwzFyasKd4KQ.png</url>
            <title>Stories by Sushil Maurya on Medium</title>
            <link>https://medium.com/@sushilm2011?source=rss-b21fc82d0b53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 18:42:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sushilm2011/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[Clean Code Won’t Save You. Clear Thinking Will.]]></title>
            <link>https://levelup.gitconnected.com/clean-code-wont-save-you-clear-thinking-will-77d43d7b7593?source=rss-b21fc82d0b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/77d43d7b7593</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sushil Maurya]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 04:56:59 GMT</pubDate>
            <atom:updated>2026-04-06T04:58:57.929Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI didn’t break software engineering. It exposed what we were avoiding.</h4><p>A few years ago, <strong><em>clean code</em></strong> felt like the answer to everything.</p><p>Better naming.<br>Better structure.<br>Better readability.</p><p>We believed if the code looked right, the system would be right.</p><p>It felt… safe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JM4NpAQBCnrOYXo9fqn2tw.png" /></figure><p>Then AI showed up.</p><p>Suddenly, writing clean code wasn’t a skill anymore.<br><strong>It was a <em>commodity</em>.</strong></p><p>You describe something vaguely — and within seconds, you get code that looks like it belongs in production.</p><p>Well-formatted.<br>Well-structured.<br>Even <strong><em>best practice</em></strong>.</p><p>And yet…<br>something feels off.</p><h3>The Shift No One Talks About</h3><p>For the first time, we’re seeing something uncomfortable:</p><blockquote><strong>You can have perfectly clean code… and still build the wrong system.</strong></blockquote><p>AI didn’t introduce this problem.<br>It just removed the effort that used to hide it.<br>Before, <em>writing code was slow enough to force thinking.</em><br>Now, you can skip thinking entirely — and still produce something that looks correct.</p><p>That’s the real shift.</p><h3>The One-Line Truth</h3><p><em>Clean code is about </em><strong>how it looks</strong><em><br>Clear thinking is about </em><strong>whether it should exist</strong></p><p>AI is excellent at the first.<br>It depends on <strong><em>you</em></strong> for the second.</p><h3>Where Things Quietly Go Wrong</h3><p>The scary part isn’t obvious bugs.<br>It’s systems that look right… but slowly drift into confusion.</p><p>Three patterns that are becoming common:</p><h4>1. Everything Looks Right — Until It Doesn’t</h4><p>You give a vague prompt.<br>AI fills the gaps confidently.<br>It creates APIs, models, flows — all clean, consistent, reasonable.<br>But the assumptions are slightly off.<br>Nothing breaks immediately.</p><p>But over time:</p><ul><li>responsibilities blur</li><li>data lives in the wrong places</li><li>logic starts leaking across boundaries</li></ul><p>And fixing it later feels <strong><em>harder than building it from scratch</em></strong>.<br>Again AI can help you build the wrong system from scratch again.</p><h4>2. Complexity That Feels Justified</h4><p>AI loves structure.<br>Layers. Interfaces. Patterns.</p><p>So you end up with:</p><ul><li>abstractions you didn’t ask for</li><li>flexibility you don’t need</li><li>indirection you can’t explain</li></ul><p>Everything <strong><em>feels well-designed</em></strong>.<br>But it’s heavier than it should be.</p><p>And deep down, you know it.</p><h4>3. Decisions Without Memory</h4><p>AI doesn’t carry context the way you do.<br>Every prompt is a fresh start.</p><p>So over time:</p><ul><li>similar problems get solved differently</li><li>conventions drift</li><li>consistency fades</li></ul><p>And because the code is clean,<strong><em> it doesn’t look wrong</em></strong>.<br>It just becomes <strong><em>harder to understand</em></strong>.</p><h3>Where AI Actually Helps</h3><p>AI is not the problem.<br>In fact, it’s the biggest leverage we’ve ever had.<br>But only if you shift how you use it.</p><blockquote><strong>AI should write the code.<br>You should decide what deserves to be written.</strong></blockquote><p>That’s the difference.</p><h3>What This Looks Like in Practice</h3><p>Not complicated. <br>Just uncomfortable at first.</p><h4>1. Pause Before You Prompt</h4><p>Before typing anything, ask:</p><ul><li>What exactly am I building?</li><li>Where does it belong?</li><li>What should it <em>not</em> do?</li><li>What could go wrong later?</li></ul><p>Even a few lines of intent changes everything.<br>It slows you down just enough to think.</p><h4>2. Be Specific — Not Clever</h4><p><strong>Bad prompt:</strong><br><em>Build a user system</em></p><p><strong>Better:</strong><br><em>We already handle authentication.<br>This service only manages user preferences.<br>No duplication of auth data.<br>Optimized for reads.</em></p><p>AI doesn’t need creativity.<br>It needs clarity.</p><h4>3. Review Like It’s Your System (Because It Is)</h4><p>Don’t just check:</p><ul><li>naming</li><li>formatting</li><li>style</li></ul><p>Look deeper:</p><ul><li>Does this responsibility make sense here?</li><li>Is this introducing hidden coupling?</li><li>Will this still make sense in 3 months?</li></ul><blockquote><strong>If you can’t explain it, don’t accept it.</strong></blockquote><h4>4. Own the Decisions</h4><p>AI can generate code faster than you ever could.</p><p>But it cannot:</p><ul><li>understand trade-offs</li><li>anticipate future problems</li><li>take responsibility for outcomes</li></ul><p><strong><em>That part is still yours.</em></strong></p><h3>The Quiet Identity Shift</h3><p>This is the part that takes time to accept.</p><blockquote>You’re no longer valuable because you write clean code.<br>You’re valuable because you “<strong>see clearly”</strong>.</blockquote><p>Before:<br><em>I write good code</em></p><p>Now:<br><em>I make good decisions</em></p><p>It’s a subtle shift.<br>But it changes everything.</p><h3>What Changes When You Get This Right</h3><p>Not overnight. But noticeably.</p><ul><li>Less rework</li><li>Fewer “why is it built like this?” moments</li><li>Systems that stay understandable</li><li>Confidence in what you ship</li></ul><p>You don’t just move faster.<br>You feel more certain.</p><h3>Three Small Changes This Week</h3><p>No new tools needed.<br>Just different habits.</p><h4>1. Write intent before prompting</h4><p>Even 3–4 lines.<br>It forces clarity.</p><h4>2. Say no to unnecessary structure</h4><p>If you can’t justify it simply — remove it.</p><h4>3. Ask “Is this right?” — not “Is this clean?”</h4><p>That question alone changes how you review everything.</p><blockquote>Sometimes the code looks perfect.<br>And still, something feels off.<br>That feeling is important.<br>Don’t ignore it.</blockquote><h3>One question before you go:</h3><p>What’s harder for you right now — <br>Thinking clearly before prompting,<br>or saying no to code that <em>looks</em> right?</p><p>Happy Thinking. <br>Not Happy Coding ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77d43d7b7593" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/clean-code-wont-save-you-clear-thinking-will-77d43d7b7593">Clean Code Won’t Save You. Clear Thinking Will.</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Architecture That Actually Scales in 2025]]></title>
            <link>https://levelup.gitconnected.com/the-architecture-that-actually-scales-in-2025-e07ab846f75e?source=rss-b21fc82d0b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/e07ab846f75e</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sushil Maurya]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 04:16:30 GMT</pubDate>
            <atom:updated>2025-12-03T03:18:34.934Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simplicity Beats Microservices for 90% of Teams</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNGJDDZz_PetAUkjqhFtQQ.png" /></figure><p>Ask any engineer what “scaling” means and you’ll hear the same answers: break things into services, deploy independently, make everything async, add queues everywhere, and act like Google or Netflix from day one.</p><p>But here’s the quiet truth the industry doesn’t say out loud:</p><p><strong><em>Most companies serving millions of users are still running a monolith. Not because they’re outdated — but because simplicity scales better than anything else.</em></strong></p><p>Shopify runs a massive monolith.<br>GitHub runs a monolith powering over 100M developers.<br>Airbnb still has a monolithic heart.<br>Linear and Basecamp built their entire business on elegant, modular monoliths.<br>Gusto scaled to hundreds of thousands of businesses without microservices.</p><p><strong>These aren’t exceptions — they’re proof.</strong></p><p>Let’s unpack why.</p><h3>Why Monoliths Are Still Faster</h3><p>Inside a monolith, every module interacts through <strong>function calls and memory</strong>, not over a network.</p><p>A function call takes nanoseconds.</p><p>A microservice call takes:</p><ul><li>retries</li><li>load balancers</li><li>network hops</li><li>serialization/deserialization</li><li>authentication tokens between services</li><li>distributed tracing</li><li>logs</li><li>metrics</li><li>tracing</li></ul><p><em>Millions of times slower.</em></p><p>When Shopify hits Black Friday traffic or when GitHub handles millions of CI events per minute, they don’t ship those requests through a web of services — they push them through a highly-structured monolith optimized to live inside one process.</p><blockquote><strong>Performance isn’t magical. It’s physics.</strong></blockquote><p>A monolith simply uses physics in your favor.</p><h3>Your Database Is Faster Than Any Queue</h3><p>There’s a misconception that queues and streams magically scale better than a database.</p><p>Reality:</p><ul><li>A single index-optimized Postgres table can handle <strong>tens of thousands of writes per second</strong>.</li><li>A well-tuned read replica can serve <strong>millions of queries per minute</strong>.</li><li>A materialized view can rebuild thousands of denormalized rows in milliseconds.</li></ul><p>You know what’s slower?</p><p>Splitting your data across 12 microservices and hoping they all maintain consistency.</p><p>Most mature teams quietly rely on:</p><ul><li><strong>DB transactions</strong> for consistency</li><li><strong>DB row locks</strong> for state guarantees</li><li><strong>Outbox tables</strong> for async reliability</li><li><strong>Read replicas</strong> and <strong>read models</strong> for UI performance</li></ul><p>These aren’t “<em>legacy tricks.</em>”<br>They’re what large-scale systems actually use when the <strong><em>hype</em></strong> fades.</p><blockquote>Once you trust the database, scaling feels like removing handbrakes.</blockquote><h3>Boundaries Matter — Even With 5 Engineers, Let Alone 50</h3><p>A monolith is not a blob. A <strong><em>good monolith</em></strong> is —</p><p><strong>modular</strong>, <strong>composed of boundaries</strong>, and <strong>shaped like a future distributed system</strong> — without the cost.</p><pre>/modules<br>  /orders<br>  /users<br>  /payments<br>  /inventory</pre><p>Each module owns its logic.<br>Each module behaves like a mini-service.<br>Each module has clear ownership and clean contracts.</p><p>This is exactly how companies like Github/Shopify<strong> </strong>organize their monoliths — strict internal boundaries enforced through structure, not through network calls.</p><p>The structure gives you microservice-level clarity <strong>without</strong> microservice-level pain.</p><p>And for a team of 50?</p><p>It is the difference between:</p><p><em>“</em><strong><em>I know exactly where to change this</em></strong><em>”</em></p><p>and</p><p><em>“</em><strong><em>Which service owns this logic again? And who’s on call for it?</em></strong><em>”</em></p><blockquote>Microservices don’t create boundaries.<br>Boundaries create boundaries.</blockquote><p><strong><em>Boundaries create speed.<br>Speed reduces bugs.<br>Reduced bugs reduce operational load.</em></strong></p><h3>Simplicity Scales (More Than Engineers Admit)</h3><p>Most big outages in tech don’t happen because servers are slow.<br> They happen because systems are too complicated.</p><p>With microservices, each new service introduces:</p><ul><li>another deployable unit</li><li>another on-call rotation</li><li>another log stream</li><li>another tracing path</li><li>another API contract</li><li>another failure mode</li><li>another version mismatch</li></ul><p>At 5 services, it’s annoying.<br>At 20, it becomes a job.<br>At 200, you need platform staff.<br>At 500, you become Netflix — and Netflix has a separate engineering organization just to keep the system alive.</p><p>Monoliths are simple enough to reason about, fast enough to handle real traffic, and structured enough to evolve gracefully.</p><p><strong><em>Simplicity gives you speed.<br>Speed gives you leverage.<br>Leverage beats complexity.</em></strong></p><h3>Async Doesn’t Require a Distributed System</h3><p><strong><em>The Outbox Pattern Is the Secret Weapon</em></strong></p><p>You don’t need 12 microservices and a queue mesh to build asynchronous behavior. Most reliable architectures — fintechs, CRMs, trading systems, logistics apps — use a simple pattern:</p><p>The <strong>Outbox Pattern</strong>.</p><ol><li>Write business data into the DB.</li><li>In the same transaction, insert an event into outbox_events.</li><li>A background worker reads unprocessed rows and performs side effects.</li><li>Update processed_at once done.</li></ol><p>That’s it.</p><p>This tiny flow gives you:</p><ul><li>guaranteed consistency</li><li>no lost messages</li><li>exactly-once semantics</li><li>fault-tolerant side effects</li><li>simple retries</li><li>decoupled logic</li></ul><p>And it can still live inside the monolith.</p><p>This is the pattern used <strong><em>quietly</em></strong> by thousands of high-scale engineering teams — because it just works.</p><p>It’s how Shopify syncs work across systems.<br>It’s how many financial platforms generate ledger events safely.<br>It’s how modern SaaS products add features without turning synchronous flows into a mess.</p><blockquote>Async does not require microservices.<br>Async requires <strong>discipline</strong>, not <strong>distribution</strong>.</blockquote><h3>Optimizing Reads: The Secret to “Fast”</h3><p>Most performance bottlenecks are not writes — they are <em>reads</em>, especially the reads powering UI screens.</p><p>That’s why the smartest engineering teams embrace a read/write split:</p><ul><li>Writes stay normalized and correct</li><li>Reads become denormalized and fast</li></ul><p>This “M<strong>ini-CQRS</strong>” approach is used by:</p><ul><li>LinkedIn (feeds, views, messaging)</li><li>Amazon (product pages and recommendations)</li><li>Every serious financial ledger system</li><li>Shopify’s Storefront API</li><li>Airbnb’s search views</li></ul><pre>orders               → write model (normalized)<br>order_overview_view  → read model  (denormalized)</pre><p><strong><em>Reads become instant.<br>Servers breathe.<br>Users feel the difference.</em></strong></p><p><em>And again — no need for 15 services.</em></p><h3>The Small-Team Superpower: Focus</h3><p>Microservices scatter your focus.<br>A monolith concentrates it.</p><p>When everything is in one place:</p><ul><li>you debug faster</li><li>you ship features faster</li><li>you refactor safely</li><li>you onboard new engineers easily</li><li>you experiment without cross-service meetings</li><li>you spend time on product, not plumbing</li></ul><p>This is why companies like <strong>GitHub</strong> maintain incredible speed with small teams — they picked an architecture that amplifies focus instead of diluting it.</p><p>Teams under 50 engineers consistently ship faster with a monolith — and have far fewer outages.</p><p><strong>Every. Single. Time.</strong></p><h3>The Architecture That Works in 2025</h3><p>Not the trendiest.<br>Not the flashiest.<br>Not the one with the most conference talks.</p><p>But the one that:</p><ul><li>scales</li><li>stays reliable</li><li>is cheap to run</li><li>is easy to understand</li><li>is fast to iterate on</li><li>keeps teams aligned</li><li>reduces cognitive overhead</li></ul><p>Looks like this:</p><ul><li>A <strong>modular monolith</strong> with strong domain boundaries</li><li>A <strong>simple async layer</strong></li><li><strong>Read models</strong> designed for UI speed</li><li>Good indexing, transactions, and replication</li><li>And services extracted <strong><em>only when a module truly deserves independence</em></strong></li></ul><p>This is the architecture behind <strong>Shopify’s Black Friday</strong>, <strong>GitHub’s billions of requests</strong>, <strong>Airbnb’s core flows</strong>, <strong>Gusto’s payroll engine</strong>, and <strong>Linear’s silky-fast UX</strong>.</p><blockquote>It’s not old-fashioned — it’s engineering maturity.</blockquote><h3>Final Thought</h3><blockquote>Microservices are not bad — they’re just not step one</blockquote><p>Microservices are powerful.<br>They solve real problems at the right stage of growth.<br>They unlock independent scaling, team autonomy, and isolation.</p><p>But only <strong>after</strong> your domain is stable, your boundaries are clear, and your team is large enough to support the operational overhead.</p><p>For most companies:</p><blockquote><strong>The problem is not performance — it’s complexity.<br>And complexity is a self-inflicted wound.</strong></blockquote><p>A well-designed monolith avoids it.<br>A modular monolith scales past what most teams will ever need.<br>And you can always extract services later — cleanly, intentionally, and with confidence.</p><p><strong><em>Start simple.<br>Scale smart.<br>Evolve when ready.</em></strong></p><p><strong>That’s architecture that actually works in 2025.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e07ab846f75e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-architecture-that-actually-scales-in-2025-e07ab846f75e">The Architecture That Actually Scales in 2025</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Temporal 101: What It Is and Why You Should Care]]></title>
            <link>https://medium.com/@sushilm2011/temporal-101-what-it-is-and-why-you-should-care-709822260532?source=rss-b21fc82d0b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/709822260532</guid>
            <category><![CDATA[temporal]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sushil Maurya]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 04:33:46 GMT</pubDate>
            <atom:updated>2025-06-27T04:33:46.298Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Imagine</strong> building a complex application that needs to coordinate dozens of tasks — retries on failure, tracking progress, scheduling delays, and handling timeouts.<br>Now imagine doing all this <strong>without writing spaghetti code</strong>, <strong>without cron jobs</strong>, <strong>without messy retry loops</strong>, and <strong>without worrying about losing state after server crashes</strong>.</p><p><strong>Welcome to Temporal.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PP_YjX1Q4pqGsXE1nNkHLg.png" /></figure><h3>What Is Temporal?</h3><p><strong>Temporal</strong> is an open-source platform that lets you write reliable, scalable, long-running applications without worrying about:</p><ul><li>Failure recovery</li><li>Task orchestration</li><li>State persistence</li><li>Retries, timeouts, and scheduling</li></ul><p>It lets you <strong>write code like normal</strong> (in your favorite language like Go, Java, TypeScript) — but Temporal <strong>manages the execution and recovery automatically</strong> behind the scenes.</p><p>You write <em>Workflows</em> and <em>Activities</em> as simple functions, and Temporal makes sure they <strong>survive crashes, network issues, retries, delays, and even server migrations</strong> — <em>without you having to do anything extra</em>.</p><h3>Why Should You Care?</h3><p>Here’s why developers and companies are <strong>adopting Temporal</strong>:</p><ul><li>Manual retry logic everywhere: Temporal <strong>auto-retries</strong> failed tasks</li><li>Cron jobs + databases to track job states: Temporal stores <strong>workflow state</strong> natively</li><li>Hard to recover after server crash: Temporal <strong>resumes workflow</strong> exactly where it left off</li><li>Error-prone distributed systems: Temporal handles <strong>task queues, retries, timeouts automatically</strong></li><li>Workflow versioning nightmare: Temporal supports <strong>safe workflow upgrades</strong> in production</li><li>Need reliable long-running processes (weeks/months): Temporal supports <strong>workflows that last years</strong></li></ul><blockquote><strong>Temporal makes your distributed systems bulletproof.</strong></blockquote><h3>Real-World Examples of Where Temporal Shines</h3><p>Let’s make it very real:</p><ul><li><strong>Order Processing Systems: </strong>Retry failed payments, update inventory, send emails reliably</li><li><strong>Batch Jobs and Data Pipelines: </strong>Handle millions of records with retry and checkpointing</li><li><strong>Subscription Management: </strong>Handle billing cycles, send reminders, auto-cancel unpaid subscriptions</li><li><strong>IoT Device Management: </strong>Orchestrate firmware updates across thousands of devices safely</li><li><strong>Financial Services: </strong>Manage long-running trades, settlement processes, complex approvals</li></ul><h3>How Temporal Works (At a High Level)</h3><p>Here’s the <strong>core idea</strong>:</p><ul><li>You write <strong>Workflows</strong> → code that represents business processes</li><li>You call <strong>Activities</strong> → smaller units of work (e.g., API calls, database updates)</li></ul><p><strong>Temporal ensures:</strong></p><ul><li>Activities get executed</li><li>Failures are retried</li><li>Workflow state is persisted after every step</li><li>If a server dies, another worker can continue the process exactly where it left off</li><li>You don’t worry about <strong>infrastructure</strong>, <strong>state recovery</strong>, <strong>retry loops</strong>, or <strong>timers</strong> anymore.</li></ul><p>Here’s a simple mental picture:</p><pre>Temporal Server<br> ├── Workflow 1<br> │    ├── Activity A<br> │    ├── Activity B<br> │    └── Activity C<br> ├── Workflow 2<br> │    └── Activity D<br> └── ...</pre><p>The Temporal Server handles:</p><ul><li>State Management</li><li>Event History</li><li>Retry Scheduling</li><li>Task Dispatching</li><li>Failover and Recovery</li></ul><p>You just <strong>focus on writing simple, clean business logic</strong>.</p><h3>But… Is Temporal Overkill for Small Projects?</h3><p><strong>No, not necessarily.</strong></p><ul><li>If your project has retries, cron jobs, timers, or workflows — <strong>Temporal can simplify it.</strong></li><li>Even simple tasks like <strong>sending reminder emails</strong>, <strong>delayed order cancellation</strong>, or <strong>processing asynchronous approvals</strong> become easier and more reliable with Temporal.</li></ul><p>You might not <em>need</em> Temporal for a <em>tiny</em> script — but for <strong>any serious application that scales, grows, or coordinates complex steps</strong>, Temporal pays off <strong>huge dividends</strong>.</p><blockquote><strong>Temporal</strong> was actually <strong>started by the team who built Amazon SWF (Simple Workflow Service)</strong> — after learning what a modern, flexible, scalable system should really look like.</blockquote><h3>Summary: Why You Should Love Temporal</h3><ul><li><strong>Write code like normal functions</strong> → Temporal turns them into scalable, reliable workflows.</li><li><strong>Forget about crashes, retries, and failures</strong> → Temporal handles it automatically.</li><li><strong>Scale infinitely</strong> → From one worker to hundreds.</li><li><strong>Upgrade your workflows safely</strong> → With built-in versioning support.</li><li><strong>Open source, battle-tested at companies like Netflix, Coinbase, Stripe, Snap, etc.</strong></li></ul><p>If you’re building <strong>complex business systems</strong>, Temporal <strong>will make your life significantly easier</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=709822260532" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Edge Cases at the Edge: How Proxies Rewrite the Web]]></title>
            <link>https://medium.com/@sushilm2011/edge-cases-at-the-edge-how-proxies-rewrite-the-web-569170b484ac?source=rss-b21fc82d0b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/569170b484ac</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[reverse-proxy]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Sushil Maurya]]></dc:creator>
            <pubDate>Tue, 06 May 2025 04:32:35 GMT</pubDate>
            <atom:updated>2025-05-06T04:32:35.585Z</atom:updated>
            <content:encoded><![CDATA[<p>Your code works in dev. Your tests pass in staging. Then something breaks in production — and the culprit isn’t your code. It’s a silent mutation, a disappearing header, or an unexpected behavior introduced by something sitting in between: <strong>the edge proxy</strong>.</p><p>Welcome to the edge.</p><p>In this post, we’ll take a deep dive into how reverse proxies (like NGINX, Envoy, HAProxy, or CDNs like Cloudflare) can subtly, silently, and sometimes savagely rewrite your HTTP requests. We’ll explore the mechanisms, the gotchas, and the best practices you should know to survive (and thrive) in a distributed system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tmXB_8_V_CL9O9c0gq5IDw.png" /></figure><h3>The Anatomy of an HTTP Request</h3><p>Before diving into proxy behavior, let’s quickly recall what a typical HTTP request looks like:</p><pre>GET /api/user HTTP/1.1<br>Host: example.com<br>Authorization: Bearer abc123<br>Content-Type: application/json<br>User-Agent: curl/7.64.1<br>X-Custom-Header: some-value</pre><p>These headers carry everything — from routing metadata to security tokens. But what if something — or someone — in the middle modifies, removes, or limits them?</p><h3>The Invisible Hand of the Proxy</h3><h4>1. Header Stripping</h4><p>Reverse proxies often <strong>remove headers</strong> either for security, performance, or misconfiguration.</p><p><strong>Common examples:</strong></p><ul><li>Authorization: stripped to prevent credential leakage</li><li>X-Forwarded-*: overwritten by proxy or CDN</li><li>Custom headers like X-Internal-Token: removed unless explicitly passed</li></ul><p><strong>NGINX example:</strong></p><pre>proxy_pass http://backend;<br>proxy_set_header Authorization $http_authorization;</pre><p>If you forget the proxy_set_header, that Authorization header is gone.</p><h4>2. Underscores in Headers: The Silent Dropper</h4><p>NGINX by default will drop any header with an underscore:</p><pre>underscores_in_headers off;</pre><p>If your app expects X_Custom_Header, NGINX just won&#39;t forward it.</p><p>Fix:</p><pre>underscores_in_headers on;</pre><p>Or better: use dashes like X-Custom-Header instead.</p><h4>3. Header Case Sensitivity (or Lack Thereof)</h4><p>HTTP/1.1 headers are case-insensitive. But some downstream systems (especially older Java or Go libraries) may treat them case-sensitively.</p><p>You send: authorization Your service expects: Authorization Boom: 401 Unauthorized.</p><h4>4. Header Size and Count Limits</h4><p>Reverse proxies have default limits on the number and size of headers:</p><ul><li><strong>NGINX:</strong> large_client_header_buffers</li><li><strong>Envoy:</strong> max_request_headers_kb</li><li><strong>AWS API Gateway:</strong> 10KB max header size (combined)</li></ul><p>Too many headers? Too long? The request might be silently rejected or truncated.</p><h4>5. HTTP/2 vs HTTP/1.1 Differences</h4><p>HTTP/2 uses HPACK compression, and proxies might re-encode headers. Certain headers like Connection, Upgrade, or Transfer-Encoding behave differently or are disallowed.</p><p>This leads to subtle behavior changes when switching between HTTP/1.1 and HTTP/2 at the edge.</p><h3>Debugging the Edge</h3><p><strong>Tools to the rescue:</strong></p><ul><li>curl -v or httpie to inspect headers</li><li>NGINX logs: access.log and error.log</li><li>Envoy access logs with %REQ(:HEADER-NAME)%</li><li>tcpdump or Wireshark for raw packet analysis</li><li>Trace headers like X-Request-ID, Traceparent, etc.</li></ul><h3>Final Thoughts: Trust but Verify</h3><p>In a distributed system, your request doesn’t just go from A to B — it passes through C, D, E, and sometimes Z. Each hop can modify, drop, or transform it. That’s not a bug. That’s the nature of the edge.</p><p>But with the right observability, configuration hygiene, and paranoia, you can build systems that are robust — no matter how sharp the edge gets.</p><p>Let your headers be seen. Let your intentions be explicit.</p><p>Stay sharp.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=569170b484ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Channels — Communicating Between Goroutines]]></title>
            <link>https://medium.com/@sushilm2011/go-channels-communicating-between-goroutines-d33573e30971?source=rss-b21fc82d0b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/d33573e30971</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Sushil Maurya]]></dc:creator>
            <pubDate>Sat, 26 Apr 2025 09:12:09 GMT</pubDate>
            <atom:updated>2025-04-26T09:12:09.925Z</atom:updated>
            <content:encoded><![CDATA[<h3>Go Channels — Communicating Between Goroutines</h3><p>In the last section — <a href="https://medium.com/gitconnected/a-beginners-guide-to-concurrency-in-golang-introduction-c2f6a8c77250">A Beginner’s Guide to Concurrency in Golang — Introduction</a> we explored what are go routines, taking a step further let’s look at what channels are and why are they used in this blog post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ONJpsaSyt8oPAqdyN-8wA.png" /></figure><blockquote>“Goroutines are like workers. Channels are like message queues to coordinate them.”</blockquote><h3>Why Channels?</h3><p>When multiple goroutines are running, they often <strong>need to exchange information</strong>.</p><p>But how do we do it <strong>safely</strong>?</p><ul><li>Using shared variables (bad idea — needs locks, leads to race conditions)</li><li>Using <strong>channels</strong> (Go’s built-in way to safely communicate between goroutines)</li></ul><p>In Go, <strong>channels</strong> are the communication pipes between goroutines — they allow you to <strong>send and receive values</strong> in a synchronized and safe manner.</p><h3>What is a Channel?</h3><p>A <strong>channel</strong> is a typed conduit to pass values between goroutines. Channels synchronize the execution between sender and receiver.</p><h3>Creating a Channel</h3><pre>ch := make(chan int) // create a channel for integers</pre><ul><li>make(chan Type) creates a <strong>channel</strong> of a specific type.</li><li>Here, ch can carry int values between goroutines.</li></ul><h3>Sending and Receiving</h3><pre>ch &lt;- 10   // Send value 10 into channel ch<br>value := &lt;-ch // Receive value from channel ch</pre><ul><li>Send: Syntax ch &lt;- value</li><li>Receive: value := &lt;-ch</li></ul><p>When sending or receiving, <strong>both sides must be ready</strong>.<br> Otherwise, the operation <strong>blocks</strong> until the other side appears.</p><h3>Simple Example</h3><p>Let’s put everything together:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>func main() {<br> ch := make(chan string)<br><br> go func() {<br>  ch &lt;- &quot;Hello from goroutine&quot; // send<br> }()<br><br> msg := &lt;-ch // receive<br> fmt.Println(msg)<br>}</pre><p>Explaination:</p><ul><li>We created a channel ch for strings.</li><li>In a goroutine, we <strong>send</strong> “Hello from goroutine”.</li><li>In the main function, we <strong>receive</strong> the message and print it.</li><li>The send blocks until the receive is ready — <strong>this ensures synchronization!</strong></li></ul><p>Output:</p><pre>Hello from goroutine</pre><h3>Buffered vs Unbuffered Channels</h3><p><strong>1. Unbuffered Channels</strong> (default)</p><ul><li>Sends block until a receiver is ready.</li><li>Ensures synchronization.</li></ul><pre>ch := make(chan int) // unbuffered</pre><p><strong>2. Buffered Channels</strong></p><ul><li>Sends <strong>don’t block</strong> until the buffer is full.</li><li>Receivers <strong>don’t block</strong> until the buffer is empty.</li></ul><pre>ch := make(chan int, 2) // buffered with capacity 2</pre><h4>Example:</h4><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br> ch := make(chan string, 2) // buffered<br><br> ch &lt;- &quot;one&quot;<br> ch &lt;- &quot;two&quot;<br> <br> fmt.Println(&lt;-ch)<br> fmt.Println(&lt;-ch)<br>}</pre><p>Explanation:</p><ul><li>You can <strong>send two messages</strong> without needing a receiver immediately.</li><li>When you <strong>read</strong> from the channel, values come out in FIFO (first in, first out) order.</li></ul><p>Output:</p><pre>one<br>two</pre><p><strong>Note:</strong> Buffered channels can <strong>decouple</strong> senders and receivers.</p><h3>What Happens if a Channel Blocks?</h3><p>Example of <strong>deadlock</strong>:</p><pre>package main<br><br>func main() {<br> ch := make(chan int)<br> ch &lt;- 1 // blocks forever<br>}</pre><p>Here:</p><ul><li>No goroutine is reading from ch.</li><li>The main goroutine <strong>blocks forever</strong> trying to send into ch.</li><li>Go runtime detects this and <strong>panics</strong> with a “deadlock” error.</li></ul><p><strong>Lesson: </strong>Always have a <strong>receiver</strong> ready if you’re sending on an <strong>unbuffered</strong> channel.</p><h3>Real-World Example: Task Dispatcher</h3><p>Imagine you want to send tasks to workers:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func worker(tasks &lt;-chan int) {<br> for task := range tasks {<br>  fmt.Println(&quot;Processing task:&quot;, task)<br>  time.Sleep(1 * time.Second) // simulate work<br> }<br>}<br><br>func main() {<br> tasks := make(chan int)<br><br> go worker(tasks)<br><br> for i := 1; i &lt;= 5; i++ {<br>  tasks &lt;- i<br> }<br><br> close(tasks) // close the channel after sending all tasks<br><br> time.Sleep(6 * time.Second) // wait for all tasks to complete<br>}</pre><h3>Explanation:</h3><ul><li>worker() reads tasks from the tasks channel.</li><li>main() sends 5 tasks into the channel.</li><li>close(tasks) signals no more tasks will be sent.</li><li>worker() exits after all tasks are processed.</li></ul><p><strong>Note:</strong> range works automatically on closed channels to receive all remaining values!</p><h3>Key Takeaways</h3><ul><li><strong>Channel: </strong>A pipe to communicate between goroutines</li><li><strong>Send/Receive block: </strong>Until the other side is ready</li><li><strong>Buffered channel: </strong>Provides a queue with a fixed capacity</li><li><strong>Deadlock: </strong>Happens if no matching receiver/sender exists</li><li><strong>Closing channels: </strong>Tells receivers no more values are coming</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d33573e30971" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to Concurrency in Golang — Introduction]]></title>
            <link>https://levelup.gitconnected.com/a-beginners-guide-to-concurrency-in-golang-introduction-c2f6a8c77250?source=rss-b21fc82d0b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2f6a8c77250</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[goroutines]]></category>
            <dc:creator><![CDATA[Sushil Maurya]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 04:22:56 GMT</pubDate>
            <atom:updated>2025-04-23T13:21:24.383Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Beginner’s Guide to Concurrency in Golang — Introduction</h3><blockquote>“Do not communicate by sharing memory; instead, share memory by communicating.” — Go Proverbs</blockquote><h3>First things first — Why Learn Concurrency?</h3><p>Imagine you’re baking cookie, boiling water and cleaning dishes — all at the same time. That’s concurrency — multiple tasks running independently and progressing together.</p><p>Modern apps need to handle multiple users, API Calls, background jobs, streaming etc., all without slowing down. Go makes writing concurrent programs not just possible — but elegant and simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3UNwg8Qo4zFReEhfiST2cA.png" /></figure><h3>Concurrency vs Parallelism</h3><p>Before diving into Go’s tools, let’s clarify two important terms:</p><p><strong>Concurrency</strong>: Structuring your code to <em>deal with multiple tasks at once</em><strong>.<br>Parallelism: </strong>Actually <em>executing multiple tasks simultaneously</em> on multiple cores</p><p>Go focuses on <strong>concurrency first</strong>, but it also enables parallelism when needed.</p><h3>Concurrency in Go = Goroutines + Channels</h3><p>Go provides — <br><strong>Goroutines:</strong> Lightweight functions that run concurrently<br><strong>Channels:</strong> Safe communication pipes between goroutines</p><p>In this part, we’ll focus on <strong>goroutines</strong>.</p><h4>Your First Goroutine</h4><p>Let’s say we want to print “Hello” and “World” from two separate tasks.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func sayHello() {<br> fmt.Println(&quot;Hello&quot;)<br>}<br><br>func main() {<br> go sayHello()         // run in a goroutine<br> fmt.Println(&quot;World&quot;)  // run in main goroutine<br><br> time.Sleep(1 * time.Second) // wait for the goroutine<br>}</pre><h4>Explanation:</h4><ul><li>go sayHello() launches the function <strong>asynchronously</strong> — it doesn’t block.</li><li>fmt.Println(&quot;World&quot;) runs in the <strong>main goroutine</strong>.</li><li>We add time.Sleep() to <strong>give the goroutine time to complete</strong>, or else the program might end before it prints anything.</li></ul><p>Note: If we remove time.Sleep, you may see only &quot;World&quot; printed — because the program exits too quickly.</p><h3>What is a Goroutine?</h3><ul><li>Created using the go keyword.</li><li><strong>Very lightweight</strong> compared to traditional threads (starts with ~2KB of stack).</li><li>Go <strong>runtime handles</strong> scheduling and multiplexes thousands of goroutines on fewer OS threads.</li></ul><h3>The Common Trap</h3><p>Let’s try this:</p><pre>package main<br><br>import &quot;fmt&quot;<br><br>func main() {<br> go fmt.Println(&quot;Hi from goroutine&quot;)<br>}</pre><h4>What will happen?</h4><p>Most likely — <strong>nothing is printed</strong>.</p><h4>Why?</h4><p>Because the main function exits <strong>before</strong> the goroutine gets a chance to run. Goroutines live only as long as the program runs.</p><h3>How to Wait for Goroutines?</h3><p><strong>Option 1:</strong> Use time.Sleep() (not recommended for production)</p><pre>go fmt.Println(&quot;Hello&quot;)<br>time.Sleep(1 * time.Second) // crude waiting</pre><p>This is okay for demos but not reliable or scalable.</p><p><strong>Option 2:</strong> Use sync.WaitGroup (recommended)</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;sync&quot;<br>)<br><br>func main() {<br> var wg sync.WaitGroup<br><br> wg.Add(1) // Tell it we’re going to wait for 1 goroutine<br><br> go func() {<br>  defer wg.Done() // Mark as done when goroutine finishes<br>  fmt.Println(&quot;Hello from goroutine&quot;)<br> }()<br><br> wg.Wait() // Block until all added goroutines are done<br>}</pre><h4>Explanation:</h4><ul><li>wg.Add(1) tells Go we’ll wait for one task.</li><li>wg.Done() is called when the goroutine finishes.</li><li>wg.Wait() <strong>blocks the main function</strong> until all goroutines are finished.</li></ul><p>This is <strong>the idiomatic Go way</strong> to wait for multiple goroutines to finish.</p><h3>Real-Life Example: Concurrent Web Requests</h3><p>Imagine you’re fetching multiple URLs at once.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br> &quot;sync&quot;<br>)<br><br>func fetch(url string, wg *sync.WaitGroup) {<br> defer wg.Done()<br><br> resp, err := http.Get(url)<br> if err != nil {<br>  fmt.Println(&quot;Error:&quot;, err)<br>  return<br> }<br> defer resp.Body.Close()<br><br> fmt.Println(url, &quot;-&gt;&quot;, resp.Status)<br>}<br><br>func main() {<br> var wg sync.WaitGroup<br><br> urls := []string{<br>  &quot;https://golang.org&quot;,<br>  &quot;https://example.com&quot;,<br>  &quot;https://httpbin.org/get&quot;,<br> }<br><br> for _, url := range urls {<br>  wg.Add(1)<br>  go fetch(url, &amp;wg)<br> }<br><br> wg.Wait()<br>}</pre><h4>Explanation:</h4><ul><li>Each fetch() runs in its <strong>own goroutine</strong>.</li><li>WaitGroup ensures the main function waits for <strong>all the fetches</strong> to complete.</li><li>This pattern is incredibly useful for <strong>parallel API calls, crawling, etc.</strong></li></ul><h3>Summary</h3><p><strong>Goroutines: </strong>Lightweight, concurrent functions created with go<br><strong>time.Sleep()</strong>: Basic way to delay for demo purposes<br><strong>sync.WaitGroup</strong>: Proper way to wait for goroutines to finish</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2f6a8c77250" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/a-beginners-guide-to-concurrency-in-golang-introduction-c2f6a8c77250">A Beginner’s Guide to Concurrency in Golang — Introduction</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Promises in JavaScript: A Deep Dive]]></title>
            <link>https://blog.stackademic.com/designing-promises-in-javascript-a-deep-dive-d7b1e82d8d47?source=rss-b21fc82d0b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7b1e82d8d47</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sushil Maurya]]></dc:creator>
            <pubDate>Fri, 30 Aug 2024 06:37:25 GMT</pubDate>
            <atom:updated>2024-09-15T17:21:38.135Z</atom:updated>
            <content:encoded><![CDATA[<p>Promises in JavaScript are a powerful tool for handling asynchronous operations. Understanding how they work internally can provide valuable insights into their usage, making you a better developer. In this blog, we’ll explore the design of promises, exploring the mechanics, how the state is managed, and how to implement a custom promise class from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DN7ToydkJZEdVaJVK_Nhvw.png" /></figure><h4>What is a Promise?</h4><p>A promise is an object representing the eventual completion or failure of an asynchronous operation. It allows you to write asynchronous code in a more synchronous-like fashion, improving readability and maintainability. Promises follow a simple state machine model with three possible states:</p><ol><li><strong>Pending</strong>: The initial state, neither fulfilled nor rejected.</li><li><strong>Fulfilled</strong>: The operation was completed successfully.</li><li><strong>Rejected</strong>: The operation failed.</li></ol><p>Promises provide a clean way to handle success and failure cases using .then(), .catch(), and .finally() methods.</p><h4>Designing a Custom Promise Class</h4><p>While JavaScript provides a built-in Promise object, understanding how to design a custom promise can be a great learning experience. Let’s walk through how to build a basic promise class.</p><p>1. <strong>Setting Up the Class Structure</strong></p><p>Start by defining a class with a constructor that takes an executor function. The executor function receives two arguments: resolve and reject.</p><pre>class MyPromise {<br>    constructor(executor) {<br>        this.state = &#39;pending&#39;;<br>        this.value = undefined;<br>        this.reason = undefined;<br><br>        this.onFulfilledCallbacks = [];<br>        this.onRejectedCallbacks = [];<br><br>        try {<br>            executor(this.resolve.bind(this), this.reject.bind(this));<br>        } catch (error) {<br>            this.reject(error);<br>        }<br>    }<br>}</pre><p>Here, we have initialized the state to pending, and define arrays to hold success and failure callbacks. The executor is called with two methods resolve and reject which we will implement in next section.</p><p>value =&gt; This stores the fulfilled value if resolved</p><p>reson =&gt; This stored the failure reason if rejected</p><p>2. <strong>Implementing Resolve and Reject</strong></p><p>The resolve and reject methods handle transitioning the promise from pending to either fulfilled or rejected. They also trigger the corresponding callbacks.</p><pre>    resolve(value) {<br>        if (this.state === &#39;pending&#39;) {<br>            this.state = &#39;fulfilled&#39;;<br>            this.value = value;<br>            this.onFulfilledCallbacks.forEach(callback =&gt; callback(value));<br>        }<br>    }<br><br>    reject(reason) {<br>        if (this.state === &#39;pending&#39;) {<br>            this.state = &#39;rejected&#39;;<br>            this.reason = reason;<br>            this.onRejectedCallbacks.forEach(callback =&gt; callback(reason));<br>        }<br>    }</pre><p>These methods ensure that the state can only transition once from pending to either fulfilled or rejected.</p><p>When promise resolves, i.e if resolve is called by the executor, we set the value and call all the callbacks which are registered. (We will implement this in next section)</p><p>3. <strong>Chaining with </strong><strong>then()</strong></p><p>The then() method is the cornerstone of promise chaining, allowing you to define what happens when the promise is fulfilled or rejected.</p><pre>    then(onFulfilled, onRejected) {<br>        return new MyPromise((resolve, reject) =&gt; {<br>            if (this.state === &#39;fulfilled&#39;) {<br>                try {<br>                    const result = onFulfilled(this.value);<br>                    resolve(result);<br>                } catch (error) {<br>                    reject(error);<br>                }<br>            }<br><br>            if (this.state === &#39;rejected&#39;) {<br>                try {<br>                    if (onRejected) {<br>                      const result = onRejected(this.reason);<br>                      resolve(result);<br>                    } else {<br>                        reject(this.reason);<br>                    }<br>                } catch (error) {<br>                    reject(error);<br>                }<br>            }<br><br>            if (this.state === &#39;pending&#39;) {<br>                this.onFulfilledCallbacks.push(() =&gt; {<br>                    try {<br>                        const result = onFulfilled(this.value);<br>                        resolve(result);<br>                    } catch (error) {<br>                        reject(error);<br>                    }<br>                });<br><br>                this.onRejectedCallbacks.push(() =&gt; {<br>                    try {<br>                        if (onRejected) {<br>                          const result = onRejected(this.reason);<br>                          resolve(result);<br>                        }<br>                    } catch (error) {<br>                        reject(error);<br>                    }<br>                });<br>            }<br>        });<br>    }</pre><p>In this implementation, then() checks the current state of the promise and executes the appropriate callback. If the promise is still pending, it stores the callbacks to be executed once the promise state changes to fulfilled.</p><p>4. <strong>Adding Utility Methods</strong></p><p>Promises also come with catch(), finally(), and static methods like resolve, reject, all, and race. These methods enhance the functionality of promises.</p><ul><li><strong>catch()</strong>: A shorthand for handling rejected cases.</li><li><strong>finally()</strong>: Executes a callback regardless of the promise’s outcome.</li><li><strong>resolve() and reject()</strong>: Static methods to create a resolved or rejected promise.</li></ul><p>Let’s implement them one by one:</p><ul><li><strong>catch</strong></li></ul><pre>catch(onRejected) {<br>    return this.then(null, onRejected);<br>}</pre><p>Here we call the then method internally with a rejected handler.</p><ul><li><strong>finally</strong></li></ul><pre>finally(callback) {<br>      return this.then(<br>          value =&gt; {<br>              callback();<br>              return value;<br>          },<br>          reason =&gt; {<br>              callback();<br>              throw reason;<br>          }<br>      );<br>}</pre><p>The finally() method internally uses the then() method to handle both fulfillment and rejection of the promise. The then() method takes two arguments:</p><ul><li>The first argument is the function to handle the fulfilled state.</li><li>The second argument is the function to handle the rejected state.</li></ul><p>The finally() method allows you to run a piece of code after a promise has settled (fulfilled or rejected) without interfering with the promise’s resolution or rejection. This means the finally() callback does not alter the value or reason of the promise.</p><ul><li><strong>Defining the static methods — resolve and reject</strong></li></ul><pre>static resolve(value) {<br>    return new MyPromise(resolve =&gt; resolve(value));<br>}<br><br>static reject(reason) {<br>    return new MyPromise((_, reject) =&gt; reject(reason));<br>}</pre><ul><li><strong>static method — all</strong></li></ul><pre>static all(promises) {<br>    return new MyPromise((resolve, reject) =&gt; {<br>        let results = [];<br>        let completedPromises = 0;<br><br>        promises.forEach((promise, index) =&gt; {<br>            MyPromise.resolve(promise).then(value =&gt; {<br>                results[index] = value;<br>                completedPromises += 1;<br><br>                if (completedPromises === promises.length) {<br>                    resolve(results);<br>                }<br>            }).catch(reject);<br>        });<br>    });<br>}</pre><p>The all() method in the Promise API is used to handle multiple promises concurrently. It returns a new promise that resolves when all the promises in the iterable passed to it have resolved, or it rejects as soon as one of the promises in the iterable rejects.</p><p>It takes a single argument, promises, which is an iterable (usually an array) of promises. We are populating two variables:</p><p>results: An array to store the resolved values from each promise in the order they were received.</p><p>completedPromises: A counter to keep track of how many promises have been fulfilled. So that we can finally return all the results.</p><p>If any of the promises reject, the .catch(reject) is triggered, immediately rejecting the new promise with the reason from the rejected promise. This prevents further processing and ensures the first rejection is propagated.</p><ul><li><strong>static method: race</strong></li></ul><pre>static race(promises) {<br>    return new MyPromise((resolve, reject) =&gt; {<br>        promises.forEach(promise =&gt; {<br>            MyPromise.resolve(promise).then(resolve).catch(reject);<br>        });<br>    });<br>}</pre><p>The race() method in the Promise API is used to handle multiple promises, but unlike Promise.all(), it returns a new promise that resolves or rejects as soon as one of the promises in the iterable settles (either fulfills or rejects). The result of the first promise to settle is the result of the race().</p><p>Concluding the blog post with the final implementation</p><pre>class MyPromise {<br>  constructor(executor) {<br>    this.state = &#39;pending&#39;<br>    this.value = undefined<br>    this.reason = undefined<br><br>    this.onFulfilledCallbacks = []<br>    this.onRejectedCallbacks = []<br><br>    try {<br>      executor(this.resolve.bind(this), this.reject.bind(this))<br>    } catch (error) {<br>      this.reject(error)<br>    }<br>  }<br><br>  resolve(value) {<br>    if (this.state === &#39;pending&#39;) {<br>      this.state = &#39;fulfilled&#39;<br>      this.value = value<br>      this.onFulfilledCallbacks.forEach((callback) =&gt; callback(value))<br>    }<br>  }<br><br>  reject(reason) {<br>    if (this.state === &#39;pending&#39;) {<br>      this.state = &#39;rejected&#39;<br>      this.reason = reason<br>      this.onRejectedCallbacks.forEach((callback) =&gt; callback(reason))<br>    }<br>  }<br><br>  then(onFulfilled, onRejected) {<br>    return new MyPromise((resolve, reject) =&gt; {<br>      if (this.state === &#39;fulfilled&#39;) {<br>        try {<br>          const result = onFulfilled(this.value)<br>          resolve(result)<br>        } catch (error) {<br>          reject(error)<br>        }<br>      }<br><br>      if (this.state === &#39;rejected&#39;) {<br>        try {<br>          if (onRejected) {<br>            const result = onRejected(this.reason);<br>            resolve(result);<br>          } else {<br>              reject(this.reason);<br>          }<br>        } catch (error) {<br>          reject(error)<br>        }<br>      }<br><br>      if (this.state === &#39;pending&#39;) {<br>        this.onFulfilledCallbacks.push(() =&gt; {<br>          try {<br>            const result = onFulfilled(this.value)<br>            resolve(result)<br>          } catch (error) {<br>            reject(error)<br>          }<br>        })<br><br>        this.onRejectedCallbacks.push(() =&gt; {<br>          try {<br>            if (onRejected) {<br>              const result = onRejected(this.reason)<br>              resolve(result)<br>            }<br>          } catch (error) {<br>            reject(error)<br>          }<br>        })<br>      }<br>    })<br>  }<br><br>  catch(onRejected) {<br>    return this.then(null, onRejected)<br>  }<br><br>  finally(callback) {<br>    return this.then(<br>      (value) =&gt; {<br>        callback()<br>        return value<br>      },<br>      (reason) =&gt; {<br>        callback()<br>        throw reason<br>      }<br>    )<br>  }<br><br>  static resolve(value) {<br>    return new MyPromise((resolve) =&gt; resolve(value))<br>  }<br><br>  static reject(reason) {<br>    return new MyPromise((_, reject) =&gt; reject(reason))<br>  }<br><br>  static all(promises) {<br>    return new MyPromise((resolve, reject) =&gt; {<br>      let results = []<br>      let completedPromises = 0<br><br>      promises.forEach((promise, index) =&gt; {<br>        MyPromise.resolve(promise)<br>          .then((value) =&gt; {<br>            results[index] = value<br>            completedPromises += 1<br><br>            if (completedPromises === promises.length) {<br>              resolve(results)<br>            }<br>          })<br>          .catch(reject)<br>      })<br>    })<br>  }<br><br>  static race(promises) {<br>    return new MyPromise((resolve, reject) =&gt; {<br>      promises.forEach((promise) =&gt; {<br>        MyPromise.resolve(promise).then(resolve).catch(reject)<br>      })<br>    })<br>  }<br>}</pre><p>Also the code is accessible at: <a href="https://gist.github.com/sushilm2011/b194f6296f17e956d7e7a1d9ee8ccc5f">https://gist.github.com/sushilm2011/b194f6296f17e956d7e7a1d9ee8ccc5f</a></p><p><strong>Testing</strong></p><pre>const testResolve = () =&gt; {<br>  const promise = new MyPromise((resolve, reject) =&gt; {<br>    resolve(&#39;Resolved&#39;);<br>  });<br><br>  promise.then(value =&gt; {<br>    console.log(value);<br>  });<br>};<br><br>const testReject = () =&gt; {<br>  const promise = new MyPromise((resolve, reject) =&gt; {<br>    reject(&#39;Rejected&#39;);<br>  });<br><br>  promise.catch(reason =&gt; {<br>    console.log(reason);<br>  });<br>};<br><br>const testChaining = () =&gt; {<br>  const promise = new MyPromise((resolve, reject) =&gt; {<br>    resolve(1);<br>  });<br><br>  promise<br>    .then(value =&gt; value + 1)<br>    .then(value =&gt; value * 2)<br>    .then(value =&gt; {<br>      console.log(value); // Expected output: 4<br>    });<br>};<br><br>const testCatch = () =&gt; {<br>  const promise = new MyPromise((resolve, reject) =&gt; {<br>    reject(&#39;Error&#39;);<br>  });<br><br>  promise<br>    .then(value =&gt; value)<br>    .catch(reason =&gt; {<br>      console.log(reason); // Expected output: &#39;Error&#39;<br>    });<br>};<br><br>const testFinally = () =&gt; {<br>  const promise = new MyPromise((resolve, reject) =&gt; {<br>    resolve(&#39;Done&#39;);<br>  });<br><br>  promise<br>    .then(value =&gt; {<br>      console.log(value); // Expected output: &#39;Done&#39;<br>    })<br>    .finally(() =&gt; {<br>      console.log(&#39;Finally called&#39;); // Expected output: &#39;Finally called&#39;<br>    });<br>};<br><br>const testStaticResolve = () =&gt; {<br>  const promise = MyPromise.resolve(&#39;Static Resolve&#39;);<br><br>  promise.then(value =&gt; {<br>    console.log(value); // Expected output: &#39;Static Resolve&#39;<br>  });<br>};<br><br>const testStaticReject = () =&gt; {<br>  const promise = MyPromise.reject(&#39;Static Reject&#39;);<br><br>  promise.catch(reason =&gt; {<br>    console.log(reason); // Expected output: &#39;Static Reject&#39;<br>  });<br>};<br><br>const testAll = () =&gt; {<br>  const promise1 = MyPromise.resolve(1);<br>  const promise2 = MyPromise.resolve(2);<br>  const promise3 = MyPromise.resolve(3);<br><br>  MyPromise.all([promise1, promise2, promise3]).then(results =&gt; {<br>    console.log(results); // Expected output: [1, 2, 3]<br>  });<br>};<br><br>const testRace = () =&gt; {<br>  const promise1 = new MyPromise((resolve) =&gt; setTimeout(resolve, 100, &#39;First&#39;));<br>  const promise2 = new MyPromise((resolve) =&gt; setTimeout(resolve, 50, &#39;Second&#39;));<br>  const promise3 = new MyPromise((resolve) =&gt; setTimeout(resolve, 150, &#39;Third&#39;));<br><br>  MyPromise.race([promise1, promise2, promise3]).then(result =&gt; {<br>    console.log(result); // Expected output: &#39;Second&#39;<br>  });<br>};<br><br>const testAllCatch = () =&gt; {<br>  const promise1 = MyPromise.resolve(1);<br>  const promise2 = MyPromise.reject(&#39;Error in promise 2&#39;);<br>  const promise3 = MyPromise.resolve(3);<br><br>  MyPromise.all([promise1, promise2, promise3])<br>    .then(results =&gt; {<br>      console.log(results); // This won&#39;t be called<br>    })<br>    .catch(reason =&gt; {<br>      console.log(reason); // Expected output: &#39;Error in promise 2&#39;<br>    });<br>};<br><br>const testFinallyAfterReject = () =&gt; {<br>  const promise = MyPromise.reject(&#39;Failed&#39;);<br><br>  promise<br>    .catch(reason =&gt; {<br>      console.log(reason); // Expected output: &#39;Failed&#39;<br>    })<br>    .finally(() =&gt; {<br>      console.log(&#39;Finally called after reject&#39;); // Expected output: &#39;Finally called after reject&#39;<br>    });<br>};<br><br>const testChainingErrors = () =&gt; {<br>  const promise = new MyPromise((resolve, reject) =&gt; {<br>    resolve(&#39;Start&#39;);<br>  });<br><br>  promise<br>    .then(value =&gt; {<br>      throw new Error(&#39;Something went wrong&#39;);<br>    })<br>    .then(value =&gt; {<br>      console.log(value); // This won&#39;t be called<br>    })<br>    .catch(error =&gt; {<br>      console.log(error.message); // Expected output: &#39;Something went wrong&#39;<br>    });<br>};<br><br>// Executing Tests:<br>testResolve()<br>testReject()<br>testChaining()<br>testCatch()<br>testFinally()<br>testStaticResolve()<br>testStaticReject()<br>testAll()<br>testRace()<br>testAllCatch()<br>testFinallyAfterReject()<br>testChainingErrors()</pre><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7b1e82d8d47" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/designing-promises-in-javascript-a-deep-dive-d7b1e82d8d47">Designing Promises in JavaScript: A Deep Dive</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detailed Guide to Prometheus and Grafana for Monitoring Applications Using Docker]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@sushilm2011/detailed-guide-to-prometheus-and-grafana-for-monitoring-applications-using-docker-e0f693f92551?source=rss-b21fc82d0b53------2"><img src="https://cdn-images-1.medium.com/max/1920/1*vkJcDr-MSI5qmhFg8H56zg.png" width="1920"></a></p><p class="medium-feed-snippet">Monitoring and observability are crucial for maintaining the performance, reliability, and health of modern applications. Prometheus and&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@sushilm2011/detailed-guide-to-prometheus-and-grafana-for-monitoring-applications-using-docker-e0f693f92551?source=rss-b21fc82d0b53------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@sushilm2011/detailed-guide-to-prometheus-and-grafana-for-monitoring-applications-using-docker-e0f693f92551?source=rss-b21fc82d0b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0f693f92551</guid>
            <category><![CDATA[production]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Sushil Maurya]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 18:33:16 GMT</pubDate>
            <atom:updated>2024-07-29T18:43:54.279Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[The “Click Twice, Get Charged Once” Problem: Building Reliable APIs in NestJs with Idempotency]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/the-click-twice-get-charged-once-problem-building-reliable-apis-in-nestjs-with-idempotency-8d7febd7e3cd?source=rss-b21fc82d0b53------2"><img src="https://cdn-images-1.medium.com/max/699/1*bo84w0KwIJQJcT3Ku7ZPYg.png" width="699"></a></p><p class="medium-feed-snippet">Ever been coding an API endpoint and worried about that classic user experience nightmare&#x200A;&#x2014;&#x200A;the double submit? You know the scenario: they&#x2026;</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/the-click-twice-get-charged-once-problem-building-reliable-apis-in-nestjs-with-idempotency-8d7febd7e3cd?source=rss-b21fc82d0b53------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/the-click-twice-get-charged-once-problem-building-reliable-apis-in-nestjs-with-idempotency-8d7febd7e3cd?source=rss-b21fc82d0b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d7febd7e3cd</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[idempotency]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Sushil Maurya]]></dc:creator>
            <pubDate>Sun, 12 May 2024 06:38:38 GMT</pubDate>
            <atom:updated>2024-05-13T10:35:28.371Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[WebSockets for Real-Time Insights: A NestJS Server Metrics Dashboard]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/websockets-for-real-time-insights-a-nestjs-server-metrics-dashboard-35fc6345be1f?source=rss-b21fc82d0b53------2"><img src="https://cdn-images-1.medium.com/max/752/1*JpRQFBZptfObFk-gYlRpKg.png" width="752"></a></p><p class="medium-feed-snippet">In web development and system management, the ability to gain immediate insights into server performance can significantly enhance&#x2026;</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/websockets-for-real-time-insights-a-nestjs-server-metrics-dashboard-35fc6345be1f?source=rss-b21fc82d0b53------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/websockets-for-real-time-insights-a-nestjs-server-metrics-dashboard-35fc6345be1f?source=rss-b21fc82d0b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/35fc6345be1f</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Sushil Maurya]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 09:26:03 GMT</pubDate>
            <atom:updated>2024-02-29T02:36:51.753Z</atom:updated>
        </item>
    </channel>
</rss>