<?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 Abhijit Patil on Medium]]></title>
        <description><![CDATA[Stories by Abhijit Patil on Medium]]></description>
        <link>https://medium.com/@abhijitpatil669?source=rss-b39db99eda0b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*A1bxCBJPSqsbDsI0</url>
            <title>Stories by Abhijit Patil on Medium</title>
            <link>https://medium.com/@abhijitpatil669?source=rss-b39db99eda0b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 23:09:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhijitpatil669/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 I Solved DynamoDB’s 400 KB Item Limit Without Rebuilding My System]]></title>
            <link>https://medium.com/@abhijitpatil669/how-i-solved-dynamodbs-400-kb-item-limit-without-rebuilding-my-system-688ff3df8882?source=rss-b39db99eda0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/688ff3df8882</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-s3]]></category>
            <dc:creator><![CDATA[Abhijit Patil]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 15:10:04 GMT</pubDate>
            <atom:updated>2026-07-05T15:10:04.982Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I evolved a pricing platform beyond DynamoDB’s hard item size constraint while preserving existing access patterns.</em></p><h3>Introduction</h3><p>Amazon DynamoDB is one of the most popular choices for building highly scalable, low-latency applications. It offers predictable performance, managed infrastructure, and excellent horizontal scalability.</p><p>But every technology comes with design constraints, and one of DynamoDB’s most important limitations is its <strong>400 KB maximum item size</strong>.</p><p>It’s a constraint that’s easy to ignore in the early stages of a project. Most applications start with relatively small records, so the limit feels comfortably distant. As products evolve and datasets grow, though, what was once a simple data model can slowly creep toward that boundary.</p><p>That’s exactly what happened on a pricing platform I worked on recently.</p><p>Each pricing formula was stored as a single DynamoDB item. As customers added more SKUs, formula complexity increased, and new business attributes were introduced, some records eventually exceeded DynamoDB’s maximum item size.</p><p>The result was immediate:</p><blockquote><strong><em>ValidationException: Item size has exceeded the maximum allowed size</em></strong></blockquote><p>At first glance, this looked like a storage limitation. In reality, it turned into a system design problem that touched data modeling, read/write patterns, update semantics, scalability, and operational reliability.</p><p>In this article, I’ll walk through:</p><ul><li>The original design</li><li>Why the 400 KB limit became a bigger architectural challenge than it looked</li><li>The alternatives I evaluated (and rejected)</li><li>Why I landed on a hybrid DynamoDB + S3 architecture</li><li>How I rolled it out with minimal impact to existing consumers</li><li>Some operational lessons I picked up along the way</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQEomGvupbRnfNmxCqxScg.jpeg" /></figure><h3>The Original Design</h3><p>My pricing platform stored every computed formula as a single DynamoDB item.</p><pre>PK = PVF#{pvfId}<br>SK = FORMULA#{formulaId}</pre><p>A typical record looked like this:</p><pre>{<br>  &quot;PK&quot;: &quot;PVF#123&quot;,<br>  &quot;SK&quot;: &quot;FORMULA#456&quot;,<br>  &quot;assigned&quot;: false,<br>  &quot;expdate&quot;: 123456789,<br>  &quot;formulaDetails&quot;: {<br>      // SKU information<br>      // Material configuration<br>      // Model settings<br>      // Computation results<br>  }<br>}</pre><p>Most of the payload lived inside the formulaDetails attribute.</p><p>At first this worked fine.</p><p>Then the business grew.</p><h3>When Growth Becomes a Problem</h3><p>Over time, several factors pushed record sizes up:</p><ul><li>Customers added far more SKUs</li><li>Pricing models got more sophisticated</li><li>Additional metadata crept in</li><li>New product features expanded the payload</li></ul><p>Item sizes drifted roughly like this:</p><pre>50 KB → 100 KB → 250 KB → 400 KB+</pre><p>Eventually, writes started failing as records crossed DynamoDB’s hard limit.</p><p>Unlike throughput or capacity limits, this isn’t something you can autoscale away. Once an item passes <strong>400 KB</strong>, it simply can’t be stored, full stop.</p><h3>Why This Was More Than a Storage Problem</h3><p>The obvious first question was: <em>“Where do I put the larger payloads?”</em></p><p>But that wasn’t really the hard part.</p><p>The actual question I needed to answer was closer to:</p><blockquote><strong><em>How do I get rid of the item-size limitation without rewriting a system that’s already in production?</em></strong></blockquote><p>Changing storage touches a lot more than persistence. It reaches into data modeling, read paths, update operations, existing APIs, performance, and operational complexity.</p><p>I needed something that solved today’s problem without quietly creating next year’s.</p><h3>Understanding My Access Patterns</h3><p>Before evaluating any solutions, I spent time looking at how the application actually used formula data. That turned out to be the most important part of the whole exercise.</p><p><strong>Pattern 1: Full formula reads</strong></p><p>Several workflows genuinely needed the complete payload: formula computation, approval workflows, validation, supersession processing, and alert generation. No way around loading everything for these.</p><p><strong>Pattern 2: Metadata-only reads</strong></p><p>What surprised me was how many requests only touched lightweight metadata:</p><pre>{<br>  &quot;assigned&quot;: false,<br>  &quot;expdate&quot;: 123456789<br>}</pre><p>They never went near formulaDetails.</p><p>That single observation reshaped my thinking. Most requests didn’t need the large payload at all, and that insight is what eventually drove the architecture.</p><h3>Why I Didn’t Just Move Everything to S3</h3><p>A fair question came up early: if S3 has effectively unlimited object size, why not store every formula there and be done with it?</p><p>On paper it sounds simpler. In practice it would have made the whole system slower.</p><p><strong>Most records were already small.</strong> Looking at production data, the vast majority of formulas sat comfortably below 400 KB. Only a small slice exceeded it, and those records tended to share the same traits: very high SKU counts, complex pricing models, extra business attributes. The problem wasn’t universal. It affected a minority of records.</p><p><strong>An S3-first design would penalize everyone.</strong> Today’s write path looked like:</p><pre>Application → DynamoDB</pre><p>An S3-first approach would look more like:</p><pre>Application → S3 → DynamoDB Metadata</pre><p>Every write, even a tiny 50 KB one, would now need an S3 upload, dual-write coordination, retry handling, and cross-service consistency checks.</p><p>The read path suffers too. Right now:</p><pre>Application → DynamoDB</pre><p>Under an S3-first model:</p><pre>Application → DynamoDB → S3</pre><p>Every single request picks up an extra network hop. That runs against one of the most basic principles in distributed systems: optimize for the common case.</p><p>Most requests already fit comfortably inside DynamoDB. Slowing all of them down to fix a problem that only affects a few didn’t make sense.</p><h3>Solutions I Considered</h3><h3>1. Compression</h3><p>The first idea was compressing the payload before writing it to DynamoDB.</p><p>It’s appealing on paper: smaller footprint, minimal schema changes.</p><p>But it breaks partial updates. Instead of a simple SET formulaDetails.skus = :data, I&#39;d have to read the compressed blob, decompress it, modify it, compress it again, and rewrite the whole document. And compression only buys time anyway. Eventually the compressed payload grows past 400 KB too.</p><p>Verdict: a stopgap, not a real fix.</p><h3>2. Vertical partitioning in DynamoDB</h3><p>The second option was splitting large formulas across multiple items, something like FORMULA#123, FORMULA#123#DETAILS, FORMULA#123#MATERIALS.</p><p>It keeps everything inside DynamoDB and sidesteps the size limit. But it comes with real costs: existing queries break, reads multiply, the application has to assemble pieces back together, updates get messier, and each individual partition still has its own 400 KB ceiling.</p><p>Verdict: more moving parts without actually solving the long-term problem.</p><h3>3. Partial S3 offload</h3><p>Another option was offloading only specific attributes to S3, say sending formulaMaterials there while keeping formulaDetails in DynamoDB.</p><p>The catch: formulaDetails was almost always the biggest attribute. So the largest records could still blow past the limit.</p><p>Verdict: treats the symptom, not the cause.</p><h3>The Hybrid DynamoDB + S3 Architecture</h3><p>After weighing all of that, I settled on a hybrid model. The idea is simple:</p><blockquote><em>Keep small items in DynamoDB. Offload only the oversized ones to S3.</em></blockquote><p>This keeps performance intact for the vast majority of requests while removing DynamoDB’s size ceiling entirely.</p><p><strong>Small formula:</strong> records under the configured threshold stay exactly as they were, fully in DynamoDB.</p><pre>{<br>  &quot;PK&quot;: &quot;PVF#123&quot;,<br>  &quot;SK&quot;: &quot;FORMULA#456&quot;,<br>  &quot;assigned&quot;: false,<br>  &quot;expdate&quot;: 123456789,<br>  &quot;formulaDetails&quot;: { ... }<br>}</pre><p><strong>Large formula:</strong> oversized records get split. DynamoDB holds metadata plus a pointer.</p><pre>{<br>  &quot;PK&quot;: &quot;PVF#123&quot;,<br>  &quot;SK&quot;: &quot;FORMULA#456&quot;,<br>  &quot;assigned&quot;: false,<br>  &quot;expdate&quot;: 123456789,<br>  &quot;dataLocation&quot;: &quot;S3&quot;,<br>  &quot;s3DetailRef&quot;: &quot;FormulaDetails/123/456.json&quot;<br>}</pre><p>The heavy payload lives in S3.</p><p>Here’s roughly what the system looks like:</p><pre>Client<br>                    |<br>             Formula Service<br>                    |<br>          +---------+---------+<br>          |                   |<br>      DynamoDB           S3 Resolver<br>          |                   |<br> Metadata / Reference   Formula Payload</pre><p>And the read-time decision flow:</p><pre>Client<br>                    |<br>             Formula Service<br>                    |<br>          Read Formula Request<br>                    |<br>             Get DynamoDB Item<br>                    |<br>          +---------+---------+<br>          |                   |<br>   Inline Formula?       S3 Reference?<br>          |                   |<br>       Return           Fetch S3 Object<br>                              |<br>                        Merge Response<br>                              |<br>                           Return</pre><h3>Designing the Write Path</h3><p>The write logic ended up pretty simple:</p><ol><li>Build the complete formula object.</li><li>Estimate the serialized size.</li><li>Compare against a threshold (I set it at 320–350 KB for a safety margin).</li><li>Route it accordingly.</li></ol><pre>Formula Object<br>                       |<br>               Estimate Size<br>                       |<br>        +--------------+--------------+<br>        |                             |<br>  Below Threshold               Above Threshold<br>        |                             |<br>  DynamoDB Only                Upload to S3<br>                                      |<br>                          Store Metadata in DynamoDB</pre><p>As a sequence, it looks like this:</p><pre>Application<br>      |<br>      | Write Formula<br>      v<br> Estimate Size<br>      |<br> +----+----+<br> |         |<br>Small    Large<br> |         |<br>DDB      Upload to S3<br>            |<br>        Update DDB</pre><p>I picked a threshold well below the hard 400 KB ceiling on purpose, rather than pushing items right up against it. Schemas evolve. New attributes get added, serialization overhead shifts, and a record sitting comfortably at 390 KB today can drift past the limit after the next feature ships. Leaving that 320–350 KB buffer meant writes wouldn’t suddenly start failing just because a formula picked up a couple more fields. It turned a hard failure into something gradual and monitored instead.</p><h3>Designing the Read Path</h3><p>The key decision here was adding a resolver layer, so consumers stop caring where the data actually lives.</p><p>The application:</p><ol><li>Reads the DynamoDB item.</li><li>Checks for an S3 reference.</li><li>Fetches the S3 payload if one exists.</li><li>Returns a single merged object.</li></ol><p>Roughly:</p><pre>response = get_from_dynamodb()</pre><pre>if response.contains(&quot;s3DetailRef&quot;):<br>    payload = get_from_s3()<br>    return merge(response, payload)</pre><pre>return response</pre><p>Existing callers keep getting the same logical object they always did. Storage location becomes an implementation detail they never have to think about.</p><h3>Rethinking Updates</h3><p>Updates turned out to be the trickiest part.</p><p>Before, partial updates were dead simple: SET formulaDetails.skus = :data. That stops working the moment the payload moves to S3.</p><p>So updates now follow a storage-agnostic flow instead:</p><pre>Read → Resolve → Modify → Estimate Size → Store Inline or Offload to S3</pre><p>Doesn’t matter where the data currently sits. The update logic behaves the same either way.</p><h3>Reliability Considerations</h3><p>Adding S3 into the mix brings its own set of failure modes.</p><p><strong>Eventual consistency across two stores.</strong> The application still treats a formula as one logical object, but writes now span S3 and DynamoDB. That means the write is no longer atomic; there’s a short window where one store has the update and the other hasn’t caught up yet. I accepted that trade-off going in, but it meant putting real effort into retry handling and monitoring so a partial write never looks like corrupted or stale data to whoever’s reading it.</p><p><strong>Dual-write consistency.</strong> If DynamoDB succeeds but the S3 upload fails (or the reverse), you can end up with an inconsistent record. I reduced this by uploading to S3 first and only updating DynamoDB metadata once that upload succeeds.</p><p><strong>Missing objects.</strong> S3 objects can get deleted by accident. To catch that, I added resolver-side validation, error handling, monitoring, and alerts.</p><p><strong>Orphaned files.</strong> Formulas that expire in DynamoDB can leave behind unused S3 objects. I handle cleanup through S3 lifecycle policies, scheduled jobs, and DynamoDB Streams-based deletion.</p><h3>Performance Characteristics</h3><p>The main win of this whole approach is that it leaves performance alone for the common case.</p><p>Scenario Storage Additional Latency Small formula DynamoDB None Metadata-only read DynamoDB None Large formula DynamoDB + S3 ~50–100 ms Large formula update DynamoDB + S3 Additional S3 operations</p><p>Only the oversized records take the S3 hit. Everything else keeps DynamoDB’s low latency.</p><p>A rough sense of the numbers from production:</p><p>Before the change, about 98% of formulas sat under 300 KB, while roughly 2% exceeded the 400 KB limit and were failing outright.</p><p>After the change, writes succeeded across all formula sizes, existing consumers needed zero changes, and metadata-only reads stayed in the single-digit millisecond range.</p><p>There’s a cost angle worth mentioning too. Because only oversized payloads get offloaded, most records never touch S3 at all. Smaller formulas keep the same DynamoDB pricing profile they always had, without picking up extra S3 storage or request costs. The “two systems” overhead only applies to the slice of records that actually need it.</p><h3>Rolling It Out Safely</h3><p>Instead of migrating everything in one go, I rolled this out in stages.</p><p><strong>Phase 1, read compatibility.</strong> Deploy the resolver layer first. The application can now read both old inline records and newly offloaded ones. This meant I could ship the change without any downtime or a hard cutover; the resolver just handles both formats transparently while records migrate over time.</p><p><strong>Phase 2, update refactoring.</strong> Rework every update path to follow read, modify, write. Updates become storage-independent from this point on.</p><p><strong>Phase 3, enable offloading.</strong> Turn on size estimation and threshold-based routing so oversized writes start going to S3. This is the point where writes stop failing for good.</p><p><strong>Phase 4, operational hardening.</strong> Add infrastructure as code, monitoring, storage metrics, lifecycle policies, and cleanup automation.</p><h3>Key Takeaways</h3><p>The real lesson from this project wasn’t about DynamoDB specifically. It was about system design in general.</p><p>The 400 KB item limit isn’t just a database rule. It’s an architectural constraint that shapes how your data model needs to evolve as the product grows.</p><p>Rather than rebuild the entire data model or dump everything into object storage, I optimized for the workload that actually mattered most. The hybrid DynamoDB + S3 approach ended up giving me:</p><ul><li>No more item-size failures</li><li>The same access patterns consumers already relied on</li><li>Very few application-level changes</li><li>Room to scale well past DynamoDB’s storage limits</li><li>Fast reads and writes for the vast majority of traffic</li></ul><p>The bigger takeaway is that the best fix isn’t always swapping out a technology. Sometimes it’s knowing when to pair two technologies that are each good at different things.</p><p>DynamoDB is great at serving low-latency operational data. S3 is great at storing large, mostly-static payloads. Put both behind a simple abstraction and you get the size limit removed without giving up performance or forcing every consumer to change how they work.</p><p><strong>That’s usually what good system design comes down to: solving next year’s problem without making this year any harder than it needs to be.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=688ff3df8882" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Serverless Bottleneck: Mastering Lambda-to-Lambda Communication]]></title>
            <link>https://medium.com/@abhijitpatil669/the-serverless-bottleneck-mastering-lambda-to-lambda-communication-c9b4f060ca24?source=rss-b39db99eda0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9b4f060ca24</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Abhijit Patil]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 08:54:40 GMT</pubDate>
            <atom:updated>2026-07-05T08:54:40.710Z</atom:updated>
            <content:encoded><![CDATA[<h3>A system design guide to avoiding tight coupling, distributed monoliths, and messy service dependencies</h3><p>When you start building serverless systems with AWS Lambda, service communication feels almost too easy. One Lambda calls another through InvokeFunction, and that&#39;s it, done.</p><p>That simplicity holds up right until your system crosses 5–10 services. Past that point, you start noticing:</p><ul><li>Hidden coupling between services that were never supposed to know about each other</li><li>Payload shapes that quietly diverge across callers</li><li>Service boundaries that are nearly impossible to test in isolation</li><li>Latency chains that grow with every new hop</li><li>Handlers full of “wait, who’s calling this?” logic</li></ul><p>At scale, Lambda-to-Lambda communication stops being about <em>making calls</em> and becomes a question of:</p><blockquote><em>How do you design service boundaries that stay clean even when everything is connected to everything else?</em></blockquote><h3>The Core Problem</h3><p>Picture four services: Order, Inventory, Payment, and Notification.</p><p>Order calls Inventory, which leads to Payment, which leads to Notification:</p><pre>Order → Inventory → Payment → Notification</pre><p>Straightforward enough until the system evolves:</p><ul><li>Payment Service also needs its own inventory checks</li><li>A batch job reuses the same inventory logic</li><li>An admin tool needs to bypass Order Service entirely</li><li>New services join, each with a slightly different payload shape</li></ul><p>Inventory Service quietly turns into this:</p><pre>Inventory Service:<br>  if caller == OrderService → format A<br>  if caller == BatchJob     → format B<br>  if caller == AdminTool    → format C</pre><p>This is the moment a system silently becomes <strong>a distributed monolith with network hops</strong> — all the coupling of a monolith, none of the simplicity.</p><h3>What You’re Actually Designing For</h3><p>Before picking an approach, it helps to name what you actually want out of it:</p><p><strong>Loose coupling</strong> — a service shouldn’t need to know who’s calling it.</p><p><strong>Stable contracts</strong> — a service’s contract shouldn’t evolve based on who’s using it.</p><p><strong>Reusability</strong> — any service should be callable from any other, without rewriting its internals.</p><p><strong>Testability</strong> — services should be testable without spinning up AWS infrastructure.</p><p><strong>Clear sync vs. async semantics</strong> — request/response flows and event-driven side effects need to stay visibly distinct from each other.</p><h3>Four Approaches, and Where Each One Breaks</h3><h3>1. Direct Lambda Invoke</h3><p>The straightforward option: one service calls another Lambda directly via the AWS SDK.</p><p><strong>Strengths:</strong> simple, low latency, full control over the call.</p><p><strong>Weaknesses:</strong> couples services tightly, payload contracts diverge fast, callers end up needing to understand the target’s internals, and reuse across multiple callers gets messy.</p><p><strong>Where it breaks:</strong> every new caller adds complexity to the target service the coupling problem compounds with each addition.</p><h3>2. Event-Driven Messaging (SNS / EventBridge)</h3><p>Services publish events; any number of consumers react independently.</p><p><strong>Strengths:</strong> highly decoupled, ideal for fan-out, consumers scale independently of each other.</p><p><strong>Weaknesses:</strong> not request-response, there’s no immediate result, and tracing/debugging gets harder.</p><p><strong>Where it shines:</strong> async workflows. Where it doesn’t: anything with a real computational dependency on the result.</p><h3>3. Step Functions (Orchestration)</h3><p>A workflow engine coordinates a sequence of Lambdas.</p><p><strong>Strengths:</strong> built-in retries and branching, strong visibility into what happened at each step.</p><p><strong>Weaknesses:</strong> latency accumulates per step, cost climbs at volume, and it’s overkill for a plain service-to-service call.</p><p><strong>Where it lands:</strong> scales well operationally, but isn’t the right tool for high-frequency internal calls.</p><h3>4. A Shared Service-Client Abstraction (the Synthetic Event pattern)</h3><p>This is the approach worth focusing on. Instead of treating an internal call as “Lambda invokes Lambda,” you treat every call, no matter the source as a synthetic API request event.</p><h3>The Key Insight: One Contract for Every Caller</h3><p>Whether a request originates from API Gateway, a sibling Lambda, or a test runner, it should look identical by the time it reaches the service:</p><pre>{<br>  &quot;httpMethod&quot;: &quot;GET&quot;,<br>  &quot;resource&quot;: &quot;/inventory/check&quot;,<br>  &quot;queryStringParameters&quot;: {},<br>  &quot;body&quot;: &quot;{}&quot;,<br>  &quot;requestContext&quot;: {}<br>}</pre><p>The service simply doesn’t care who called it.</p><p><strong>Before</strong>, Inventory Service has to handle an API Gateway shape, an Order Service shape, and a batch-job shape, which inevitably leads to branching logic buried inside core business code.</p><p><strong>After</strong>, Inventory Service has one handler, one contract, one execution path. It has no concept of who’s on the other end of the call.</p><h3>The Communication Layer, Conceptually</h3><p>Rather than scattering direct Lambda invocations throughout your codebase, you introduce a thin shared abstraction, a service client responsible for:</p><ul><li>Building the synthetic event</li><li>Invoking the target Lambda</li><li>Normalizing the response shape</li><li>Handling errors consistently</li><li>Supporting both sync and async invocation</li></ul><p>Every caller goes through this one layer instead of reinventing the invocation logic each time.</p><h3>What This Looks Like in Code</h3><p>In practice, this abstraction lives inside a shared Lambda Layer attached to every function, so any service can pull it in with a single require.</p><pre>// service-connection/index.js<br>const { LambdaClient, InvokeCommand } = require(&#39;@aws-sdk/client-lambda&#39;);const lambda = new LambdaClient({ maxAttempts: 2 });<br>const PREFIX = process.env.SERVICE_PREFIX; // e.g. &quot;myapp-prod&quot;<br><br>const invoke = async (service, method, body, queryParams, invocationType) =&gt; {<br>    const functionName = service.split(&#39;/&#39;)[1];<br>    const syntheticEvent = {<br>        httpMethod: method,<br>        resource: service,<br>        queryStringParameters: queryParams,<br>        body: JSON.stringify(body),<br>        requestContext: { internalCall: true }, // trusted call, skip re-auth<br>    };<br>    const response = await lambda.send(new InvokeCommand({<br>        FunctionName: `${PREFIX}-${functionName}`,<br>        InvocationType: invocationType,<br>        Payload: JSON.stringify(syntheticEvent),<br>    }));<br>    if (invocationType === &#39;Event&#39;) return true;<br>    if (response.FunctionError) {<br>        const err = JSON.parse(Buffer.from(response.Payload).toString());<br>        throw Object.assign(new Error(`[${functionName}] ${err.errorMessage}`), { statusCode: 502 });<br>    }<br>    const payload = JSON.parse(Buffer.from(response.Payload).toString());<br>    if (payload.statusCode &gt;= 400) {<br>        const errorBody = JSON.parse(payload.body);<br>        throw Object.assign(new Error(errorBody.message), { statusCode: payload.statusCode, service });<br>    }<br>    return JSON.parse(payload.body).data;<br>};<br>// Synchronous - waits for a response<br>const readService = (service, queryParams = {}) =&gt; invoke(service, &#39;GET&#39;, {}, queryParams, &#39;RequestResponse&#39;);<br>const callService = (service, body = {}, queryParams = {}) =&gt; invoke(service, &#39;POST&#39;, body, queryParams, &#39;RequestResponse&#39;);<br>// Asynchronous - fire-and-forget<br>const fireAndForget = (service, body = {}, queryParams = {}) =&gt; invoke(service, &#39;POST&#39;, body, queryParams, &#39;Event&#39;);<br>module.exports = { readService, callService, fireAndForget };</pre><p>Every caller then gets the same three primitives, with the sync/async decision made explicit at the call site:</p><pre>// order-service/index.js<br>const { readService, callService, fireAndForget } = require(&#39;service-connection&#39;);<br><br>const createOrder = async (event) =&gt; {<br>    const { itemId, quantity, customerId } = JSON.parse(event.body);<br><br>    // Synchronous - business logic depends on this<br>    const stock = await readService(&#39;/inventory/check&#39;, { itemId });<br><br>    if (stock.available &lt; quantity) {<br>        return { statusCode: 400, body: JSON.stringify({ message: &#39;Out of stock&#39; }) };<br>    }<br><br>    // Synchronous - need confirmation before returning<br>    const payment = await callService(&#39;/payment/charge&#39;, { customerId, amount: 49.99 });<br>    <br>    // Asynchronous - a side effect, not a dependency<br>    await fireAndForget(&#39;/notification/send&#39;, { type: &#39;ORDER_CONFIRMED&#39;, to: customerId });<br><br>    return { statusCode: 201, body: JSON.stringify({ data: { payment } }) };<br>};</pre><p>Three calls, three different semantics, and the calling code never touches the AWS SDK directly.</p><p>On the receiving end, the target service’s auth middleware just checks one flag to decide whether to skip re-validation:</p><pre>// middleware/auth.js<br>const authMiddleware = async (event) =&gt; {<br>    if (event.requestContext?.internalCall === true) return; // trusted call<br><br>const token = event.headers?.Authorization?.replace(&#39;Bearer &#39;, &#39;&#39;);<br>    if (!token) throw Object.assign(new Error(&#39;Unauthorized&#39;), { statusCode: 401 });<br>    event.user = await verifyJWT(token);<br>};</pre><p>This is safe because internalCall is never something an external caller can set API Gateway has no path to forward it, and invoking the function at all requires an IAM permission on lambda:InvokeFunction that only sibling services hold.</p><p>The same contract that makes this pattern clean in production is what makes it easy to test a test runner can call the handler directly with a synthetic event and skip AWS entirely, which is a big part of why this abstraction pays for itself quickly.</p><h3>Sync vs. Async: The Decision That Matters Most</h3><p><strong>Synchronous (request/response)</strong> — use this when you need the data right now and your business logic depends on the answer. Order Service checking stock before confirming a purchase is the canonical example. The tradeoff: it adds to your latency chain and opens the door to cascading failures.</p><p><strong>Asynchronous (fire-and-forget)</strong> — use this for side effects with no immediate dependency on the result: sending a notification, logging an event, feeding an analytics pipeline. The tradeoff: no guaranteed response, harder debugging, and a real need for idempotency on the receiving end.</p><h3>The Chaining Tradeoff</h3><p>Lambda-to-Lambda calls scale poorly the deeper you chain them:</p><pre>Order → Inventory → Pricing → Tax → Payment</pre><p>Even at a modest 150–300ms per hop, four hops alone puts you at 600ms–1.2s of baseline latency — and cold starts can push that into multiple seconds.</p><p><strong>Rule of thumb:</strong> keep synchronous chains shallow — two hops, max.</p><h3>The Real Risk: Coupling You Can’t See</h3><p>Without a disciplined pattern, coupling creeps in quietly through shared payload assumptions, internal flags, and caller-specific branches buried in handlers.</p><p>This is worse than ordinary code coupling, because it’s <strong>distributed and invisible, </strong>nobody notices until three services break at once because one payload shape changed.</p><h3>A Better Mental Model</h3><p>Stop thinking:</p><blockquote><em>“Lambda A calls Lambda B.”</em></blockquote><p>Start thinking:</p><blockquote><em>“Service A makes a request to Service B through a standard API contract.”</em></blockquote><p>That reframing moves you from infrastructure thinking to API design thinking — and it’s a more durable way to reason about a growing system.</p><h3>What Scales and What Doesn’t</h3><p><strong>Scales well:</strong> adding new services with zero changes to existing ones, dramatically improved testability, services that stay genuinely independent, and trivial reuse across multiple callers.</p><p><strong>Doesn’t scale well:</strong> deep synchronous chains that amplify latency, large payloads crossing multiple hops, weak idempotency design, and leaning on request-response where an event would do.</p><h3>When to Skip This Pattern Entirely</h3><p>Synchronous Lambda-to-Lambda calls aren’t the right tool when:</p><ul><li>You’re building an event pipeline</li><li>You need fan-out to multiple consumers</li><li>You don’t actually need an immediate response</li><li>The workflow is long-running</li></ul><p>In those cases, reach for SNS or EventBridge instead.</p><h3>Design Summary</h3><p>Lambda-to-Lambda communication isn’t just a technical decision — it’s a <strong>service boundary design problem</strong>. Three models, each with a real tradeoff:</p><p><strong>Direct invocation — </strong>simple, but tightly coupled.</p><p><strong>Event-driven architecture</strong> — highly scalable, but no synchronous response.</p><p><strong>Synthetic Event abstraction</strong> — a balanced model for request-response, strong reuse, and clean boundaries, at the cost of requiring real discipline to maintain.</p><h3>Final Thought</h3><p>At scale, the question isn’t “how do Lambdas talk to each other?”</p><p>It’s:</p><blockquote><em>How do you keep service communication from turning into service dependency chaos?</em></blockquote><p>The fix isn’t more infrastructure. It’s a <strong>stronger abstraction around your communication contracts, </strong>one that every service, regardless of who’s calling it, can rely on staying the same.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9b4f060ca24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering call, apply, and bind — Practical Guide to Control "this" (Part 2)]]></title>
            <link>https://medium.com/@abhijitpatil669/mastering-call-apply-and-bind-practical-guide-to-control-this-part-2-343c0082aefd?source=rss-b39db99eda0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/343c0082aefd</guid>
            <category><![CDATA[apply]]></category>
            <category><![CDATA[bind]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[this-keyword]]></category>
            <category><![CDATA[call]]></category>
            <dc:creator><![CDATA[Abhijit Patil]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 06:02:47 GMT</pubDate>
            <atom:updated>2026-04-08T06:22:23.321Z</atom:updated>
            <content:encoded><![CDATA[<p>In Part 1, we understood how this works and why it often behaves unexpectedly. <br>You can check part 1 : <a href="https://medium.com/@abhijitpatil669/understanding-this-in-javascript-a-practical-guide-to-stop-the-confusion-fd092b274785">https://medium.com/@abhijitpatil669/understanding-this-in-javascript-a-practical-guide-to-stop-the-confusion-fd092b274785</a></p><p>Now comes the real question:</p><p>What do we do when this goes wrong?<br> How do we control it?</p><p>That’s exactly where call, apply, and bind comes in.</p><p>By the end of this article, you should be able to:</p><ul><li>Recognize when this will break</li><li>Fix it confidently</li><li>Understand what happens internally</li><li>Solve interview questions easily</li></ul><h3>First, Build the Right Mental Model</h3><p>Before jumping into the methods, get this clear:</p><p>JavaScript decides this at execution time, based on how a function is called.</p><p>So when this feels wrong, it’s usually not a bug—it’s just JavaScript doing what it’s supposed to.</p><p>call, apply, and bind give you a way to take control when needed.</p><h3>The Problem Pattern (Very Important)</h3><p>A lot of real-world bugs come from this pattern:</p><pre>const obj = {<br>  name: &quot;JS&quot;,<br>  print() {<br>    console.log(this.name);<br>  }<br>};<br><br>const fn = obj.print;<br>fn();</pre><p>What’s actually happening?</p><p>Call stack will call <strong>“fn()”</strong> Not <strong>“obj.print()”</strong></p><p>So:</p><ul><li>this is lost</li><li>Output: undefined</li></ul><h3>Key Insight</h3><p>Whenever a function is called without an object, this is usually not what you expect.</p><h3>1. call() — Execute Immediately with Correct this</h3><p>Think of it as:</p><p>“Run this function right now with this object”</p><p>Example:</p><pre>function greet() {<br>  console.log(this.name);<br>}<br><br>const user = { name: &quot;Abhijit&quot; };<br><br>greet.call(user);</pre><p>What’s happening internally?</p><p>Instead of <strong>“greet()”</strong></p><p>It behaves like:</p><pre>greet.call(user);<br>// similar to:<br>user.greet();</pre><p>Call Stack View: <strong>greet() (with this = user)</strong></p><p><strong>When to use:</strong></p><ul><li>Reusing functions across objects</li><li>Immediate execution</li><li>Simple scenarios</li></ul><h3>2. apply() — Same as call, but with Array</h3><p>Think of it as:</p><p>“Run this function now with this object and arguments as an array”</p><p>Example:</p><pre>function introduce(age, city) {<br>  console.log(this.name, age, city);<br>}<br><br>const user = { name: &quot;Abhijit&quot; };<br><br>introduce.apply(user, [25, &quot;Pune&quot;]);</pre><p>When to use:</p><ul><li>When arguments come as an array (API data, dynamic input)</li></ul><h3>3. bind() — Fix this for Later</h3><p>Think of it as:</p><p>“Create a new function where this is permanently fixed”</p><p>Example:</p><pre>function greet() {<br>  console.log(this.name);<br>}<br><br>const user = { name: &quot;Abhijit&quot; };<br><br>const fn = greet.bind(user);<br><br>fn();</pre><p>What’s happening internally?</p><pre>const fn = greet.bind(user);</pre><p>Creates a new function like:</p><pre>function () {<br>  return greet.call(user);<br>}</pre><p>Call Stack View:</p><pre>fn()<br> -&gt; greet() with this = user</pre><p>When to use:</p><ul><li>Callbacks</li><li>Event handlers</li><li>Async code</li><li>Anywhere this might get lost</li></ul><p><strong>Real-World Case 1: setTimeout Bug</strong></p><pre>const user = {<br>  name: &quot;Abhijit&quot;,<br>  greet() {<br>    setTimeout(function () {<br>      console.log(this.name);<br>    }, 1000);<br>  }<br>};</pre><p>Execution Flow:</p><ol><li>greet() runs with this = user</li><li>setTimeout registers callback</li><li>After 1 second: <strong>“callback()” </strong>NOT<strong> “user.callback()”</strong></li></ol><p>Problem:</p><ul><li>this becomes window or undefined</li></ul><p>Fix:</p><pre>setTimeout(function () {<br>  console.log(this.name);<br>}.bind(this), 1000);</pre><p>Learning:</p><ul><li>When function runs later (async), this can be lost</li><li>Use bind or arrow functions</li></ul><p><strong>Real-World Case 2: Event Handlers</strong></p><pre>const button = {<br>  text: &quot;Click&quot;,<br>  handleClick() {<br>    console.log(this.text);<br>  }<br>};<br><br>document.addEventListener(&quot;click&quot;, button.handleClick);</pre><p>What happens?</p><pre>handleClick()<br><br>&quot;this&quot; is lost</pre><p>Fix:</p><pre>document.addEventListener(<br>  &quot;click&quot;,<br>  button.handleClick.bind(button)<br>);</pre><p>Learning:</p><ul><li>Always bind when passing object methods as event handlers</li></ul><p><strong>Pattern Recognition (Most Important Skill)</strong></p><p>These patterns break this:</p><pre>setTimeout(obj.method, 1000);<br>const fn = obj.method;<br>return obj.method;</pre><p>Fix using:</p><pre>.bind(obj)<br><br>OR<br><br>() =&gt; obj.method()</pre><p><strong>Execution-Level Understanding</strong></p><p>Without bind:</p><pre>callback()<br> -&gt; this = window</pre><p>With bind:</p><pre>callback()<br> -&gt; behaves like:<br>callback.call(user)<br> -&gt; this = user</pre><h3>When to Use What</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TLxRiFyR0FcDiDI8fnB_mQ.png" /></figure><p><strong>Practice (Think Before Answer)</strong></p><pre>function show() {<br>  console.log(this.name);<br>}<br><br>const user = { name: &quot;JS&quot; };<br><br>setTimeout(show, 1000);<br><br>// Fix it</pre><pre>const obj = {<br>  name: &quot;JS&quot;,<br>  print() {<br>    console.log(this.name);<br>  }<br>};<br><br>const fn = obj.print;<br>fn();<br><br>// fix it</pre><p><strong>Tricky Interview Questions</strong></p><pre>var name = &quot;Global&quot;;<br><br>const obj = {<br>  name: &quot;Object&quot;,<br>  getName() {<br>    return this.name;<br>  }<br>};<br><br>const fn = obj.getName;<br>console.log(fn());<br><br><br>// Answer:<br>// Browser → &quot;Global&quot;<br>// Node → undefined</pre><pre>const obj = {<br>  name: &quot;JS&quot;,<br>  print() {<br>    console.log(this.name);<br>  }<br>};<br><br>setTimeout(obj.print, 1000);<br><br>// OUTPUT : Undefined<br><br>// FIX:<br>setTimeout(obj.print.bind(obj), 1000);</pre><pre>const obj = {<br>  name: &quot;JS&quot;,<br>  print() {<br>    return function () {<br>      console.log(this.name);<br>    };<br>  }<br>};<br><br>obj.print()();<br><br>// Output: undefined</pre><pre>function show() {<br>  console.log(this.name);<br>}<br><br>const user = { name: &quot;A&quot; };<br><br>const fn = show.bind(user);<br>fn.call({ name: &quot;B&quot; });<br><br>// Output: &quot;A&quot;<br>// Reason: bind cannot be overridden</pre><pre>function add(a, b) {<br>  console.log(this.name, a + b);<br>}<br><br>const obj = { name: &quot;Test&quot; };<br><br>add.apply(obj, [1, 2]);<br><br>// Output: &quot;Test 3&quot;</pre><pre>const obj = {<br>  name: &quot;JS&quot;,<br>  print() {<br>    console.log(this.name);<br>  }<br>};<br><br>(obj.print = obj.print)();<br><br>// Output: undefined<br>// Reason: assignment breaks reference</pre><pre>const obj = {<br>  name: &quot;JS&quot;,<br>  print() {<br>    console.log(this.name);<br>  }<br>};<br><br>const fn = obj.print.bind(obj);<br>setTimeout(fn, 1000);<br><br>//Output: &quot;JS&quot;<br>// Reason: bind permanently fixes this</pre><h3>Execution Mindset</h3><p>Whenever you see a function, ask:</p><p>How is it being called?</p><pre>Case 1:<br>fn()<br> -&gt; this lost<br><br>Case 2:<br>obj.fn()<br> -&gt; this = obj<br><br>Case 3:<br>fn.bind(obj)()<br> -&gt; this = obj</pre><h3>Final Takeaway</h3><ul><li>this breaks when a function loses its object</li><li>call and apply fix it immediately</li><li>bind fixes it permanently</li><li>Most bugs happen in async or detached functions</li></ul><h3>Final Mental Model</h3><p>Whenever you see a function, ask:</p><p>“How will this function be called?”</p><pre>If it&#39;s: callback()<br>this is gone<br><br>If it’s:obj.method()<br>this is safe</pre><p>Once you start spotting these patterns, you won’t just understand this — you’ll be able to predict it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=343c0082aefd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding “this" in JavaScript — A Practical Guide to Stop the Confusion (Part 1)]]></title>
            <link>https://medium.com/@abhijitpatil669/understanding-this-in-javascript-a-practical-guide-to-stop-the-confusion-fd092b274785?source=rss-b39db99eda0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd092b274785</guid>
            <category><![CDATA[this-binding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[js-function]]></category>
            <category><![CDATA[javascript-this-keyword]]></category>
            <dc:creator><![CDATA[Abhijit Patil]]></dc:creator>
            <pubDate>Mon, 06 Apr 2026 05:43:12 GMT</pubDate>
            <atom:updated>2026-04-07T13:35:06.603Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever been confused by this in JavaScript, you’re not alone.</p><p>At some point, almost every developer hits a wall with it. You write code thinking this refers to one thing… and it turns out to be something completely different.</p><p>The good news?<br>Once you understand one core idea, everything starts making sense.</p><h3>The One Rule You Need to Remember</h3><p>Let’s start with the most important line in this entire topic:</p><blockquote><strong><em>this depends on how a function is called, not where it is written.</em></strong></blockquote><p>That’s it.</p><p>Most confusion happens when we assume this is tied to where the function is defined. It’s not. It’s tied to how the function is executed.</p><h3>Function Creation vs Function Execution</h3><p>Before diving into examples, there’s one important concept.</p><p>When JavaScript sees a function, it doesn’t execute it immediately. It just stores it in memory.</p><pre>function greet() {<br>  console.log(this);<br>}</pre><p>At this stage:</p><ul><li>The function is created</li><li>Its code is stored</li><li>Its surrounding variables are stored</li><li>But this is NOT decided yet</li></ul><p><strong>this only gets its value when the function actually runs.</strong></p><h3>Case 1: Method Call (Most Straightforward)</h3><pre>const user = {<br>  name: &quot;Abhijit&quot;,<br>  greet() {<br>    console.log(this.name);<br>  }<br>};</pre><pre>user.greet();</pre><p>Here, the function is called as a method of user.</p><p>So naturally:</p><pre>this → user</pre><p>Output:</p><pre>Abhijit</pre><p>No surprises here.</p><h3>Case 2: Normal Function Call</h3><pre>function show() {<br>  console.log(this);<br>}</pre><pre>show();</pre><p>This is a standalone function call.</p><p>So what is this?</p><ul><li>In browser (non-strict): window</li><li>In strict mode: undefined</li><li>In Node.js: global</li></ul><p>This is where things start getting tricky.</p><h3>Case 3: Constructor Function (new keyword)</h3><pre>function Person(name) {<br>  this.name = name;<br>}</pre><pre>const p1 = new Person(&quot;Abhijit&quot;);</pre><p>When you use new, JavaScript:</p><ul><li>Creates a new object</li><li>Sets this to that object</li></ul><p>So:</p><pre>this → newly created object</pre><h3>Case 4: Arrow Functions (Very Important)</h3><pre>const user = {<br>  name: &quot;Abhijit&quot;,<br>  greet() {<br>    const inner = () =&gt; {<br>      console.log(this.name);<br>    };<br>    inner();<br>  }<br>};</pre><pre>user.greet();</pre><p>Arrow functions behave differently.</p><p>They don’t create their own this. Instead, they use whatever this was outside.</p><p>In this case:</p><ul><li>greet() has this = user</li><li>Arrow function uses the same this</li></ul><p>Output:</p><pre>Abhijit</pre><h3>The Famous setTimeout Problem</h3><p>This is one of the most common interview questions.</p><pre>const user = {<br>  name: &quot;Abhijit&quot;,<br>  greet() {<br>    setTimeout(function () {<br>      console.log(this.name);<br>    }, 1000);<br>  }<br>};</pre><pre>user.greet();</pre><p>At first glance, it looks like it should print &quot;Abhijit&quot;.</p><p>But it doesn’t.</p><h3>What Actually Happens</h3><ol><li>user.greet() runs → this = user</li><li>setTimeout receives the function</li><li>Timer starts</li><li>greet() finishes</li><li>After 1 second, the function runs like this:</li></ol><pre>callback();</pre><p>Not:</p><pre>user.callback();</pre><p>So now it’s just a normal function call.</p><p>Which means:</p><pre>this → window (or undefined in strict mode)</pre><p>Output:</p><pre>undefined</pre><h3>Fixing It</h3><p>Use an arrow function:</p><pre>setTimeout(() =&gt; {<br>  console.log(this.name);<br>}, 1000);</pre><p>Now it works because the arrow function uses the outer this.</p><h3>Method Detachment — A Subtle Bug</h3><pre>const user = {<br>  name: &quot;JS&quot;,<br>  sayHi() {<br>    console.log(this.name);<br>  }<br>};</pre><pre>const fn = user.sayHi;<br>fn();</pre><p>Here, you extracted the function from the object.</p><p>So when you call fn():</p><pre>this → lost</pre><p>It’s no longer connected to user.</p><h3>Returning a Function — Another Trap</h3><pre>const obj = {<br>  name: &quot;JS&quot;,<br>  print() {<br>    return function () {<br>      console.log(this.name);<br>    };<br>  }<br>};</pre><pre>obj.print()();</pre><p>What happens here?</p><ul><li>print() returns a function</li><li>That function is called separately</li></ul><p>So again:</p><pre>this → not obj</pre><p>Output:</p><pre>undefined</pre><h3>Browser vs Node Difference</h3><p>This one confuses a lot of people.</p><pre>var name = &quot;Global&quot;;</pre><p>In browser:</p><pre>window.name = &quot;Global&quot;</pre><p>In Node:</p><pre>name is NOT attached to global</pre><p>So the same code can behave differently depending on where you run it.</p><h3>Understanding the Flow (Quick Version)</h3><p>For async cases like setTimeout:</p><ol><li>Function runs</li><li>Timer is registered</li><li>Function finishes</li><li>After delay → callback executes</li><li>Callback runs as a normal function</li><li>this is assigned at that moment</li></ol><h3>Practice Questions</h3><p>Try to solve these before checking answers mentally.</p><h3>1</h3><pre>const obj = {<br>  name: &quot;JS&quot;,<br>  getName() {<br>    return this.name;<br>  }<br>};</pre><pre>const fn = obj.getName;<br>console.log(fn());</pre><h3>2</h3><pre>const obj = {<br>  name: &quot;JS&quot;,<br>  print() {<br>    console.log(this.name);<br>  }<br>};</pre><pre>(obj.print)();</pre><h3>3</h3><pre>const obj = {<br>  name: &quot;JS&quot;,<br>  print() {<br>    setTimeout(() =&gt; {<br>      console.log(this.name);<br>    }, 1000);<br>  }<br>};</pre><pre>obj.print();</pre><h3>4</h3><pre>function Person(name) {<br>  this.name = name;<br>}</pre><pre>const p = Person(&quot;JS&quot;);<br>console.log(p);</pre><h3>5</h3><pre>function show() {<br>  console.log(this);<br>}</pre><pre>show.call({ name: &quot;JS&quot; });</pre><h3>Final Takeaway</h3><p>If you’re ever confused about this, pause and ask:</p><blockquote><strong><em>“How is this function being called?”</em></strong></blockquote><p>That one question will solve most problems.</p><h3>Closing Thoughts</h3><p>Once you understand this, a lot of JavaScript starts to feel more predictable.</p><p>You’ll:</p><ul><li>Debug faster</li><li>Avoid common mistakes</li><li>Handle async code better</li><li>Perform well in interviews</li></ul><p>And most importantly, you won’t feel confused every time you see this in code.</p><p>Take some time to practice these patterns, and you’ll be in a very strong position.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd092b274785" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Clearing a Number Input in React Turns It Into 0 (And How I Finally Fixed It)]]></title>
            <link>https://medium.com/@abhijitpatil669/why-clearing-a-number-input-in-react-turns-it-into-0-and-how-i-finally-fixed-it-50f2a5ec294b?source=rss-b39db99eda0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/50f2a5ec294b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[type-coercion]]></category>
            <category><![CDATA[react-forms]]></category>
            <dc:creator><![CDATA[Abhijit Patil]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 11:23:37 GMT</pubDate>
            <atom:updated>2026-01-28T11:23:57.997Z</atom:updated>
            <content:encoded><![CDATA[<p>I still remember the first time this happened.</p><p>I typed 2 into a React &lt;input type=&quot;number&quot;&gt;.<br> Everything worked fine.</p><p>Then I pressed backspace.</p><p>Suddenly, my state became 0.</p><p>No error.<br> No warning.<br> Just… 0.</p><p>If you’ve ever worked with <strong>React forms</strong>, chances are you’ve seen this too — and probably blamed React for it.</p><p>I did.</p><p>Turns out, React was innocent all along.</p><h3>The Bug That Isn’t Actually a Bug</h3><p>Here’s the kind of code most of us have written at least once:</p><pre>import { useState } from &quot;react&quot;;<br><br>function Example() {<br>  const [value, setValue] = useState(0);<br><br>  return (<br>    &lt;input<br>      type=&quot;number&quot;<br>      value={value}<br>      onChange={(e) =&gt; setValue(Number(e.target.value))}<br>    /&gt;<br>  );<br>}</pre><h3>What happens?</h3><ul><li>Type 2 → state becomes 2</li><li>Clear the input → state becomes 0</li></ul><p>At first glance, this feels <strong>wrong</strong>.</p><p>From a user’s perspective:</p><ul><li>Empty input ≠ zero</li><li>Clearing a field should keep it empty</li></ul><p>So why does this happen?</p><h3>The Real Culprit: JavaScript, Not React</h3><p>The answer lies in a single JavaScript rule:</p><pre>Number(&quot;&quot;) === 0</pre><p>When a number input is cleared:</p><ul><li>e.target.value becomes an <strong>empty string</strong></li><li>You explicitly convert it using Number(...)</li><li>JavaScript converts &quot;&quot; into 0</li></ul><p>React is doing exactly what you asked it to do.</p><p>This is not a React bug.<br> It’s <strong>type coercion</strong>.</p><h3>Why &lt;input type=&quot;number&quot;&gt; Is Misleading</h3><p>Here’s the part that trips up many developers:</p><blockquote><strong><em>Even number inputs return strings</em></strong></blockquote><p>Yes — always.</p><pre>typeof e.target.value // &quot;string&quot;</pre><p>HTML inputs are <strong>text-based UI controls</strong>, regardless of their type.</p><p>That means:</p><ul><li>Users can delete values</li><li>Users can type partial values (-, ., 1.)</li><li>The input must support “invalid” intermediate states</li></ul><p>And numbers… don’t.</p><h3>The Moment It Clicked for Me</h3><p>The breakthrough came when I stopped thinking like this:</p><blockquote><em>“This is a number input, so I should store a number”</em></blockquote><p>And started thinking like this:</p><blockquote><em>“This is a user typing text, and I’ll interpret it later”</em></blockquote><p>That mental shift changes everything.</p><h3><strong>The Correct Way to Handle Number Inputs in React</strong></h3><p>Store the value as a <strong>string</strong></p><pre>import { useState } from &quot;react&quot;;<br><br>function Example() {<br>  const [value, setValue] = useState(&quot;&quot;);<br><br>  return (<br>    &lt;input<br>      type=&quot;number&quot;<br>      value={value}<br>      onChange={(e) =&gt; setValue(e.target.value)}<br>    /&gt;<br>  );<br>}</pre><h3>What changes?</h3><ul><li>Type 2 → &quot;2&quot;</li><li>Clear input → “ ”</li><li>No forced 0</li><li>No broken UX</li></ul><p>This is the pattern used in <strong>real production React apps</strong>.</p><h3>Convert to Number Only When It Actually Matters</h3><p>Instead of converting on every keystroke, convert when you need to:</p><ul><li>On submit</li><li>Before calculations</li><li>Before API calls</li></ul><pre>const numericValue =<br>  value === &quot;&quot; ? null : Number(value);</pre><p>Now your:</p><ul><li>UI stays flexible</li><li>Logic stays predictable</li><li>Validation becomes easier</li></ul><h3><strong>The Common Anti-Pattern</strong></h3><pre>onChange={(e) =&gt; setValue(Number(e.target.value))}</pre><p>Why this causes problems:</p><ul><li>Empty input becomes 0</li><li>Partial typing breaks</li><li>Validation becomes messy</li><li>UX feels broken</li></ul><p>This pattern looks clean — but behaves badly.</p><h3>“But My State Must Be a Number”</h3><p>Sometimes you’re stuck with legacy APIs or strict schemas.</p><p>In that case:</p><pre>onChange={(e) =&gt; {<br>  const val = e.target.value;<br>  setValue(val === &quot;&quot; ? &quot;&quot; : Number(val));<br>}}</pre><p>Your state becomes:</p><pre>number | &quot;&quot;</pre><p>It works — but it’s still a compromise.</p><h3>Bonus UX Tip Most People Miss</h3><p>Number inputs change when users scroll their mouse wheel.</p><p>Disable it like this:</p><pre>&lt;input<br>  type=&quot;number&quot;<br>  onWheel={(e) =&gt; e.target.blur()}<br>/&gt;</pre><h3>Interview Question You’ll Probably Get</h3><p><strong>Q: Why does clearing a number input set the value to 0 in React?</strong><br> <strong>A:</strong> Because clearing the input produces an empty string, and Number(&quot;&quot;) evaluates to 0. The correct approach is to store the value as a string and convert it only when required.</p><h3>Final Thoughts</h3><p>This issue looks small.<br> But it reveals something important:</p><ul><li>How well you understand the browser</li><li>How React actually handles inputs</li><li>Whether you think in terms of <strong>user behavior</strong>, not just types</li></ul><p>Once you see inputs as <strong>text first, data later</strong>, many React form problems disappear.</p><p>And yes — the next time your number input turns into 0, you’ll know exactly why.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50f2a5ec294b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete React Rendering Flow]]></title>
            <link>https://medium.com/@abhijitpatil669/the-complete-react-rendering-flow-2831fcc45529?source=rss-b39db99eda0b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2831fcc45529</guid>
            <category><![CDATA[react-internal]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[optimize-react-rendering]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[react-interview]]></category>
            <dc:creator><![CDATA[Abhijit Patil]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 07:38:46 GMT</pubDate>
            <atom:updated>2026-01-28T07:38:46.595Z</atom:updated>
            <content:encoded><![CDATA[<h3>Render Phase, DOM Commit, Browser Paint &amp; Effects (with Diagrams)</h3><p>If you’ve ever been confused by statements like:</p><ul><li>“Render does NOT mean UI is shown”</li><li>“useEffect runs after paint”</li><li>“JSX runs but nothing is visible yet”</li></ul><p>You’re not alone.</p><p>This article explains <strong>how React actually works internally</strong>, using:</p><ul><li>Simple language</li><li>Clear step-by-step flow</li><li>Easy diagrams</li><li>A real‑world <strong>house construction analogy</strong></li></ul><h3>The Core Idea (Most Important)</h3><blockquote><strong><em>React does not show UI when it renders.<br>It only </em>decides<em> what the UI should look like.</em></strong></blockquote><p>Showing UI on the screen is the <strong>browser’s job</strong>, not React’s.</p><p><strong>Render = deciding WHAT the UI should look like</strong><br><strong>Paint = actually SHOWING it on screen</strong></p><h3>High‑Level Flow</h3><pre>React (JS Thread)<br>│<br>├─ Render Phase<br>│<br>├─ DOM Commit Phase<br>│<br>│        ↓<br>│   Browser Paint (UI visible)<br>│        ↓<br>└─ React useEffect</pre><p>Key clarification:</p><ul><li>useEffect is <strong>React code</strong></li><li>It runs <strong>after</strong> the browser paints</li><li>It is <strong>not executed by the browser</strong></li></ul><h3>The House Construction Analogy</h3><p>Real World React Architect draws blueprint — Render phase</p><p>Builders construct house — DOM Commit</p><p>House opens to people — Browser Paint</p><p>Furniture &amp; setup — useEffect</p><p>Blueprint ≠ House<br>JSX ≠ Screen UI</p><h3>Step 1: Render Phase — Creating the Blueprint</h3><h3>What “render” actually means in React</h3><p>In React, rendering simply means <strong>calling your component function</strong>.</p><pre>function App() {<br>  console.log(&quot;render&quot;);<br>  return &lt;div&gt;Hello&lt;/div&gt;;<br>}</pre><h3>What happens during render?</h3><pre>React calls component()<br>      ↓<br>JavaScript executes<br>      ↓<br>JSX is evaluated<br>      ↓<br>Virtual DOM (blueprint) is created</pre><p>No real DOM updates<br>Nothing visible on screen</p><p>Render is <strong>pure calculation</strong>, just like an architect drawing plans.</p><h3>Step 2: JSX Is NOT the UI</h3><p>This JSX:</p><pre>&lt;div&gt;Hello&lt;/div&gt;</pre><p>Becomes a plain JavaScript object:</p><pre>{<br>  type: &quot;div&quot;,<br>  props: { children: &quot;Hello&quot; }<br>}</pre><p>Diagram:</p><pre>JSX<br> ↓<br>JavaScript Object<br> ↓<br>Virtual DOM</pre><p>This is <strong>data</strong>, not pixels.</p><h3>Why {console.log()} Runs Inside JSX</h3><pre>return (<br>  &lt;div&gt;<br>    {console.log(&quot;inside JSX&quot;)}<br>    Hello<br>  &lt;/div&gt;<br>);</pre><p>Because JSX is just JavaScript, expressions inside {} run <strong>during render</strong>, while the blueprint is being created.</p><h3>Step 3: DOM Commit Phase — Construction Begins</h3><p>Once React finishes render, it moves to the <strong>commit phase</strong>.</p><h3>What happens here?</h3><pre>Virtual DOM<br>    ↓<br>Real DOM nodes created<br>    ↓<br>Text &amp; attributes applied</pre><p>This is equivalent to <strong>builders constructing the house</strong>.</p><p>First time the real DOM is touched<br>Still not visible yet</p><h3>Step 4: useLayoutEffect — Before the House Opens</h3><pre>useLayoutEffect(() =&gt; {<br>  console.log(&quot;useLayoutEffect&quot;);<br>}, []);</pre><h3>When it runs</h3><pre>Render → Commit → useLayoutEffect → Paint</pre><p>Diagram:</p><pre>DOM Built<br>   ↓<br>useLayoutEffect<br>   ↓<br>Browser Paint</pre><h3>Analogy</h3><p>This is like:</p><ul><li>Measuring door frames</li><li>Fixing wall alignment</li><li>Making last‑minute layout adjustments</li></ul><p>⚠️ Heavy work here blocks painting and hurts performance.</p><h3>Step 5: Browser Paint — UI Becomes Visible</h3><p>Now the browser takes control.</p><h3>What paint means</h3><ul><li>Layout calculation</li><li>Pixel drawing</li><li>Layer compositing</li></ul><p>Diagram:</p><pre>DOM Ready<br>   ↓<br>Browser Paint<br>   ↓<br>UI visible to user</pre><p>This is the <strong>first moment the user sees the UI</strong>.</p><h3>Step 6: useEffect — After UI Is Visible</h3><pre>useEffect(() =&gt; {<br>  console.log(&quot;useEffect&quot;);<br>}, []);</pre><h3>Important clarification</h3><ul><li>useEffect is <strong>executed by React</strong></li><li>It runs on the <strong>JS thread</strong></li><li>It runs <strong>after browser paint</strong></li></ul><h3>Timing</h3><pre>Browser Paint<br>     ↓<br>React useEffect</pre><h3>Analogy</h3><p>This is like:</p><ul><li>Adding furniture</li><li>Connecting electricity</li><li>Installing Wi‑Fi</li></ul><p>These tasks should <strong>not delay opening the house</strong>.</p><h3>Full Timeline Diagram</h3><pre>JS Thread (React)<br>│<br>├─ Render Phase<br>│    ├─ component function runs<br>│    ├─ JSX executes<br>│<br>├─ DOM Commit Phase<br>│    ├─ real DOM updates<br>│    ├─ useLayoutEffect<br>│<br>│        (handoff)<br>│        ↓<br>│   Browser Paint (UI visible)<br>│        ↓<br>│        (back to JS)<br>│<br>└─ React useEffect</pre><h3>Real Code Example With Output Order</h3><pre>function App() {<br><br>  console.log(&quot;1. render&quot;);<br><br>  useLayoutEffect(() =&gt; {<br>    console.log(&quot;2. useLayoutEffect&quot;);<br>  }, []);<br><br>  useEffect(() =&gt; {<br>    console.log(&quot;3. useEffect&quot;);<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      {console.log(&quot;4. inside return&quot;)}<br>      Hello<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Output</h3><pre>1. render<br>4. inside return<br>----------------<br>DOM Commit<br>2. useLayoutEffect<br>----------------<br>Browser Paint (UI visible)<br>3. useEffect</pre><h3>Common Mistakes This Model Fixes</h3><p>Doing side effects in render<br>Accessing DOM in render<br>Overusing useLayoutEffect<br>Thinking re‑render = repaint</p><h3>Golden Rules to Remember</h3><ul><li>Render must be <strong>pure</strong></li><li>JSX is <strong>calculation</strong>, not UI</li><li>DOM commit updates structure</li><li>Browser paint shows UI</li><li>useEffect runs <strong>after paint</strong>, but is <strong>React’s job</strong></li></ul><h3>One‑Line Summary (Interview Gold)</h3><blockquote><strong><em>Render creates the blueprint, commit builds the DOM, paint shows the UI, and effects run after.</em></strong></blockquote><h3>Final Thoughts</h3><p>Once you separate <strong>calculation</strong> from <strong>visual output</strong>, React becomes predictable and intuitive.</p><p>This mental model helps you:</p><ul><li>Write correct hooks</li><li>Avoid performance bugs</li><li>Think clearly about rendering</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2831fcc45529" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>