<?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 Krishna bokefod on Medium]]></title>
        <description><![CDATA[Stories by Krishna bokefod on Medium]]></description>
        <link>https://medium.com/@krishnabokefod?source=rss-bb29547748c8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*63_YVVzvcdFLDvWa4bvb0w.jpeg</url>
            <title>Stories by Krishna bokefod on Medium</title>
            <link>https://medium.com/@krishnabokefod?source=rss-bb29547748c8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:57:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krishnabokefod/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[CQRS Explained: When Separating Reads and Writes Actually Makes Sense]]></title>
            <link>https://medium.com/@krishnabokefod/cqrs-explained-when-separating-reads-and-writes-actually-makes-sense-7df80211cba7?source=rss-bb29547748c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7df80211cba7</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[cqrs]]></category>
            <dc:creator><![CDATA[Krishna bokefod]]></dc:creator>
            <pubDate>Sat, 22 Aug 2026 07:01:02 GMT</pubDate>
            <atom:updated>2026-08-22T07:01:02.993Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8O_ItblgsyS6NM9tZWll4A.png" /></figure><p>There is a point in almost every growing backend system where the database starts doing two very different jobs.</p><p>One part of the application is constantly changing data.</p><p>Orders are being created.</p><p>Payments are being processed.</p><p>Accounts are being updated.</p><p>Inventory is being reserved.</p><p>Transactions are being recorded.</p><p>At the same time, another part of the application is constantly asking questions about that data.</p><p>Show me the customer’s order history.</p><p>Give me today’s sales dashboard.</p><p>Search for products.</p><p>Show the top-selling products.</p><p>Generate the monthly report.</p><p>Give me the customer’s current balance.</p><p>And eventually, someone notices something uncomfortable:</p><p><strong>The way we store data for reliable writes is not necessarily the best way to read that data.</strong></p><p>A normalized relational model might be excellent for maintaining consistency.</p><p>But the same model can become painful when the application needs complex dashboards, search, reporting, aggregations, joins, and high-volume reads.</p><p>This is where <strong>CQRS</strong> enters the conversation.</p><p>CQRS stands for:<br><strong><em>Command Query Responsibility Segregation</em></strong></p><p>The idea sounds simple:</p><pre>Commands → Change state<br><br>Queries → Read state</pre><p>But CQRS is often misunderstood.</p><p>It does <strong>not</strong> simply mean:<br><em>“Use two databases.”</em></p><p>It does <strong>not</strong> automatically mean:<br><em>“Use microservices.”</em></p><p>It does <strong>not</strong> require:<br><em>“Event sourcing.”</em></p><p>And it definitely does not mean:<br><em>“Every application should have separate read and write models.”</em></p><p>CQRS is fundamentally about <strong>separating the responsibility of changing state from the responsibility of reading state</strong>.</p><p>Once you understand why that separation can be useful, you can also understand when it is completely unnecessary.</p><p>Let’s start with the problem CQRS is trying to solve.</p><h3>The Traditional CRUD Application</h3><p>Imagine an e-commerce application.</p><p>We have customers, orders, products, payments, and inventory.</p><p>A simplified relational database might look like:</p><pre>customers<br>---------<br>id<br>name<br>email<br><br>orders<br>------<br>id<br>customer_id<br>status<br>created_at<br><br>order_items<br>-----------<br>id<br>order_id<br>product_id<br>quantity<br><br>products<br>--------<br>id<br>name<br>price</pre><p>This is a perfectly reasonable design.</p><p>When someone creates an order, the application might execute several operations:</p><pre>Create Order<br>     ↓<br>Insert order<br>     ↓<br>Insert order items<br>     ↓<br>Update inventory<br>     ↓<br>Record payment</pre><p>The database is designed to maintain strong consistency between these entities.</p><p>Now imagine the customer opens:</p><pre>&quot;My Orders&quot;</pre><p>The application needs something like:</p><pre>SELECT ...<br>FROM orders<br>JOIN order_items ...<br>JOIN products ...<br>WHERE customer_id = ?;</pre><p>That is still manageable.</p><p>But now the business asks for a dashboard.</p><p>They want:</p><pre>Revenue today<br>Orders today<br>Average order value<br>Top products<br>Orders by country<br>Orders by payment method<br>Customer lifetime value<br>Refund rate<br>Conversion rate</pre><p>Suddenly, the same database is being asked to do something very different.</p><p>The write model is optimized around maintaining the correctness of business data.</p><p>The dashboard wants a model optimized around <strong>reading and aggregating information quickly</strong>.</p><p>And this is where the tension begins.</p><h3>The Same Model Is Being Asked to Do Two Different Jobs</h3><p>Traditional CRUD often looks like this:</p><pre>Application<br>                   │<br>          ┌────────┴────────┐<br>          │                 │<br>       Commands           Queries<br>          │                 │<br>          └────────┬────────┘<br>                   ↓<br>               Database</pre><p>The same model handles:</p><pre>Create<br>Read<br>Update<br>Delete</pre><p>This is completely fine for many applications.</p><p>In fact, it should usually be your starting point.</p><p>But imagine a system where:</p><pre>Writes:<br>100 requests/sec</pre><pre>Reads:<br>50,000 requests/sec</pre><p>And the read queries are completely different from the write operations.</p><p>The application might spend most of its resources serving queries that don’t resemble the way data is written.</p><p>At this point, separating responsibilities can become attractive.</p><h3>What Does CQRS Actually Mean?</h3><p>CQRS says:<br><em>Instead of forcing the same model to handle both commands and queries, allow the command side and query side to have different models optimized for their respective responsibilities.</em></p><p>So instead of:</p><pre>Application<br>                  │<br>          ┌───────┴───────┐<br>          │               │<br>        Write            Read<br>          │               │<br>          └───────┬───────┘<br>                  ↓<br>              One Model</pre><p>we can have:</p><pre>Application<br>                     │<br>           ┌─────────┴─────────┐<br>           │                   │<br>        Commands             Queries<br>           │                   │<br>           ▼                   ▼<br>      Write Model          Read Model<br>           │                   │<br>           ▼                   ▼<br>      Write Store           Read Store</pre><p>The important part is not necessarily two physical databases.</p><p>The important part is:</p><pre>Different responsibilities<br>        ↓<br>Different models<br>        ↓<br>Different optimization strategies</pre><p>The physical storage can be separated later if necessary.</p><h3>Command and Query</h3><p>Let’s define the two terms properly.</p><p>A <strong>command</strong> represents an operation that wants to change the state of the system.</p><p>For example:</p><pre>CreateOrder<br>CancelOrder<br>UpdateAddress<br>ApprovePayment<br>ReserveInventory<br>ChangePassword<br>TransferMoney</pre><p>A command says:<br><em>“I want the system to perform this operation.”</em></p><p>A <strong>query</strong>, on the other hand, asks for information.</p><p>For example:</p><pre>GetOrder<br>GetCustomer<br>SearchProducts<br>GetOrderHistory<br>GetDashboard<br>GetAccountBalance</pre><p>A query says:<br><em>“Tell me something about the current state.”</em></p><p>The conceptual separation is:</p><pre>Command<br>   ↓<br>Change State<br></pre><pre>Query<br>   ↓<br>Read State</pre><p>That is the foundation of CQRS.</p><h3>Commands Are About Intent</h3><p>One subtle but important idea is that commands often represent <strong>business intent</strong>, rather than simply exposing database operations.</p><p>Instead of:</p><pre>UPDATE orders<br>SET status = &#39;cancelled&#39;<br>WHERE id = 123;</pre><p>the application might have:</p><pre>CancelOrder</pre><p>The command represents a business action.</p><p>The command handler can then enforce rules:</p><pre>CancelOrder<br>    ↓<br>Does the order exist?<br>    ↓<br>Is it cancellable?<br>    ↓<br>Has payment already settled?<br>    ↓<br>Are items already shipped?<br>    ↓<br>Apply cancellation<br>    ↓<br>Persist changes</pre><p>This makes the command side a natural place for business rules.</p><h3>Queries Should Not Change State</h3><p>A query should conceptually be:</p><pre>Read something<br>      ↓<br>Return result</pre><p>For example:</p><pre>GetOrderDetails</pre><p>might return:</p><pre>{<br>  &quot;id&quot;: &quot;ORD-123&quot;,<br>  &quot;customer&quot;: &quot;Krishna&quot;,<br>  &quot;status&quot;: &quot;SHIPPED&quot;,<br>  &quot;total&quot;: 2499,<br>  &quot;items&quot;: [<br>    {<br>      &quot;name&quot;: &quot;Keyboard&quot;,<br>      &quot;quantity&quot;: 1<br>    }<br>  ]<br>}</pre><p>The query shouldn’t modify the order.</p><p>That distinction is the reason for the word:<br><strong><em>Responsibility Segregation</em></strong></p><p>The command side owns state changes.</p><p>The query side owns retrieval.</p><h3>Why Not Just Use the Same Database?</h3><p>This is where CQRS becomes interesting.</p><p>Imagine your write database has a normalized structure:</p><pre>Customer<br>   ↓<br>Order<br>   ↓<br>OrderItem<br>   ↓<br>Product<br>   ↓<br>Category</pre><p>This structure can be excellent for maintaining consistency.</p><p>But a dashboard might need:</p><pre>Dashboard<br>--------------------------------<br>Customer Name<br>Order Count<br>Revenue<br>Last Order<br>Top Product<br>Average Order Value</pre><p>If you build this dynamically from the normalized model every time, the query might require:</p><pre>joins<br>+<br>aggregations<br>+<br>grouping<br>+<br>sorting<br>+<br>filtering</pre><p>and potentially large amounts of data.</p><p>Instead, we can create a read model specifically designed for this query.</p><p>For example:</p><pre>customer_dashboard<br>-------------------<br>customer_id<br>customer_name<br>order_count<br>total_revenue<br>last_order_date<br>top_product<br>average_order_value</pre><p>Now the query becomes much simpler.</p><pre>SELECT *<br>FROM customer_dashboard<br>WHERE customer_id = ?;</pre><p>This is the core power of CQRS.</p><h3>The Read Model Can Look Completely Different</h3><p>The write model might look like:</p><pre>customers<br>orders<br>order_items<br>products<br>payments<br>shipments</pre><p>while the read model might look like:</p><pre>customer_order_summary</pre><p>or:</p><pre>order_search_index</pre><p>or:</p><pre>sales_dashboard</pre><p>or:</p><pre>product_catalog_view</pre><p>These models don’t need to mirror each other.</p><p>That’s actually one of the biggest advantages.</p><p>The write model answers:<br><em>“How do we correctly maintain the business state?”</em></p><p>The read model answers:<br><em>“How do we efficiently answer this particular question?”</em></p><p>Those are different questions.</p><h3>Denormalization Becomes Useful</h3><p>Traditional relational design often encourages normalization.</p><p>For example:</p><pre>Order<br>  ↓<br>Customer<br>  ↓<br>Product</pre><p>We don’t want to duplicate the same customer information everywhere because updates become difficult to manage.</p><p>But a read model can intentionally be denormalized.</p><p>For example:</p><pre>order_summary<br>--------------------------------<br>order_id<br>customer_name<br>customer_email<br>product_name<br>quantity<br>total<br>status<br>shipping_city</pre><p>Yes, information may be duplicated.</p><p>And that’s okay.</p><p>The read model isn’t necessarily the source of truth.</p><p>It is a representation optimized for consumption.</p><p>This is a crucial distinction.</p><h3>The Source of Truth Usually Lives on the Write Side</h3><p>Suppose:</p><pre>Write Database</pre><p>contains the authoritative business state.</p><p>The read model can be derived from it.</p><p>Conceptually:</p><pre>Commands<br>                     │<br>                     ▼<br>                Write Model<br>                     │<br>                     ▼<br>                Write Store<br>                     │<br>                     ▼<br>                   Event<br>                     │<br>                     ▼<br>                Read Model<br>                     │<br>                     ▼<br>                 Queries</pre><p>The read side becomes a projection of the authoritative state.</p><p>This is where events often enter the architecture.</p><h3>CQRS and Event-Driven Architecture</h3><p>Suppose a customer places an order.</p><p>The command might be:</p><pre>CreateOrder</pre><p>The command handler validates the operation and stores the new state.</p><p>Then the system can publish an event:</p><pre>OrderCreated</pre><p>Now different consumers can react to that event.</p><p>For example:</p><pre>OrderCreated<br>      │<br>      ├── Update Search Index<br>      │<br>      ├── Update Customer Dashboard<br>      │<br>      ├── Update Analytics<br>      │<br>      ├── Send Notification<br>      │<br>      └── Update Recommendation System</pre><p>This is where CQRS becomes especially powerful in event-driven systems.</p><p>But there is an important distinction:<br><strong><em>CQRS does not require event sourcing.</em></strong></p><p>Events can be used to synchronize read models without making the event log itself the primary source of truth.</p><h3>CQRS Does Not Mean Event Sourcing</h3><p>These concepts are often treated as one package.</p><p>They are not.</p><p>CQRS says:</p><pre>Separate command and query responsibilities.</pre><p>Event sourcing says:</p><pre>Store state changes as a sequence of events.</pre><p>You can have:</p><pre>CQRS without Event Sourcing</pre><p>and:</p><pre>Event Sourcing without full CQRS</pre><p>and:</p><pre>CQRS + Event Sourcing</pre><p>as a more sophisticated architecture.</p><p>For example:</p><pre>Command<br>  ↓<br>Write Database<br>  ↓<br>Publish Event<br>  ↓<br>Read Model</pre><p>is already CQRS.</p><p>You don’t need to reconstruct the entire state from an event stream.</p><h3>A Complete CQRS Example</h3><p>Let’s build a simple order system.</p><p>A customer sends:</p><pre>CreateOrder</pre><p>The request goes to the command side.</p><pre>Client<br>  ↓<br>API<br>  ↓<br>CreateOrder Command<br>  ↓<br>Command Handler</pre><p>The command handler performs business validation.</p><pre>Is customer valid?<br>Is product available?<br>Is quantity valid?<br>Is payment allowed?</pre><p>Then it writes the authoritative state:</p><pre>Write Database</pre><p>After successful persistence:</p><pre>OrderCreated</pre><p>is published.</p><p>Now an event consumer updates the read model:</p><pre>OrderCreated<br>      ↓<br>Projection<br>      ↓<br>Read Database</pre><p>The read database might contain:</p><pre>orders_view<br>--------------------------------<br>order_id<br>customer_name<br>status<br>total<br>item_count<br>created_at</pre><p>Now when the UI requests:</p><pre>GET /orders/123</pre><p>the query side can read directly from the optimized projection.</p><p>The complete flow becomes:</p><pre>WRITE SIDE</pre><pre>Client<br>  │<br>  ▼<br>CreateOrder<br>  │<br>  ▼<br>Command Handler<br>  │<br>  ▼<br>Business Rules<br>  │<br>  ▼<br>Write Database<br>  │<br>  ▼<br>OrderCreated Event<br>  │<br>  ▼<br>Message Broker<br>  │<br>  ▼<br>Projection<br></pre><pre>                    READ SIDE</pre><pre>Projection<br>  │<br>  ▼<br>Read Database<br>  │<br>  ▼<br>GetOrder Query<br>  │<br>  ▼<br>Client</pre><p>Now the architecture has a very clear separation.</p><h3>Why Use a Message Broker?</h3><p>If the system is large, events might travel through infrastructure such as:</p><pre>Kafka<br>RabbitMQ<br>Pulsar<br>SNS/SQS</pre><p>The command side publishes:</p><pre>OrderCreated</pre><p>and consumers process it asynchronously.</p><p>This creates another important property:<br><strong><em>The read model may not update immediately.</em></strong></p><p>Suppose:</p><pre>10:00:00.000<br>Order created<br><br>10:00:00.050<br>Write transaction committed<br><br>10:00:00.100<br>Event published<br><br>10:00:00.200<br>Read projection updated</pre><p>For a short period, the write model and read model may disagree.</p><p>This is called:</p><h3>Eventual Consistency</h3><p>And it is one of the biggest trade-offs of CQRS.</p><h3>Eventual Consistency</h3><p>Imagine the user creates an order.</p><p>Immediately after the write succeeds:</p><pre>Write Model:<br>Order = CREATED</pre><p>But the read model hasn’t processed the event yet:</p><pre>Read Model:<br>Order = not visible</pre><p>For a small amount of time:</p><pre>Write Model ≠ Read Model</pre><p>Eventually:</p><pre>Event processed<br>     ↓<br>Projection updated<br>     ↓<br>Read Model = Write Model</pre><p>This is eventual consistency.</p><p>And it is one of the most important things you must understand before adopting CQRS.</p><h3>This Can Create Interesting UI Problems</h3><p>Imagine:</p><pre>POST /orders</pre><p>returns:</p><pre>{<br>  &quot;orderId&quot;: &quot;123&quot;<br>}</pre><p>The frontend immediately calls:</p><pre>GET /orders/123</pre><p>But the read model hasn’t processed the event yet.</p><p>The response could be:</p><pre>404 Not Found</pre><p>even though the order was successfully created.</p><p>That can be surprising if you’re coming from a traditional CRUD system.</p><p>The architecture therefore needs to account for consistency boundaries.</p><h3>One Solution: Return the Write Result Directly</h3><p>After creating the order, the command side can return:</p><pre>{<br>  &quot;orderId&quot;: &quot;123&quot;,<br>  &quot;status&quot;: &quot;CREATED&quot;<br>}</pre><p>The frontend can use that result immediately.</p><p>Then later, the read model catches up.</p><p>Another approach is to use a consistency strategy where the system can read from the write model immediately after a command when necessary.</p><p>There isn’t one universal solution.</p><p>The correct choice depends on the business requirements.</p><h3>CQRS Gives You Independent Scaling</h3><p>One of the strongest reasons to adopt CQRS is that read and write workloads can be very different.</p><p>Imagine:</p><pre>Writes:<br>500 requests/sec</pre><pre>Reads:<br>100,000 requests/sec</pre><p>If both operations share the same database infrastructure, scaling can become difficult.</p><p>With CQRS:</p><pre>Application<br>                    │<br>          ┌─────────┴─────────┐<br>          │                   │<br>       Commands            Queries<br>          │                   │<br>          ▼                   ▼<br>    Write Service        Read Service<br>          │                   │<br>          ▼                   ▼<br>    Write Database       Read Database</pre><p>You can scale:</p><pre>Read Service<br>Read Database</pre><p>independently from:</p><pre>Write Service<br>Write Database</pre><p>That can be extremely valuable for read-heavy systems.</p><h3>The Read Database Doesn’t Have to Be Relational</h3><p>This is another powerful property.</p><p>The write side might use:</p><pre>PostgreSQL</pre><p>because the system needs:</p><pre>transactions<br>constraints<br>relational consistency</pre><p>The read side might use:</p><pre>Elasticsearch</pre><p>because the application needs:</p><pre>full-text search<br>filtering<br>faceting<br>ranking</pre><p>Or:</p><pre>Redis</pre><p>for extremely fast access to a specific projection.</p><p>Or:</p><pre>MongoDB</pre><p>for a document-oriented read model.</p><p>Or even specialized analytical systems for reporting.</p><p>Conceptually:</p><pre>Write Model<br>                     │<br>                 PostgreSQL<br>                     │<br>                     ▼<br>                   Events<br>                     │<br>        ┌────────────┼────────────┐<br>        ▼            ▼            ▼<br>     Redis      Elasticsearch   Analytics DB<br>        │            │            │<br>        └────────────┼────────────┘<br>                     ▼<br>                  Queries</pre><p>This is where CQRS becomes much more than simply separating classes in a codebase.</p><h3>Search Is a Great Example</h3><p>Imagine an e-commerce system.</p><p>The write database stores:</p><pre>products<br>categories<br>inventory<br>prices<br>vendors</pre><p>The application wants search functionality:</p><pre>&quot;wireless headphones&quot;</pre><p>with:</p><pre>price filters<br>brand filters<br>category filters<br>rating filters<br>sorting<br>autocomplete</pre><p>A relational write model may not be the ideal structure for this search workload.</p><p>Instead, the application can publish:</p><pre>ProductCreated<br>ProductUpdated<br>ProductDeleted<br>PriceChanged<br>InventoryChanged</pre><p>and a search projection updates an Elasticsearch index.</p><p>Now:</p><pre>Write Model<br>    ↓<br>Events<br>    ↓<br>Search Projection<br>    ↓<br>Elasticsearch<br>    ↓<br>Search Queries</pre><p>The search model is optimized for exactly what the search experience needs.</p><h3>Analytics Is Another Natural Fit</h3><p>Consider an airline or e-commerce company.</p><p>The operational database needs to answer questions such as:</p><pre>Is this order valid?<br>Is this payment valid?<br>Can this seat be booked?</pre><p>Analytics needs completely different questions:</p><pre>What was revenue by region?<br>What is the 90-day retention rate?<br>Which product category grew fastest?<br>What is average order value?</pre><p>Trying to force one operational schema to serve both transactional workloads and large analytical queries can be expensive.</p><p>CQRS-style projections can create models specifically designed for reporting.</p><p>For example:</p><pre>Operational Events<br>       ↓<br>Analytics Projection<br>       ↓<br>Sales Fact Table<br>       ↓<br>Dashboard</pre><p>Now the reporting workload doesn’t constantly compete with the transactional workload.</p><h3>CQRS Can Also Be Used Without Separate Databases</h3><p>This is worth emphasizing.</p><p>Suppose you have a modular monolith.</p><p>You could have:</p><pre>Command<br>  ↓<br>Write Model</pre><pre>Query<br>  ↓<br>Read Model</pre><p>while both ultimately use the same PostgreSQL database.</p><p>For example:</p><pre>Command Repository<br>        │<br>        ▼<br>   PostgreSQL<br></pre><pre>Query Repository<br>        │<br>        ▼<br>   PostgreSQL</pre><p>The separation exists at the application/model level.</p><p>Later, if read traffic becomes large, you can evolve toward:</p><pre>Read Model<br>    ↓<br>Read Replica</pre><p>or:</p><pre>Read Model<br>    ↓<br>Separate Read Store</pre><p>This is often a much more sensible evolution path than immediately introducing multiple databases.</p><h3>CQRS Is Not the Same as Read Replicas</h3><p>This distinction is important.</p><p>A read replica is essentially:</p><pre>Primary DB<br>   ↓<br>Replication<br>   ↓<br>Read Replica</pre><p>The schema is generally the same.</p><p>CQRS can have:</p><pre>Write Model<br>   ↓<br>Events<br>   ↓<br>Different Read Model</pre><p>The read model can have a completely different structure.</p><p>So:</p><pre>Read Replica<br>=<br>Same model, different copy</pre><p>while:</p><pre>CQRS Read Model<br>=<br>Potentially different representation optimized for queries</pre><p>You can also combine the two.</p><h3>CQRS Does Not Mean Two Microservices</h3><p>Another common misconception is:</p><pre>CQRS<br>=<br>Write Microservice + Read Microservice</pre><p>Not necessarily.</p><p>You can implement CQRS inside:</p><pre>One class<br>One module<br>One service<br>One monolith<br>Multiple services</pre><p>The architectural scale depends on the problem.</p><p>For a small application:</p><pre>Application<br> ├── Commands<br> └── Queries</pre><p>may be enough.</p><p>For a large distributed system:</p><pre>Command Services<br>        │<br>        ▼<br>Event Infrastructure<br>        │<br>        ▼<br>Read Services</pre><p>might make sense.</p><p>The principle comes first.</p><p>The infrastructure follows the requirements.</p><h3>CQRS in a Modular Monolith</h3><p>A very practical architecture is:</p><pre>Application<br>                    │<br>          ┌─────────┴─────────┐<br>          │                   │<br>       Commands             Queries<br>          │                   │<br>          ▼                   ▼<br>   Command Handlers      Query Handlers<br>          │                   │<br>          ▼                   ▼<br>   Domain Model          Read Models<br>          │                   │<br>          └─────────┬─────────┘<br>                    ▼<br>                 Database</pre><p>This gives you the conceptual benefits of CQRS without introducing distributed-system complexity.</p><p>And this can be a great stepping stone.</p><p>If the application later requires independent scaling or specialized stores, the architecture can evolve.</p><h3>The Write Model Can Be Highly Normalized</h3><p>The command side often benefits from a domain model that represents business invariants.</p><p>For example:</p><pre>Order<br> ├── Customer<br> ├── OrderItems<br> ├── Payment<br> └── Shipment</pre><p>The command handler can enforce rules such as:</p><pre>Cannot ship unpaid order<br>Cannot cancel shipped order<br>Cannot reserve unavailable inventory<br>Cannot refund more than paid amount</pre><p>This is where a rich domain model can be useful.</p><p>The goal isn’t to make the write model convenient for every query.</p><p>Its priority is:<br><strong><em>Correctly changing business state.</em></strong></p><h3>The Read Model Can Be Extremely Simple</h3><p>The query side doesn’t necessarily need all those business rules.</p><p>It might simply need:</p><pre>order_id<br>customer_name<br>status<br>total<br>shipping_status</pre><p>The read model can be a flattened representation.</p><p>This can make queries incredibly fast and predictable.</p><p>Instead of:</p><pre>JOIN<br>JOIN<br>JOIN<br>GROUP BY<br>COUNT<br>SUM<br>ORDER BY</pre><p>you may have:</p><pre>SELECT *<br>FROM order_summary<br>WHERE order_id = ?;</pre><p>The complexity hasn’t disappeared.</p><p>It has moved from query time to <strong>projection/update time</strong>.</p><p>That is a crucial architectural insight.</p><h3>CQRS Moves Complexity Around</h3><p>This is perhaps the most honest way to describe CQRS.</p><p>CQRS does not magically remove complexity.</p><p>It often changes where the complexity lives.</p><p>Traditional system:</p><pre>Simple writes<br>+<br>Complex reads</pre><p>CQRS system:</p><pre>Complex synchronization<br>+<br>Simple reads</pre><p>You are effectively saying:<br><em>“Instead of repeatedly calculating the same complicated read result at query time, let’s calculate and maintain a representation that is already optimized for the query.”</em></p><p>That can be a huge win.</p><p>But it isn’t free.</p><h3>The Cost of CQRS</h3><p>Once you introduce separate models, you now have more things to maintain.</p><p>Instead of:</p><pre>Application<br>   ↓<br>Database</pre><p>you may have:</p><pre>Command Handler<br>      ↓<br>Write Database<br>      ↓<br>Event<br>      ↓<br>Message Broker<br>      ↓<br>Projection<br>      ↓<br>Read Database<br>      ↓<br>Query Handler</pre><p>Now you need to think about:</p><pre>event delivery<br>retries<br>duplicate events<br>ordering<br>idempotency<br>projection failures<br>rebuilding projections<br>schema evolution<br>monitoring<br>eventual consistency</pre><p>This is a significant operational cost.</p><h3>Idempotency Becomes Important</h3><p>Suppose:</p><pre>OrderCreated</pre><p>is delivered twice.</p><p>If your projection blindly processes it twice, you could create duplicate data.</p><p>Therefore, projection handlers should often be designed to be idempotent.</p><p>Conceptually:</p><pre>Event<br> ↓<br>Have I already processed this event?<br> ↓<br>Yes → Ignore<br>No  → Apply</pre><p>This becomes particularly important when using message brokers that provide at-least-once delivery semantics.</p><h3>What If the Read Model Breaks?</h3><p>Imagine:</p><pre>Write Database<br>      ↓<br>Events<br>      ↓<br>Read Projection</pre><p>The projection service crashes.</p><p>The write database remains correct.</p><p>But the read model may become stale.</p><p>This is one of the reasons event-driven CQRS architectures need strong operational tooling.</p><p>You want to be able to:</p><pre>Replay events<br>Rebuild projections<br>Monitor lag<br>Retry failed events<br>Inspect dead-letter queues</pre><p>The ability to rebuild a read model is one of the major advantages of deriving it from durable events or other authoritative state changes.</p><h3>Projection Rebuilding</h3><p>Suppose your current read model is:</p><pre>orders_view_v1</pre><p>Later you realize you need:</p><pre>orders_view_v2</pre><p>with additional information.</p><p>If your architecture retains a reliable source of historical events, you can create a new projection:</p><pre>Events<br>  ↓<br>Projection V2<br>  ↓<br>New Read Model</pre><p>The old read model doesn’t necessarily need to be manually migrated row by row.</p><p>This can be extremely powerful.</p><p>But again, this is where event-driven architectures introduce operational complexity.</p><h3>CQRS and Eventual Consistency Change How You Design APIs</h3><p>In a traditional CRUD system:</p><pre>POST /orders<br>     ↓<br>Database commit<br>     ↓<br>GET /orders/123</pre><p>you often expect the GET to immediately reflect the POST.</p><p>With asynchronous CQRS:</p><pre>POST /orders<br>     ↓<br>Write succeeds<br>     ↓<br>Event published<br>     ↓<br>Projection updates<br>     ↓<br>GET /orders/123</pre><p>there may be a small delay.</p><p>The API and frontend need to understand this.</p><p>For example, the command response might return:</p><pre>{<br>  &quot;orderId&quot;: &quot;123&quot;,<br>  &quot;status&quot;: &quot;processing&quot;<br>}</pre><p>The UI can then update based on the command response while the query model catches up.</p><p>This is not necessarily a problem.</p><p>It’s a trade-off.</p><h3>CQRS Works Best When Reads and Writes Have Different Shapes</h3><p>This is one of the strongest indicators that CQRS might be useful.</p><p>Imagine your write operation needs:</p><pre>Customer<br>Order<br>OrderItem<br>Payment<br>Inventory</pre><p>but your UI wants:</p><pre>Order Card<br>--------------------<br>Customer Name<br>Total<br>Status<br>Item Count<br>Shipping ETA<br>Payment Status</pre><p>Those shapes are fundamentally different.</p><p>The write side is optimized around business consistency.</p><p>The read side is optimized around presentation.</p><p>That’s a natural CQRS boundary.</p><h3>Another Strong Signal: Read-Heavy Systems</h3><p>Suppose:</p><pre>Reads = 99%<br>Writes = 1%</pre><p>The system may benefit from an architecture where read infrastructure can scale independently.</p><p>For example:</p><pre>Commands<br>                 │<br>                 ▼<br>           Write Service<br>                 │<br>                 ▼<br>           Write Database<br>                 │<br>                 ▼<br>              Events<br>                 │<br>       ┌─────────┼─────────┐<br>       ▼         ▼         ▼<br>     Read 1    Read 2     Read 3<br>       │         │         │<br>       ▼         ▼         ▼<br>     Cache     Search    Dashboard</pre><p>The same underlying business changes can feed multiple specialized read models.</p><h3>Another Strong Signal: Complex Business Logic</h3><p>Suppose an operation isn’t just:</p><pre>UPDATE user</pre><p>but:</p><pre>ApproveLoan</pre><p>which involves:</p><pre>credit checks<br>risk rules<br>documents<br>income validation<br>fraud checks<br>approval limits<br>audit records</pre><p>A command-based architecture can make these business operations explicit.</p><p>Instead of exposing generic CRUD:</p><pre>PATCH /loan/123</pre><p>you can model:</p><pre>ApproveLoan<br>RejectLoan<br>RequestAdditionalDocuments<br>CancelLoan</pre><p>This can make complex domains easier to reason about.</p><h3>But CQRS Is Often Overkill</h3><p>This is probably the most important section of the article.</p><p>Imagine a simple application:</p><pre>Users<br>Products<br>Orders</pre><p>with:</p><pre>100 users<br>1,000 orders</pre><p>and a handful of CRUD screens.</p><p>Introducing:</p><pre>Command handlers<br>Query handlers<br>Events<br>Kafka<br>Projections<br>Read databases<br>Event replay<br>Distributed tracing</pre><p>would be architectural overengineering.</p><p>You have created a distributed system to solve a problem that doesn’t exist.</p><p>A simple CRUD architecture is probably better.</p><h3>Don’t Use CQRS Just Because It Sounds Like System Design</h3><p>This happens surprisingly often.</p><p>Someone learns:</p><pre>CQRS<br>Event Sourcing<br>Kafka<br>Microservices</pre><p>and then tries to put all of them into the next application.</p><p>That’s backwards.</p><p>Architecture should follow constraints.</p><p>Not fashion.</p><p>The right question isn’t:<br><em>“Can I use CQRS?”</em></p><p>The right question is:<br><em>“What problem does CQRS solve in this system, and is that problem large enough to justify the additional complexity?”</em></p><h3>CQRS Is a Trade-Off, Not a Performance Button</h3><p>It’s tempting to think:</p><pre>CQRS<br> ↓<br>Faster system</pre><p>But that’s not guaranteed.</p><p>You are introducing:</p><pre>more components<br>+<br>more data flows<br>+<br>more synchronization<br>+<br>more operational complexity</pre><p>in exchange for benefits such as:</p><pre>independent scaling<br>+<br>optimized read models<br>+<br>optimized write models<br>+<br>clear business commands<br>+<br>specialized projections</pre><p>Whether that is a net win depends entirely on the workload.</p><h3>A Practical Decision Framework</h3><p>Before introducing CQRS, ask:</p><pre>Are reads and writes fundamentally different?</pre><p>If no:</p><pre>Stay with CRUD.</pre><p>If yes, ask:</p><pre>Are the read queries expensive enough to justify a separate model?</pre><p>If no:</p><pre>Keep it simple.</pre><p>If yes:</p><pre>Could a materialized view or read replica solve the problem?</pre><p>If yes:</p><pre>Try that first.</pre><p>If you need:</p><pre>different data shape<br>+<br>independent scaling<br>+<br>specialized read stores<br>+<br>event-driven projections</pre><p>then CQRS becomes much more compelling.</p><h3>You Don’t Have to Adopt Full CQRS on Day One</h3><p>This is one of the most practical approaches.</p><p>Start with:</p><pre>Simple CRUD</pre><p>Then observe the system.</p><p>Maybe reads become expensive.</p><p>Introduce:</p><pre>Read Model</pre><p>Maybe reads need independent scaling.</p><p>Introduce:</p><pre>Read Replica</pre><p>Maybe the read representation needs to be completely different.</p><p>Introduce:</p><pre>Projection</pre><p>Maybe multiple systems need to react to state changes.</p><p>Introduce:</p><pre>Events</pre><p>Maybe the architecture eventually becomes:</p><pre>CQRS<br>+<br>Event-Driven Architecture</pre><p>This is much healthier than starting with maximum complexity.</p><h3>CQRS in a Real E-Commerce Platform</h3><p>Let’s put everything together.</p><p>Imagine Amazon-scale commerce.</p><p>The write side needs to maintain:</p><pre>Orders<br>Payments<br>Inventory<br>Customers<br>Shipments<br>Refunds</pre><p>The system receives commands:</p><pre>PlaceOrder<br>CancelOrder<br>RefundOrder<br>ReserveInventory<br>ConfirmPayment<br>ShipOrder</pre><p>The command side validates and persists those operations.</p><p>Then events are emitted:</p><pre>OrderPlaced<br>PaymentConfirmed<br>InventoryReserved<br>OrderShipped<br>OrderCancelled</pre><p>Different consumers build different projections.</p><pre>OrderPlaced<br>    │<br>    ├── Customer Order History<br>    │<br>    ├── Admin Dashboard<br>    │<br>    ├── Search Index<br>    │<br>    ├── Analytics<br>    │<br>    ├── Recommendation System<br>    │<br>    └── Notification System</pre><p>Now the system doesn’t need one giant database query to satisfy every consumer.</p><p>Each consumer gets a representation optimized for its needs.</p><p>That is where CQRS starts becoming extremely powerful.</p><h3>The Architecture Becomes a Data Flow</h3><p>Instead of thinking:</p><pre>Request → Database → Response</pre><p>we start thinking:</p><pre>Command<br>   ↓<br>Business Logic<br>   ↓<br>Authoritative State<br>   ↓<br>Event<br>   ↓<br>Projection<br>   ↓<br>Read Model<br>   ↓<br>Query</pre><p>This is a very different mental model.</p><p>The system is no longer simply storing data.</p><p>It is maintaining multiple representations of business state for different purposes.</p><h3>CQRS and Caching Are Also Different</h3><p>You might ask:<br><em>“Why not just cache the expensive query?”</em></p><p>Sometimes that is exactly the right answer.</p><p>For example:</p><pre>Database<br>   ↓<br>Query<br>   ↓<br>Redis<br>   ↓<br>Client</pre><p>Caching can solve a lot of read-performance problems without CQRS.</p><p>The difference is that a cache usually stores a temporary copy of a query result.</p><p>A CQRS read model is often a deliberate representation of the domain designed specifically for querying.</p><p>You can even combine both:</p><pre>Write Model<br>     ↓<br>Read Model<br>     ↓<br>Cache<br>     ↓<br>Client</pre><p>Again, architecture is compositional.</p><h3>CQRS and Database Views</h3><p>Sometimes the problem can be solved with:</p><pre>CREATE VIEW ...</pre><p>or:</p><pre>Materialized View</pre><p>A materialized view can precompute expensive query results.</p><p>This can provide some of the benefits people seek from CQRS without introducing a full event-driven architecture.</p><p>So before introducing:</p><pre>Kafka<br>+<br>Projection Service<br>+<br>Read Database</pre><p>ask:<br><em>“Would a materialized view solve this?”</em></p><p>Sometimes the answer is yes.</p><p>And that’s a much simpler architecture.</p><h3>CQRS and Microservices</h3><p>CQRS can fit naturally into microservices, but they are independent architectural decisions.</p><p>You can have:</p><pre>Monolith + CQRS</pre><p>or:</p><pre>Microservices + CRUD</pre><p>or:</p><pre>Microservices + CQRS</pre><p>or:</p><pre>Monolith + Event-Driven Architecture</pre><p>There is no rule saying these concepts must be bundled together.</p><p>This matters because architecture becomes much easier to reason about when you understand each pattern independently.</p><h3>The Most Important Trade-Off</h3><p>At its core, CQRS asks you to accept:</p><pre>More complexity</pre><p>in exchange for:</p><pre>More flexibility</pre><p>You gain the ability to optimize:</p><pre>writes independently<br>reads independently<br>data models independently<br>storage independently<br>scaling independently</pre><p>But you also inherit:</p><pre>synchronization problems<br>eventual consistency<br>projection failures<br>more infrastructure<br>more operational complexity</pre><p>The architecture is powerful precisely because you’re willing to pay that price when the problem justifies it.</p><h3>The Golden Rule of CQRS</h3><p>If there is one thing to remember, it should be this:</p><p><strong><em>Don’t introduce CQRS because your system is getting bigger. Introduce it when the responsibilities of reading and writing have become different enough that separating them creates more value than complexity.</em></strong></p><p>A simple system should stay simple.</p><p>If you have:</p><pre>10 tables<br>1,000 users<br>simple CRUD</pre><p>you probably don’t need CQRS.</p><p>If you have:</p><pre>millions of users<br>extremely different read/write workloads<br>complex business rules<br>specialized read requirements<br>multiple projections<br>independent scaling requirements</pre><p>then CQRS might be exactly the right tool.</p><h3>The Final Mental Model</h3><p>Traditional CRUD looks like:</p><pre>Application<br>                  │<br>          ┌───────┴───────┐<br>          │               │<br>        Write            Read<br>          │               │<br>          └───────┬───────┘<br>                  ▼<br>              One Model<br>                  │<br>                  ▼<br>              Database</pre><p>CQRS looks more like:</p><pre>Application<br>                     │<br>            ┌────────┴────────┐<br>            │                 │<br>        Commands            Queries<br>            │                 │<br>            ▼                 ▼<br>       Write Model        Read Model<br>            │                 │<br>            ▼                 ▼<br>       Write Store        Read Store<br>            │<br>            ▼<br>          Events<br>            │<br>            ▼<br>       Projections<br>            │<br>            └──────────────► Read Model</pre><p>The write model is responsible for:</p><pre>Changing state correctly.</pre><p>The read model is responsible for:</p><pre>Returning information efficiently.</pre><p>And the synchronization between them is where much of the architectural complexity lives.</p><p>That’s the real idea behind CQRS.</p><p>Not two databases.</p><p>Not Kafka.</p><p>Not microservices.</p><p>Not event sourcing.</p><p>Not a fashionable architecture diagram.</p><p><strong>CQRS is about recognizing that the best way to change data and the best way to read data do not always have to be the same model.</strong></p><p>And when those two responsibilities become fundamentally different, separating them can turn a system that is difficult to scale and evolve into one where each side is optimized for exactly what it needs to do.</p><p>But if those responsibilities aren’t actually different?</p><p><strong>Don’t use CQRS.</strong></p><p>Your simple CRUD application will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7df80211cba7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promises, Microtasks & Macrotasks: What Actually Runs First?]]></title>
            <link>https://medium.com/@krishnabokefod/promises-microtasks-macrotasks-what-actually-runs-first-6bd10c08bc5b?source=rss-bb29547748c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bd10c08bc5b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[macrotask-vs-microtask]]></category>
            <category><![CDATA[promises-in-javascript]]></category>
            <dc:creator><![CDATA[Krishna bokefod]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 07:01:03 GMT</pubDate>
            <atom:updated>2026-08-19T07:01:03.516Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNd7sxkrFWKiM22GdpXX0g.png" /></figure><p>There is a piece of JavaScript code that has confused almost every frontend developer at some point:</p><pre>console.log(&quot;1&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;2&quot;);<br>}, 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;3&quot;);<br>});<br><br>console.log(&quot;4&quot;);</pre><p>What gets printed?</p><p>Most developers eventually learn the answer:</p><pre>1<br>4<br>3<br>2</pre><p>But memorizing that output isn’t really useful.</p><p>The interesting question is <strong>why</strong>.</p><p>Why does the Promise callback run before a setTimeout(..., 0) callback?</p><p>Why does synchronous JavaScript always run first?</p><p>What exactly is a microtask?</p><p>What exactly is a macrotask?</p><p>Where does the event loop fit?</p><p>When does the browser get a chance to render?</p><p>Why can a huge chain of Promises freeze the browser even though Promises are supposed to be asynchronous?</p><p>And why does the answer become slightly different when we move from the browser to Node.js?</p><p>To understand all of this, we need to stop thinking about JavaScript as simply:</p><pre>Code → Output</pre><p>and start thinking about JavaScript as a program running inside a runtime with queues, scheduling rules, and an event loop.</p><p>The most important idea is this:<br><strong><em>JavaScript executes synchronous code first. After the current execution finishes, the runtime processes pending microtasks before moving on to another task such as a timer callback.</em></strong></p><p>That single sentence explains a huge amount of JavaScript behavior.</p><p>But let’s build the mental model from the beginning.</p><h3>JavaScript is not continuously executing everything at once</h3><p>When we write:</p><pre>console.log(&quot;Hello&quot;);<br>console.log(&quot;World&quot;);</pre><p>the JavaScript engine executes the code synchronously.</p><p>It doesn’t decide:</p><pre>Maybe Hello later.<br>Maybe World now.</pre><p>It follows the execution flow.</p><pre>console.log(&quot;Hello&quot;)<br>        ↓<br>console.log(&quot;World&quot;)</pre><p>But real applications don’t only contain synchronous code.</p><p>We also have:</p><pre>setTimeout(...)<br>fetch(...)<br>Promise.then(...)<br>addEventListener(...)<br>queueMicrotask(...)</pre><p>Now the runtime has to deal with work that becomes available at different times.</p><p>That’s where the event loop enters the story.</p><h3>The JavaScript engine and the JavaScript runtime are not the same thing</h3><p>This distinction is extremely important.</p><p>When people say:<br><em>“JavaScript has an event loop.”</em></p><p>they are simplifying the architecture.</p><p>The JavaScript engine is responsible for executing JavaScript.</p><p>For example, a browser might use a JavaScript engine such as V8.</p><p>The engine handles things such as:</p><pre>Parsing<br> ↓<br>Compilation<br> ↓<br>Execution<br> ↓<br>Call Stack<br> ↓<br>Heap</pre><p>But things such as:</p><pre>Timers<br>Network requests<br>DOM events<br>Rendering<br>Task queues<br>Microtask queues</pre><p>are provided by the surrounding runtime and host environment.</p><p>In a browser, that host environment is the browser.</p><p>In Node.js, the host environment is Node.js, with its own event-loop machinery.</p><p>So a better mental model is:</p><pre>JavaScript Runtime<br>                       │<br>          ┌────────────┴────────────┐<br>          │                         │<br>    JavaScript Engine          Host Environment<br>          │                         │<br>      Call Stack               Timers<br>      Heap                     Network<br>                               DOM Events<br>                               Queues<br>                               Rendering</pre><p>The JavaScript engine executes the code.</p><p>The runtime coordinates everything around it.</p><h3>The Call Stack: where synchronous JavaScript actually runs</h3><p>Let’s start with something simple.</p><pre>function one() {<br>  console.log(&quot;one&quot;);<br>}</pre><pre>function two() {<br>  one();<br>  console.log(&quot;two&quot;);<br>}</pre><pre>two();</pre><p>When two() is called, JavaScript needs somewhere to keep track of the currently executing functions.</p><p>That’s the <strong>call stack</strong>.</p><p>Conceptually:</p><pre>Call Stack</pre><pre>┌──────────────┐<br>│ console.log  │<br>├──────────────┤<br>│ one()        │<br>├──────────────┤<br>│ two()        │<br>└──────────────┘</pre><p>As functions finish, they are removed from the stack.</p><p>Eventually:</p><pre>Call Stack<br>    ↓<br>empty</pre><p>This is the first important rule:<br><strong><em>JavaScript executes the currently running synchronous work on the call stack before it can move on to other queued work.</em></strong></p><h3>Let’s introduce a timer</h3><p>Now consider:</p><pre>console.log(&quot;A&quot;);</pre><pre>setTimeout(() =&gt; {<br>  console.log(&quot;B&quot;);<br>}, 0);</pre><pre>console.log(&quot;C&quot;);</pre><p>The output is:</p><pre>A<br>C<br>B</pre><p>But why?</p><p>The important detail is that:</p><pre>setTimeout(...)</pre><p>doesn’t mean:<br><em>“Put this callback onto the call stack immediately.”</em></p><p>It asks the host environment to schedule a timer.</p><p>Conceptually:</p><pre>JavaScript<br>    │<br>    │ setTimeout(...)<br>    ▼<br>Browser Timer System<br>    │<br>    │ wait until timer is eligible<br>    ▼<br>Task Queue</pre><p>Meanwhile, JavaScript continues executing:</p><pre>console.log(&quot;C&quot;);</pre><p>So the sequence is roughly:</p><pre>console.log(&quot;A&quot;)<br>      ↓<br>setTimeout(...)<br>      ↓<br>console.log(&quot;C&quot;)<br>      ↓<br>Current JavaScript finishes<br>      ↓<br>Timer callback becomes eligible<br>      ↓<br>Callback eventually runs</pre><p>That’s why:</p><pre>A<br>C<br>B</pre><h3>But what does “0 milliseconds” actually mean?</h3><p>This is one of the biggest misconceptions around timers.</p><p>When you write:</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;Hello&quot;);<br>}, 0);</pre><p>you are not saying:<br><em>Run this exactly 0 milliseconds from now.</em></p><p>You are saying something closer to:<br><em>Make this callback eligible to run after the minimum timer delay has elapsed, subject to the runtime’s scheduling rules.</em></p><p>The callback still has to wait for currently executing JavaScript to finish.</p><p>For example:</p><pre>console.log(&quot;start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;timer&quot;);<br>}, 0);<br><br>for (let i = 0; i &lt; 1_000_000_000; i++) {<br>  // expensive work<br>}<br><br>console.log(&quot;end&quot;);</pre><p>The timer doesn’t interrupt the loop.</p><p>You won’t see:</p><pre>start<br>timer<br>end</pre><p>Instead, you’ll see:</p><pre>start<br>end<br>timer</pre><p>The timer is ready, but the call stack is still busy.</p><p>This gives us our first major rule:<br><strong><em>Asynchronous scheduling does not interrupt currently executing synchronous JavaScript.</em></strong></p><h3>Now Promises enter the picture</h3><p>Consider:</p><pre>console.log(&quot;A&quot;);</pre><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;B&quot;);<br>});</pre><pre>console.log(&quot;C&quot;);</pre><p>The output is:</p><pre>A<br>C<br>B</pre><p>At first glance, this seems similar to setTimeout.</p><p>But there is an important difference.</p><p>The callback registered with:</p><pre>.then(...)</pre><p>is scheduled as a <strong>microtask</strong>.</p><p>So conceptually:</p><pre>Promise.then(...)<br>        ↓<br>Microtask Queue</pre><p>Whereas:</p><pre>setTimeout(...)</pre><p>schedules a callback through the timer/task mechanism.</p><p>Conceptually:</p><pre>setTimeout(...)<br>        ↓<br>Task Queue</pre><pre>Promise.then(...)<br>        ↓<br>Microtask Queue</pre><p>And this difference determines what runs first.</p><h3>The first major rule of the event loop</h3><p>A simplified browser model is:</p><pre>Run current task<br>      ↓<br>Finish synchronous JavaScript<br>      ↓<br>Drain microtasks<br>      ↓<br>Rendering opportunity<br>      ↓<br>Next task</pre><p>That means if both a task and a microtask are waiting, the microtask gets processed before the runtime moves on to the next task.</p><p>This is why:</p><pre>console.log(&quot;1&quot;);</pre><pre>setTimeout(() =&gt; {<br>  console.log(&quot;2&quot;);<br>}, 0);</pre><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;3&quot;);<br>});</pre><pre>console.log(&quot;4&quot;);</pre><p>produces:</p><pre>1<br>4<br>3<br>2</pre><p>Let’s walk through it carefully.</p><h3>First: synchronous JavaScript</h3><p>The first statement is:</p><pre>console.log(&quot;1&quot;);</pre><p>So:</p><pre>1</pre><p>is printed immediately.</p><p>Then:</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;2&quot;);<br>}, 0);</pre><p>The timer is registered.</p><p>Its callback isn’t executed immediately.</p><p>Then:</p><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;3&quot;);<br>});</pre><p>The Promise is already resolved, so the .then() callback is scheduled as a microtask.</p><p>Then:</p><pre>console.log(&quot;4&quot;);</pre><p>runs synchronously.</p><p>So the first phase produces:</p><pre>1<br>4</pre><p>At this point, the current JavaScript execution has finished.</p><p>Now the runtime checks the microtask queue.</p><p>It contains:</p><pre>console.log(&quot;3&quot;)</pre><p>So that runs next.</p><p>Now we have:</p><pre>1<br>4<br>3</pre><p>Only after the microtask queue has been drained can the runtime move on to another task such as the timer callback.</p><p>So finally:</p><pre>2</pre><p>The result:</p><pre>1<br>4<br>3<br>2</pre><h3>The most important distinction: tasks vs microtasks</h3><p>The terminology can vary slightly between environments and specifications, and you may still see developers use the older term “macrotask.”</p><p>A useful browser-level mental model is:</p><pre>Tasks<br>├── timers<br>├── user interaction events<br>├── some network-related callbacks<br>└── other scheduled callbacks</pre><pre>Microtasks<br>├── Promise reactions<br>├── queueMicrotask()<br>└── MutationObserver callbacks</pre><p>The critical scheduling relationship is:</p><pre>Current Task<br>     ↓<br>Microtasks<br>     ↓<br>Rendering opportunity<br>     ↓<br>Another Task</pre><p>The exact browser scheduling details are more nuanced than this diagram, but this model is extremely useful for reasoning about normal frontend code.</p><h3>Why are Promise callbacks microtasks?</h3><p>Consider:</p><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;Hello&quot;);<br>});</pre><p>A Promise doesn’t directly execute the callback.</p><p>Instead, when the Promise settles, its reaction is scheduled as a microtask.</p><p>That’s why this:</p><pre>Promise.resolve().then(...)</pre><p>doesn’t behave like:</p><pre>setTimeout(...)</pre><p>The callback isn’t simply “another async callback.”</p><p>It belongs to a different scheduling category.</p><h3>queueMicrotask() makes this easier to see</h3><p>The browser also gives us:</p><pre>queueMicrotask(() =&gt; {<br>  console.log(&quot;microtask&quot;);<br>});</pre><p>Now compare:</p><pre>console.log(&quot;start&quot;);</pre><pre>queueMicrotask(() =&gt; {<br>  console.log(&quot;microtask&quot;);<br>});</pre><pre>setTimeout(() =&gt; {<br>  console.log(&quot;timer&quot;);<br>}, 0);</pre><pre>console.log(&quot;end&quot;);</pre><p>The result is:</p><pre>start<br>end<br>microtask<br>timer</pre><p>The sequence is:</p><pre>Synchronous code<br>      ↓<br>Microtasks<br>      ↓<br>Tasks</pre><h3>Promise callbacks and queueMicrotask() share the same queue</h3><p>Consider:</p><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;promise&quot;);<br>});<br><br>queueMicrotask(() =&gt; {<br>  console.log(&quot;microtask&quot;);<br>});</pre><p>Both schedule microtasks.</p><p>They are processed according to their enqueue order.</p><p>So you’ll generally see:</p><pre>promise<br>microtask</pre><p>because the Promise reaction was queued first.</p><p>Reverse the order:</p><pre>queueMicrotask(() =&gt; {<br>  console.log(&quot;microtask&quot;);<br>});</pre><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;promise&quot;);<br>});</pre><p>and:</p><pre>microtask<br>promise</pre><p>The important thing isn’t:<br><em>Promises always run before </em><em>queueMicrotask.</em></p><p>They don’t.</p><p>The important thing is:<br><strong><em>Both participate in microtask processing, and queue order matters.</em></strong></p><h3>What exactly is the microtask queue?</h3><p>Think of it as a queue of work that needs to run after the current JavaScript execution finishes but before the runtime moves on to another task.</p><p>For example:</p><pre>Current JavaScript<br>       ↓<br>┌──────────────────┐<br>│ Microtask Queue  │<br>├──────────────────┤<br>│ Promise callback │<br>│ queueMicrotask   │<br>│ MutationObserver │<br>└──────────────────┘<br>       ↓<br>Next Task</pre><p>And here’s the important part:<br><em>The runtime doesn’t normally process just one microtask and then move on.</em></p><p>It drains the microtask queue.</p><p>If running one microtask creates another microtask, that new microtask can also be processed before the runtime moves on.</p><h3>This is where things become interesting</h3><p>Consider:</p><pre>queueMicrotask(() =&gt; {<br>  console.log(&quot;A&quot;);<br><br>  queueMicrotask(() =&gt; {<br>    console.log(&quot;B&quot;);<br>  });<br>});<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;C&quot;);<br>}, 0);</pre><p>What happens?</p><p>The first microtask runs:</p><pre>A</pre><p>During that microtask, another microtask is added:</p><pre>B</pre><p>The runtime continues draining microtasks.</p><p>So:</p><pre>A<br>B<br>C</pre><p>The timer waits until the microtask queue is empty.</p><p>This leads to a very important rule:<br><strong><em>Microtasks can enqueue more microtasks, and the runtime keeps draining them before moving on to another task.</em></strong></p><h3>This means microtasks can starve the event loop</h3><p>Now imagine:</p><pre>function loop() {<br>  queueMicrotask(loop);<br>}<br><br>loop();</pre><p>Conceptually:</p><pre>Microtask<br>   ↓<br>Microtask<br>   ↓<br>Microtask<br>   ↓<br>Microtask<br>   ↓<br>...</pre><p>The microtask queue never becomes empty.</p><p>That means other tasks may not get an opportunity to run.</p><p>A similar thing can happen with Promise chains:</p><pre>function keepGoing() {<br>  Promise.resolve().then(keepGoing);<br>}</pre><pre>keepGoing();</pre><p>This is asynchronous in the Promise sense, but it is still capable of monopolizing the event loop.</p><p>And this is an important lesson:<br><strong><em>Asynchronous does not automatically mean non-blocking.</em></strong></p><h3>Promises don’t create another JavaScript thread</h3><p>This misconception is extremely common.</p><p>When you write:</p><pre>Promise.resolve().then(() =&gt; {<br>  // work<br>});</pre><p>you haven’t created another JavaScript thread.</p><p>The callback still executes JavaScript on the runtime’s JavaScript execution thread, typically the main thread in a browser page.</p><p>So this:</p><pre>Promise.resolve().then(() =&gt; {<br>  expensiveCalculation();<br>});</pre><p>can still block the browser.</p><p>The Promise changes <strong>when the callback is scheduled</strong>.</p><p>It doesn’t magically change <strong>where the JavaScript executes</strong>.</p><h3>fetch() makes the model more interesting</h3><p>Consider:</p><pre>fetch(&quot;/api/users&quot;)<br>  .then(response =&gt; response.json())<br>  .then(users =&gt; {<br>    console.log(users);<br>  });</pre><p>A common misconception is:<br><em>“The Promise is doing the network request.”</em></p><p>That’s not quite right.</p><p>The browser’s networking infrastructure performs the network operation.</p><p>Conceptually:</p><pre>JavaScript<br>    │<br>    │ fetch()<br>    ▼<br>Browser Network Layer<br>    │<br>    │ network work<br>    ▼<br>Response<br>    │<br>    ▼<br>Promise settles<br>    │<br>    ▼<br>Microtask<br>    │<br>    ▼<br>.then(...)</pre><p>So Promises provide a convenient abstraction for representing the eventual result.</p><p>They don’t themselves perform the network operation.</p><h3>Let’s combine fetch, Promise, and timer</h3><p>Consider:</p><pre>console.log(&quot;A&quot;);</pre><pre>fetch(&quot;/data&quot;).then(() =&gt; {<br>  console.log(&quot;B&quot;);<br>});</pre><pre>setTimeout(() =&gt; {<br>  console.log(&quot;C&quot;);<br>}, 0);</pre><pre>console.log(&quot;D&quot;);</pre><p>We can confidently say:</p><pre>A<br>D</pre><p>will happen synchronously.</p><p>But we cannot blindly say:</p><pre>B<br>C</pre><p>in every situation.</p><p>Why?</p><p>Because the network operation may take some amount of time.</p><p>If the timer becomes ready before the fetch response arrives:</p><pre>A<br>D<br>C<br>B</pre><p>might happen.</p><p>If the fetch completes quickly enough:</p><pre>A<br>D<br>B<br>C</pre><p>could happen.</p><p>The important point is:<br><strong><em>Microtasks have priority when they are ready, but you cannot assume an asynchronous operation will become ready before another task.</em></strong></p><p>This is a subtle but extremely important distinction.</p><h3>A Promise callback runs as a microtask once the Promise settles</h3><p>This wording is more accurate than:<br><em>“Promises always run before timers.”</em></p><p>Suppose:</p><pre>const promise = new Promise(resolve =&gt; {<br>  setTimeout(resolve, 1000);<br>});</pre><pre>promise.then(() =&gt; {<br>  console.log(&quot;done&quot;);<br>});</pre><p>The .then() callback is a microtask.</p><p>But it can’t become a microtask until the Promise settles.</p><p>The Promise is waiting for the timer.</p><p>So:</p><pre>setTimeout<br>   ↓<br>1000ms<br>   ↓<br>resolve()<br>   ↓<br>Promise settles<br>   ↓<br>.then callback becomes microtask<br>   ↓<br>Microtask executes</pre><p>This is why saying:<br><em>“Promises run before timers”</em></p><p>is too simplistic.</p><p>A better statement is:<br><strong><em>Promise reactions are processed as microtasks after the Promise settles.</em></strong></p><h3>The event loop is not simply a queue</h3><p>Many diagrams show:</p><pre>Call Stack<br>    ↓<br>Callback Queue<br>    ↓<br>Event Loop</pre><p>and stop there.</p><p>That’s useful for beginners, but it becomes misleading once you start studying real browser behavior.</p><p>There isn’t just one universal queue containing everything.</p><p>There are different kinds of scheduled work, and the browser has rules governing when those pieces of work can run.</p><p>A more useful conceptual model is:</p><pre>Browser Runtime<br>                     │<br>        ┌────────────┴────────────┐<br>        │                         │<br>   JavaScript                Host APIs<br>   Execution                    │<br>        │                       │<br>        │             ┌─────────┼─────────┐<br>        │             │         │         │<br>        │           Timers    Network   Events<br>        │             │         │         │<br>        └─────────────┴─────────┴─────────┘<br>                      │<br>                    Tasks<br>                      │<br>                      ▼<br>                Microtasks<br>                      │<br>                      ▼<br>               Rendering<br>                      │<br>                      ▼<br>                 Next Task</pre><p>The real specification model is much more precise, but this gives us the right intuition.</p><h3>So when does the browser render?</h3><p>This is where the topic becomes especially important for frontend developers.</p><p>Suppose we write:</p><pre>console.log(&quot;start&quot;);</pre><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;microtask&quot;);<br>});</pre><pre>setTimeout(() =&gt; {<br>  console.log(&quot;timer&quot;);<br>}, 0);</pre><p>We know:</p><pre>start<br>microtask<br>timer</pre><p>But where does browser rendering happen?</p><p>A simplified mental model is:</p><pre>Task<br> ↓<br>JavaScript<br> ↓<br>Microtasks<br> ↓<br>Rendering opportunity<br> ↓<br>Next task</pre><p>This means microtasks can delay a rendering opportunity.</p><p>And that’s why a huge Promise chain can make a page feel frozen even though there are no obvious long synchronous loops.</p><h3>Imagine a button click</h3><p>Suppose the user clicks a button.</p><p>The browser processes an event task.</p><p>Inside the event handler:</p><pre>button.addEventListener(&quot;click&quot;, () =&gt; {<br>  updateUI();</pre><pre>  Promise.resolve().then(() =&gt; {<br>    doMoreWork();<br>  });<br>});</pre><p>The rough flow is:</p><pre>User Click<br>    ↓<br>Event Task<br>    ↓<br>Event Handler<br>    ↓<br>updateUI()<br>    ↓<br>Synchronous JavaScript finishes<br>    ↓<br>Microtasks<br>    ↓<br>doMoreWork()<br>    ↓<br>Rendering opportunity</pre><p>If doMoreWork() is expensive, it can delay the browser&#39;s opportunity to update the screen.</p><p>So this:</p><pre>Promise.resolve().then(() =&gt; {<br>  expensiveCalculation();<br>});</pre><p>is not necessarily a performance-friendly way to “move work off the main thread.”</p><p>It doesn’t move the work anywhere.</p><p>It simply schedules it as a microtask.</p><h3>setTimeout behaves differently</h3><p>Now consider:</p><pre>button.addEventListener(&quot;click&quot;, () =&gt; {<br>  updateUI();</pre><pre>  setTimeout(() =&gt; {<br>    doMoreWork();<br>  }, 0);<br>});</pre><p>The timer callback becomes another task.</p><p>That creates an opportunity for the browser to process other work before the timer callback executes.</p><p>This doesn’t guarantee a paint before the timer.</p><p>But it is a different scheduling boundary from a microtask.</p><p>That’s why developers sometimes use:</p><pre>setTimeout(...)</pre><p>as a way to yield back to the event loop.</p><p>Even then, it’s important not to treat it as a precise rendering primitive.</p><p>For rendering-sensitive work, APIs such as requestAnimationFrame() are more explicit.</p><h3>Microtasks have higher scheduling priority than ordinary tasks</h3><p>Consider:</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;timer&quot;);<br>}, 0);</pre><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;promise&quot;);<br>});</pre><p>The timer is scheduled as a task.</p><p>The Promise reaction is scheduled as a microtask.</p><p>Once the current task finishes:</p><pre>Current Task<br>     ↓<br>Microtask Queue<br>     ↓<br>Promise callback<br>     ↓<br>Next Task<br>     ↓<br>Timer callback</pre><p>Therefore:</p><pre>promise<br>timer</pre><p>This is the rule people usually memorize.</p><p>But the deeper understanding is:<br><strong><em>The runtime drains ready microtasks at the appropriate checkpoint before proceeding to another task.</em></strong></p><h3>Let’s make the example harder</h3><p>Now look at this:</p><pre>console.log(&quot;1&quot;);</pre><pre>setTimeout(() =&gt; {<br>  console.log(&quot;2&quot;);</pre><pre>  Promise.resolve().then(() =&gt; {<br>    console.log(&quot;3&quot;);<br>  });<br>}, 0);</pre><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;4&quot;);<br>});</pre><pre>console.log(&quot;5&quot;);</pre><p>Let’s reason about it.</p><p>Synchronous execution:</p><pre>1<br>5</pre><p>The Promise schedules:</p><pre>4</pre><p>The timer waits as a task.</p><p>The current task finishes.</p><p>Microtasks run:</p><pre>4</pre><p>Then the timer task runs:</p><pre>2</pre><p>Inside the timer callback, another Promise reaction is scheduled:</p><pre>3</pre><p>The timer callback finishes.</p><p>The microtask checkpoint processes the new microtask:</p><pre>3</pre><p>So the output is:</p><pre>1<br>5<br>4<br>2<br>3</pre><p>This is where understanding the queues becomes much more useful than memorizing rules.</p><h3>What happens with multiple microtasks?</h3><p>Consider:</p><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;A&quot;);<br>});</pre><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;B&quot;);<br>});</pre><pre>queueMicrotask(() =&gt; {<br>  console.log(&quot;C&quot;);<br>});</pre><pre>setTimeout(() =&gt; {<br>  console.log(&quot;D&quot;);<br>}, 0);</pre><p>The current task finishes.</p><p>The microtask queue contains:</p><pre>A<br>B<br>C</pre><p>They are processed in order.</p><p>Only after they are drained does the timer task get its turn.</p><p>So:</p><pre>A<br>B<br>C<br>D</pre><h3>Microtasks created inside microtasks</h3><p>Now:</p><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;A&quot;);<br><br>Promise.resolve().then(() =&gt; {<br>    console.log(&quot;B&quot;);<br>  });<br>});<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;C&quot;);<br>});</pre><p>The initial microtask queue is:</p><pre>A<br>C</pre><p>The runtime starts with A.</p><p>While executing A, it schedules B.</p><p>The queue becomes:</p><pre>C<br>B</pre><p>Then:</p><pre>C</pre><p>runs.</p><p>Then:</p><pre>B</pre><p>runs.</p><p>So:</p><pre>A<br>C<br>B</pre><p>This demonstrates that microtasks are not recursively executed immediately when created.</p><p>They are queued and processed as part of the microtask queue.</p><h3>async and await are also part of this story</h3><p>Now we reach one of the most important pieces.</p><p>Consider:</p><pre>async function test() {<br>  console.log(&quot;A&quot;);<br>  await Promise.resolve();<br>  console.log(&quot;B&quot;);<br>}<br><br>test();<br><br>console.log(&quot;C&quot;);</pre><p>What happens?</p><pre>A<br>C<br>B</pre><p>Why?</p><p>Because:</p><pre>await Promise.resolve();</pre><p>suspends the continuation of the async function.</p><p>The code after the await resumes asynchronously.</p><p>Conceptually:</p><pre>test()<br> ↓<br>&quot;A&quot;<br> ↓<br>await<br> ↓<br>function continuation scheduled<br> ↓<br>current synchronous code continues<br> ↓<br>&quot;C&quot;<br> ↓<br>microtask<br> ↓<br>&quot;B&quot;</pre><p>This is why await does not mean:<br><em>“Stop the entire JavaScript thread.”</em></p><p>It means:<br><em>“Suspend this async function’s continuation until the awaited Promise settles.”</em></p><h3>await is not the same as blocking</h3><p>Consider:</p><pre>async function test() {<br>  console.log(&quot;before&quot;);<br>  await something();<br>  console.log(&quot;after&quot;);<br>}</pre><p>The JavaScript thread isn’t sitting there frozen waiting.</p><p>Instead, the async function yields its continuation.</p><p>Other JavaScript work can execute.</p><p>That’s one of the reasons async/await makes asynchronous programming easier to reason about.</p><p>But remember:</p><pre>await expensiveSynchronousFunction();</pre><p>doesn’t magically make the expensive function asynchronous.</p><p>The function executes before the Promise machinery can help you.</p><h3>A subtle example with await</h3><p>Consider:</p><pre>async function foo() {<br>  console.log(&quot;A&quot;);</pre><pre>  await Promise.resolve();</pre><pre>  console.log(&quot;B&quot;);<br>}</pre><pre>console.log(&quot;C&quot;);</pre><pre>foo();</pre><pre>console.log(&quot;D&quot;);</pre><p>Output:</p><pre>C<br>A<br>D<br>B</pre><p>Why?</p><p>foo() begins synchronously.</p><p>So:</p><pre>A</pre><p>runs.</p><p>Then await suspends the continuation.</p><p>Control returns to the surrounding synchronous code:</p><pre>D</pre><p>After the current task finishes, the continuation runs through the microtask mechanism:</p><pre>B</pre><p>So:</p><pre>C<br>A<br>D<br>B</pre><h3>What about await inside a loop?</h3><p>Consider:</p><pre>for (const item of items) {<br>  await process(item);<br>}</pre><p>Each iteration waits for the previous asynchronous operation to settle before continuing.</p><p>Conceptually:</p><pre>process(A)<br> ↓<br>await<br> ↓<br>resume<br> ↓<br>process(B)<br> ↓<br>await<br> ↓<br>resume</pre><p>This is sequential asynchronous work.</p><p>If the operations are independent, you might instead use:</p><pre>await Promise.all(<br>  items.map(process)<br>);</pre><p>Now the operations can progress concurrently at the asynchronous-operation level.</p><p>But once the results are ready, their Promise reactions still interact with the microtask queue.</p><p>Understanding this distinction is critical:</p><pre>Concurrency<br>≠<br>Parallel JavaScript execution</pre><h3>JavaScript concurrency is not the same as parallelism</h3><p>This is another concept that often gets mixed up.</p><p>JavaScript in a browser page typically executes on a main JavaScript thread.</p><p>But the browser can perform other work outside that JavaScript execution context:</p><pre>Network<br>Image decoding<br>Timers<br>Browser internals<br>GPU work</pre><p>So you can have:</p><pre>JavaScript thread<br>        +<br>Browser subsystems</pre><p>working concurrently.</p><p>But that doesn’t mean two JavaScript functions are executing simultaneously on the same thread.</p><p>For actual CPU-heavy parallel JavaScript work, browsers provide mechanisms such as:</p><pre>Web Workers</pre><p>which run JavaScript in separate worker contexts.</p><h3>Why Promises can still freeze your UI</h3><p>Consider:</p><pre>function createHugeMicrotaskChain() {<br>  Promise.resolve().then(() =&gt; {<br>    for (let i = 0; i &lt; 100_000_000; i++) {<br>      // expensive work<br>    }<br>  });<br>}</pre><p>Some developers see:</p><pre>Promise.resolve().then(...)</pre><p>and think:<br><em>“This is asynchronous, so the UI won’t block.”</em></p><p>But the expensive loop still executes as JavaScript on the main thread.</p><p>The Promise only determines when that callback gets scheduled.</p><p>The work itself is still synchronous once the callback begins executing.</p><h3>Even worse: recursive microtasks</h3><p>Consider:</p><pre>function forever() {<br>  queueMicrotask(forever);<br>}</pre><pre>forever();</pre><p>This can continuously generate microtasks.</p><p>Conceptually:</p><pre>Task<br> ↓<br>Microtask<br> ↓<br>new Microtask<br> ↓<br>new Microtask<br> ↓<br>new Microtask<br> ↓<br>...</pre><p>Because the runtime keeps draining microtasks, the browser may struggle to reach a rendering opportunity.</p><p>The result can be a page that becomes unresponsive.</p><p>This is why microtasks are powerful but should not be abused.</p><h3>Microtasks are useful precisely because they run before the next task</h3><p>There is a reason the platform gives microtasks this behavior.</p><p>Suppose you have a Promise-based API:</p><pre>doSomething().then(() =&gt; {<br>  // continuation<br>});</pre><p>You often want the continuation to run as soon as the current JavaScript execution has completed, without waiting for a later timer-style task.</p><p>This allows APIs to provide predictable asynchronous sequencing.</p><p>For example:</p><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;async&quot;);<br>});</pre><pre>console.log(&quot;sync&quot;);</pre><p>gives:</p><pre>sync<br>async</pre><p>The callback is asynchronous relative to the current stack, but it doesn’t have to wait for a future timer task.</p><h3>The phrase “microtask runs immediately” is wrong</h3><p>You’ll often hear:<br><em>“Microtasks execute immediately.”</em></p><p>They don’t.</p><p>They execute after the current JavaScript execution reaches an appropriate microtask checkpoint.</p><p>So:</p><pre>console.log(&quot;A&quot;);<br><br>queueMicrotask(() =&gt; {<br>  console.log(&quot;B&quot;);<br>});<br><br>console.log(&quot;C&quot;);</pre><p>doesn’t produce:</p><pre>A<br>B<br>C</pre><p>It produces:</p><pre>A<br>C<br>B</pre><p>Because the current synchronous execution must finish first.</p><p>A better mental model is:</p><pre>Synchronous execution<br>        ↓<br>Microtask checkpoint<br>        ↓<br>Microtasks</pre><h3>What about DOM events?</h3><p>Consider:</p><pre>button.addEventListener(&quot;click&quot;, () =&gt; {<br>  console.log(&quot;click&quot;);<br>  Promise.resolve().then(() =&gt; {<br>    console.log(&quot;promise&quot;);<br>  });<br>  setTimeout(() =&gt; {<br>    console.log(&quot;timer&quot;);<br>  }, 0);<br>});</pre><p>When the user clicks:</p><pre>Click Event Task<br>      ↓<br>&quot;click&quot;<br>      ↓<br>Current handler finishes<br>      ↓<br>Microtask<br>      ↓<br>&quot;promise&quot;<br>      ↓<br>Next task<br>      ↓<br>&quot;timer&quot;</pre><p>So:</p><pre>click<br>promise<br>timer</pre><p>This pattern appears constantly in real applications.</p><h3>Where React fits into this</h3><p>Now connect everything to React.</p><p>Suppose a React event handler does:</p><pre>function Button() {<br>  const [count, setCount] = useState(0);<br>  return (<br>    &lt;button<br>      onClick={() =&gt; {<br>        setCount(count + 1);<br>        Promise.resolve().then(() =&gt; {<br>          console.log(&quot;microtask&quot;);<br>        });<br>      }}<br>    &gt;<br>      {count}<br>    &lt;/button&gt;<br>  );<br>}</pre><p>A simplified mental model is:</p><pre>Browser receives click<br>        ↓<br>React event handling<br>        ↓<br>State update<br>        ↓<br>React schedules rendering work<br>        ↓<br>Current JavaScript continues<br>        ↓<br>Microtasks run<br>        ↓<br>Browser gets rendering opportunities</pre><p>The exact React scheduling behavior depends on the update and priority involved, so don’t reduce modern React to a single simplistic event-loop rule.</p><p>But the larger relationship remains:<br><em>React scheduling exists inside the browser’s scheduling environment.</em></p><p>React doesn’t replace the browser event loop.</p><h3>React batching and microtasks are not the same thing</h3><p>This is another common misunderstanding.</p><p>React may batch state updates.</p><p>The browser processes microtasks.</p><p>These are separate concepts.</p><p>For example:</p><pre>setCount(1);<br>setName(&quot;Krishna&quot;);</pre><p>React may batch these updates.</p><p>Meanwhile:</p><pre>Promise.resolve().then(...)</pre><p>uses the JavaScript microtask mechanism.</p><p>So:</p><pre>React batching</pre><p>and:</p><pre>Microtask scheduling</pre><p>shouldn’t be treated as the same feature.</p><p>They can interact, but they solve different problems.</p><h3>The browser also needs time to render</h3><p>Imagine:</p><pre>Promise.resolve().then(() =&gt; {<br>  expensiveCalculation();<br>});</pre><p>If the calculation takes:</p><pre>50ms</pre><p>then the browser may not get an opportunity to present the next frame until that work is complete.</p><p>So even though:</p><pre>Current task<br> ↓<br>Microtask</pre><p>sounds harmless, a large microtask can still delay visual updates.</p><p>This is why performance engineers care about:</p><pre>Long Tasks<br>Long JavaScript execution<br>Microtask starvation<br>Layout work<br>Paint work</pre><p>They all affect responsiveness.</p><h3>A useful mental timeline</h3><p>Imagine a user clicks a button at time T.</p><p>A simplified timeline could look like:</p><pre>T0<br>│<br>├── Click event task<br>│<br>├── JavaScript handler<br>│<br>├── Promise callbacks<br>│<br>├── Other microtasks<br>│<br>├── Rendering opportunity<br>│<br>├── Next task<br>│<br>└── Next frame</pre><p>The browser is constantly moving through this cycle.</p><p>That’s what makes the page interactive.</p><h3>So what actually runs first?</h3><p>Now we can answer the original question properly.</p><p>Suppose you have:</p><pre>console.log(&quot;A&quot;);<br>setTimeout(() =&gt; {<br>  console.log(&quot;B&quot;);<br>}, 0);<br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;C&quot;);<br>});<br>queueMicrotask(() =&gt; {<br>  console.log(&quot;D&quot;);<br>});<br>console.log(&quot;E&quot;);</pre><p>First, synchronous JavaScript:</p><pre>A<br>E</pre><p>Then the microtask queue:</p><pre>C<br>D</pre><p>Then, assuming the timer is ready and no other higher-priority scheduling details intervene:</p><pre>B</pre><p>So:</p><pre>A<br>E<br>C<br>D<br>B</pre><p>The important thing isn’t the letters.</p><p>It’s the model:</p><pre>Synchronous JavaScript<br>        ↓<br>Microtasks<br>        ↓<br>Tasks</pre><p>with the understanding that real browser scheduling includes additional details and that asynchronous operations become ready at different times.</p><h3>A deeper example</h3><p>Let’s make the code slightly more complicated:</p><pre>console.log(&quot;1&quot;);<br>setTimeout(() =&gt; {<br>  console.log(&quot;2&quot;);<br>  Promise.resolve().then(() =&gt; {<br>    console.log(&quot;3&quot;);<br>  });<br>}, 0);<br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;4&quot;);<br>  queueMicrotask(() =&gt; {<br>    console.log(&quot;5&quot;);<br>  });<br>});<br>console.log(&quot;6&quot;);</pre><p>Start with synchronous code:</p><pre>1<br>6</pre><p>Then the microtask queue contains:</p><pre>4</pre><p>Run 4.</p><p>During 4, another microtask is created:</p><pre>5</pre><p>The queue now contains:</p><pre>5</pre><p>So:</p><pre>4<br>5</pre><p>Then the timer task runs:</p><pre>2</pre><p>During the timer callback, another Promise reaction is created.</p><p>That becomes a microtask.</p><p>So after the timer task:</p><pre>3</pre><p>The final output:</p><pre>1<br>6<br>4<br>5<br>2<br>3</pre><p>Once you can mentally simulate this, most event-loop interview questions become much easier.</p><h3>But don’t turn this into a memorization game</h3><p>The real skill isn’t memorizing:</p><pre>Promise &gt; setTimeout</pre><p>That’s incomplete.</p><p>The real skill is being able to ask:<br><em>What kind of work is this?<br></em>Is it:</p><pre>Synchronous JavaScript?</pre><p>Or:</p><pre>A Promise reaction?</pre><p>Or:</p><pre>A timer task?</pre><p>Or:</p><pre>A DOM event?</pre><p>Or:</p><pre>A network completion?</pre><p>And then:<br><em>When does that work become eligible to run?</em></p><p>That question is far more powerful.</p><h3>The event loop is really about giving different work opportunities to run</h3><p>A browser has to coordinate many things:</p><pre>JavaScript<br>User input<br>Timers<br>Network<br>DOM changes<br>Rendering<br>Animations<br>Microtasks</pre><p>If JavaScript could randomly interrupt itself, the system would become impossible to reason about.</p><p>Instead, the runtime follows scheduling rules.</p><p>Synchronous execution gets to finish.</p><p>Then pending microtasks get their opportunity.</p><p>Then the browser can move toward another task and rendering opportunity.</p><p>Then the cycle continues.</p><p>That is the core idea behind the event loop.</p><h3>The biggest misconception: “JavaScript is single-threaded, so nothing else happens”</h3><p>This statement is technically incomplete.</p><p>JavaScript execution in a browser page is typically single-threaded on the main JavaScript thread.</p><p>But the browser itself is not a single-threaded application.</p><p>It has many subsystems and can perform work outside the JavaScript execution context.</p><p>Conceptually:</p><pre>Browser<br>                   │<br>       ┌───────────┼───────────┐<br>       │           │           │<br>   JavaScript   Network      GPU<br>       │           │           │<br>       │        Response      │<br>       │           │           │<br>       └───────────┴───────────┘<br>                   │<br>              Event Loop</pre><p>That’s why a network request can progress while JavaScript isn’t executing the request itself.</p><p>The browser handles the network operation.</p><p>JavaScript handles the callbacks when the relevant result becomes available.</p><h3>The second biggest misconception: “Async means parallel”</h3><p>It doesn’t.</p><p>Consider:</p><pre>Promise.resolve().then(() =&gt; {<br>  expensiveCalculation();<br>});</pre><p>This is asynchronous scheduling.</p><p>But:</p><pre>expensiveCalculation();</pre><p>still executes on the JavaScript thread.</p><p>If you need CPU-heavy work to run independently from the main thread, you need a mechanism such as a Web Worker.</p><p>The distinction is:</p><pre>Asynchronous<br>=<br>When work runs</pre><pre>Parallel<br>=<br>Where/how work executes concurrently</pre><p>These are different concepts.</p><h3>The third biggest misconception: “setTimeout(fn, 0) runs immediately after the current line”</h3><p>It doesn’t.</p><p>It waits until:</p><pre>Timer becomes eligible<br>+<br>Current execution has finished<br>+<br>The runtime gets to the task</pre><p>And before that timer task gets its turn, pending microtasks can run.</p><p>That’s why:</p><pre>setTimeout(() =&gt; console.log(&quot;timer&quot;), 0);</pre><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;promise&quot;);<br>});</pre><p>normally produces:</p><pre>promise<br>timer</pre><h3>The fourth biggest misconception: “Promises are always faster”</h3><p>A Promise isn’t inherently faster than a timer.</p><p>They represent different scheduling mechanisms.</p><p>You shouldn’t choose:</p><pre>Promise</pre><p>versus:</p><pre>setTimeout</pre><p>based on which one is “faster.”</p><p>You choose based on the semantics you need.</p><p>Promises are excellent for representing asynchronous results and chaining asynchronous operations.</p><p>Microtasks are useful for scheduling continuation work after the current execution completes.</p><p>Timers are useful for scheduling future tasks after a delay.</p><p>requestAnimationFrame() is useful when work needs to align with rendering.</p><p>Web Workers are useful when CPU-heavy JavaScript needs to move off the main thread.</p><p>Different tools solve different scheduling problems.</p><h3>One final mental model</h3><p>Forget the complicated diagrams for a moment.</p><p>Imagine the browser saying:<br><em>“I’m currently executing this JavaScript. I’m not going to interrupt it.”</em></p><p>Then:<br><em>“The current execution is finished. Let me process the microtasks that are ready.”</em></p><p>Then:<br><em>“Those microtasks are finished. Now I can move toward the next task and a rendering opportunity.”</em></p><p>Then:<br><em>“Another task is ready. Let’s execute it.”</em></p><p>And the cycle continues.</p><p>Conceptually:</p><pre>┌───────────────────────────┐<br>│       Current Task        │<br>│                           │<br>│   JavaScript executes     │<br>└─────────────┬─────────────┘<br>              │<br>              ▼<br>┌───────────────────────────┐<br>│      Microtask Queue      │<br>│                           │<br>│ Promise.then()            │<br>│ queueMicrotask()          │<br>│ MutationObserver          │<br>└─────────────┬─────────────┘<br>              │<br>              ▼<br>┌───────────────────────────┐<br>│   Rendering Opportunity   │<br>│                           │<br>│ Style / Layout / Paint    │<br>│ Composite                 │<br>└─────────────┬─────────────┘<br>              │<br>              ▼<br>┌───────────────────────────┐<br>│        Next Task          │<br>│                           │<br>│ Timer / Event / etc.      │<br>└─────────────┬─────────────┘<br>              │<br>              └───────────→</pre><p>This isn’t a literal implementation diagram of every browser.</p><p>It’s a mental model.</p><p>And it’s a very useful one.</p><h3>The real takeaway</h3><p>Promises aren’t magic.</p><p>setTimeout(..., 0) doesn&#39;t mean &quot;run now.&quot;</p><p>async/await doesn&#39;t create another thread.</p><p>Microtasks don’t execute in the middle of synchronous JavaScript.</p><p>And asynchronous doesn’t automatically mean non-blocking.</p><p>The most useful hierarchy to remember is:</p><pre>Synchronous JavaScript<br>        ↓<br>Current execution finishes<br>        ↓<br>Microtasks<br>        ↓<br>Rendering opportunity<br>        ↓<br>Next task</pre><p>And within that model:</p><pre>Promise.then()<br>queueMicrotask()<br>MutationObserver<br>        ↓<br>Microtask processing</pre><p>while things such as:</p><pre>setTimeout()<br>DOM events<br>other host-scheduled callbacks<br>        ↓<br>Tasks</pre><p>are scheduled through the task mechanism.</p><p>Once you understand this, a huge number of JavaScript behaviors stop being mysterious.</p><p>Why does a Promise callback beat a zero-delay timer?</p><p>Because it is processed as a microtask before the runtime moves on to another task.</p><p>Why can a Promise chain freeze the UI?</p><p>Because microtasks still execute JavaScript on the main thread and can delay rendering.</p><p>Why doesn’t await block the entire application?</p><p>Because it suspends the async function’s continuation rather than blocking the JavaScript thread.</p><p>Why doesn’t setTimeout(fn, 0) run immediately?</p><p>Because the callback must wait until its timer is eligible and the runtime gets to its task.</p><p>Why can fetch().then(...) run after a timer sometimes?</p><p>Because the Promise reaction cannot enter the microtask queue until the asynchronous operation has actually settled.</p><p>And perhaps the most important lesson:<br><strong><em>Don’t memorize the event loop. Understand what kind of work you are scheduling, when that work becomes ready, and which queue it enters.</em></strong></p><p>Once you understand that, the event loop stops being a collection of confusing interview questions.</p><p>It becomes a model for understanding how JavaScript actually runs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bd10c08bc5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Does a Browser Actually Render Your React App?]]></title>
            <link>https://medium.com/@krishnabokefod/how-does-a-browser-actually-render-your-react-app-ae1df4bd8bd9?source=rss-bb29547748c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae1df4bd8bd9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[rendering]]></category>
            <dc:creator><![CDATA[Krishna bokefod]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 07:06:01 GMT</pubDate>
            <atom:updated>2026-08-16T07:06:01.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7Sr-cWkfCb3e_nuxTSU_A.png" /></figure><p>We write React code every day.</p><pre>function App() {<br>  return (<br>    &lt;div className=&quot;app&quot;&gt;<br>      &lt;h1&gt;Hello World&lt;/h1&gt;<br>      &lt;button&gt;Click me&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Then we run the application, open the browser, and somehow those few lines of JSX become something we can see, click, scroll, and interact with.</p><p>It feels almost instantaneous.</p><p>But the browser is doing an enormous amount of work between the moment you enter a URL and the moment those pixels appear on your screen.</p><p>And React is only one part of that story.</p><p>A useful way to think about it is:</p><pre>URL<br> ↓<br>Network<br> ↓<br>HTML<br> ↓<br>DOM<br> ↓<br>CSS<br> ↓<br>CSSOM<br> ↓<br>JavaScript<br> ↓<br>React<br> ↓<br>Fiber<br> ↓<br>Reconciliation<br> ↓<br>DOM mutations<br> ↓<br>Style Calculation<br> ↓<br>Layout<br> ↓<br>Paint<br> ↓<br>Rasterization<br> ↓<br>Compositing<br> ↓<br>Pixels</pre><p>That entire journey is happening inside a system much larger than React.</p><p>This is also where a lot of frontend terminology becomes confusing.</p><p>We say:<br><em>“React rendered the component.”</em></p><p>Then we say:<br><em>“The browser rendered the page.”</em></p><p>Then we talk about:<br><em>“Rendering the DOM.”</em></p><p>These are not necessarily the same thing.</p><p>React rendering, DOM mutation, browser layout, painting, and displaying pixels are different stages of the system.</p><p>To really understand React performance, we need to start before React even exists.</p><h3>It starts when you enter a URL</h3><p>Imagine opening:</p><pre>https://example.com</pre><p>At this point, there is no React.</p><p>The browser first needs to establish communication with the server and retrieve the resources required by the page.</p><p>Very roughly, the journey looks like this:</p><pre>URL<br> ↓<br>DNS<br> ↓<br>TCP<br> ↓<br>TLS<br> ↓<br>HTTP<br> ↓<br>HTML Response</pre><p>The details can become much more complicated because of caching, HTTP/2, HTTP/3, connection reuse, service workers, CDNs, preconnects, and other optimizations.</p><p>But eventually, the browser receives bytes.</p><p>For example, the server might return:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;My React App&lt;/title&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;/styles.css&quot;&gt;<br>  &lt;/head&gt;</pre><pre>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;</pre><pre>    &lt;script type=&quot;module&quot; src=&quot;/src/main.jsx&quot;&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>And this is an important moment.</p><p>There is still no React UI.</p><p>The browser initially sees:</p><pre>&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;</pre><p>React hasn’t created the application yet.</p><h3>The browser doesn’t understand JSX</h3><p>This is one of the most important things to understand about React.</p><p>The browser doesn’t understand:</p><pre>&lt;App /&gt;</pre><p>It doesn’t understand:</p><pre>&lt;div className=&quot;app&quot;&gt;<br>  &lt;Button /&gt;<br>&lt;/div&gt;</pre><p>JSX is not a browser rendering language.</p><p>It is syntax that gets transformed into JavaScript.</p><p>Conceptually, something like:</p><pre>&lt;h1&gt;Hello&lt;/h1&gt;</pre><p>becomes a JavaScript representation similar to:</p><pre>React.createElement(<br>  &quot;h1&quot;,<br>  null,<br>  &quot;Hello&quot;<br>);</pre><p>Modern React uses the newer JSX transform, so the generated code can look different, but the fundamental idea remains the same:</p><p><strong>JSX becomes JavaScript.</strong></p><p>The browser executes JavaScript.</p><p>React runs inside that JavaScript environment.</p><p>And React eventually interacts with the browser’s DOM.</p><p>So the browser doesn’t really know that you wrote:</p><pre>function App() {<br>  return &lt;h1&gt;Hello&lt;/h1&gt;;<br>}</pre><p>It eventually needs to deal with something much closer to:</p><pre>&lt;h1&gt;Hello&lt;/h1&gt;</pre><h3>Before React, the browser builds the DOM</h3><p>When the browser receives HTML, it parses it.</p><p>The HTML is text.</p><p>The DOM is an in-memory representation of that document.</p><p>For example:</p><pre>&lt;div class=&quot;app&quot;&gt;<br>  &lt;h1&gt;Hello World&lt;/h1&gt;<br>  &lt;button&gt;Click me&lt;/button&gt;<br>&lt;/div&gt;</pre><p>becomes conceptually:</p><pre>Document<br>└── html<br>    └── body<br>        └── div.app<br>            ├── h1<br>            │   └── &quot;Hello World&quot;<br>            │<br>            └── button<br>                └── &quot;Click me&quot;</pre><p>This is the DOM tree.</p><p>And this distinction is worth remembering:</p><p><strong>HTML is a document format. DOM is an object model created from that document.</strong></p><p>When JavaScript executes:</p><pre>document.querySelector(&quot;button&quot;);</pre><p>JavaScript is interacting with the DOM.</p><p>When React eventually creates or updates elements, it is ultimately interacting with this browser-managed document structure.</p><h3>The DOM is not what the browser paints</h3><p>Now we have another interesting problem.</p><p>The DOM tells the browser:<br><em>These elements exist.</em></p><p>But it doesn’t completely tell the browser:<br><em>What should these elements look like?</em></p><p>That’s where CSS comes in.</p><p>Suppose the browser receives:</p><pre>body {<br>  margin: 0;<br>}</pre><pre>.app {<br>  display: flex;<br>  min-height: 100vh;<br>}</pre><pre>h1 {<br>  font-size: 32px;<br>}</pre><p>The browser parses the CSS and builds its own internal representation of the styles, commonly referred to as the <strong>CSSOM</strong>, or CSS Object Model.</p><p>So now the browser has two important pieces of information:</p><pre>DOM<br> ↓<br>What elements exist</pre><pre>CSSOM<br> ↓<br>What styles apply</pre><p>But it still hasn’t answered an even more important question:<br><em>Where exactly should everything appear?</em></p><h3>The browser has to resolve the cascade</h3><p>CSS isn’t just a list of properties.</p><p>The browser has to determine which rules actually win.</p><p>Imagine:</p><pre>button {<br>  color: black;<br>}</pre><pre>.primary {<br>  color: blue;<br>}</pre><pre>#checkout {<br>  color: red;<br>}</pre><p>And:</p><pre>&lt;button id=&quot;checkout&quot; class=&quot;primary&quot;&gt;<br>  Checkout<br>&lt;/button&gt;</pre><p>The browser has to calculate the final style.</p><p>It considers the cascade, specificity, inheritance, and the applicable CSS rules.</p><p>Eventually, it arrives at computed values for the element.</p><p>Conceptually:</p><pre>DOM<br> +<br>CSSOM<br> +<br>Cascade<br> +<br>Inheritance<br> ↓<br>Computed Style</pre><p>This is why changing a class in a React application can trigger more work than simply changing a JavaScript object.</p><p>The browser has to understand what that change means for the document’s styling.</p><h3>Now the browser needs geometry</h3><p>Knowing that a button is blue isn’t enough.</p><p>The browser also needs to know:</p><pre>Where is the button?<br>How wide is it?<br>How tall is it?<br>Where is its text?<br>Where are its siblings?<br>Where does its parent end?</pre><p>This is where <strong>layout</strong> comes in.</p><p>Imagine:</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;h1&gt;Hello&lt;/h1&gt;<br>  &lt;p&gt;Welcome to the application.&lt;/p&gt;<br>&lt;/div&gt;</pre><p>The browser has to calculate something conceptually similar to:</p><pre>container<br>x: 100<br>y: 50<br>width: 800<br>height: 200</pre><pre>h1<br>x: 120<br>y: 70<br>width: 760<br>height: 40</pre><pre>p<br>x: 120<br>y: 120<br>width: 760<br>height: 30</pre><p>These numbers are simplified, but they represent the problem the browser is solving.</p><p>It needs to calculate the geometry of the page.</p><p>And geometry is connected.</p><p>If the width of the parent changes, the child may change.</p><p>If the height of one element changes, another element below it may move.</p><p>If text wraps onto another line, the height changes.</p><p>If the height changes, everything below it might move.</p><p>That’s why layout can propagate through a portion of the document.</p><h3>This is where React developers often misunderstand performance</h3><p>Consider:</p><pre>&lt;div style={{ width }}&gt;<br>  ...<br>&lt;/div&gt;</pre><p>If React changes:</p><pre>width: 200px</pre><p>to:</p><pre>width: 500px</pre><p>React’s responsibility is primarily to update the DOM.</p><p>But after that DOM mutation, the browser may need to reconsider the geometry of the page.</p><p>The actual journey becomes:</p><pre>State Update<br> ↓<br>React Render<br> ↓<br>Reconciliation<br> ↓<br>Commit<br> ↓<br>DOM Mutation<br> ↓<br>Style Calculation<br> ↓<br>Layout<br> ↓<br>Paint<br> ↓<br>Composite</pre><p>This is why saying:<br><em>“The component rendered in 2ms.”</em></p><p>doesn’t necessarily mean:<br><em>“The browser finished rendering in 2ms.”</em></p><p>Those are different measurements.</p><h3>React enters the picture</h3><p>Now let’s finally bring React into the story.</p><p>Suppose our application starts with:</p><pre>const root = createRoot(<br>  document.getElementById(&quot;root&quot;)<br>);</pre><pre>root.render(&lt;App /&gt;);</pre><p>React receives:</p><pre>&lt;App /&gt;</pre><p>React doesn’t immediately start manually drawing pixels.</p><p>Instead, it creates an internal representation of the UI.</p><p>Conceptually:</p><pre>&lt;App /&gt;<br> ↓<br>React Element<br> ↓<br>Fiber<br> ↓<br>DOM</pre><p>The internal representation is where React can reason about the application’s UI.</p><p>And this is where <strong>Fiber</strong> becomes important.</p><h3>Fiber is React’s internal unit of work</h3><p>React Fiber is an internal architecture that allows React to represent work on the component tree.</p><p>A simplified mental model looks like:</p><pre>App<br> │<br> ├── Header<br> │<br> ├── Main<br> │    ├── Sidebar<br> │    └── Content<br> │<br> └── Footer</pre><p>React maintains internal structures corresponding to this tree.</p><p>A Fiber node can contain information associated with things such as:</p><pre>component type<br>props<br>state<br>parent<br>child<br>sibling<br>DOM reference<br>pending work<br>effects</pre><p>The actual Fiber implementation is much more sophisticated than this simplified picture.</p><p>The important idea is that React doesn’t need to immediately mutate the DOM every time it evaluates a component.</p><p>It can first determine what the next UI should look like.</p><p>That leads us to the distinction between the <strong>render phase</strong> and the <strong>commit phase</strong>.</p><h3>The render phase is React figuring things out</h3><p>Consider:</p><pre>function Counter() {<br>  const [count, setCount] = useState(0);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{count}&lt;/h1&gt;</pre><pre>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>        Increment<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Initially:</p><pre>count = 0</pre><p>The UI represents:</p><pre>&lt;h1&gt;0&lt;/h1&gt;</pre><p>Now the user clicks the button.</p><p>React receives:</p><pre>setCount(1);</pre><p>React needs to determine what the UI should become.</p><p>It conceptually calculates:</p><pre>&lt;h1&gt;1&lt;/h1&gt;</pre><p>This work belongs to React’s rendering process.</p><p>But here’s the important part:</p><p><strong>React rendering does not necessarily mean DOM mutation.</strong></p><p>React is figuring out what should change.</p><h3>Then comes reconciliation</h3><p>React now has two conceptual trees:</p><pre>Previous UI</pre><pre>&lt;div&gt;<br>  &lt;h1&gt;0&lt;/h1&gt;<br>  &lt;button&gt;Increment&lt;/button&gt;<br>&lt;/div&gt;</pre><p>and:</p><pre>Next UI</pre><pre>&lt;div&gt;<br>  &lt;h1&gt;1&lt;/h1&gt;<br>  &lt;button&gt;Increment&lt;/button&gt;<br>&lt;/div&gt;</pre><p>React compares them.</p><p>The structure is largely the same.</p><p>The div is still a div.</p><p>The button is still a button.</p><p>The h1 is still an h1.</p><p>The meaningful difference is:</p><pre>&quot;0&quot;<br> ↓<br>&quot;1&quot;</pre><p>React can therefore avoid replacing the entire DOM subtree.</p><p>Conceptually, the required change is closer to:</p><pre>h1.textContent = &quot;1&quot;;</pre><p>than:</p><pre>delete everything<br>create everything again</pre><p>This process of determining how the previous UI relates to the next UI is part of React’s reconciliation process.</p><h3>Re-rendering does not mean repainting</h3><p>This deserves its own distinction because the terminology causes endless confusion.</p><p>When React re-renders a component, React is executing its rendering logic to determine the next UI.</p><p>That does not mean the browser necessarily repaints the entire screen.</p><p>You can think about three separate layers:</p><pre>React Render<br>    ↓<br>What should change?</pre><pre>DOM Commit<br>    ↓<br>What DOM mutations are required?</pre><pre>Browser Rendering<br>    ↓<br>How should those DOM changes become pixels?</pre><p>These layers interact, but they are not interchangeable.</p><p>A component can re-render while producing no meaningful DOM changes.</p><p>A DOM change can occur without requiring a full layout of the entire page.</p><p>A style change can require paint without requiring layout.</p><p>A composited transform can sometimes avoid layout and paint for the affected content.</p><p>The word “render” hides all of these distinctions.</p><h3>The commit phase is where React touches the DOM</h3><p>Once React has determined the required changes, it enters the commit phase.</p><p>This is where React applies changes to the host environment.</p><p>For the browser, that ultimately means DOM operations.</p><p>Conceptually:</p><pre>React Fiber<br> ↓<br>Commit<br> ↓<br>DOM Mutation</pre><p>The browser might see operations conceptually similar to:</p><pre>appendChild(...)<br>removeChild(...)<br>insertBefore(...)<br>setAttribute(...)<br>textContent = ...</pre><p>React isn’t painting the button onto the screen.</p><p>It is changing the DOM.</p><p>The browser now has to deal with those changes.</p><p>And this is where the browser’s rendering engine takes over again.</p><h3>From DOM to Pixels</h3><p>At this point, we can temporarily forget React.</p><p>The browser has a DOM.</p><p>It has CSS.</p><p>Something changed.</p><p>Now it needs to produce a new visual result.</p><p>A useful simplified pipeline is:</p><pre>DOM + CSS<br>    ↓<br>Style Calculation<br>    ↓<br>Layout<br>    ↓<br>Paint<br>    ↓<br>Rasterization<br>    ↓<br>Compositing<br>    ↓<br>Screen</pre><p>Let’s look at what each part actually means.</p><h3>Style calculation</h3><p>The browser determines the styles that apply to the affected elements.</p><p>If React changes:</p><pre>&lt;div class=&quot;card active&quot;&gt;</pre><p>the browser needs to determine whether the new class affects the element’s computed style.</p><p>It may need to reconsider rules such as:</p><pre>.card {<br>  opacity: 0.5;<br>}</pre><pre>.card.active {<br>  opacity: 1;<br>}</pre><p>The result becomes part of the browser’s computed style information.</p><h3>Layout calculates geometry</h3><p>If the new styles affect geometry, the browser may need to perform layout.</p><p>For example:</p><pre>.card {<br>  width: 500px;<br>}</pre><p>can affect:</p><pre>card width<br> ↓<br>child positions<br> ↓<br>text wrapping<br> ↓<br>card height<br> ↓<br>siblings</pre><p>This is why layout changes can be more expensive than purely visual changes.</p><p>But not every change causes layout.</p><p>For example:</p><pre>color: red;</pre><p>doesn’t normally change the geometry of the element.</p><p>That’s an important distinction.</p><h3>Paint turns geometry and styles into drawing instructions</h3><p>Once the browser knows:</p><pre>what exists<br>where it is<br>what it looks like</pre><p>it needs to determine how those things should be drawn.</p><p>For example:</p><pre>.card {<br>  background: white;<br>  border-radius: 12px;<br>  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.2);<br>}</pre><p>The browser needs to generate the appropriate drawing operations for the background, rounded corners, shadow, text, borders, and so on.</p><p>This is the <strong>paint</strong> stage.</p><p>Paint is not the same as DOM manipulation.</p><p>React changed the DOM earlier.</p><p>Now the browser is figuring out how to visually represent the DOM.</p><h3>Rasterization turns drawing instructions into pixels</h3><p>Paint operations aren’t necessarily the final pixels immediately.</p><p>Modern browser rendering pipelines can use display lists, tiles, rasterization systems, and GPU acceleration.</p><p>Eventually, visual content needs to become pixel data.</p><p>Conceptually:</p><pre>Paint Instructions<br> ↓<br>Rasterization<br> ↓<br>Pixel data</pre><p>This is one reason browsers can optimize rendering by only rasterizing affected regions instead of blindly repainting everything.</p><h3>Compositing brings layers together</h3><p>Modern browsers can divide parts of a page into composited layers.</p><p>Conceptually:</p><pre>Layer A<br>Layer B<br>Layer C<br>   ↓<br>Compositor<br>   ↓<br>Final Frame</pre><p>The compositor can combine these layers to produce the final image.</p><p>This is especially important for things like:</p><pre>transform<br>opacity</pre><p>and certain animations and scrolling scenarios.</p><p>This is also why frontend performance isn’t simply:</p><pre>DOM = slow</pre><p>The browser has several different stages, each with different costs.</p><h3>Why transform is often used for animations</h3><p>Consider moving an element.</p><p>One approach might involve changing layout-related properties.</p><p>Another might use:</p><pre>transform: translateX(100px);</pre><p>A transform can, under the right circumstances, allow the browser to move an already-rasterized/composited layer without recalculating the layout of the surrounding document.</p><p>This is why animation guidance often prefers:</p><pre>transform</pre><p>and:</p><pre>opacity</pre><p>for certain animations.</p><p>But there is an important caveat.</p><p>Creating and maintaining composited layers also has costs.</p><p>So:<br><em>transform is not a magic &quot;make everything faster&quot; property.</em></p><p>The browser decides how elements are actually composited.</p><h3>Where the main thread enters the story</h3><p>A huge amount of frontend work is associated with the browser’s main thread.</p><p>A simplified mental model looks like:</p><pre>Main Thread<br>│<br>├── JavaScript<br>├── DOM operations<br>├── Style calculation<br>├── Layout<br>├── Some paint-related work<br>└── Event processing</pre><p>This is why a huge JavaScript calculation can make a React application feel frozen.</p><p>Consider:</p><pre>for (let i = 0; i &lt; 10_000_000_000; i++) {<br>  // expensive work<br>}</pre><p>While the browser’s main thread is busy with that work, other important work can be delayed.</p><p>The user doesn’t care that:<br><em>“React itself only needed 3ms.”</em></p><p>They care that:<br><em>“The button didn’t respond.”</em></p><p>That’s the difference between thinking about a framework and thinking about the browser.</p><h3>React cannot make expensive JavaScript disappear</h3><p>React has powerful scheduling capabilities, but React is still JavaScript running inside the browser.</p><p>If you perform expensive synchronous work:</p><pre>calculateHugeDataset();</pre><p>the browser still has to execute it.</p><p>This is why performance engineering sometimes requires things outside React:</p><pre>Web Workers<br>Code splitting<br>Lazy loading<br>Virtualization<br>Caching<br>Memoization<br>CSS containment<br>Image optimization<br>Scheduling</pre><p>The framework is only one part of the system.</p><h3>What happens when useEffect() runs?</h3><p>Now let’s connect React’s lifecycle with the browser’s lifecycle.</p><p>Suppose:</p><pre>useEffect(() =&gt; {<br>  console.log(&quot;Effect&quot;);<br>}, []);</pre><p>A useful mental model is:</p><pre>React Render<br> ↓<br>React Commit<br> ↓<br>DOM Updated<br> ↓<br>Browser Rendering<br> ↓<br>Effect</pre><p>useEffect is generally intended for work that doesn&#39;t need to synchronously block the browser&#39;s visual update.</p><p>This makes it appropriate for things like:</p><pre>subscriptions<br>network-related side effects<br>logging<br>external integrations</pre><p>The exact timing has nuances, particularly around interaction-driven updates, but the important conceptual distinction is that useEffect is not primarily a layout-measurement mechanism.</p><h3>Then why does useLayoutEffect exist?</h3><p>Consider a component that needs to measure itself.</p><pre>const rect = element.getBoundingClientRect();</pre><p>The measurement needs to happen after React has placed the element into the DOM.</p><p>But if you wait until after the browser visually updates the page, you might briefly show an incorrect layout.</p><p>This is where:</p><pre>useLayoutEffect()</pre><p>can be useful.</p><p>Conceptually:</p><pre>React Render<br> ↓<br>DOM Commit<br> ↓<br>useLayoutEffect<br> ↓<br>Browser Paint</pre><p>This allows you to measure or synchronously adjust the DOM before the visual update in the relevant rendering flow.</p><p>But it comes with a cost.</p><p>If you do too much work inside useLayoutEffect, you are delaying paint.</p><p>So the question isn’t:<br><em>“Should I use useLayoutEffect because it is faster?”</em></p><p>The better question is:<br><em>“Do I actually need to perform this work before the browser paints?”</em></p><h3>This is also where layout thrashing appears</h3><p>Consider:</p><pre>element.style.width = &quot;500px&quot;;</pre><pre>console.log(<br>  element.getBoundingClientRect().width<br>);</pre><pre>element.style.width = &quot;600px&quot;;</pre><pre>console.log(<br>  element.getBoundingClientRect().width<br>);</pre><p>The browser normally tries to batch rendering work.</p><p>But when JavaScript requests layout information immediately after making changes, the browser may need to make sure its layout state is current.</p><p>APIs such as:</p><pre>offsetWidth<br>offsetHeight<br>offsetTop<br>offsetLeft<br>getBoundingClientRect()</pre><p>can require up-to-date layout information.</p><p>When code repeatedly alternates:</p><pre>write<br>read<br>write<br>read<br>write<br>read</pre><p>it can force the browser into repeated synchronous layout work.</p><p>This pattern is commonly called <strong>layout thrashing</strong>.</p><p>A common strategy is to separate reads from writes:</p><pre>Read<br>Read<br>Read</pre><pre>then</pre><pre>Write<br>Write<br>Write</pre><p>instead of constantly switching between them.</p><h3>The browser also works in frames</h3><p>The browser isn’t rendering the page once.</p><p>It continuously produces frames.</p><p>At 60Hz, a frame interval is approximately:</p><pre>16.67ms</pre><p>At 120Hz:</p><pre>8.33ms</pre><p>That means a modern 120Hz device gives the browser significantly less time per frame.</p><p>A simplified frame might look like:</p><pre>Frame<br>│<br>├── JavaScript<br>├── Style<br>├── Layout<br>├── Paint<br>├── Composite<br>└── Display</pre><p>If the work takes longer than the available frame budget, the browser can miss a frame.</p><p>And the user sees:</p><pre>jank</pre><h3>Why requestAnimationFrame exists</h3><p>When you need to perform visual updates, you can use:</p><pre>requestAnimationFrame(() =&gt; {<br>  // visual update<br>});</pre><p>This allows your callback to be scheduled around the browser’s rendering cycle.</p><p>It’s fundamentally different from:</p><pre>setTimeout(..., 0);</pre><p>A timeout schedules a task.</p><p>requestAnimationFrame communicates:<br><em>“I have visual work that should happen around the next rendering opportunity.”</em></p><p>That distinction becomes extremely important when building animations and high-frequency interactions.</p><h3>Now think about a React list with 100,000 elements</h3><p>Suppose:</p><pre>{items.map(item =&gt; (<br>  &lt;Row key={item.id} item={item} /&gt;<br>))}</pre><p>and:</p><pre>items.length = 100000</pre><p>React might be able to efficiently reconcile a particular update.</p><p>But the browser still has a massive DOM tree.</p><p>That’s a different problem.</p><p>The browser has to maintain:</p><pre>100,000 DOM nodes</pre><p>and those nodes participate in style, layout, memory, accessibility, and other browser work.</p><p>This is where virtualization becomes useful.</p><p>Instead of rendering 100,000 rows:</p><pre>100,000 items<br>       ↓<br>Only visible items<br>       ↓<br>~20–50 DOM rows</pre><p>As the user scrolls, the application reuses or changes the visible rows.</p><p>This isn’t simply a React optimization.</p><p>It reduces the amount of work the browser has to manage.</p><h3>React optimization and browser optimization are different things</h3><p>This distinction is incredibly useful.</p><p>Suppose you use:</p><pre>React.memo(Component);</pre><p>You may reduce unnecessary React rendering.</p><p>That’s valuable.</p><p>But if the browser is spending most of its time painting huge shadows, filters, or massive visual surfaces, React.memo won&#39;t solve the bottleneck.</p><p>Likewise, suppose React rendering takes:</p><pre>2ms</pre><p>but layout takes:</p><pre>40ms</pre><p>Optimizing component renders isn’t addressing the real problem.</p><p>This is why performance optimization should begin with:<br><strong><em>Where is the time actually being spent?</em></strong></p><h3>Chrome DevTools can show you the answer</h3><p>Open:</p><pre>Chrome DevTools<br>→ Performance</pre><p>Record an interaction.</p><p>You can often see a chain resembling:</p><pre>User Interaction<br> ↓<br>Event Handler<br> ↓<br>JavaScript<br> ↓<br>React Work<br> ↓<br>DOM Mutation<br> ↓<br>Style Recalculation<br> ↓<br>Layout<br> ↓<br>Paint<br> ↓<br>Composite</pre><p>Now performance debugging becomes much more concrete.</p><p>Instead of saying:<br><em>“React is slow.”</em></p><p>you can ask:<br><em>“Is React rendering expensive?”</em></p><p>or:<br><em>“Is JavaScript blocking the main thread?”</em></p><p>or:<br><em>“Is layout taking too long?”</em></p><p>or:<br><em>“Is paint expensive?”</em></p><p>or:<br><em>“Are too many elements being rendered?”</em></p><p>Those are engineering questions that can actually lead to a solution.</p><h3>React Profiler and the browser Performance panel answer different questions</h3><p>React DevTools Profiler helps answer questions like:</p><pre>Which component rendered?<br>How long did React spend rendering it?<br>Which updates caused the render?</pre><p>Chrome Performance helps answer questions like:</p><pre>What was the browser doing?<br>How long did JavaScript run?<br>Did layout happen?<br>How much paint work occurred?<br>Were frames dropped?<br>Were there long tasks?</pre><p>A serious frontend performance investigation often needs both perspectives.</p><p>You need to understand:</p><pre>React<br>+<br>Browser</pre><p>not just one of them.</p><h3>And then there is SSR</h3><p>Everything we’ve discussed so far can begin with an empty:</p><pre>&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;</pre><p>But modern React applications don’t always work that way.</p><p>With server-side rendering, the server can send HTML that already contains meaningful content.</p><p>For example:</p><pre>&lt;div id=&quot;root&quot;&gt;<br>  &lt;h1&gt;Hello World&lt;/h1&gt;<br>  &lt;button&gt;Buy Now&lt;/button&gt;<br>&lt;/div&gt;</pre><p>Now the browser can parse and render meaningful content before the full client-side React application is ready.</p><p>The architecture becomes:</p><pre>Server<br> ↓<br>React<br> ↓<br>HTML<br> ↓<br>Browser<br> ↓<br>DOM<br> ↓<br>CSS<br> ↓<br>Layout<br> ↓<br>Paint<br> ↓<br>Pixels</pre><pre>Meanwhile...</pre><pre>JavaScript<br> ↓<br>React<br> ↓<br>Hydration<br> ↓<br>Interactivity</pre><h3>Hydration is where React reconnects with the DOM</h3><p>The browser already has:</p><pre>&lt;h1&gt;Hello World&lt;/h1&gt;</pre><p>React doesn’t want to throw that entire DOM away and recreate it unnecessarily.</p><p>Instead, React can hydrate the existing server-rendered markup.</p><p>Conceptually:</p><pre>Server HTML<br> ↓<br>Browser DOM<br> ↓<br>React loads<br> ↓<br>Hydration<br> ↓<br>React takes control<br> ↓<br>Interactive UI</pre><p>This creates another important distinction:</p><p><strong>Visible HTML and interactive React are not necessarily available at exactly the same moment.</strong></p><p>The page can be visible before all JavaScript has finished loading and executing.</p><h3>But SSR doesn’t remove the browser rendering pipeline</h3><p>This is important.</p><p>Server-side rendering does not mean:</p><pre>Server → Pixels</pre><p>The server cannot directly place pixels on your monitor.</p><p>The browser still needs to do:</p><pre>HTML<br> ↓<br>DOM<br> ↓<br>CSS<br> ↓<br>Style<br> ↓<br>Layout<br> ↓<br>Paint<br> ↓<br>Rasterization<br> ↓<br>Compositing<br> ↓<br>Screen</pre><p>SSR changes where some UI generation work happens.</p><p>It doesn’t remove the browser’s responsibility for rendering.</p><h3>The same idea applies to React Server Components</h3><p>React Server Components push certain component execution to the server.</p><p>That can reduce the amount of JavaScript that needs to be sent to the browser for those components.</p><p>But eventually, the browser still has to display the resulting interface.</p><p>The architecture may now look like:</p><pre>Server Components<br>       ↓<br>Server<br>       ↓<br>React Payload / HTML<br>       ↓<br>Browser<br>       ↓<br>Client Components<br>       ↓<br>DOM<br>       ↓<br>Browser Rendering Pipeline<br>       ↓<br>Pixels</pre><p>Again, React and the browser have different responsibilities.</p><h3>The browser doesn’t care that your component is called UserProfile</h3><p>This is perhaps the simplest way to understand the entire relationship.</p><p>React might have:</p><pre>&lt;UserProfile /&gt;</pre><p>Inside it:</p><pre>&lt;Avatar /&gt;<br>&lt;Username /&gt;<br>&lt;FollowButton /&gt;</pre><p>React understands these abstractions.</p><p>The browser eventually deals with things much closer to:</p><pre>&lt;div&gt;<br>  &lt;img&gt;<br>  &lt;span&gt;<br>  &lt;button&gt;<br>&lt;/div&gt;</pre><p>The browser doesn’t know that:</p><pre>&lt;UserProfile /&gt;</pre><p>was a React component.</p><p>It doesn’t care about:</p><pre>useState<br>useMemo<br>useCallback<br>React.memo<br>Fiber<br>Suspense</pre><p>Those are React-level concepts.</p><p>The browser cares about things such as:</p><pre>DOM<br>CSS<br>JavaScript<br>Layout<br>Paint<br>Compositing<br>Input<br>Frames</pre><p>Understanding this boundary is one of the most valuable mental models a frontend engineer can develop.</p><h3>So what actually happens when you click a React button?</h3><p>Let’s follow one interaction all the way through.</p><p>You click:</p><pre>Increment</pre><p>The browser receives the input.</p><p>JavaScript executes the event handler.</p><p>React receives:</p><pre>setCount(count + 1);</pre><p>React schedules the update.</p><p>The component renders again.</p><p>React produces the next UI representation.</p><p>React reconciles the previous and next trees.</p><p>React determines that the text changed from:</p><pre>0</pre><p>to:</p><pre>1</pre><p>React commits the necessary DOM mutation.</p><p>The browser now sees a changed DOM.</p><p>It determines whether styles need recalculation.</p><p>It determines whether layout needs to change.</p><p>It determines what needs to be painted.</p><p>It rasterizes the required content.</p><p>The compositor produces the final frame.</p><p>And finally:</p><pre>1</pre><p>appears on the screen.</p><p>All of this happens because several different systems cooperate.</p><h3>The most important mental model</h3><p>When people say:<br><em>“React renders the page.”</em></p><p>that’s a useful simplification, but it hides the architecture.</p><p>A more accurate model is:</p><pre>React<br>                    │<br>        Components / State / Props<br>                    │<br>                    ▼<br>             React Render<br>                    │<br>                    ▼<br>                Fiber<br>                    │<br>                    ▼<br>             Reconciliation<br>                    │<br>                    ▼<br>                 Commit<br>                    │<br>                    ▼<br>                   DOM<br>                    │<br>                    ▼<br>            ┌───────────────┐<br>            │    Browser    │<br>            └───────────────┘<br>                    │<br>          ┌─────────┼─────────┐<br>          ▼         ▼         ▼<br>       Style      Layout     Paint<br>          │         │         │<br>          └─────────┼─────────┘<br>                    ▼<br>              Rasterization<br>                    │<br>                    ▼<br>               Compositing<br>                    │<br>                    ▼<br>                  Pixels</pre><p>React decides what the UI should become.</p><p>The browser determines how that UI should be displayed.</p><h3>The real reason this matters</h3><p>Once you understand this pipeline, many frontend concepts stop feeling like isolated interview topics.</p><p>React.memo becomes a question about unnecessary React work.</p><p>Virtualization becomes a question about DOM size.</p><p>useLayoutEffect becomes a question about work that must happen before paint.</p><p>requestAnimationFrame becomes a question about frame scheduling.</p><p>CSS containment becomes a question about limiting rendering scope.</p><p>transform becomes a question about compositing and avoiding certain layout work.</p><p>Web Workers become a question about moving expensive computation away from the main thread.</p><p>SSR becomes a question about when meaningful HTML becomes available.</p><p>Hydration becomes a question about connecting React behavior to server-generated DOM.</p><p>Chrome Performance becomes a way to see where the browser is actually spending time.</p><p>And React Profiler becomes a way to understand where React is spending time.</p><p>These aren’t separate topics.</p><p>They’re different pieces of the same rendering system.</p><h3>The browser is the final authority</h3><p>At the end of the entire React pipeline, there is one thing React cannot control directly:</p><p><strong>the pixels on your screen.</strong></p><p>React can determine:</p><pre>what the UI should look like</pre><p>and update:</p><pre>the DOM</pre><p>But the browser ultimately determines:</p><pre>how that DOM and CSS become pixels</pre><p>The complete journey is therefore not:</p><pre>JSX → UI</pre><p>It is:</p><pre>JSX<br> ↓<br>JavaScript<br> ↓<br>React<br> ↓<br>Fiber<br> ↓<br>Reconciliation<br> ↓<br>Commit<br> ↓<br>DOM<br> ↓<br>CSS<br> ↓<br>Style Calculation<br> ↓<br>Layout<br> ↓<br>Paint<br> ↓<br>Rasterization<br> ↓<br>Compositing<br> ↓<br>Pixels</pre><p>And that is the part of frontend engineering that is easy to miss when we spend all our time inside the React abstraction.</p><p>React gives us a powerful way to describe and update interfaces.</p><p>But React is still running inside a browser.</p><p>And if you want to understand why a React application feels fast, slow, smooth, or janky, you eventually have to step outside the React abstraction and look at what the browser is actually doing.</p><p><strong>React decides what should change.<br>The DOM represents that change.<br>The browser turns it into pixels.</strong></p><p>That is how your React application actually reaches the screen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae1df4bd8bd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CQRS in Modern Scalable Systems]]></title>
            <link>https://medium.com/@krishnabokefod/cqrs-in-modern-scalable-systems-304f2015f028?source=rss-bb29547748c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/304f2015f028</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[logistics]]></category>
            <dc:creator><![CDATA[Krishna bokefod]]></dc:creator>
            <pubDate>Wed, 13 May 2026 05:43:59 GMT</pubDate>
            <atom:updated>2026-05-13T05:48:02.192Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GudYRaZ86pM2HOtISu2vTA.png" /></figure><h3>Why Big Applications Split Reads and Writes</h3><p>Most developers start with a traditional backend architecture.</p><p>A client calls an API → controller talks to database → database returns response.</p><p>Simple.</p><p>But as traffic grows, this architecture slowly becomes the bottleneck of the entire system.</p><p>In this article, we’ll deeply understand:</p><ul><li>Why traditional systems fail at scale</li><li>What CQRS actually is</li><li>Why companies separate reads and writes</li><li>How event-driven systems naturally fit with CQRS</li><li>Why denormalized databases become powerful</li><li>How AWS services fit into the architecture</li><li>Why Kafka/Event Streams become game changers</li></ul><h3>Traditional Application Architecture</h3><p>In most applications, everything happens in a single database.</p><h3>Example Flow</h3><ul><li>User requests product data</li><li>API calls controller</li><li>Controller queries database</li><li>Database returns result</li></ul><p>Similarly:</p><ul><li>User updates product</li><li>API hits update controller</li><li>Controller updates same database</li></ul><p>Everything — reads and writes — happens in one place.</p><h3>Traditional Architecture Diagram</h3><pre>                ┌─────────────┐<br>                │    Client   │<br>                └──────┬──────┘<br>                       │<br>                 API Request<br>                       │<br>                ┌──────▼──────┐<br>                │ API Server  │<br>                └──────┬──────┘<br>                       │<br>         ┌─────────────┴─────────────┐<br>         │                           │<br>   Read Operation              Write Operation<br>         │                           │<br>         └─────────────┬─────────────┘<br>                       │<br>                ┌──────▼──────┐<br>                │  SQL DB     │<br>                └─────────────┘</pre><h3>The Scaling Problem</h3><p>Initially this works perfectly.</p><p>But when traffic grows:</p><ul><li>Millions of reads happen</li><li>Thousands of writes happen</li><li>Complex joins increase</li><li>Heavy reporting queries start running</li><li>Real-time updates increase</li></ul><p>Now one database handles:</p><ul><li>Authentication</li><li>Product data</li><li>Orders</li><li>Payments</li><li>Search</li><li>Analytics</li><li>Dashboards</li><li>Notifications</li></ul><p>Everything.</p><p>Eventually the database becomes overloaded.</p><h3>Traditional Scaling Solutions</h3><h3>Vertical Scaling</h3><p>Increase server power:</p><ul><li>More RAM</li><li>More CPU</li><li>Bigger machine</li></ul><p>Problem:</p><p>Eventually hardware has limits.</p><h3>Horizontal Scaling</h3><p>Add replicas and distribute traffic.</p><p>Problem:</p><p>Still difficult when:</p><ul><li>Reads are extremely high</li><li>Writes lock tables</li><li>Joins become expensive</li><li>Complex queries slow down transactions</li></ul><p>This is where CQRS becomes powerful.</p><h3>What is CQRS?</h3><p>CQRS stands for:</p><h3>Command Query Responsibility Segregation</h3><p>The core idea is simple:<br><em>Separate READ operations from WRITE operations.</em></p><p>Instead of one database doing everything:</p><ul><li>One side handles commands (writes)</li><li>Another side handles queries (reads)</li></ul><h3>CQRS Architecture</h3><pre>                      ┌──────────────┐<br>                      │    Client    │<br>                      └──────┬───────┘<br>                             │<br>                     ┌───────▼────────┐<br>                     │  API Gateway   │<br>                     └───────┬────────┘<br>                             │<br>        ┌────────────────────┴────────────────────┐<br>        │                                         │<br>        │                                         │<br>┌───────▼────────┐                      ┌─────────▼────────┐<br>│ Command Side   │                      │   Query Side     │<br>│ (WRITE MODEL)  │                      │   (READ MODEL)   │<br>└───────┬────────┘                      └─────────┬────────┘<br>        │                                         │<br>        │                                 Optimized Reads<br>        │                                         │<br>┌───────▼────────┐                      ┌─────────▼────────┐<br>│  Write DB      │                      │    Read DB       │<br>│  (Normalized)  │                      │ (Denormalized)   │<br>└───────┬────────┘                      └─────────▲────────┘<br>        │                                         │<br>        └────────── Event Stream / Queue ─────────┘</pre><h3>Understanding Commands</h3><p>In CQRS, we don’t directly mutate the database.</p><p>Instead, business actions are represented as commands.</p><p>Examples:</p><ul><li>CreateProductCommand</li><li>UpdateProductPriceCommand</li><li>PlaceOrderCommand</li><li>CancelOrderCommand</li></ul><p>The business interacts with the system through commands.</p><h3>Command Flow</h3><pre>Client<br>   │<br>   ▼<br>API Gateway<br>   │<br>   ▼<br>Command Handler<br>   │<br>   ▼<br>Business Logic<br>   │<br>   ▼<br>Write Database<br>   │<br>   ▼<br>Emit Event</pre><h3>Why Commands are Powerful</h3><p>Commands provide:</p><ul><li>Better validation</li><li>Clear business intent</li><li>Auditability</li><li>Event generation</li><li>Easy async processing</li><li>Better scalability</li></ul><p>Instead of random SQL updates:</p><pre>UPDATE products SET price = 100</pre><p>You now have:</p><pre>UpdateProductPriceCommand</pre><p>This represents actual business intent.</p><h3>Query Side</h3><p>The query side exists only for reading.</p><p>Its job is:</p><ul><li>Fast reads</li><li>Optimized responses</li><li>Aggregated data</li><li>Denormalized structures</li><li>Zero heavy joins</li></ul><h3>Why Separate Read Database?</h3><p>In traditional SQL systems:</p><ul><li>Multiple joins become expensive</li><li>Large relational queries slow down reads</li><li>Analytics affect transactional performance</li></ul><p>CQRS solves this by creating a dedicated read model.</p><h3>Read Model Example</h3><p>Instead of storing:</p><pre>Products Table<br>Categories Table<br>Reviews Table<br>Users Table</pre><p>and joining them every time…</p><p>We create a denormalized read document like this:</p><pre>{<br>  &quot;productId&quot;: 1,<br>  &quot;name&quot;: &quot;iPhone&quot;,<br>  &quot;category&quot;: &quot;Mobile&quot;,<br>  &quot;rating&quot;: 4.8,<br>  &quot;reviewCount&quot;: 1920,<br>  &quot;sellerName&quot;: &quot;Apple Store&quot;<br>}</pre><p>Now reads become extremely fast.</p><p>No joins needed.</p><h3>SQL for Writes, NoSQL for Reads</h3><p>This is one of the biggest advantages of CQRS.</p><h3>Write Database</h3><p>Usually:</p><ul><li>PostgreSQL</li><li>MySQL</li><li>SQL Server</li></ul><p>Because writes need:</p><ul><li>Transactions</li><li>Consistency</li><li>Foreign keys</li><li>ACID guarantees</li></ul><h3>Read Database</h3><p>Usually:</p><ul><li>MongoDB</li><li>DynamoDB</li><li>Elasticsearch</li><li>Redis</li></ul><p>Because reads need:</p><ul><li>Speed</li><li>Flexible schema</li><li>Denormalized structures</li><li>High scalability</li></ul><h3>But How Do Both Databases Stay in Sync?</h3><p>This is where Event-Driven Architecture enters.</p><p>Whenever something changes in the write database:</p><p>An event is emitted.</p><p>Example:</p><pre>ProductPriceUpdatedEvent</pre><p>This event is pushed to:</p><ul><li>Kafka</li><li>RabbitMQ</li><li>AWS SNS/SQS</li><li>EventBridge</li></ul><p>Consumers listen to these events and update the read database.</p><h3>Event Flow Diagram</h3><pre>          ┌────────────────────┐<br>          │  Command Handler   │<br>          └─────────┬──────────┘<br>                    │<br>             Write Successful<br>                    │<br>                    ▼<br>          ┌────────────────────┐<br>          │   Emit Event       │<br>          └─────────┬──────────┘<br>                    │<br>         ┌──────────┴──────────┐<br>         │                     │<br>         ▼                     ▼<br> ┌──────────────┐      ┌──────────────┐<br> │ Read Updater │      │ Notification │<br> └──────┬───────┘      └──────┬───────┘<br>        │                     │<br>        ▼                     ▼<br> ┌──────────────┐      ┌──────────────┐<br> │ Read DB      │      │ Send Emails  │<br> └──────────────┘      └──────────────┘</pre><h3>Eventual Consistency</h3><p>One important thing:</p><p>CQRS systems are usually <strong>eventually consistent</strong>.</p><p>Meaning:</p><p>When data is updated:</p><ul><li>Write DB updates immediately</li><li>Read DB may update after 1–2 seconds</li></ul><p>So there can be small delays.</p><p>Example:</p><p>User updates product price.</p><p>For a few milliseconds or seconds:</p><ul><li>Write DB has latest value</li><li>Read DB may still show old value</li></ul><p>This is completely normal in distributed systems.</p><h3>Why This Tradeoff is Worth It</h3><p>In exchange, you get:</p><ul><li>Massive scalability</li><li>Faster reads</li><li>Independent scaling</li><li>Better reliability</li><li>Event-driven workflows</li><li>Better fault tolerance</li></ul><p>This is why large systems prefer CQRS.</p><h3>Event Sourcing + CQRS</h3><p>CQRS naturally fits with Event Sourcing.</p><p>Instead of storing only current state:</p><p>We store all events.</p><p>Example:</p><pre>ProductCreated<br>PriceUpdated<br>StockUpdated<br>ProductArchived</pre><p>These events become an append-only log.</p><h3>Huge Advantage</h3><p>If your read database gets corrupted:</p><p>You can regenerate it completely from event logs.</p><p>Just replay all events.</p><p>This is extremely powerful.</p><h3>Kafka Becomes a Central Nervous System</h3><p>With Kafka:</p><p>Every event becomes reusable.</p><p>Example:</p><p>When PriceDroppedEvent occurs:</p><p>Different systems can react independently.</p><pre>PriceDroppedEvent<br>        │<br> ┌──────┼─────────┐<br> ▼      ▼         ▼<br>Email  Analytics  Recommendation Engine</pre><p>One event powers multiple systems.</p><p>This creates loosely coupled architecture.</p><h3>Real AWS CQRS Architecture</h3><p>Here’s how CQRS can look in AWS.</p><h3>AWS CQRS Diagram</h3><pre>                    ┌─────────────────┐<br>                    │   API Gateway   │<br>                    └────────┬────────┘<br>                             │<br>                ┌────────────┴────────────┐<br>                │                         │<br>                ▼                         ▼<br><br>       ┌─────────────────┐       ┌─────────────────┐<br>       │ Command Service │       │  Query Service  │<br>       └────────┬────────┘       └────────┬────────┘<br>                │                         │<br>                ▼                         ▼<br><br>       ┌─────────────────┐       ┌─────────────────┐<br>       │   DynamoDB      │       │   MongoDB /     │<br>       │  (Write Store)  │       │ Elasticsearch   │<br>       └────────┬────────┘       └─────────────────┘<br>                │<br>                ▼<br><br>       ┌─────────────────┐<br>       │ Kafka / Kinesis │<br>       └────────┬────────┘<br>                │<br>     ┌──────────┼──────────┐<br>     ▼          ▼          ▼<br><br>┌─────────┐ ┌─────────┐ ┌────────────┐<br>│ Lambda  │ │ Emails  │ │ Analytics  │<br>└─────────┘ └─────────┘ └────────────┘</pre><h3>When Should You Use CQRS?</h3><p>CQRS is useful when:</p><ul><li>Reads are much higher than writes</li><li>System has huge traffic</li><li>Complex business logic exists</li><li>Independent scaling is required</li><li>Real-time event processing is important</li><li>Analytics and operational systems must be separated</li></ul><h3>When NOT to Use CQRS</h3><p>CQRS adds complexity.</p><p>Avoid it for:</p><ul><li>Small applications</li><li>CRUD dashboards</li><li>Early-stage MVPs</li><li>Simple admin panels</li></ul><p>Sometimes a normal monolith is the better solution.</p><h3>Final Thoughts</h3><p>CQRS is not just a pattern.</p><p>It changes how you think about applications.</p><p>Traditional systems treat reads and writes the same.</p><p>CQRS says:<br><em>Reads and writes have completely different scaling requirements.</em></p><p>Once systems become large:</p><ul><li>Reads need speed</li><li>Writes need consistency</li><li>Events need distribution</li><li>Services need independence</li></ul><p>CQRS solves these problems by separating responsibilities cleanly.</p><p>That’s why modern large-scale systems heavily rely on:</p><ul><li>CQRS</li><li>Event-driven architecture</li><li>Kafka</li><li>Denormalized read models</li><li>Distributed databases</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=304f2015f028" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Saying “I Used an API” — Explain Your AI Projects Like an Engineer]]></title>
            <link>https://medium.com/@krishnabokefod/stop-saying-i-used-an-api-explain-your-ai-projects-like-an-engineer-88b00fdcab80?source=rss-bb29547748c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/88b00fdcab80</guid>
            <category><![CDATA[ai-projects]]></category>
            <category><![CDATA[ai-prompt-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Krishna bokefod]]></dc:creator>
            <pubDate>Thu, 07 May 2026 16:14:42 GMT</pubDate>
            <atom:updated>2026-05-07T16:19:01.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjozJiMQqm6KS9GyixkhYA.png" /></figure><p>If you’re interviewing for an AI or backend-heavy role and you say:<br><strong><em>“I used the OpenAI API”</em></strong></p><p>…you’ve already lost the opportunity to stand out.</p><p>Not because it’s wrong but because it signals <strong>tool usage, not system design</strong>.</p><p>Interviewers don’t care that you can call an API. They care whether you can <strong>design, reason about, and scale an intelligent system</strong>.</p><p>So instead of talking about tools, structure your explanation around five core pillars:</p><ul><li>Data Pipeline</li><li>Retrieval Strategy</li><li>Prompt Structure</li><li>Evaluation Metrics</li><li>Failure Handling</li></ul><p>This is what separates a <em>builder</em> from an <em>engineer</em>.</p><p>Let’s break it down.</p><h3>1. Data Pipeline: Where Intelligence Begins</h3><p>Every AI system is only as good as the data it consumes.</p><p>A strong explanation starts with:</p><ul><li>Where your data comes from</li><li>How it’s processed</li><li>How it’s stored and updated</li></ul><h3>What good sounds like:</h3><p>Instead of:<em>“We used some documents as input”</em></p><p>Say: <em>“I designed a pipeline that ingests raw documents, removes noise, chunks them into semantically meaningful segments, and converts them into embeddings stored in a vector database.”</em></p><h3>Why this matters:</h3><p>You’re showing:</p><ul><li>Understanding of unstructured data</li><li>Trade-offs (chunk size vs context)</li><li>Awareness of scalability (batch vs real-time updates)</li></ul><p>This is engineering thinking.</p><h3>2. Retrieval Strategy: Finding the Right Context</h3><p>In most real-world AI systems (especially RAG systems), the model doesn’t “know everything.” It relies on retrieving relevant information.</p><p>So the question becomes:<br><strong>How do you fetch the <em>right</em> data?</strong></p><h3>What to explain:</h3><ul><li>Semantic search vs keyword search</li><li>Ranking and filtering</li><li>How many results you fetch (Top-K)</li></ul><h3>Strong answer:</h3><p>“I used semantic search over embeddings to retrieve the top 5 relevant chunks, then applied keyword filtering to improve precision before passing context to the model.”</p><h3>What this shows:</h3><ul><li>You understand relevance vs noise</li><li>You’ve thought about accuracy, not just functionality</li><li>You can optimize retrieval, not just use it</li></ul><h3>3. Prompt Structure: Controlling the Model</h3><p>Most candidates say:</p><p><em>“I wrote a prompt”</em></p><p>That’s like saying:</p><p><em>“I wrote some code”</em></p><p>It says nothing.</p><h3>What actually matters:</h3><ul><li>How you structure the prompt</li><li>What constraints you define</li><li>How you inject context</li></ul><h3>Example:</h3><p>“I separated system-level instructions (tone, constraints, behavior) from user input, and injected retrieved context dynamically. I also enforced a structured output format to ensure consistency.”</p><h3>Advanced signals:</h3><ul><li>Few-shot vs zero-shot prompting</li><li>Token optimization</li><li>Guardrails against prompt injection</li></ul><p>This shows you’re not <em>using</em> the model you’re <strong>controlling it</strong>.</p><h3>4. Evaluation Metrics: Does It Actually Work?</h3><p>This is where most candidates fail.</p><p>They build something… but never measure it.</p><h3>What to explain:</h3><ul><li>What does “good output” mean in your system?</li><li>How do you track it?</li></ul><h3>Examples:</h3><ul><li>Accuracy (is the answer correct?)</li><li>Latency (how fast is the response?)</li><li>Retrieval quality</li><li>User feedback</li></ul><h3>Strong answer:</h3><p>“I evaluated the system using both automated accuracy checks and human review. I also tracked latency and iterated on prompt design using A/B testing.”</p><h3>Why this stands out:</h3><p>You’re showing:</p><ul><li>Ownership of quality</li><li>Ability to iterate</li><li>Product thinking, not just coding</li></ul><h3>5. Failure Handling: Real Systems Don’t Always Work</h3><p>This is where you differentiate yourself the most.</p><p>Because real-world systems fail.</p><h3>Common failures:</h3><ul><li>Irrelevant retrieval</li><li>Hallucinated answers</li><li>API timeouts</li><li>Empty or broken responses</li></ul><h3>Strong answer:</h3><p>“I implemented fallback mechanisms when retrieval confidence was low, added retry logic for API failures, and designed prompts that encourage the model to say ‘I don’t know’ instead of hallucinating.”</p><h3>Bonus points if you mention:</h3><ul><li>Logging and monitoring</li><li>Rate limiting</li><li>Graceful degradation</li></ul><p>This shows you think about <strong>production systems</strong>, not just demos.</p><h3>Putting It All Together</h3><p>A strong AI project explanation doesn’t sound like a tutorial it sounds like a system design walkthrough.</p><h3>Example:</h3><p>“I built a retrieval-augmented AI system where I designed a data pipeline to process and chunk internal documents, stored embeddings in a vector database, and implemented a hybrid retrieval strategy combining semantic and keyword search.<br>I structured prompts with clear system instructions and dynamically injected context to ensure grounded responses.<br>For evaluation, I tracked accuracy, latency, and user feedback, and improved performance through iterative testing.<br>I also handled failures by adding fallback responses, retry mechanisms, and safeguards against hallucinations.”</p><p>That’s the difference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88b00fdcab80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Reconciliation Deep Dive]]></title>
            <link>https://medium.com/@krishnabokefod/react-reconciliation-deep-dive-6f72b92cbeca?source=rss-bb29547748c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f72b92cbeca</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[reconciliation]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-fiber]]></category>
            <dc:creator><![CDATA[Krishna bokefod]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 09:26:44 GMT</pubDate>
            <atom:updated>2026-02-27T09:26:44.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>How React Decides What to Render, When to Skip, and Why Fiber Changed Everything</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cw14hx_pf5DyS-wIthJXYg.png" /></figure><p>When people say “React efficiently updates the DOM,” they usually simplify it to:</p><p><em>“React compares Virtual DOM and updates only what changed.”</em></p><p>That explanation is only partially true.</p><p>Modern React reconciliation is not just Virtual DOM diffing. It is a carefully engineered system built on Fiber architecture, interruptible rendering, priority scheduling, bailout optimizations, and atomic commits.</p><p>To truly understand React performance and rendering behavior, we need to understand how reconciliation actually works under the hood.</p><h3>The Core Question React Solves</h3><p>Every update in React starts with one question:</p><p><strong>What changed between the previous UI and the next UI?</strong></p><p>When state or props change, React does not directly mutate the DOM. Instead, it builds a new in-memory tree representation and compares it to the previous one.</p><p>But here’s the important correction:</p><p>React does not compare two DOM trees.<br>React compares two Fiber trees.</p><h3>The Two-Tree Architecture (The Foundation of Everything)</h3><p>React always maintains two trees:</p><ul><li><strong>Current Tree</strong> → The UI currently visible on the screen.</li><li><strong>Work-In-Progress Tree (WIP)</strong> → The new UI React is building.</li></ul><p>When an update happens:</p><ol><li>React clones nodes from the current tree into the WIP tree.</li><li>It performs reconciliation inside the WIP tree.</li><li>Once finished, it swaps the trees atomically.</li><li>Then it performs DOM mutations in the commit phase.</li></ol><p>Why not mutate the current tree directly?</p><p>Because rendering in modern React is interruptible.</p><p>If React mutated the live tree and rendering was paused midway, the UI could become inconsistent. With two trees, React always keeps one stable version while safely building the next.</p><p>This is the architectural foundation of concurrency.</p><h3>Render Phase vs Commit Phase</h3><p>Reconciliation happens in the <strong>render phase</strong>.</p><p>The render phase:</p><ul><li>Is pure</li><li>Can be paused</li><li>Can be restarted</li><li>Can be abandoned</li><li>Does not mutate the DOM</li></ul><p>This means React may call your component function multiple times before committing.</p><p>After render completes, React enters the <strong>commit phase</strong>.</p><p>The commit phase:</p><ul><li>Is synchronous</li><li>Cannot be interrupted</li><li>Applies DOM mutations</li><li>Runs useEffect</li></ul><p>This separation ensures heavy calculations can be interrupted, but DOM updates remain consistent.</p><h3>When Does React Re-Render?</h3><p>Let’s move from theory to practical behavior.</p><p>React re-renders a component when:</p><ol><li>Its state changes</li><li>Its props change</li><li>Its parent re-renders</li><li>Context value it consumes changes</li><li>A hook dependency changes (useEffect, useMemo, useCallback)</li><li>A forceUpdate is triggered</li></ol><p>Let’s see real examples.</p><h3>Case 1: State Change (Always Re-Renders That Component)</h3><pre>function Counter() {<br>  const [count, setCount] = React.useState(0)<br><br>  return (<br>    &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>      {count}<br>    &lt;/button&gt;<br>  )<br>}</pre><p>When setCount runs:</p><ul><li>React schedules update</li><li>Counter fiber is marked dirty</li><li>Counter re-renders</li></ul><p>Even if parent is memoized, this component will re-render because state updates schedule work directly on that fiber.</p><p>Important distinction:</p><p>Bailouts prevent parent-driven renders not internal state updates.</p><h3>Case 2: Parent Re-Renders (Child May or May Not Render)</h3><pre>function Parent() {<br>  const [count, setCount] = React.useState(0)<br><br>  return (<br>    &lt;&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;+&lt;/button&gt;<br>      &lt;Child /&gt;<br>    &lt;/&gt;<br>  )<br>}</pre><p>If Parent re-renders:</p><ul><li>React will visit Child</li><li>Child will also render by default</li></ul><p>Because by default, React re-renders children when parent renders.</p><h3>Case 3: React.memo Preventing Render (Bailout)</h3><pre>const Child = React.memo(function Child() {<br>  console.log(&quot;Child Rendered&quot;)<br>  return &lt;div&gt;Hello&lt;/div&gt;<br>})</pre><p>Now when Parent re-renders:</p><p>React performs shallow comparison of props.</p><p>If props didn’t change:</p><ul><li>React clones the fiber</li><li>Skips executing Child function</li><li>Skips traversing its subtree</li></ul><p>This is called a bailout.</p><p>Grandchildren also won’t reconcile.</p><p>This is a subtree-level optimization.</p><h3>Case 4: Function Props Breaking Memoization</h3><pre>function Parent() {<br>  const handleClick = () =&gt; {<br>    console.log(&quot;Clicked&quot;)<br>  }<br><br>  return &lt;Child onClick={handleClick} /&gt;<br>}</pre><p>Even if Child is wrapped in React.memo, it will re-render.</p><p>Why?</p><p>Because every render creates a new function reference.</p><p>Shallow comparison fails:</p><p>previousProps.onClick !== nextProps.onClick</p><p>Solution:</p><pre>const handleClick = React.useCallback(() =&gt; {<br>  console.log(&quot;Clicked&quot;)<br>}, [])</pre><p>Now reference remains stable, and Child can bail out.</p><p>But there’s a catch.</p><h3>Case 5: Stale Closure Bug</h3><pre>const handleClick = useCallback(() =&gt; {<br>  console.log(count)<br>}, [])</pre><p>If count changes, the callback still logs the initial value.</p><p>Because the function was memoized once and captured stale state.</p><p>Correct version:</p><pre>const handleClick = useCallback(() =&gt; {<br>  console.log(count)<br>}, [count])</pre><p>But now function reference changes when count changes, and Child re-renders.</p><p>This is the trade-off between correctness and stability.</p><p>Senior-level optimization:</p><pre>const handleClick = useCallback(() =&gt; {<br>  setCount(prev =&gt; prev + 1)<br>}, [])</pre><p>Functional updates remove dependency.</p><h3>When React Does NOT Re-Render</h3><p>React skips rendering when:</p><ol><li>React.memo props comparison passes</li><li>useMemo dependencies didn’t change (value reused)</li><li>useCallback dependencies didn’t change (function reused)</li><li>State is set to the same value</li><li>Context value is unchanged</li><li>During bailout in reconciliation</li></ol><p>Example:</p><pre>setCount(0)</pre><p>If count was already 0:</p><p>React compares previous and next state using Object.is</p><p>No re-render happens.</p><h3>Fiber Bailout Internals</h3><p>During reconciliation:</p><ul><li>React reaches a fiber</li><li>Compares props and state</li><li>If no changes → bailoutOnAlreadyFinishedWork runs</li><li>It clones fiber into WIP</li><li>Reuses child pointer</li><li>Skips subtree traversal</li></ul><p>Important detail:</p><p>React does NOT reuse the old fiber object directly.</p><p>It creates a work-in-progress fiber but avoids reconciling deeper.</p><p>This preserves tree immutability and supports concurrency.</p><h3>Concurrency and Lanes</h3><p>React 18 introduced lanes to assign priority levels to updates.</p><p>High-priority updates:</p><ul><li>Typing</li><li>Clicks</li></ul><p>Low-priority updates:</p><ul><li>Filtering large lists</li><li>Navigation transitions</li></ul><p>Example:</p><pre>startTransition(() =&gt; {<br>  setSearchQuery(value)<br>})</pre><p>This does not delay execution.</p><p>It assigns the update to a lower-priority lane.</p><p>If a high-priority update occurs, React can pause the low-priority render and handle urgent work first.</p><p>This is only possible because reconciliation happens in the WIP tree.</p><h3>Suspense and Reconciliation</h3><p>When a component suspends, it throws a Promise.</p><p>React catches it during render phase.</p><p>React then:</p><ul><li>Stops rendering that subtree</li><li>Renders fallback UI</li><li>Retries when Promise resolves</li></ul><p>Without two trees, suspension would corrupt the UI.</p><h3>The Complete Mental Model</h3><p>Reconciliation is not:</p><p>“Comparing two DOM trees.”</p><p>It is:</p><ul><li>Building a new Fiber tree</li><li>Comparing fibers</li><li>Skipping unchanged branches</li><li>Scheduling work with priorities</li><li>Supporting interruption</li><li>Committing atomically</li></ul><p>React is essentially a cooperative scheduler that builds UI trees safely in memory before committing them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f72b92cbeca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rendering vs JavaScript — When Does the Browser Actually Paint?]]></title>
            <link>https://medium.com/@krishnabokefod/rendering-vs-javascript-when-does-the-browser-actually-paint-801aaada14dc?source=rss-bb29547748c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/801aaada14dc</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[how-browser-works]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[javascript-engine]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Krishna bokefod]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 17:20:24 GMT</pubDate>
            <atom:updated>2026-02-11T17:20:24.664Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZDHhys_bfojI0OjvmpXidg.png" /></figure><p>You click a button.</p><p>You change its color using JavaScript.</p><p>But nothing happens.</p><p>For a split second… the UI freezes.</p><p>Then suddenly — everything updates at once.</p><p>Why?</p><p>If JavaScript runs instantly, why doesn’t the browser paint instantly?</p><p>This is one of the most misunderstood parts of frontend development the silent tension between <strong>JavaScript execution</strong> and the <strong>browser rendering engine</strong>.</p><p>Let’s unpack what really happens.</p><h3>JavaScript Is Not the Browser</h3><p>When we say “JavaScript runs in the browser,” we oversimplify reality.</p><p>The browser is not just a JavaScript engine.</p><p>It contains:</p><ul><li>A JavaScript engine (V8, SpiderMonkey)</li><li>A rendering engine (Blink, WebKit, Gecko)</li><li>A compositor</li><li>A layout engine</li><li>Web APIs</li><li>An event loop tying everything together</li></ul><pre>+----------------------------------------------------------------------------------+<br>|                                   BROWSER                                        |<br>|----------------------------------------------------------------------------------|<br>|                                                                                  |<br>|   +----------------------+        +------------------------------------------+   |<br>|   |  JavaScript Engine   |        |              Web APIs                    |   |<br>|   |----------------------|        |------------------------------------------|   |<br>|   |  V8 / SpiderMonkey   | &lt;----&gt; |  DOM API                                  |   |<br>|   |  JS Heap             |        |  Fetch / XHR                              |   |<br>|   |  Call Stack          |        |  setTimeout / setInterval                 |   |<br>|   +----------------------+        |  WebSockets                                |   |<br>|                                   |  Canvas / Storage / etc.                  |   |<br>|                                   +--------------------+---------------------+   |<br>|                                                        |                         |<br>|                                                        v                         |<br>|                                           +------------------------+             |<br>|                                           |      Event Loop        |             |<br>|                                           |------------------------|             |<br>|                                           |  Task Queue            |             |<br>|                                           |  Microtask Queue       |             |<br>|                                           +-----------+------------+             |<br>|                                                       |                          |<br>|                                                       v                          |<br>|   +----------------------------------------------------------------------------------+<br>|   |                              Rendering Engine                                   |<br>|   |----------------------------------------------------------------------------------|<br>|   |   HTML Parser → DOM Tree                                                         |<br>|   |   CSS Parser  → CSSOM                                                            |<br>|   |   Layout Engine (calculates geometry)                                            |<br>|   |   Paint (draw pixels)                                                            |<br>|   |   Compositor (GPU layer compositing)                                             |<br>|   +----------------------------------------------------------------------------------+<br>|                                                                                  |<br>+----------------------------------------------------------------------------------+</pre><p>And here’s the critical detail:<br> <em>JavaScript and rendering share the same main thread.</em></p><p>That single thread is responsible for:</p><ul><li>Executing JavaScript</li><li>Handling user input</li><li>Calculating styles</li><li>Performing layout</li><li>Painting pixels to the screen</li></ul><p>Only one of these can run at a time.</p><p>So if JavaScript is busy…</p><p>Rendering must wait.</p><h3>A Simple Example That Breaks the Illusion</h3><p>Consider this:</p><pre>button.addEventListener(&quot;click&quot;, () =&gt; {<br>  button.style.background = &quot;red&quot;;</pre><pre>  for (let i = 0; i &lt; 1000000000; i++) {}</pre><pre>  console.log(&quot;Done&quot;);<br>});</pre><p>You expect the button to turn red immediately.</p><p>But it doesn’t.</p><p>The UI freezes.</p><p>The color changes only after the loop finishes.</p><p>Why?</p><p>Because while that loop is running, the main thread is occupied.</p><p>And the browser cannot paint while JavaScript is executing.</p><p>Rendering only happens when the call stack is empty.</p><h3>The Moment the Browser Gets to Paint</h3><p>The browser doesn’t paint continuously.</p><p>It paints in frames usually targeting 60 frames per second.</p><p>That gives us about 16.6 milliseconds per frame.</p><p>Inside that tiny time window, the browser must:</p><ul><li>Run JavaScript</li><li>Process microtasks</li><li>Recalculate styles</li><li>Perform layout</li><li>Paint</li><li>Composite layers</li></ul><p>If JavaScript takes too long, the frame is missed.</p><p>The result?</p><p>Lag. Jank. Frozen UI.</p><p>Rendering happens only when:</p><ul><li>The call stack is empty</li><li>All microtasks are finished</li><li>The browser scheduler decides it’s time for a frame</li></ul><p>In other words: <br><em>The browser paints between tasks never during JavaScript execution.</em></p><h3>The Event Loop’s Hidden Role in Rendering</h3><p>After each macrotask:</p><ol><li>All microtasks are executed.</li><li>If the stack is empty…</li><li>The browser may render before moving to the next task.</li></ol><p>That “may” is important.</p><p>Rendering is not guaranteed after every task.<br> It depends on frame timing.</p><p>This is why setTimeout(..., 0) doesn’t force immediate UI updates.</p><p>And it’s also why microtasks can delay rendering entirely.</p><h3>The Dangerous Side of Microtasks</h3><p>Consider this:</p><pre>function loop() {<br>  Promise.resolve().then(loop);<br>}</pre><pre>loop();</pre><p>This creates an infinite microtask chain.</p><p>Since the event loop must clear all microtasks before rendering…</p><p>The browser never gets a chance to paint.</p><p>No animation.<br> No scroll.<br> No updates.</p><p>Promises can block rendering just as effectively as a while(true) loop — if misused.</p><h3>What Actually Happens During Rendering</h3><p>When the browser does get its chance to paint, it doesn’t just “draw.”</p><p>It performs a pipeline:</p><ol><li>Style calculation resolving CSS rules</li><li>Layout calculating sizes and positions</li><li>Paint drawing pixels</li><li>Compositing — combining layers using the GPU</li></ol><p>Only after these stages does the user see visual change.</p><p>And each of these steps takes time.</p><p>That’s why minimizing layout recalculations and avoiding layout thrashing matters so much in performance optimization.</p><h3>Why requestAnimationFrame Feels Smoother</h3><p>requestAnimationFrame exists because rendering is frame-based.</p><p>It schedules your callback right before the next repaint.</p><p>That means:</p><ul><li>It runs at the correct time in the frame lifecycle</li><li>It syncs with display refresh</li><li>It avoids unnecessary layout recalculations</li></ul><p>This is why animations powered by requestAnimationFrame feel smoother than those driven by timers.</p><h3>The Mental Model That Changes Everything</h3><p>Imagine the main thread as a narrow bridge.</p><p>Across that bridge must pass:</p><ul><li>JavaScript</li><li>Microtasks</li><li>Layout</li><li>Paint</li><li>User input</li></ul><p>If JavaScript hogs the bridge…</p><p>Nothing else moves.</p><p>Understanding this changes how you write code.</p><p>You stop asking:</p><p>“Why didn’t it update instantly?”</p><p>And start asking:</p><p>“Is the main thread free to render?”</p><h3>Why This Matters in Real Applications</h3><p>In large React or dashboard applications:</p><ul><li>Heavy synchronous loops freeze UI</li><li>Excessive microtasks delay rendering</li><li>Large layout recalculations cause frame drops</li><li>Unbatched DOM writes create jank</li></ul><p>Performance is not just about faster algorithms.</p><p>It’s about respecting the rendering cycle.</p><h3>Final Thought</h3><p>Most developers learn:</p><p>“JavaScript is single-threaded.”</p><p>Few truly internalize:</p><p>“The browser can only paint when JavaScript lets it.”</p><p>Rendering isn’t magical.<br> It’s scheduled.</p><p>And once you understand that timing, you stop fighting the browser and start working with it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=801aaada14dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Loop Deep Dive — How JavaScript Really Executes Your Code]]></title>
            <link>https://medium.com/@krishnabokefod/event-loop-deep-dive-how-javascript-really-executes-your-code-fa60f454e50c?source=rss-bb29547748c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa60f454e50c</guid>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Krishna bokefod]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 13:30:27 GMT</pubDate>
            <atom:updated>2026-02-08T13:30:27.139Z</atom:updated>
            <content:encoded><![CDATA[<h3>Event Loop Deep Dive — How JavaScript Really Executes Your Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*us-he6SDdhbkLuCAhQoXCQ.png" /></figure><p>If you’ve been writing JavaScript for a while, you’ve probably heard this sentence: <br><em>“JavaScript is single-threaded.”</em></p><p>And then immediately wondered:</p><p><strong>If JavaScript runs on a single thread, how does it handle API calls, timers, animations, and user clicks all at the same time?</strong></p><p>The answer lives in one of the most misunderstood (and interview-favorite) concepts in JavaScript:</p><p>👉 <strong>The Event Loop</strong></p><p>This article is a deep dive not just <em>what</em> the Event Loop is, but <em>how it actually works under the hood</em>, step by step.</p><h3>Why JavaScript Even Needs an Event Loop</h3><p>JavaScript was originally designed to run in browsers and interact with the DOM.</p><p>Imagine this situation:</p><ul><li>A button click triggers a heavy calculation</li><li>While that calculation runs, the user tries to scroll or click again</li></ul><p>If JavaScript blocked the browser until it finished everything, the UI would freeze.<br> That would be a terrible user experience.</p><p>So JavaScript chose a different path:</p><p>✔ <strong>Single-threaded execution</strong><br> ✔ <strong>Non-blocking, asynchronous behavior</strong></p><p>And the Event Loop is the system that makes this possible.</p><h3>First, a Quick Call Stack Recap</h3><p>At the heart of JavaScript execution is the <strong>Call Stack</strong>.</p><p>Think of the Call Stack as a stack of plates:</p><ul><li>Functions are added (pushed) when called</li><li>Functions are removed (popped) when they return</li></ul><p>Example:</p><pre>function first() {<br>  second();<br>}<br><br>function second() {<br>  console.log(&quot;Hello&quot;);<br>}<br><br>first();</pre><p>Execution order:</p><ol><li>first() goes on the stack</li><li>second() goes on the stack</li><li>console.log() executes</li><li>second() finishes → removed</li><li>first() finishes → removed</li></ol><p>Simple and synchronous.<br> But this model alone cannot handle async tasks.</p><h3>Where Asynchronous Code Goes</h3><p>Now look at this:</p><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Timeout&quot;);<br>}, 0);<br><br>console.log(&quot;End&quot;);</pre><p>Most beginners expect:</p><pre>Start<br>Timeout<br>End</pre><p>But the real output is:</p><pre>Start<br>End<br>Timeout</pre><p>Why?</p><p>Because setTimeout <strong>does not run on the Call Stack</strong>.</p><h3>Web APIs — The Hidden Helpers</h3><p>When JavaScript encounters asynchronous operations like:</p><ul><li>setTimeout</li><li>fetch</li><li>DOM events</li><li>setInterval</li></ul><p>These tasks are <strong>handed over to Web APIs</strong> (provided by the browser or Node.js runtime).</p><p>So what happens here:</p><pre>setTimeout(callback, 0);</pre><ol><li>JavaScript sends the timer to the Web API</li><li>The Call Stack continues executing other code</li><li>Once the timer expires, the callback is moved to a queue</li></ol><p>But <em>which</em> queue?</p><p>That’s where things get interesting 👀</p><h3>Task Queue (Macrotask Queue)</h3><p>The <strong>Task Queue</strong> (also called the Macrotask Queue) stores callbacks from:</p><ul><li>setTimeout</li><li>setInterval</li><li>UI events (click, scroll)</li><li>Message events</li></ul><p>These tasks <strong>wait patiently</strong> until the Call Stack is empty.</p><h3>Microtask Queue — The VIP Line</h3><p>JavaScript has another, higher-priority queue:</p><p>👉 <strong>Microtask Queue</strong></p><p>This queue is used for:</p><ul><li>Promise.then</li><li>Promise.catch</li><li>Promise.finally</li><li>queueMicrotask</li><li>MutationObserver</li></ul><p>Microtasks always run <strong>before</strong> macrotasks.</p><p>Example:</p><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; console.log(&quot;Timeout&quot;), 0);<br><br>Promise.resolve().then(() =&gt; console.log(&quot;Promise&quot;));<br><br>console.log(&quot;End&quot;);</pre><p>Output:</p><pre>Start<br>End<br>Promise<br>Timeout</pre><p>Why?</p><p>Because after the Call Stack is empty:</p><ol><li>JavaScript executes <strong>all microtasks</strong></li><li>Only then does it execute <strong>one macrotask</strong></li><li>Then the cycle repeats</li></ol><h3>So What Exactly Is the Event Loop?</h3><p>The <strong>Event Loop</strong> is not a line of code you write.</p><p>It’s a continuous process that does this:</p><ol><li>Check if the Call Stack is empty</li><li>If yes:</li></ol><ul><li>Execute <strong>all microtasks</strong></li><li>Execute <strong>one macrotask</strong></li></ul><ol><li>Repeat forever</li></ol><p>That’s it.</p><p>That loop never stops while your program is running.</p><h3>Visualizing the Event Loop Flow</h3><p>Think of it like this:</p><pre>┌─────────────┐<br>│ Call Stack  │<br>└─────▲───────┘<br>      │<br>┌─────┴───────┐<br>│ Microtasks  │  ← Promises (High priority)<br>└─────▲───────┘<br>      │<br>┌─────┴───────┐<br>│ Macrotasks  │  ← setTimeout, events<br>└─────────────┘</pre><p>Microtasks always cut the line.</p><h3>Real-Life Example: API Call + UI Update</h3><pre>console.log(&quot;Fetching data&quot;);<br><br>fetch(&quot;/api/data&quot;)<br>  .then(() =&gt; console.log(&quot;Data received&quot;));<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;UI animation&quot;);<br>}, 0);<br><br>console.log(&quot;Rendering page&quot;);</pre><p>Execution order:</p><pre>Fetching data<br>Rendering page<br>Data received<br>UI animation</pre><p>Why this matters:</p><ul><li>Promises are used for <strong>data consistency</strong></li><li>Timers and UI events are intentionally lower priority</li></ul><h3>Why Microtasks Can Be Dangerous</h3><p>Microtasks can <strong>starve the Event Loop</strong>.</p><p>Example:</p><pre>function loop() {<br>  Promise.resolve().then(loop);<br>}<br><br>loop();</pre><p>This creates an infinite microtask loop.</p><p>Result:</p><p>❌ UI freezes<br> ❌ No macrotasks ever execute</p><p>That’s why misuse of promises can be just as harmful as blocking code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa60f454e50c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Main Thread vs Web Workers — What Really Runs Where in the Browser?]]></title>
            <link>https://medium.com/@krishnabokefod/main-thread-vs-web-workers-what-really-runs-where-in-the-browser-99c8e9d66647?source=rss-bb29547748c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/99c8e9d66647</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[main-thread]]></category>
            <category><![CDATA[webworker]]></category>
            <dc:creator><![CDATA[Krishna bokefod]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 11:31:10 GMT</pubDate>
            <atom:updated>2026-01-29T11:31:10.531Z</atom:updated>
            <content:encoded><![CDATA[<h3>Main Thread vs Web Workers — What Really Runs Where in the Browser?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nF9PFzWW6N4tQPU1yXbBBg.png" /></figure><p>Why does your browser seem to be doing a hundred tasks at once if JavaScript is single-threaded?</p><p>Although most explanations reduce this question to one-liners or bullet lists, it is at the core of frontend performance. Let’s do this correctly, both conceptually and visually, and with enough nuance to make it truly stick.</p><h3>🧠 The Browser Is Not JavaScript</h3><p>The first mistake most developers make is equating <strong>JavaScript</strong> with the <strong>browser</strong>.</p><p>JavaScript is just <em>one</em> piece of a much larger system.</p><p>A modern browser is:</p><ul><li>Multi-process</li><li>Multi-threaded</li><li>Highly parallel</li></ul><p>JavaScript, however, runs under <strong>very strict rules </strong>and those rules exist to protect the user experience.</p><h3>🎯 The Main Thread: The One Thread That Matters Most</h3><p>Think of the <strong>main thread</strong> as the control room of the browser.</p><p>Everything the user sees, touches, or feels flows through it.</p><pre>┌────────────────────────────┐<br>│ MAIN THREAD                │<br>├────────────────────────────┤<br>│ JavaScript Execution       │<br>│ DOM Updates                │<br>│ Style Calculation (CSS)    │<br>│ Layout (Reflow)            │<br>│ Paint &amp; Composite          │<br>│ User Events (click, scroll)│<br>└────────────────────────────┘</pre><p>This is not accidental design it’s a safety guarantee.</p><p>If multiple threads were allowed to mutate the DOM simultaneously, the UI would become nondeterministic. Buttons could move while being clicked. Layout could change mid‑paint. Browsers avoid this chaos by enforcing a single authority over the UI: <strong>the main thread</strong>.</p><h3>⏱️ Why the Main Thread Gets Blocked</h3><p>The main thread can only do <strong>one thing at a time</strong>.</p><p>When JavaScript runs, it occupies the thread completely.</p><pre>JS running ────────────────▶<br>UI updates ❌ events ❌ paint ❌</pre><p>A task that takes:</p><ul><li>5ms → invisible</li><li>50ms → noticeable</li><li>200ms → <em>the site feels broken</em></li></ul><p>This is why users don’t complain about “slow code.” They complain about <strong>lag</strong>.</p><h3>🔥 Async JavaScript Is Still Main‑Thread JavaScript</h3><p>This is where confusion usually begins.</p><p>Promises, async/await, callbacks they <strong>do not create parallelism</strong>.</p><p>They only control <em>when</em> code runs, not <em>where</em> it runs.</p><pre>Main Thread<br>│<br>├─ fetch()<br>│ └─ waiting (network)<br>│<br>├─ .then()<br>│ └─ back on main thread ❗</pre><p>Async keeps the thread free <em>while waiting</em>, but once execution resumes, it resumes on the same thread responsible for rendering.</p><h3>💥 The Real Enemy: Heavy Computation</h3><p>Problems appear when JavaScript does real work:</p><ul><li>Parsing large JSON responses</li><li>Sorting thousands of items</li><li>Image manipulation</li><li>Data analytics</li><li>Cryptography</li></ul><p>None of these are bad. They’re just <strong>bad on the main thread</strong>.</p><h3>🧵 Enter Web Workers: Parallelism Without Chaos</h3><p>Web Workers exist for one reason:<br><strong><em>Move heavy JavaScript off the main thread without breaking the UI.</em></strong></p><p>When you create a worker, the browser does something powerful.</p><pre>Main Thread Worker Thread<br>────────────── ──────────────<br>UI + DOM JS Engine<br>Rendering Event Loop<br>User Events Heavy Computation</pre><p>This is real parallel execution. Not scheduling tricks. Not async illusions.</p><h3>🚫 Why Workers Cannot Touch the DOM</h3><p>This limitation is intentional and essential.</p><p>If workers could access the DOM:</p><ul><li>Every DOM operation would need locks</li><li>Rendering would stall</li><li>Performance would collapse</li></ul><p>Instead, browsers enforce isolation.</p><p>Workers communicate through <strong>messages</strong>, not shared state.</p><h3>📦 Message Passing: What Actually Happens</h3><p>When data moves between threads:</p><pre>Main Thread<br>│ postMessage(data)<br>▼<br>[ StructuredThis is real parallel execution. Not scheduling tricks. Not async illusions.<br><br><br>🚫 Why Workers Cannot Touch the DOM<br>This limitation is intentional — and essential.<br><br><br>If workers could access the DOM:<br><br><br>Every DOM operation would need locks<br><br><br>Rendering would stall<br><br><br>Performance would collapse<br><br><br>Instead, browsers enforce isolation.<br><br><br>Workers communicate through messages, not shared state.<br><br><br>📦 Message Passing: What Actually Happens<br>When data moves between threads:<br><br><br>Clone ]<br>▼<br>Worker Thread</pre><p>Large data means expensive copying. That’s why <strong>Transferable Objects</strong> (like ArrayBuffer) exist ownership moves instead of copying.</p><p>This is one of those details that separates <em>working</em> code from <em>fast</em> code.</p><h3>🧩 The Mental Model That Finally Works</h3><p>Think in responsibilities, not APIs.</p><pre>Main Thread → Experience<br>Worker → Work</pre><p>They run in parallel. They never touch each other directly. They cooperate through messages.</p><h3>⚖️ When Web Workers Are Worth It</h3><p>Use them when work is:</p><ul><li>CPU‑heavy</li><li>Long‑running</li><li>Independent of UI</li></ul><p>Avoid them when tasks are:</p><ul><li>Small</li><li>DOM‑dependent</li><li>Short‑lived</li></ul><p>Workers are powerful not free.<br>🧵 Web Workers Going Deeper Than the Definition</p><p>So far, we’ve treated Web Workers as a solution to “heavy computation”. That’s true but incomplete. To really <em>understand</em> workers, we need to look at how they behave internally and how they fit into the browser’s execution model.</p><p>When you create a Web Worker, the browser does <strong>not</strong> simply move your function to another queue. It creates a <strong>new execution environment</strong>. This environment has its own:</p><ul><li>JavaScript engine instance</li><li>Call stack</li><li>Event loop</li><li>Microtask queue</li><li>Heap</li></ul><p>In other words, a worker is closer to a <em>mini JavaScript runtime</em> than a helper thread.</p><h3>⚙️ What Actually Happens When a Worker Starts</h3><p>When the main thread executes new Worker(&#39;worker.js&#39;), several things happen behind the scenes:</p><ol><li>The browser allocates a new OS-level thread (or reuses one from a pool)</li><li>A new JS engine context is initialized</li><li>The worker script is loaded and parsed</li><li>A separate event loop starts running</li></ol><p>From this point onward, the worker runs <strong>independently</strong>. It does not pause when the main thread is busy, and it does not block rendering.</p><p>This independence is the key reason workers are effective.</p><h3>🔁 Event Loop Inside a Web Worker</h3><p>Just like the main thread, a worker has its own event loop.</p><p>That means inside a worker:</p><ul><li>Timers (setTimeout) work</li><li>Promises and microtasks work</li><li>Async/await works</li></ul><p>But all of this happens <strong>inside the worker thread</strong>, not on the UI thread.</p><p>This is a subtle but powerful point: async code inside a worker never competes with rendering.</p><h3>📡 Message Passing Is the Only Bridge</h3><p>Workers do not share memory with the main thread by default.</p><p>Every interaction happens through messages:</p><pre>Main Thread ── postMessage(data) ──▶ Worker<br>Worker ── postMessage(result) ─▶ Main Thread</pre><p>The browser enforces this boundary strictly.</p><p>Why? Because shared mutable state across threads is the fastest way to create nondeterministic bugs.</p><h3>🚀 Structured Clone vs Transferables</h3><p>When data is sent to a worker, the browser uses the <strong>structured clone algorithm</strong>.</p><p>This means:</p><ul><li>Objects are deep-copied</li><li>Functions are not allowed</li><li>DOM nodes are blocked</li></ul><p>For large datasets, this copying can become expensive.</p><p>That’s why browsers support <strong>transferable objects</strong> like ArrayBuffer, where ownership moves instead of copying. After transfer, the sender loses access.</p><p>This single detail often determines whether workers actually improve performance or quietly make it worse.</p><h3>🧪 Real-World Use Cases Where Workers Shine</h3><p>Web Workers are most effective when:</p><ul><li>Parsing very large JSON payloads</li><li>Running data transformations or analytics</li><li>Image or video processing</li><li>Compression or encryption</li><li>Complex calculations repeated over time</li></ul><p>In all these cases, the UI stays responsive because the main thread remains free.</p><h3>⚠️ Why Workers Are Not Used Everywhere</h3><p>Despite their power, workers are not free.</p><p>They come with:</p><ul><li>Startup overhead</li><li>Message serialization cost</li><li>More complex architecture</li></ul><p>This is why you don’t offload <em>everything</em> to a worker. Workers are a precision tool, not a default choice.</p><h3>🧠 Summary</h3><p>JavaScript being single‑threaded is not a flaw. It’s a deliberate design to keep the UI predictable and safe.</p><p>Web Workers exist to <strong>protect the main thread</strong>, not replace it.</p><p>Once you understand what runs where performance stops being mysterious and starts being intentional.</p><p>That’s the difference between <em>using</em> JavaScript and <em>understanding</em> the browser.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99c8e9d66647" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Microtasks vs Macrotasks — How JavaScript Really Schedules Work]]></title>
            <link>https://medium.com/@krishnabokefod/microtasks-vs-macrotasks-how-javascript-really-schedules-work-66a9303018d9?source=rss-bb29547748c8------2</link>
            <guid isPermaLink="false">https://medium.com/p/66a9303018d9</guid>
            <category><![CDATA[microtask-queue]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Krishna bokefod]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 15:45:38 GMT</pubDate>
            <atom:updated>2026-01-27T15:45:38.902Z</atom:updated>
            <content:encoded><![CDATA[<h3>end Microtasks vs Macrotasks — How JavaScript Really Schedules Work</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pCLKhhR5Lj3-1bPuJyPfg.png" /></figure><p>If you’ve ever stared at JavaScript output like this:</p><pre>console.log(&quot;A&quot;);<br><br>setTimeout(() =&gt; console.log(&quot;B&quot;), 0);<br><br>Promise.resolve().then(() =&gt; console.log(&quot;C&quot;));<br><br>console.log(&quot;D&quot;);</pre><p>…and wondered <strong>why the output is</strong>:</p><pre>A<br>D<br>C<br>B</pre><p>Congratulations you’ve just bumped into the <strong>real JavaScript runtime</strong>, not the simplified one we learn on day one.</p><p>This article is about <strong>how JavaScript actually schedules work</strong>, using <strong>macrotasks</strong>, <strong>microtasks</strong>, and the <strong>event loop </strong>and why understanding this matters deeply for frontend developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ceBb_qC6kE3ORssbHiQLHg.png" /></figure><h3>Why JavaScript Needs Task Queues at All</h3><p>JavaScript is <strong>single-threaded</strong>.</p><p>That means:</p><ul><li>One <strong>call stack</strong></li><li>One thing executing at a time</li><li>No true parallel execution on the main thread</li></ul><p>So how does JS handle:</p><ul><li>API calls?</li><li>Timers?</li><li>User clicks?</li><li>Promises?</li><li>Animations?</li></ul><p>👉 <strong>By deferring work</strong> instead of blocking execution.</p><p>This is where <strong>task queues</strong> come in.</p><p>Without task queues:</p><ul><li>UI would freeze during network calls</li><li>Animations would stutter</li><li>The browser would feel broken</li></ul><p>Task queues allow JavaScript to <strong>pause work</strong>, finish current execution, and <strong>resume later in a controlled order</strong>.</p><h3>Quick Call Stack Recap (Short but Critical)</h3><p>The <strong>call stack</strong> is where JavaScript executes synchronous code.</p><p>Example:</p><pre>function a() {<br>  b();<br>}<br><br>function b() {<br>  console.log(&quot;Hello&quot;);<br>}<br><br>a();</pre><p>Execution:</p><ol><li>a() pushed to stack</li><li>b() pushed to stack</li><li>console.log() runs</li><li>Stack clears</li></ol><p>⚠️ Important rule:</p><p><strong><em>JavaScript can only do ONE thing at a time on the call stack.</em></strong></p><p>If the stack is busy, <strong>nothing else runs</strong>.</p><h3>So Where Do Async Tasks Go?</h3><p>Not onto the call stack.</p><p>They go into <strong>task queues</strong>, waiting for:</p><ul><li>Call stack to become empty</li><li>Event loop to pick them up</li></ul><p>But here’s the twist 👇<br> <strong>There is not just one task queue.</strong></p><p>There are <strong>two major categories</strong>:</p><ul><li><strong>Macrotasks</strong></li><li><strong>Microtasks</strong></li></ul><h3>What Are Macrotasks?</h3><p>Macrotasks represent <strong>large, scheduled chunks of work</strong>.</p><p>They include:</p><ul><li>setTimeout</li><li>setInterval</li><li>UI events (click, scroll, keypress)</li><li>setImmediate (Node.js)</li><li>MessageChannel callbacks</li></ul><h3>Example:</h3><pre>setTimeout(() =&gt; {<br>  console.log(&quot;Macrotask executed&quot;);<br>}, 0);</pre><p>Even with 0ms, this does <strong>not</strong> mean “run immediately”.</p><p>It means:<br><em>“Run </em><strong><em>after</em></strong><em> the current call stack finishes and </em><strong><em>after microtasks</em></strong><em> are done.”</em></p><p>Macrotasks live in the <strong>macrotask queue</strong> (also called the <em>task queue</em>).</p><h3>What Are Microtasks?</h3><p>Microtasks are <strong>higher-priority tasks</strong> that must run <strong>before the browser moves on</strong>.</p><p>They include:</p><ul><li>Promise.then / catch / finally</li><li>queueMicrotask</li><li>MutationObserver</li></ul><h3>Example:</h3><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;Microtask executed&quot;);<br>});</pre><p>Microtasks live in the <strong>microtask queue</strong>.</p><p>And this queue has <strong>special rules</strong>.</p><h3>Why Microtasks Run First (The Golden Rule)</h3><p>After the call stack becomes empty:</p><ol><li><strong>All microtasks are executed</strong></li><li>Only <strong>then</strong> does the event loop pick <strong>one macrotask</strong></li><li>After that macrotask completes → microtasks are drained again</li><li>Repeat</li></ol><h3>The rule:</h3><p><strong><em>Microtasks are flushed completely before any macrotask runs.</em></strong></p><p>This is <strong>not optional</strong>.<br> It’s enforced by the JavaScript specification.</p><h3>Event Loop — The Actual Order</h3><p>The real execution cycle looks like this:</p><pre>Call Stack<br>   ↓<br>Microtask Queue (drain completely)<br>   ↓<br>Macrotask Queue (take ONE task)<br>   ↓<br>Microtask Queue (drain again)<br>   ↓<br>Render (if needed)<br>   ↓<br>Repeat</pre><p>This explains why promises feel “faster” than timers.</p><h3>Real-Life Example: API Call + UI Update</h3><p>Imagine this code in a frontend app:</p><pre>fetch(&quot;/api/data&quot;)<br>  .then(res =&gt; res.json())<br>  .then(data =&gt; {<br>    console.log(&quot;Data received&quot;);<br>    updateUI(data);<br>  });<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Loading spinner timeout&quot;);<br>}, 0);</pre><h3>What happens?</h3><ol><li>fetch starts (handled by browser Web APIs)</li><li>Main thread continues</li><li>API resolves → .then() goes to <strong>microtask queue</strong></li><li>Call stack becomes empty</li><li><strong>Microtasks run first</strong></li></ol><ul><li>UI updates immediately</li></ul><ol><li>Only then:</li></ol><ul><li>setTimeout callback runs</li></ul><h3>Result:</h3><ul><li>UI updates <strong>before</strong> timeout logic</li><li>App feels responsive</li><li>User sees data ASAP</li></ul><p>This is <strong>by design</strong>.</p><h3>Common Confusions &amp; Mistakes</h3><h3>❌ “setTimeout 0 runs immediately”</h3><p>Nope.</p><pre>setTimeout(fn, 0);</pre><p>Means:<br><em>“Run after </em><strong><em>current stack + all microtasks</em></strong><em> finish.”</em></p><h3>❌ “Promises are async like setTimeout”</h3><p>They’re both async <strong>but not equal</strong>.</p><p>FeaturePriorityPromise.then🔥 High (Microtask)setTimeout🐢 Lower (Macrotask)</p><h3>❌ Infinite Microtask Loop</h3><p>This is dangerous:</p><pre>function loop() {<br>  Promise.resolve().then(loop);<br>}<br>loop();</pre><p>This <strong>blocks rendering</strong>, freezes the UI, and starves macrotasks.</p><p>Why?</p><ul><li>Microtasks never finish</li><li>Event loop never reaches macrotasks</li><li>Browser never paints</li></ul><h3>Why Frontend Developers Should Care</h3><p>Understanding this changes how you:</p><h3>✅ Optimize Performance</h3><ul><li>Schedule heavy work in macrotasks</li><li>Use microtasks for critical updates</li></ul><h3>✅ Prevent UI Freezes</h3><ul><li>Avoid recursive promise chains</li><li>Yield control back to the browser</li></ul><h3>✅ Debug Async Bugs</h3><ul><li>Race conditions</li><li>Unexpected execution order</li><li>UI updates happening “too late” or “too early”</li></ul><h3>✅ Write Better React / Vue / Angular Code</h3><p>Frameworks rely heavily on:</p><ul><li>Promises</li><li>Microtask batching</li><li>Controlled rendering cycles</li></ul><p>If you don’t understand the scheduler, frameworks feel like magic.</p><h3>Mental Model to Remember</h3><p><strong><em>Call stack finishes → Microtasks drain → One macrotask → Repeat</em></strong></p><p>Or even simpler:<br><strong><em>Promises cut the line. Timers wait their turn.</em></strong></p><h3>Final Thoughts</h3><p>JavaScript isn’t slow.<br> It’s <strong>precise</strong>.</p><p>Once you understand <strong>microtasks vs macrotasks</strong>, async behavior stops feeling random — and starts feeling <strong>predictable</strong>.</p><p>This is the difference between:</p><ul><li>Writing code that <em>works</em></li><li>Writing code that <em>scales, performs, and feels smooth</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66a9303018d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>