<?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 yshn4v on Medium]]></title>
        <description><![CDATA[Stories by yshn4v on Medium]]></description>
        <link>https://medium.com/@vyshnavpcnaravoor?source=rss-3d151edb9c4c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*1hajy52EUqo0xoCp</url>
            <title>Stories by yshn4v on Medium</title>
            <link>https://medium.com/@vyshnavpcnaravoor?source=rss-3d151edb9c4c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 11:11:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vyshnavpcnaravoor/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[SQL Categories Explained: What They Are and How SQL Queries Actually Work]]></title>
            <link>https://medium.com/@vyshnavpcnaravoor/sql-categories-explained-what-they-are-and-how-sql-queries-actually-work-817d3c8d4b67?source=rss-3d151edb9c4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/817d3c8d4b67</guid>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql-injection]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[yshn4v]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 06:14:56 GMT</pubDate>
            <atom:updated>2026-08-17T06:14:56.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HBo_EUyVqxdMyiWS-D4ENg.png" /></figure><p>When learning SQL, one of the first confusing things is seeing terms like <strong>DDL, DML, DQL, DCL, and TCL</strong>.</p><p>You may know how to write a SELECT query, but then questions start appearing:</p><ul><li>What category does SELECT belong to?</li><li>Is CREATE TABLE the same type of SQL?</li><li>What happens first when a query runs?</li><li>Does SQL execute from top to bottom?</li><li>If SELECT runs first, where does the data come from?</li><li>What exactly happens between writing a query and getting a result?</li></ul><p>Let’s break SQL down from the basics and then understand the <strong>actual execution order</strong>.</p><h3>What is SQL?</h3><p><strong>SQL (Structured Query Language)</strong> is a language used to communicate with relational databases.</p><p>For example, imagine a users table:</p><pre>users<br>--------------------------------<br>id | name    | email<br>--------------------------------<br>1  | Rahul   | rahul@gmail.com<br>2  | Anu     | anu@gmail.com<br>3  | Vishnu  | vishnu@gmail.com</pre><p>We can ask the database:</p><pre>SELECT name<br>FROM users;</pre><p>The database processes the SQL statement and returns:</p><pre>Rahul<br>Anu<br>Vishnu</pre><p>SQL isn’t only about retrieving data, though.</p><p>We also use SQL to:</p><ul><li>Create databases and tables</li><li>Insert data</li><li>Update data</li><li>Delete data</li><li>Control permissions</li><li>Manage transactions</li></ul><p>That’s why SQL commands are divided into different categories.</p><h3>The Main SQL Categories</h3><p>SQL is commonly divided into five major categories:</p><p>CategoryFull FormMain PurposeDDLData Definition LanguageDefine database structureDMLData Manipulation LanguageModify dataDQLData Query LanguageRetrieve dataDCLData Control LanguageControl permissionsTCLTransaction Control LanguageManage transactions</p><p>Let’s understand each one.</p><h3>1. DDL — Data Definition Language</h3><p>DDL is used to define or change the <strong>structure of the database</strong>.</p><p>Think of it as building the structure in which your data will live.</p><p>Common DDL commands include:</p><pre>CREATE<br>ALTER<br>DROP<br>TRUNCATE</pre><h3>CREATE</h3><p>Create a table:</p><pre>CREATE TABLE users (<br>    id INT,<br>    name VARCHAR(100),<br>    email VARCHAR(255)<br>);</pre><p>This doesn’t insert a user.</p><p>It creates the <strong>structure</strong> of the users table.</p><h3>ALTER</h3><p>Change an existing table.</p><pre>ALTER TABLE users<br>ADD age INT;</pre><p>Now the table has an additional age column.</p><h3>DROP</h3><p>Remove a database object.</p><pre>DROP TABLE users;</pre><p>The table itself is removed.</p><h3>TRUNCATE</h3><p>Remove all rows from a table while keeping the table structure.</p><pre>TRUNCATE TABLE users;</pre><p>After this:</p><pre>Table exists<br>Columns exist<br>Rows = 0</pre><p>So DDL is primarily concerned with <strong>database structure</strong>.</p><h3>2. DML — Data Manipulation Language</h3><p>DML is used to manipulate the <strong>actual data inside tables</strong>.</p><p>Common commands include:</p><pre>INSERT<br>UPDATE<br>DELETE</pre><h3>INSERT</h3><p>Add data:</p><pre>INSERT INTO users (id, name, email)<br>VALUES (1, &#39;Rahul&#39;, &#39;rahul@gmail.com&#39;);</pre><p>Now a row exists inside the table.</p><h3>UPDATE</h3><p>Modify existing data:</p><pre>UPDATE users<br>SET name = &#39;Rahul Kumar&#39;<br>WHERE id = 1;</pre><h3>DELETE</h3><p>Remove rows:</p><pre>DELETE FROM users<br>WHERE id = 1;</pre><p>Notice the difference:</p><pre>DDL → changes structure<br>DML → changes data</pre><p>For example:</p><pre>ALTER TABLE users ADD age INT;</pre><p>changes the structure.</p><p>While:</p><pre>UPDATE users SET age = 25;</pre><p>changes the data.</p><h3>3. DQL — Data Query Language</h3><p>DQL is used to <strong>retrieve data</strong> from the database.</p><p>The main command is:</p><pre>SELECT</pre><p>For example:</p><pre>SELECT *<br>FROM users;</pre><p>Or:</p><pre>SELECT name, email<br>FROM users;</pre><p>You can also filter:</p><pre>SELECT name<br>FROM users<br>WHERE age &gt; 18;</pre><p>This is where SQL becomes interesting.</p><p>When we write:</p><pre>SELECT name<br>FROM users<br>WHERE age &gt; 18;</pre><p>it looks like SQL should execute from top to bottom.</p><p>But that’s <strong>not how SQL logically processes the query</strong>.</p><p>We’ll come back to this shortly.</p><h3>4. DCL — Data Control Language</h3><p>DCL deals with <strong>permissions and access control</strong>.</p><p>The common commands are:</p><pre>GRANT<br>REVOKE</pre><p>For example:</p><pre>GRANT SELECT ON users TO analyst;</pre><p>This gives the analyst user permission to read the users table.</p><p>And:</p><pre>REVOKE SELECT ON users FROM analyst;</pre><p>removes that permission.</p><p>So:</p><pre>DCL → Who is allowed to do what?</pre><h3>5. TCL — Transaction Control Language</h3><p>TCL is used to manage <strong>transactions</strong>.</p><p>Common commands include:</p><pre>COMMIT<br>ROLLBACK<br>SAVEPOINT</pre><p>Suppose we transfer ₹1,000 from Account A to Account B.</p><p>We might have:</p><pre>UPDATE accounts<br>SET balance = balance - 1000<br>WHERE id = 1;</pre><pre>UPDATE accounts<br>SET balance = balance + 1000<br>WHERE id = 2;</pre><p>Both operations should succeed together.</p><p>If something goes wrong after the first operation, we don’t want money to disappear.</p><p>That’s where transactions help.</p><pre>BEGIN;</pre><pre>UPDATE accounts<br>SET balance = balance - 1000<br>WHERE id = 1;</pre><pre>UPDATE accounts<br>SET balance = balance + 1000<br>WHERE id = 2;</pre><pre>COMMIT;</pre><p>If something fails:</p><pre>ROLLBACK;</pre><p>The transaction can be undone.</p><h3>Putting Everything Together</h3><p>A simple way to remember the categories:</p><pre>SQL<br>                 |<br>     +-----------+-----------+<br>     |           |           |<br>    DDL         DML         DQL<br> Structure      Data        Query<br>     |           |           |<br> CREATE        INSERT      SELECT<br> ALTER         UPDATE<br> DROP          DELETE<br> TRUNCATE</pre><pre>          +-----------+<br>          |           |<br>         DCL         TCL<br>      Permissions  Transactions<br>          |           |<br>       GRANT       COMMIT<br>       REVOKE      ROLLBACK<br>                   SAVEPOINT</pre><h3>But How Does a SELECT Query Actually Work?</h3><p>Now let’s look at the most important part.</p><p>Consider this query:</p><pre>SELECT<br>    name,<br>    COUNT(*) AS orders<br>FROM users<br>JOIN orders<br>    ON users.id = orders.user_id<br>WHERE users.age &gt;= 18<br>GROUP BY users.id, users.name<br>HAVING COUNT(*) &gt; 5<br>ORDER BY orders DESC<br>LIMIT 10;</pre><p>If you read it normally, you see:</p><pre>SELECT<br>FROM<br>JOIN<br>WHERE<br>GROUP BY<br>HAVING<br>ORDER BY<br>LIMIT</pre><p>But SQL doesn’t logically process it in this order.</p><p>The <strong>logical processing order</strong> is roughly:</p><pre>1. FROM<br>2. JOIN / ON<br>3. WHERE<br>4. GROUP BY<br>5. HAVING<br>6. SELECT<br>7. DISTINCT<br>8. ORDER BY<br>9. LIMIT / OFFSET</pre><p>This is extremely important when learning SQL.</p><h3>Step 1 — FROM</h3><p>SQL first determines where the data is coming from.</p><pre>FROM users</pre><p>The database starts with the users table.</p><p>You can think of it as:</p><pre>Database<br>   ↓<br>users table<br>   ↓<br>rows</pre><p>This answers your earlier question:</p><blockquote><em>“If SELECT runs first, where does the data come from?”</em></blockquote><p><strong>SELECT doesn’t logically run first.</strong></p><p>The database first determines the source of the data.</p><h3>Step 2 — JOIN</h3><p>If your query contains a join:</p><pre>JOIN orders<br>ON users.id = orders.user_id</pre><p>the database combines matching rows from the two tables.</p><p>Conceptually:</p><pre>users                  orders</pre><pre>id | name              id | user_id<br>---+------             ---+--------<br>1  | Rahul             10 | 1<br>2  | Anu               11 | 1<br>3  | Arun              12 | 3</pre><pre>             JOIN<br>              ↓</pre><pre>Rahul → order 10<br>Rahul → order 11<br>Arun  → order 12</pre><p>The ON condition determines which rows match.</p><h3>Step 3 — WHERE</h3><p>Next, filtering happens.</p><pre>WHERE users.age &gt;= 18</pre><p>Rows that don’t satisfy the condition are removed from the logical result.</p><p>For example:</p><pre>Before WHERE:</pre><pre>Rahul  25<br>Anu    17<br>Arun   30</pre><pre>After WHERE:</pre><pre>Rahul  25<br>Arun   30</pre><p>This is why you generally cannot use an aggregate result directly in WHERE.</p><p>For example, this is invalid:</p><pre>WHERE COUNT(*) &gt; 5</pre><p>Why?</p><p>Because WHERE happens <strong>before grouping and aggregation</strong>.</p><p>That’s where HAVING comes in.</p><h3>Step 4 — GROUP BY</h3><p>Now SQL groups the remaining rows.</p><pre>GROUP BY users.id, users.name</pre><p>For example:</p><pre>Rahul<br> ├── order 10<br> ├── order 11<br> ├── order 15<br> ├── order 18<br> └── order 20</pre><pre>Arun<br> ├── order 12<br> └── order 13</pre><p>Now the database can calculate:</p><pre>COUNT(*)</pre><p>for each group.</p><p>Result:</p><pre>Rahul → 5<br>Arun  → 2</pre><h3>Step 5 — HAVING</h3><p>Now we can filter groups.</p><pre>HAVING COUNT(*) &gt; 5</pre><p>This is different from WHERE.</p><h3>WHERE</h3><p>Filters individual rows <strong>before grouping</strong>.</p><h3>HAVING</h3><p>Filters groups <strong>after grouping</strong>.</p><p>Think:</p><pre>WHERE  → rows<br>HAVING → groups</pre><h3>Step 6 — SELECT</h3><p>Only now do we logically perform the SELECT projection.</p><pre>SELECT<br>    name,<br>    COUNT(*) AS orders</pre><p>The database chooses which columns/expressions should appear in the final result.</p><p>For example:</p><pre>name   | orders<br>-------+-------<br>Rahul  | 8<br>Anu    | 7</pre><p>This explains something that initially feels strange.</p><p>You write:</p><pre>SELECT ...<br>FROM ...<br>WHERE ...</pre><p>but logically:</p><pre>FROM → WHERE → SELECT</pre><h3>Step 7 — DISTINCT</h3><p>If you use:</p><pre>SELECT DISTINCT name</pre><p>duplicate results are removed.</p><p>For example:</p><pre>Rahul<br>Rahul<br>Anu<br>Rahul<br>Anu</pre><p>becomes:</p><pre>Rahul<br>Anu</pre><h3>Step 8 — ORDER BY</h3><p>Now the result can be sorted.</p><pre>ORDER BY orders DESC</pre><p>For example:</p><pre>Rahul → 15<br>Anu   → 10<br>Arun  → 5</pre><p>becomes:</p><pre>Rahul → 15<br>Anu   → 10<br>Arun  → 5</pre><p>with the highest values first.</p><h3>Step 9 — LIMIT</h3><p>Finally:</p><pre>LIMIT 10</pre><p>keeps only the required number of rows.</p><p>If there are 1,000 results:</p><pre>1,000 rows<br>     ↓<br>ORDER BY<br>     ↓<br>LIMIT 10<br>     ↓<br>10 rows</pre><h3>Logical Order vs Physical Execution</h3><p>There is one more important distinction.</p><p>When we say:</p><pre>FROM<br>WHERE<br>GROUP BY<br>SELECT<br>ORDER BY<br>LIMIT</pre><p>we are talking about <strong>logical query processing order</strong>.</p><p>The database doesn’t necessarily execute the query physically in exactly this sequence.</p><p>A database such as PostgreSQL has a <strong>query planner and optimizer</strong>.</p><p>For example:</p><pre>SELECT name<br>FROM users<br>WHERE age &gt; 18;</pre><p>The database may create an execution plan that uses an index on age.</p><p>Instead of scanning every row:</p><pre>1,000,000 rows<br>      ↓<br>scan everything<br>      ↓<br>filter age &gt; 18</pre><p>it may use:</p><pre>Index on age<br>      ↓<br>find age &gt; 18<br>      ↓<br>fetch matching rows</pre><p>This can be much faster.</p><p>So remember:</p><blockquote><strong><em>Logical order tells us how SQL semantics work. The query planner decides an efficient physical execution strategy.</em></strong></blockquote><h3>Why Can’t I Use a SELECT Alias in WHERE?</h3><p>Consider:</p><pre>SELECT<br>    salary * 12 AS annual_salary<br>FROM employees<br>WHERE annual_salary &gt; 1000000;</pre><p>This generally doesn’t work in PostgreSQL.</p><p>Why?</p><p>Because logically:</p><pre>WHERE<br> ↓<br>SELECT</pre><p>The alias annual_salary is created during the SELECT stage.</p><p>At the time WHERE is evaluated, that alias doesn&#39;t exist yet.</p><p>But ORDER BY can generally use it:</p><pre>SELECT<br>    salary * 12 AS annual_salary<br>FROM employees<br>ORDER BY annual_salary DESC;</pre><p>Because ORDER BY happens later in the logical processing order.</p><h3>A Simple Mental Model</h3><p>Whenever you see a SQL query, think about it like this:</p><pre>Where does the data come from?<br>          ↓<br>       FROM<br>          ↓<br>Are tables being combined?<br>          ↓<br>       JOIN<br>          ↓<br>Which rows do I want?<br>          ↓<br>       WHERE<br>          ↓<br>Do I need groups?<br>          ↓<br>     GROUP BY<br>          ↓<br>Which groups do I want?<br>          ↓<br>      HAVING<br>          ↓<br>What should I return?<br>          ↓<br>       SELECT<br>          ↓<br>Should duplicates be removed?<br>          ↓<br>      DISTINCT<br>          ↓<br>How should it be sorted?<br>          ↓<br>      ORDER BY<br>          ↓<br>How many should I return?<br>          ↓<br>       LIMIT</pre><p>This mental model makes complex SQL much easier to understand.</p><h3>One Important Correction: SQL Isn’t Just “SELECT”</h3><p>A common beginner mistake is thinking SQL means:</p><pre>SQL = SELECT</pre><p>Actually:</p><pre>SQL<br>├── DDL → Define structure<br>├── DML → Manipulate data<br>├── DQL → Query data<br>├── DCL → Control permissions<br>└── TCL → Control transactions</pre><p>And SELECT itself has a logical processing pipeline.</p><pre>SELECT query<br>    ↓<br>FROM<br>    ↓<br>JOIN<br>    ↓<br>WHERE<br>    ↓<br>GROUP BY<br>    ↓<br>HAVING<br>    ↓<br>SELECT<br>    ↓<br>DISTINCT<br>    ↓<br>ORDER BY<br>    ↓<br>LIMIT</pre><h3>Final Takeaway</h3><p>If you’re learning SQL for backend development, don’t just memorize query syntax.</p><p>Understand <strong>what each category is responsible for</strong> and <strong>how a query is logically processed</strong>.</p><p>The easiest way to remember it is:</p><blockquote><strong><em>DDL builds the structure.</em></strong><em><br></em><strong><em>DML changes the data.</em></strong><em><br></em><strong><em>DQL reads the data.</em></strong><em><br></em><strong><em>DCL controls access.</em></strong><em><br></em><strong><em>TCL controls transactions.</em></strong></blockquote><p>And for a SELECT query:</p><blockquote><strong><em>FROM → JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT</em></strong></blockquote><p>Once this becomes intuitive, things like JOIN, GROUP BY, HAVING, aggregate functions, aliases, and complex queries become much easier to reason about.</p><p>SQL starts looking less like a collection of commands and more like a <strong>data-processing pipeline</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=817d3c8d4b67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Node.js Event Loop — How JavaScript Handles Async Code Without Blocking]]></title>
            <link>https://medium.com/@vyshnavpcnaravoor/the-node-js-event-loop-how-javascript-handles-async-code-without-blocking-533fe3fc4048?source=rss-3d151edb9c4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/533fe3fc4048</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-call-stack]]></category>
            <category><![CDATA[event-loop]]></category>
            <dc:creator><![CDATA[yshn4v]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 09:38:40 GMT</pubDate>
            <atom:updated>2026-08-15T09:38:40.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUS6EtJv8KoXH3xdvQLYQw.png" /></figure><p>If you’ve worked with Node.js, you’ve probably heard this sentence:</p><blockquote><strong><em>“Node.js is single-threaded and uses an event loop.”</em></strong></blockquote><p>But what does that actually mean?</p><p>If Node.js has a single JavaScript thread, how can it handle thousands of HTTP requests, database queries, file operations, timers, and network calls at the same time?</p><p>The answer is the <strong>Event Loop</strong>.</p><p>Understanding the event loop is one of the most important concepts for anyone working with Node.js, because it explains:</p><ul><li>Why Node.js is good at I/O-heavy applications</li><li>Why asynchronous operations don’t block your application</li><li>What setTimeout() actually does</li><li>Why Promise.then() runs before setTimeout()</li><li>What process.nextTick() does</li><li>How Node.js handles thousands of connections with relatively few threads</li><li>Why CPU-heavy JavaScript can still kill your application’s performance</li></ul><p>Let’s break it down from the ground up.</p><h3>1. First: Is Node.js Really Single-Threaded?</h3><p>Yes — but this statement is often misunderstood.</p><p>When we say Node.js is single-threaded, we’re mainly talking about the <strong>JavaScript execution thread</strong>.</p><p>Imagine this:</p><pre>                          Node.js Application<br>                                  |<br>                                  v  <br>                          JavaScript Thread<br>                                  |<br>                           +------+------+<br>                           |             |<br>                        Execute       Execute<br>                        JS code       callbacks</pre><p>There is essentially one main thread executing your JavaScript code.</p><p>It can execute only one piece of JavaScript at a time.</p><p>For example:</p><pre>console.log(&quot;A&quot;);<br>console.log(&quot;B&quot;);<br>console.log(&quot;C&quot;);</pre><p>The execution is:</p><pre>A<br>B<br>C</pre><p>JavaScript doesn’t suddenly execute B and C simultaneously on the same thread.</p><p>So the obvious question is:</p><p><strong>If JavaScript can execute only one thing at a time, how does Node.js handle asynchronous operations?</strong></p><p>That’s where the Event Loop and the underlying Node.js runtime come in.</p><h3>2. The Node.js Runtime Is More Than JavaScript</h3><p>When we write:</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;Hello&quot;);<br>}, 1000);</pre><p>the JavaScript engine itself isn’t sitting there for one second doing nothing.</p><p>Node.js uses underlying runtime components to handle asynchronous work.</p><p>A simplified architecture looks like this:</p><pre>                 Node.js<br>                    |<br>        +-----------+-----------+<br>        |                       |<br>        v                       v<br>   JavaScript Engine        Node.js APIs<br>      (V8)                    |<br>                              |<br>                       +------+------+<br>                       |             |<br>                    libuv        OS / Kernel<br>                       |<br>                Thread Pool / I/O</pre><p>The important component here is <strong>libuv</strong>.</p><p>libuv provides Node.js with mechanisms for:</p><ul><li>Event loops</li><li>Asynchronous I/O</li><li>Timers</li><li>Networking</li><li>File system operations</li><li>Thread pool management</li></ul><p>So when we say “Node.js handles asynchronous operations”, it’s not because the JavaScript thread magically performs multiple tasks simultaneously.</p><p>Instead, Node.js delegates certain operations to the underlying runtime and continues executing JavaScript.</p><h3>3. The Simplest Example</h3><p>Consider:</p><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Timer finished&quot;);<br>}, 2000);<br><br>console.log(&quot;End&quot;);</pre><p>What do you think the output is?</p><p>Many beginners expect:</p><pre>Start<br>Timer finished<br>End</pre><p>But that’s not what happens.</p><p>The actual output is:</p><pre>Start<br>End<br>Timer finished</pre><p>Why?</p><p>Let’s walk through it.</p><h3>4. What Happens Step by Step?</h3><h3>Step 1 — Execute console.log</h3><pre>console.log(&quot;Start&quot;);</pre><p>The JavaScript thread executes it.</p><pre>Start</pre><h3>Step 2 — Encounter setTimeout</h3><pre>setTimeout(() =&gt; {<br>  console.log(&quot;Timer finished&quot;);<br>}, 2000);</pre><p>Node.js registers the timer.</p><p>The JavaScript thread <strong>doesn’t wait for two seconds</strong>.</p><p>Instead, the timer is managed by the runtime.</p><p>Conceptually:</p><pre>JavaScript Thread<br>       |<br>       | setTimeout()<br>       v<br>   Timer system<br>       |<br>       | wait 2 seconds<br>       v<br>  Callback ready</pre><p>The JavaScript thread is now free to continue.</p><h3>Step 3 — Execute the next statement</h3><pre>console.log(&quot;End&quot;);</pre><p>So we get:</p><pre>Start<br>End</pre><h3>Step 4 — Timer expires</h3><p>After approximately two seconds, the timer becomes eligible to execute.</p><p>Its callback:</p><pre>() =&gt; {<br>  console.log(&quot;Timer finished&quot;);<br>}</pre><p>is eventually picked up by the event loop.</p><p>Then:</p><pre>Timer finished</pre><p>appears.</p><p>Final result:</p><pre>Start<br>End<br>Timer finished</pre><h3>5. The Event Loop</h3><p>Now we reach the most important part.</p><p>The <strong>event loop continuously checks whether there is work that needs to be executed by the JavaScript thread.</strong></p><p>A simplified mental model:</p><pre>        JavaScript Call Stack<br>                  |<br>                  v<br>          +---------------+<br>          |  Event Loop   |<br>          +---------------+<br>             ^         |<br>             |         v<br>       Async Work    Callback<br>             |<br>       +-----+------+<br>       |            |<br>    Timers        I/O<br>       |            |<br>       +-----+------+<br>             |<br>             v<br>       Callback Queue</pre><p>The event loop keeps the application moving between synchronous JavaScript execution and callbacks that have become ready.</p><h3>6. The Call Stack</h3><p>Before understanding the event loop deeply, you need to understand the <strong>Call Stack</strong>.</p><p>Consider:</p><pre>function one() {<br>  two();<br>}<br>function two() {<br>  console.log(&quot;Hello&quot;);<br>}<br>one();</pre><p>The JavaScript engine uses a stack to track function execution.</p><p>Initially:</p><pre>Call Stack<br>-----------<br>one()</pre><p>Then one() calls two():</p><pre>Call Stack<br>-----------<br>two()<br>one()</pre><p>Then two() executes:</p><pre>Hello</pre><p>After two() finishes:</p><pre>Call Stack<br>-----------<br>one()</pre><p>Finally:</p><pre>Call Stack<br>-----------<br>empty</pre><p>The stack follows <strong>LIFO</strong>:</p><blockquote><em>Last In, First Out.</em></blockquote><h3>7. Where Does the Event Loop Come In?</h3><p>Now consider:</p><pre>console.log(&quot;A&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;B&quot;);<br>}, 0);<br><br>console.log(&quot;C&quot;);</pre><p>Even though the timer says:</p><pre>0</pre><p>the output is:</p><pre>A<br>C<br>B</pre><p>Why?</p><p>Because setTimeout(..., 0) does <strong>not</strong> mean:</p><blockquote><em>Execute this callback immediately.</em></blockquote><p>It means roughly:</p><blockquote><em>Make this callback eligible after the timer threshold has passed, then execute it when the event loop gets to it.</em></blockquote><p>The callback still needs the JavaScript call stack to be empty before it can execute.</p><h3>8. A Better Mental Model</h3><p>Think of Node.js like a restaurant.</p><p>The JavaScript thread is the <strong>chef</strong>.</p><p>The chef can cook only one dish at a time.</p><p>But the restaurant has other workers and systems handling things like:</p><ul><li>Taking orders</li><li>Waiting for ingredients</li><li>Washing dishes</li><li>Receiving deliveries</li></ul><p>The chef doesn’t stand there doing nothing while waiting for an ingredient.</p><p>Instead:</p><pre>Chef<br> |<br> | Start dish<br> v<br>Delegate waiting work<br> |<br> v<br>Cook another dish<br> |<br> v<br>Cook another dish<br> |<br> v<br>Ingredient arrives<br> |<br> v<br>Finish original dish</pre><p>That’s roughly what asynchronous programming allows Node.js to do.</p><h3>9. Synchronous vs Asynchronous Code</h3><p>Consider this:</p><pre>const data = fs.readFileSync(&quot;large-file.txt&quot;);<br><br>console.log(data);<br><br>console.log(&quot;Done&quot;);</pre><p>readFileSync() blocks the JavaScript thread.</p><p>While the file is being read, the thread can’t execute other JavaScript.</p><p>Now compare:</p><pre>fs.readFile(&quot;large-file.txt&quot;, (err, data) =&gt; {<br>  console.log(data);<br>});<br>console.log(&quot;Done&quot;);</pre><p>The asynchronous version allows Node.js to continue executing:</p><pre>Start reading file<br>        |<br>        |----&gt; File system<br>        |<br>        v<br>console.log(&quot;Done&quot;)<br>        |<br>        v<br>File finishes<br>        |<br>        v<br>Callback executes</pre><p>So:</p><pre>Done<br>[file contents]</pre><p>may be printed.</p><h3>10. Why This Makes Node.js Good for APIs</h3><p>Imagine your Node.js API receives 1,000 requests.</p><p>Each request needs to query PostgreSQL.</p><p>The application doesn’t need to keep the JavaScript thread blocked while waiting for the database response.</p><p>Conceptually:</p><pre>Request 1 ---&gt; Database<br>Request 2 ---&gt; Database<br>Request 3 ---&gt; Database<br>Request 4 ---&gt; Database<br>Request 5 ---&gt; Database<br>      ...<br>Request 1000 -&gt; Database</pre><p>While those I/O operations are waiting, Node.js can continue processing other work.</p><p>When responses become available, their callbacks/promises can continue executing on the JavaScript thread.</p><p>That’s why Node.js is particularly effective for <strong>I/O-heavy workloads</strong> such as:</p><ul><li>REST APIs</li><li>GraphQL APIs</li><li>WebSockets</li><li>Microservices</li><li>Real-time applications</li><li>Database-heavy services</li><li>Proxy/API gateway applications</li></ul><h3>11. But Node.js Isn’t “Doing Everything in One Thread”</h3><p>This is an important distinction.</p><p>People often say:</p><blockquote><em>“Node.js is single-threaded.”</em></blockquote><p>A better explanation is:</p><blockquote><strong><em>JavaScript execution in Node.js primarily happens on a single thread, while Node.js uses the operating system and libuv to handle asynchronous I/O and a worker pool for certain operations.</em></strong></blockquote><p>For example, some file-system operations and other tasks can use the libuv thread pool.</p><p>Conceptually:</p><pre>                Node.js<br>                    |<br>             JavaScript Thread<br>                    |<br>          +---------+---------+<br>          |                   |<br>       Event Loop           libuv<br>                              |<br>                    +---------+---------+<br>                    |         |         |<br>                 Worker    Worker    Worker<br>                 Thread    Thread    Thread</pre><p>This distinction becomes very important when discussing Node.js performance.</p><h3>12. What Exactly Is the Event Loop Doing?</h3><p>A simplified version is:</p><pre>1. Execute synchronous JavaScript<br>2. Check for ready asynchronous callbacks<br>3. Execute callbacks<br>4. Continue processing<br>5. Repeat</pre><p>But the real Node.js event loop has multiple <strong>phases</strong>.</p><p>A simplified representation is:</p><pre>             ┌───────────────┐<br>             │    Timers     │<br>             └───────┬───────┘<br>                     ↓<br>             ┌───────────────┐<br>             │ Pending I/O   │<br>             └───────┬───────┘<br>                     ↓<br>             ┌───────────────┐<br>             │     Poll      │<br>             └───────┬───────┘<br>                     ↓<br>             ┌───────────────┐<br>             │    Check      │<br>             └───────┬───────┘<br>                     ↓<br>             ┌───────────────┐<br>             │ Close Callbacks│<br>             └───────┬───────┘<br>                     │<br>                     └──────────&gt; Repeat</pre><p>The actual behavior is more nuanced, but this model is useful for understanding the concept.</p><h3>13. The Important Event Loop Phases</h3><h3>Timers</h3><p>This phase handles callbacks associated with:</p><pre>setTimeout()<br>setInterval()</pre><p>Example:</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;Timer&quot;);<br>}, 1000);</pre><p>The timer doesn’t guarantee execution exactly at 1 second.</p><p>It means the callback becomes eligible after the specified delay.</p><h3>Pending Callbacks</h3><p>This phase handles certain callbacks from previous I/O operations that have been deferred.</p><p>You don’t usually interact with this phase directly in application code.</p><h3>Poll</h3><p>The poll phase is responsible for handling many types of I/O-related work.</p><p>For example:</p><pre>Network response<br>File system result<br>Socket activity</pre><p>When I/O becomes available, its callback can be processed.</p><h3>Check</h3><p>This phase is where:</p><pre>setImmediate()</pre><p>callbacks are executed.</p><p>Example:</p><pre>setImmediate(() =&gt; {<br>  console.log(&quot;Immediate&quot;);<br>});</pre><h3>Close Callbacks</h3><p>This phase handles certain close-related callbacks.</p><p>For example:</p><pre>socket.on(&quot;close&quot;, () =&gt; {<br>  console.log(&quot;Socket closed&quot;);<br>});</pre><h3>14. What About Promises?</h3><p>This is where the event loop becomes really interesting.</p><p>Consider:</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>console.log(&quot;D&quot;);</pre><p>Output:</p><pre>A<br>D<br>C<br>B</pre><p>Why?</p><p>Because Promise callbacks are handled through the <strong>microtask queue</strong>.</p><p>Conceptually:</p><pre>Synchronous Code<br>       |<br>       v<br>Call Stack<br>       |<br>       v<br>Microtasks<br>       |<br>       v<br>Event Loop / Tasks</pre><p>After the current synchronous JavaScript finishes, pending microtasks are processed before moving on to timer callbacks.</p><h3>15. Microtasks vs Macrotasks</h3><p>A useful simplified model is:</p><h3>Microtasks</h3><p>Examples:</p><pre>Promise.then()<br>Promise.catch()<br>Promise.finally()<br>queueMicrotask()</pre><p>Node.js also has the special:</p><pre>process.nextTick()</pre><p>queue, which has even higher priority than the regular microtask queue in Node.js.</p><h3>Tasks / Event Loop Callbacks</h3><p>Examples include callbacks associated with:</p><pre>setTimeout()<br>setInterval()<br>setImmediate()<br>I/O</pre><p>So when you see:</p><pre>Promise.resolve().then(...)</pre><p>and:</p><pre>setTimeout(..., 0)</pre><p>the Promise callback normally gets an opportunity to run first after the current synchronous execution completes.</p><h3>16. process.nextTick() Is Special</h3><p>Node.js has:</p><pre>process.nextTick(() =&gt; {<br>  console.log(&quot;nextTick&quot;);<br>});</pre><p>It doesn’t behave exactly like a normal timer or event-loop phase.</p><p>Node processes the nextTick queue before continuing with the event loop.</p><p>For example:</p><pre>console.log(&quot;A&quot;);<br><br>process.nextTick(() =&gt; {<br>  console.log(&quot;B&quot;);<br>});<br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;C&quot;);<br>});<br>console.log(&quot;D&quot;);</pre><p>Typically:</p><pre>A<br>D<br>B<br>C</pre><p>The important takeaway is:</p><pre>Synchronous code<br>       ↓<br>process.nextTick()<br>       ↓<br>Promise microtasks<br>       ↓<br>Event loop callbacks</pre><p>This is a simplified mental model, but it is extremely useful for interviews.</p><h3>17. A Practical Example</h3><p>Consider:</p><pre>console.log(&quot;Start&quot;);<br>setTimeout(() =&gt; {<br>  console.log(&quot;Timeout&quot;);<br>}, 0);<br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;Promise&quot;);<br>});<br>process.nextTick(() =&gt; {<br>  console.log(&quot;Next Tick&quot;);<br>});<br>console.log(&quot;End&quot;);</pre><p>Let’s walk through it.</p><h3>First: synchronous code</h3><pre>Start<br>End</pre><p>Then Node processes the higher-priority nextTick queue:</p><pre>Next Tick</pre><p>Then Promise microtasks:</p><pre>Promise</pre><p>Then the timer callback becomes eligible:</p><pre>Timeout</pre><p>So the result is:</p><pre>Start<br>End<br>Next Tick<br>Promise<br>Timeout</pre><p>This kind of question is extremely common in Node.js interviews.</p><h3>18. setTimeout(0) Does Not Mean &quot;Immediately&quot;</h3><p>This is one of the biggest misconceptions about JavaScript.</p><p>Consider:</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;Hello&quot;);<br>}, 0);</pre><p>It does <strong>not</strong> mean:</p><pre>Execute immediately</pre><p>It means approximately:</p><pre>Wait until the timer threshold has passed<br>+<br>wait until the event loop can execute the callback</pre><p>For example:</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;Timer&quot;);<br>}, 0);<br>for (let i = 0; i &lt; 1_000_000_000; i++) {<br>  // CPU-heavy work<br>}</pre><p>The timer cannot interrupt the running JavaScript.</p><p>The callback must wait until the current JavaScript execution finishes.</p><h3>19. This Leads to One of the Biggest Node.js Problems</h3><p>Node.js is excellent at asynchronous I/O.</p><p>But what happens if you do this?</p><pre>app.get(&quot;/heavy&quot;, (req, res) =&gt; {<br>  for (let i = 0; i &lt; 10_000_000_000; i++) {<br>    // Heavy CPU work<br>  }<br>  res.send(&quot;Done&quot;);<br>});</pre><p>That loop executes on the JavaScript thread.</p><p>While it’s running:</p><pre>JavaScript Thread<br>       |<br>       v<br> CPU-heavy loop<br>       |<br>       |<br>       |<br>       v<br>    FINISH<br>       |<br>       v<br>  Next request</pre><p>Other requests may have to wait.</p><p>So although Node.js is asynchronous, <strong>your JavaScript code itself can still block the event loop</strong>.</p><h3>20. Why CPU-Heavy Work Is Dangerous</h3><p>Imagine:</p><pre>Request A<br>Request B<br>Request C<br>Request D<br>Request E</pre><p>The event loop processes JavaScript work.</p><p>If Request A performs a huge CPU calculation:</p><pre>Request A<br>   |<br>   v<br>CPU-heavy operation<br>   |<br>   |<br>   |<br>   v<br>Finished<br>   |<br>   v<br>Request B</pre><p>Requests B–E have to wait.</p><p>This can cause:</p><ul><li>High latency</li><li>Slow API responses</li><li>Request timeouts</li><li>Poor throughput</li><li>Event loop lag</li></ul><p>This is why CPU-intensive work may need to be moved to:</p><ul><li>Worker Threads</li><li>Separate processes</li><li>Background workers</li><li>Job queues</li><li>Dedicated services</li></ul><h3>21. Real-World Backend Example</h3><p>Imagine an insurance application.</p><p>A request comes in:</p><pre>POST /policy/decision</pre><p>The backend might need to:</p><ol><li>Validate the request</li><li>Read customer information</li><li>Query PostgreSQL</li><li>Call a decision engine</li><li>Store the decision</li><li>Return the response</li></ol><p>Database and network operations are largely I/O-bound.</p><p>A simplified flow could be:</p><pre>HTTP Request<br>     |<br>     v<br>Node.js<br>     |<br>     +----&gt; PostgreSQL<br>     |<br>     +----&gt; Decision Engine<br>     |<br>     +----&gt; External API<br>     |<br>     v<br>Continue handling other requests</pre><p>When those operations complete, Node.js processes their results.</p><p>This is one of the reasons asynchronous Node.js backends can handle many concurrent I/O operations efficiently.</p><h3>22. What the Event Loop Does NOT Do</h3><p>The event loop does <strong>not</strong>:</p><ul><li>Execute JavaScript simultaneously</li><li>Make CPU-heavy JavaScript asynchronous</li><li>Create a new thread for every request</li><li>Make every operation non-blocking automatically</li><li>Guarantee exact timer execution times</li></ul><p>This distinction is extremely important.</p><p>For example:</p><pre>const result = expensiveCalculation();</pre><p>If expensiveCalculation() is synchronous CPU work, the event loop can&#39;t magically make it asynchronous.</p><h3>23. The Most Important Mental Model</h3><p>If you remember only one diagram from this article, remember this:</p><pre>                    Node.js<br>                       |<br>                       v<br>              ┌────────────────┐<br>              │ JavaScript     │<br>              │ Call Stack     │<br>              └───────┬────────┘<br>                      |<br>                      v<br>                  Event Loop<br>                      |<br>        ┌─────────────┼─────────────┐<br>        |             |             |<br>      Timers          I/O        setImmediate<br>        |             |             |<br>        +-------------+-------------+<br>                      |<br>                      v<br>                 Microtasks<br>                /          \<br>        nextTick          Promises</pre><p>The JavaScript thread executes one piece of JavaScript at a time.</p><p>Asynchronous operations can be handled by the underlying runtime.</p><p>When their callbacks become ready, the event loop coordinates when they get a chance to execute.</p><h3>24. The Interview Explanation</h3><p>If an interviewer asks:</p><p><strong>“Explain the Node.js Event Loop.”</strong></p><p>You don’t need to dump every internal detail.</p><p>A strong answer would be:</p><blockquote><em>Node.js executes JavaScript primarily on a single thread and uses an event-driven architecture to handle asynchronous operations. When an operation such as network or file I/O is initiated, Node.js can delegate the work to the underlying runtime instead of blocking the JavaScript thread. Once the operation completes, its callback becomes eligible to run, and the event loop coordinates when that callback is executed on the JavaScript thread. The event loop processes different phases such as timers, I/O-related callbacks, poll, check, and close callbacks. Promise callbacks are handled as microtasks, while </em><em>process.nextTick() has even higher priority in Node.js. This model allows Node.js to efficiently handle many concurrent I/O operations, but CPU-heavy synchronous JavaScript can still block the event loop and delay other requests.&quot;</em></blockquote><p>That’s the level of explanation I’d aim for in a backend interview.</p><h3>25. The Biggest Misconception</h3><p>A common statement is:</p><blockquote><em>“Node.js is single-threaded, therefore Node.js can handle only one request at a time.”</em></blockquote><p>That’s wrong.</p><p>A better way to think about it is:</p><pre>One JavaScript execution thread<br>+<br>Asynchronous I/O<br>+<br>Event loop<br>+<br>Underlying OS/libuv mechanisms<br>+<br>Optional worker threads/processes<br>=<br>High concurrency for I/O-heavy workloads</pre><p>Node.js isn’t fast because one thread magically performs thousands of operations simultaneously.</p><p>It’s effective because the JavaScript thread <strong>doesn’t need to sit idle waiting for I/O</strong>.</p><h3>26. Final Mental Model</h3><p>When writing Node.js code, ask yourself:</p><h3>Is this synchronous JavaScript?</h3><p>If yes:</p><pre>JavaScript thread executes it</pre><p>It can block other JavaScript.</p><h3>Is this asynchronous I/O?</h3><p>For example:</p><pre>await database.query(...)</pre><p>or:</p><pre>await fetch(...)</pre><p>The underlying operation can proceed asynchronously while the JavaScript thread is free to do other work.</p><h3>Has the operation completed?</h3><p>Then its continuation/callback becomes eligible to execute.</p><h3>Is there a long CPU-heavy JavaScript operation?</h3><p>Be careful.</p><p>That can block the event loop.</p><h3>Conclusion</h3><p>The Node.js Event Loop is not simply a queue that “runs callbacks.”</p><p>It’s the mechanism around which Node.js’s event-driven execution model is organized.</p><p>The most important idea is:</p><blockquote><strong><em>Node.js doesn’t avoid concurrency by creating a thread for every request. Instead, it efficiently coordinates asynchronous work so the JavaScript thread can keep processing useful work while I/O operations are waiting.</em></strong></blockquote><p>Once you understand that, concepts like:</p><ul><li>Promises</li><li>async/await</li><li>setTimeout</li><li>setImmediate</li><li>process.nextTick()</li><li>Worker Threads</li><li>Event Loop lag</li><li>Non-blocking I/O</li><li>Node.js scalability</li></ul><p>all start to make much more sense.</p><p>And that’s why understanding the Event Loop isn’t just an interview requirement.</p><p><strong>It’s fundamental to understanding how a Node.js backend actually works.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=533fe3fc4048" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Reaching for WebSockets: When Server-Sent Events Are All You Need]]></title>
            <link>https://medium.com/@vyshnavpcnaravoor/stop-reaching-for-websockets-when-server-sent-events-are-all-you-need-b2f58d10d7c1?source=rss-3d151edb9c4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2f58d10d7c1</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[sse]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[yshn4v]]></dc:creator>
            <pubDate>Thu, 06 Aug 2026 09:17:38 GMT</pubDate>
            <atom:updated>2026-08-06T09:17:38.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IxNjk4-y5OUATMNFbkjzVA.png" /></figure><p>Every time a “real-time” feature comes up in a sprint planning meeting, someone says “WebSockets” before anyone’s even asked what the feature actually needs. Live notifications, a progress bar, streaming AI responses, a stock ticker — WebSockets gets nominated for all of it.</p><p>Half the time, that’s overkill. If your data only needs to flow one way — server to client — there’s a simpler, older, and honestly underrated tool sitting right there in the browser: <strong>Server-Sent Events (SSE)</strong>.</p><h3>What SSE Actually Is</h3><p>SSE is a standard that lets a server push updates to a client over a single, long-lived HTTP connection. No handshake protocol upgrade, no separate library, no extra port. It’s just HTTP, held open, streaming plain text in a specific format.</p><p>The browser gives you a built-in client for it: EventSource. No socket.io, no ws library on the frontend. You open a connection, and the server keeps sending you data whenever it has something new.</p><p>javascript</p><pre>const events = new EventSource(&#39;/api/events&#39;);<br>events.onmessage = (event) =&gt; {<br>  console.log(&#39;New event:&#39;, event.data);<br>};</pre><p>That’s the entire client-side setup for a live feed. No dependencies.</p><h3>SSE vs WebSockets vs Polling</h3><p>PollingSSEWebSocketsDirectionClient asks, server answersServer → Client onlyBidirectionalProtocolPlain HTTP requestsPlain HTTP, kept openIts own protocol (ws/wss)ReconnectionYou build itBuilt into the browserYou build itBrowser APIfetch/XHREventSourceWebSocketProxy/firewall friendlyYesYesSometimes notBest forLow-frequency checksLive feeds, notifications, streaming textChat, games, collaborative editing</p><p>The key question to ask before picking either of the last two: <strong>does the client ever need to send data back over the same connection?</strong> If the answer is no — you’re just pushing updates outward — SSE gets you there with a fraction of the moving parts.</p><h3>How the Protocol Actually Works</h3><p>An SSE response is just an HTTP response with a specific content type, kept open indefinitely:</p><pre>Content-Type: text/event-stream<br>Cache-Control: no-cache<br>Connection: keep-alive</pre><p>The body is a stream of plain-text events, each separated by a blank line:</p><pre>data: {&quot;status&quot;: &quot;processing&quot;}<br>data: {&quot;status&quot;: &quot;complete&quot;, &quot;result&quot;: 42}<br>id: 101<br>event: notification<br>data: {&quot;message&quot;: &quot;New order received&quot;}</pre><p>A few fields worth knowing:</p><ul><li>data — the payload (can be JSON, plain text, whatever)</li><li>event — a named event type, so the client can listen for specific kinds of updates</li><li>id — lets the browser track the last event it saw, for reconnection</li><li>retry — tells the browser how long to wait before reconnecting if the connection drops</li></ul><p>That’s the whole spec, more or less. No binary framing, no ping/pong keepalive protocol to implement yourself.</p><h3>Building an SSE Endpoint in Express</h3><p>Here’s a minimal but production-shaped example:</p><p>javascript</p><pre>app.get(&#39;/api/events&#39;, (req, res) =&gt; {<br>  res.writeHead(200, {<br>    &#39;Content-Type&#39;: &#39;text/event-stream&#39;,<br>    &#39;Cache-Control&#39;: &#39;no-cache&#39;,<br>    &#39;Connection&#39;: &#39;keep-alive&#39;,<br>  });<br><br>  //Send an initial event so the client knows it&#39;s connected<br>  res.write(`event: connected\ndata: ${JSON.stringify({ ok: true})}\n\n`);<br><br>  const sendUpdate = (payload) =&gt; {<br>    res.write(`data: ${JSON.stringify(payload)}\n\n`);<br>  };<br><br>  //Example: push a heartbeat every 15s to keep proxies from timing out<br>  const heartbeat = setInterval(() =&gt; {<br>    res.write(&#39;: heartbeat\n\n&#39;); // a comment line - ignored by the client, keeps the connection alive<br>  }, 15000);<br><br>  //Hook into whatever your real event source is (a queue, an emitter, DB change stream)<br>  const listener = (data) =&gt; sendUpdate(data);<br>  eventBus.on(&#39;order:update&#39;, listener);<br>  req.on(&#39;close&#39;, () =&gt; {<br>    clearInterval(heartbeat);<br>    eventBus.off(&#39;order:update&#39;, listener);<br>    res.end();<br>  });<br><br>});</pre><p>The important bit most people miss: <strong>you must handle </strong><strong>req.on(&#39;close&#39;)</strong>. If you don&#39;t clean up your listeners and intervals when the client disconnects, you&#39;ll leak memory and event listeners on every reconnect.</p><h3>Consuming It in React</h3><p>jsx</p><pre>function useSSE(url) {<br>  const [data, setData] = useState(null);<br>  useEffect(() =&gt; {<br>    const source = new EventSource(url);<br>    source.onmessage = (event) =&gt; {<br>      setData(JSON.parse(event.data));<br>    };<br>    source.addEventListener(&#39;notification&#39;, (event) =&gt; {<br>      const payload = JSON.parse(event.data);<br>      // handle a named event type separately from default messages<br>    });<br>    source.onerror = () =&gt; {<br>      // EventSource auto-reconnects by default - usually nothing to do here<br>      console.warn(&#39;SSE connection lost, browser will retry&#39;);<br>    };<br>    return () =&gt; source.close();<br>  }, [url]);<br>  return data;<br>}</pre><p>That auto-reconnect behavior is the part I actually like most about SSE. WebSockets give you nothing for free here — you write your own reconnect-with-backoff logic. EventSource reconnects automatically, and if the server sent an id field, it resumes from there using a Last-Event-ID header on the retry request. You get resumable streams without writing any of that yourself.</p><h3>The Use Case Where SSE Shines: Streaming Responses</h3><p>If you’ve used ChatGPT, Claude, or any LLM product where the response types itself out token by token — that’s almost always SSE under the hood, not WebSockets. The server generates tokens as they come off the model and streams each one down as an event the moment it’s ready.</p><p>javascript</p><pre>app.post(&#39;/api/generate&#39;, async (req, res) =&gt; {<br>  res.writeHead(200, {<br>    &#39;Content-Type&#39;: &#39;text/event-stream&#39;,<br>    &#39;Cache-Control&#39;: &#39;no-cache&#39;,<br>  });<br>  const stream = await llmClient.generateStream(req.body.prompt);<br>  for await (const token of stream) {<br>    res.write(`data: ${JSON.stringify({ token })}\n\n`);<br>  }<br>  res.write(&#39;event: done\ndata: {}\n\n&#39;);<br>  res.end();<br>});</pre><p>This pattern generalizes well beyond LLMs — long-running jobs, file processing progress, report generation. Anywhere you’d otherwise make the user stare at a spinner, SSE lets you show incremental progress with almost no extra infrastructure.</p><h3>Where SSE Falls Short</h3><p>It’s not a free lunch:</p><ul><li><strong>One-directional.</strong> If the client needs to send frequent messages back (chat input, cursor positions in a collaborative doc, game state), you’re back to WebSockets.</li><li><strong>Browser connection limits over HTTP/1.1.</strong> Some browsers cap concurrent connections per domain to 6, and each open EventSource counts as one. This mostly stops being a problem over HTTP/2, which multiplexes connections — worth checking your server/CDN setup.</li><li><strong>Text only.</strong> No binary frames. You can base64-encode binary data if you really need to, but that’s not what it’s built for.</li></ul><h3>The Decision, Simplified</h3><ul><li>Only need to push updates to the client → <strong>SSE</strong></li><li>Need real two-way, low-latency communication → <strong>WebSockets</strong></li><li>Updates are infrequent and staleness is fine → <strong>plain polling, don’t overthink it</strong></li></ul><p>Most “real-time dashboard” and “live notification” tickets fall into the first bucket. Reach for SSE first, and only pull in a WebSocket library when you actually hit a use case that needs the client talking back.</p><p><em>If you’re building this into a Node/Express backend, the whole implementation above is maybe 30 lines of code and zero new dependencies on the frontend. That’s usually a good sign you picked the right tool.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2f58d10d7c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Know Redux Before You Learn Redux Toolkit]]></title>
            <link>https://medium.com/@vyshnavpcnaravoor/know-redux-before-you-learn-redux-toolkit-bcd00698a24a?source=rss-3d151edb9c4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcd00698a24a</guid>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[yshn4v]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 06:47:00 GMT</pubDate>
            <atom:updated>2026-08-02T06:47:00.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*khrp-p6eWmPue0V8Tcaemg.png" /></figure><p>Most Redux tutorials today start with Redux Toolkit — and for new projects, that’s the right call. It’s the officially recommended way to write Redux, and there’s little reason to hand-write boilerplate that RTK generates for you.</p><p>But there’s a downside to starting there: createSlice() and configureStore() are abstractions. They work great until something breaks, or until you land on a codebase written in plain Redux, or until an interviewer asks you what a reducer actually is and &quot;the RTK function&quot; isn&#39;t a real answer. If you don&#39;t know what&#39;s underneath those functions, you&#39;re memorizing an API instead of understanding a system.</p><p>This post walks through Redux’s actual architecture — the part RTK is built on top of — so that when you do reach for RTK, you know exactly what it’s doing for you instead of just trusting that it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6fKElCqnhRfJPK9LDU46Vw.png" /><figcaption>Redux architecture diagram</figcaption></figure><h3>Why the Fundamentals Come First</h3><p>A few concrete reasons this matters, beyond principle:</p><ul><li><strong>Debugging.</strong> When state updates unexpectedly or a component doesn’t re-render, the fix usually requires understanding dispatch, reducers, and subscriptions — not RTK syntax.</li><li><strong>Legacy code.</strong> Plenty of production codebases still run plain Redux, especially in larger, older companies. If you only know RTK, you can’t read or contribute to them.</li><li><strong>RTK Query and thunks aren’t magic.</strong> They’re formalized versions of patterns you’d otherwise hand-write. Knowing the manual version means you know exactly what’s happening when the automated version misbehaves.</li><li><strong>Interviews.</strong> “Explain how Redux works” is a common interview question, and “I use createSlice&quot; doesn&#39;t answer it.</li></ul><p>With that motivation out of the way, here’s the actual architecture.</p><h3>The Three Principles of Redux</h3><p>Everything in Redux is really just an implementation of three rules.</p><p><strong>1. Single source of truth.</strong> The entire state of your application lives in one store. This makes it possible to inspect, log, or persist the whole app’s state at any point in time.</p><p><strong>2. State is read-only.</strong> The only way to change state is to dispatch an action describing what happened. Components never mutate state directly.</p><p><strong>3. Changes are made with pure functions.</strong> Reducers describe how state transforms in response to an action, and must be pure — no side effects, no randomness, no mutating their inputs. Same state and action in, same new state out, every time.</p><p>Once these three rules click, the rest of Redux’s structure just falls out of them.</p><h3>The Core Building Blocks</h3><p><strong>Store</strong> — a single object holding your app’s entire state tree. One store per app.</p><p><strong>State</strong> — the actual data, e.g. { user: {...}, cart: [...], theme: &#39;dark&#39; }.</p><p><strong>Actions</strong> — plain objects describing what happened, with a type and usually a payload:</p><pre>{ type: &#39;cart/addItem&#39;, payload: { id: 1, name: &#39;Shoes&#39; } }</pre><p><strong>Action creators</strong> — functions that build action objects for you:</p><pre>const addItem = (item) =&gt; ({ type: &#39;cart/addItem&#39;, payload: item })</pre><p><strong>Reducers</strong> — pure functions computing new state from old state + an action</p><pre>function cartReducer(state = [], action) {<br>  switch (action.type) {<br>    case &#39;cart/addItem&#39;:<br>      return [...state, action.payload]<br>    default:<br>      return state<br>  }<br>}</pre><p><strong>Dispatch</strong> — the only way to trigger a state change: store.dispatch(addItem(item)).</p><p>This is the part createSlice() generates for you later. Worth writing by hand at least once so you know what&#39;s being generated.</p><h3>The Low-Level Store API</h3><p>A raw Redux store is created with a small API:</p><pre>import { createStore } from &#39;redux&#39;</pre><pre>const store = createStore(cartReducer)</pre><pre>store.getState()          // read current state<br>store.dispatch(action)    // trigger a state change<br>store.subscribe(listener) // run a function on every state change</pre><p>subscribe() matters even though you&#39;ll rarely call it yourself — it&#39;s how React-Redux knows when to re-render a component. Every dispatched action that produces new state fires every subscribed listener.</p><p>configureStore() in RTK replaces createStore(), but the contract — getState, dispatch, subscribe — doesn&#39;t change underneath it.</p><h3>Scaling State with combineReducers</h3><p>One reducer function works for a toy app. Real apps have independent slices of state — cart, user, theme — and cramming all of it into one reducer doesn’t scale.</p><pre>import { combineReducers } from &#39;redux&#39;</pre><pre>const rootReducer = combineReducers({<br>  cart: cartReducer,<br>  user: userReducer,<br>  theme: themeReducer<br>})</pre><p>Each reducer only ever sees and returns its own slice. cartReducer has no idea user or theme exist. This is the manual version of what happens automatically when you register multiple slices with configureStore().</p><h3>Middleware: Extending Dispatch</h3><p>Middleware sits between dispatch and the reducer, intercepting every action before it arrives. Its shape:</p><pre>const logger = store =&gt; next =&gt; action =&gt; {<br>  console.log(&#39;dispatching&#39;, action)<br>  const result = next(action)<br>  console.log(&#39;next state&#39;, store.getState())<br>  return result<br>}</pre><p>Middleware can inspect, delay, cancel, or react to actions, then pass them along with next(action). Reducers have to stay pure, so anything impure — logging, async calls, side effects — happens here instead.</p><p>configureStore() sets up a sensible middleware stack (including thunk support) by default. Knowing this is what&#39;s happening explains why async logic works &quot;out of the box&quot; in RTK without you wiring anything up.</p><h3>Handling Async Logic</h3><p>Reducers can’t make API calls directly — they have to stay pure. Thunk middleware is what allows async logic to exist inside the Redux flow at all.</p><p>A thunk is an action creator that returns a function instead of a plain object:</p><pre>const fetchCart = () =&gt; async (dispatch, getState) =&gt; {<br>  dispatch({ type: &#39;cart/loading&#39; })<br>  try {<br>    const response = await fetch(&#39;/api/cart&#39;)<br>    const data = await response.json()<br>    dispatch({ type: &#39;cart/loaded&#39;, payload: data })<br>  } catch (error) {<br>    dispatch({ type: &#39;cart/error&#39;, payload: error.message })<br>  }<br>}</pre><p>The component just calls dispatch(fetchCart()). The reducer only ever sees plain, synchronous actions — cart/loading, cart/loaded, cart/error — so purity is preserved.</p><p>This pending/fulfilled/rejected pattern is exactly what createAsyncThunk() generates for you automatically. If you&#39;ve written it by hand once, createAsyncThunk() stops looking like magic and starts looking like a shortcut for code you already understand.</p><h3>Connecting Redux to React</h3><p>Redux has no built-in knowledge of React. <strong>React-Redux</strong> is the bridge.</p><p><strong>Provider</strong> makes the store available to the component tree:</p><pre>&lt;Provider store={store}&gt;<br>  &lt;App /&gt;<br>&lt;/Provider&gt;</pre><p><strong>useSelector</strong> reads state and re-renders the component when it changes:</p><pre>const cartItems = useSelector(state =&gt; state.cart)</pre><p><strong>useDispatch</strong> gives you dispatch to trigger actions:</p><pre>const dispatch = useDispatch()<br>dispatch(addItem({ id: 1, name: &#39;Shoes&#39; }))</pre><p>This layer stays the same whether the store underneath is plain Redux or RTK — it’s worth knowing it’s a separate library from Redux itself.</p><h3>Selectors and Derived State</h3><p>A selector extracts or computes a value from state:</p><pre>const selectCartTotal = state =&gt;<br>  state.cart.reduce((sum, item) =&gt; sum + item.price, 0)</pre><p>The principle: store minimal raw state, derive everything else. If you store both cart and cartTotal separately, they can drift out of sync. If cartTotal is always derived from cart, that&#39;s structurally impossible.</p><p>For expensive derived values, <strong>Reselect</strong> (createSelector) memoizes selectors so they only recompute when their inputs change.</p><h3>Debugging with Redux DevTools</h3><p>Because every state change flows through dispatched actions and pure reducers, the entire history can be recorded and replayed:</p><ul><li>A full log of every action dispatched, in order</li><li>The state snapshot after each action</li><li><strong>Time-travel debugging</strong> — scrub backward and forward through state history and watch the UI update to match</li></ul><p>This only works because reducers are pure and nothing mutates state outside the dispatch flow. It’s a direct payoff of following the three principles.</p><h3>Now Redux Toolkit Makes Sense</h3><p>With all of the above in place, RTK stops looking like a separate framework and starts looking like exactly what it is: the same architecture, with the repetitive parts automated.</p><p>What you’d hand-writeWhat RTK gives youcreateStore + manual middleware + DevTools wiringconfigureStore()Action types + action creators + reducer, kept in sync manuallycreateSlice()Manual immutable updates with spread operatorsImmer, built into createSlice()Hand-written pending/fulfilled/rejected thunk logiccreateAsyncThunk()Manually built data-fetching, caching, and loading statesRTK Query</p><p>None of the underlying flow changes — dispatch still goes through middleware to a reducer, state is still read-only, reducers are still pure. RTK just removes the ceremony around expressing that flow.</p><h3>Final Thoughts</h3><p>It’s tempting to skip straight to Redux Toolkit — and for shipping features quickly, that’s a reasonable choice. But spending a few hours writing a raw reducer, a manual thunk, and a hand-wired store first means every RTK function you use afterward has a concrete mental model behind it, instead of being a black box you’re trusting to work. Learn Redux. Then let Redux Toolkit save you the typing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcd00698a24a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Treat Your Coding Agent Like a Junior Developer, Not a Magic Code Generator]]></title>
            <link>https://medium.com/@vyshnavpcnaravoor/treat-your-coding-agent-like-a-junior-developer-not-a-magic-code-generator-84eb068d65b1?source=rss-3d151edb9c4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/84eb068d65b1</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ai-coding]]></category>
            <dc:creator><![CDATA[yshn4v]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 07:09:08 GMT</pubDate>
            <atom:updated>2026-07-30T07:09:08.615Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DShI4PfkG5a4Df9xjv8vtg.png" /></figure><p>Last week I was building Google OAuth into one of my apps. I asked the agent to generate the callback logic, and it handed me something that looked fine on the surface — until I noticed it was <strong>upserting user data on every single callback hit</strong>. Every login. Every token refresh. Every time. Straight to the database.</p><p>My first reaction was to blame the agent. My second, more honest reaction was to ask myself what I actually told it to do.</p><p>That’s when it clicked: <strong>this wasn’t an agent problem. It was a clarity problem.</strong></p><h3>Agents don’t know what’s in your head</h3><p>An agent is a tool. It doesn’t know your product, your scale, your database load, or what “done” looks like in your mind. It only knows what you put in the prompt.</p><p>If you ask it to “integrate OAuth into the app,” it will do exactly that — in whatever way it decides is reasonable. It doesn’t matter how it gets there, because you never told it how you wanted it to get there.</p><p>That upserting-on-every-callback bug wasn’t the agent misunderstanding OAuth. It was the agent doing exactly what an under-specified prompt allowed it to do.</p><h3>What actually fixed it: a real architecture plan</h3><p>Instead of throwing prompts at the problem, I started writing a proper architecture plan first — treating it almost like a skill document the agent could follow.</p><p>That plan included:</p><ul><li><strong>What I’m building</strong>, in plain terms</li><li><strong>How much scale I’m expecting</strong> — this app isn’t handling millions of logins, so don’t engineer it like it is</li><li><strong>The order of implementation</strong>: Login → Home Page → Profile</li></ul><p>That third point mattered more than I expected. Giving the agent a clear order gave it a sense of priority. It stopped guessing what was urgent and started building in the sequence I actually needed, instead of jumping around or over-engineering the first thing it touched.</p><h3>TDD helped — but not the way I expected</h3><p>On top of the architecture plan, I started asking for confirmation at every step, following a test-driven approach. Write the test, confirm expected behavior, then build. This kept the app behaving the way I expected, step by step.</p><p>But here’s the catch: <strong>TDD doesn’t automatically mean good code.</strong></p><p>The agent would pass the tests — sure — but it would get there in whatever way was fastest for it, not in whatever way was cleanest or most efficient. Tests confirm behavior, not quality. That’s on me to check, not on the agent to know.</p><p>That’s the real lesson: <strong>without optimization as an explicit step, a working feature isn’t the same as a good one.</strong> It passes, but it doesn’t hold up.</p><h3>Getting specific about the database</h3><p>Once I understood that, I went back to the OAuth issue and got specific about what I actually wanted:</p><ul><li>I don’t want a database sync on every OAuth callback</li><li>A profile doesn’t need to re-sync with OAuth data every single time</li><li>Once it’s synced, I only need to <strong>cross-check</strong> it afterward, not overwrite it</li></ul><p>That one instruction — spelled out instead of assumed — was the difference between an expensive query running on every request and a lightweight check running only when it actually mattered.</p><h3>Graphify: cutting the noise</h3><p>The other change that made a real difference was adding <strong>Graphify</strong> — a semantic, graph-based code representation tool — into the workflow.</p><p>Instead of the agent scanning my entire codebase every time it needed context, it started reading Graphify’s graph output and going straight to the relevant file. Less scanning, less guessing, fewer tokens burned, faster iterations. The context was already structured for it — it just had to use it.</p><h3>The bottom line</h3><p>No matter how good your architecture plan is, how disciplined your TDD process is, or how efficient your tooling is — <strong>the feature is still owned by the developer.</strong> Cross-checking code quality, verifying optimization, catching what the agent missed — that responsibility doesn’t transfer just because the agent wrote the first draft.</p><p>Treat your coding agent like a junior developer. If you assign a task without proper knowledge transfer, don’t expect it to read your mind. But if you give it the context — the plan, the scale, the priority order, the constraints — it gives you back something you can actually trust.</p><p>The agent isn’t the bug. The missing context is.</p><p><em>If you’re building with coding agents and running into the same “technically working but practically wrong” problem, I’d love to hear how you’re solving it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84eb068d65b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Does Redis Solve Your Database Spike Problem? (No, and Here’s Why)]]></title>
            <link>https://medium.com/@vyshnavpcnaravoor/does-redis-solve-your-database-spike-problem-no-and-heres-why-520efe72c178?source=rss-3d151edb9c4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/520efe72c178</guid>
            <category><![CDATA[replica]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[sharding]]></category>
            <dc:creator><![CDATA[yshn4v]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 10:32:59 GMT</pubDate>
            <atom:updated>2026-07-28T05:47:45.877Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4anLHtgiI5jr9LLpRzu7dQ.png" /></figure><p>If you’ve ever had your database fall over during a traffic spike, there’s a good chance someone on your team said: “let’s just add Redis.”</p><p>It’s not a bad instinct. But it’s an incomplete one.</p><p>Redis is primarily a caching layer. It’s great at storing frequently accessed data in memory so you don’t have to hit your database every single time. But it doesn’t solve the actual structural problem — it just delays it. The moment traffic hits data Redis doesn’t have cached, or writes come in that caching can’t help with, your database is right back to taking the full hit.</p><p>So what actually helps when your DB is getting hammered? Here are three approaches that go deeper than caching — along with the tradeoffs each one brings.</p><h3>1. Sharding</h3><p>Sharding means splitting your data across multiple database instances instead of relying on one big instance to handle everything.</p><p>Instead of every request hitting a single database, requests get distributed across several instances based on some key (user ID, region, tenant, etc). This is horizontal scaling in practice — you’re not making one machine bigger, you’re spreading the load across many.</p><p>The benefit here is straightforward: no single instance has to absorb the entire traffic load. When done right, sharding gives you a much more even distribution of traffic across your database layer, which means spikes get divided rather than concentrated.</p><p><em>Disadvantages:</em> Sharding adds real operational complexity. Cross-shard queries and joins become painful or impossible without extra work. Rebalancing shards as data grows is non-trivial and risky to get wrong. You also need a solid shard key up front — pick a bad one and you end up with “hot shards” that get hammered while others sit idle, which defeats the whole purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYOdlOBa-krV-YyGCxnatQ.png" /></figure><h3>2. Read/Write Replicas</h3><p>Most applications are read-heavy. It’s common to see a read-to-write ratio somewhere like 20000:400 — meaning for every 20,000 times data is read, it’s only written 400 times.</p><p>Given that imbalance, it makes sense to separate read traffic from write traffic entirely. Writes go to a primary database. Reads get routed to one or more replicas.</p><p>This does two things:</p><ul><li>It protects your primary database (the one handling critical writes) from being overwhelmed by read traffic.</li><li>It lets you scale reads independently by adding more replicas as read traffic grows, without touching your write path at all.</li></ul><p><em>Disadvantages:</em> Replication is rarely instant — there’s usually some replication lag, so a read right after a write can return stale data if it hits a replica that hasn’t caught up yet. This can cause subtle bugs (a user submits a form, then reloads and doesn’t see their own change). You also now have more infrastructure to monitor, and the primary is still a single point of failure for all writes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCmznfdnJL5PLZ7dypw4BA.png" /></figure><h3>3. Event-Driven Architecture / Queues</h3><p>The biggest DB spikes usually come from bursts — a flash sale, a viral post, a batch job kicking off, thousands of users hitting “submit” at once. If every one of those actions tries to write to the database immediately and directly, you get a spike that can bring things down.</p><p>Instead, push those actions into a queue. A worker (or set of workers) then processes that queue and writes to the database at a steady, controlled rate.</p><p>You’re not reducing the total number of operations — you’re just spreading them out over time instead of letting them all land on the database in the same second. That’s the difference between a steady stream and a spike.</p><p><em>Disadvantages:</em> Queues introduce latency by design — writes are no longer immediate, so “read your own write” gets harder to guarantee. You’re also adding a new system (the queue itself) that needs to be highly available, monitored, and scaled. And you need to handle failure cases carefully: retries, dead-letter queues, duplicate processing, and ordering guarantees all become things you now own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjhD94mWLkzEAn2VEsFPOw.png" /></figure><h3>Where Redis Actually Fits</h3><p>None of this means Redis isn’t useful. It absolutely is — for reducing repeated reads of the same data, for session storage, for rate limiting, for things that genuinely don’t need to touch the database every time.</p><p>But Redis solves a caching problem. Sharding, replicas, and queues solve a traffic distribution problem. They’re different layers of the same system, and you generally need more than one of them working together to handle real spikes at scale — and each one comes with its own tradeoffs to manage.</p><p>Redis is one tool in the toolbox. It’s just not the whole toolbox.</p><p>I write about backend and system design topics like this on LinkedIn — <a href="https://www.linkedin.com/in/vyshnav-p-c-5567ba242/">follow if you want more</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=520efe72c178" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Disabling React StrictMode — You’re Turning Off a Safety Net]]></title>
            <link>https://medium.com/@vyshnavpcnaravoor/stop-disabling-react-strictmode-youre-turning-off-a-safety-net-8f5f02a4f9c6?source=rss-3d151edb9c4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f5f02a4f9c6</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[yshn4v]]></dc:creator>
            <pubDate>Thu, 23 Jul 2026 09:01:19 GMT</pubDate>
            <atom:updated>2026-07-23T09:01:19.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVv1-Z1yJN1UTssuBbnj3w.png" /></figure><p>If you’ve ever opened your console in development and seen your useEffect fire twice, your component render twice, or your state initializer run twice — you&#39;ve probably had the same reaction most developers have: &quot;This is a bug, let me just remove StrictMode.&quot;</p><p>I used to do exactly this. Almost everyone does, at some point. But StrictMode isn’t broken. It’s doing exactly what it was built to do, and understanding why changed how I write effects.</p><h3>What StrictMode Actually Does</h3><p>React.StrictMode is a development-only tool. It never runs in production, and it doesn&#39;t render any visible UI. What it does is intentionally double-invoke certain parts of your components:</p><ul><li>Component render functions</li><li>State initializer functions (the function form passed to useState)</li><li>Effects — with a full mount → cleanup → mount cycle</li></ul><p>This double-invocation is deliberate. React is checking whether your code is “pure” — meaning it produces the same result and has no unintended side effects when run more than once with the same inputs.</p><h3>Why This Matters: The Socket Example</h3><p>Say you open a WebSocket connection inside useEffect</p><pre>useEffect(() =&gt; {<br>  const socket = new WebSocket(url);<br>  // ...<br>}, [url]);</pre><p>No cleanup function. In a normal single-run environment, this looks fine — it works, the socket connects, everything seems okay.</p><p>But what happens the moment this component unmounts and remounts? Or in StrictMode’s simulated mount → unmount → mount cycle? You now have <strong>two open sockets</strong>, and only one of them is ever referenced by your latest render. The other keeps running, silently, potentially receiving events, holding a connection open, or causing duplicate messages.</p><p>Without StrictMode, this exact bug can sit undetected through your entire development cycle and only show up in production — as a memory leak, a duplicate event handler, or a mysterious “why am I getting this event twice” ticket three weeks later.</p><p>With StrictMode, React deliberately forces that unmount/remount cycle <em>in dev</em>, so the leak shows up immediately: two connections, right there in your network tab, the day you wrote the code.</p><h3>The Fix Isn’t to Remove StrictMode — It’s to Add Cleanup</h3><pre>useEffect(() =&gt; {<br>  const socket = new WebSocket(url);<br>  return () =&gt; {<br>      socket.close();<br>  };<br>}, [url]);</pre><p>Now when StrictMode unmounts and remounts the component, the first socket is properly closed before the second one opens. No leak. The effect is now safe to run multiple times — which is the actual point.</p><h3>Why React Cares About This So Much</h3><p>React’s future direction — concurrent rendering, offscreen components, fast refresh, activity/prerendering — all depend on components being able to mount, unmount, and remount without breaking. If your effects assume they’ll only ever run once, they will break in those environments. StrictMode’s double-invocation in dev is React telling you, early, “this assumption won’t hold.”</p><h3>The Real Cost of Disabling It</h3><p>Turning off StrictMode doesn’t fix anything. It just removes the mechanism that would have shown you the problem <em>before</em> your users found it. The bug isn’t gone — it’s just invisible again, waiting to resurface in production where it’s far more expensive to diagnose.</p><h3>Takeaway</h3><ul><li>StrictMode only runs in development — it has zero effect on production behavior or performance.</li><li>It double-invokes render, state initializers, and effects to catch side effects that aren’t properly cleaned up.</li><li>The fix for “my effect runs twice” is almost always a missing cleanup function, not disabling StrictMode.</li><li>Treat every double-invocation warning as a free bug report from React, not an annoyance.</li></ul><p>Next time you see StrictMode “misbehaving,” don’t turn it off. Ask what it just caught.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f5f02a4f9c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>