<?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 Saad Amir on Medium]]></title>
        <description><![CDATA[Stories by Saad Amir on Medium]]></description>
        <link>https://medium.com/@saadamir1?source=rss-12acbde2152d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NJMYIAPTP3FGlbBt3PPZow.jpeg</url>
            <title>Stories by Saad Amir on Medium</title>
            <link>https://medium.com/@saadamir1?source=rss-12acbde2152d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 21:55:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saadamir1/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[I Spent Weeks Trying to Beat XGBoost With a Neural Network. It Won Anyway.]]></title>
            <link>https://medium.com/@saadamir1/i-spent-weeks-trying-to-beat-xgboost-with-a-neural-network-it-won-anyway-752b724bbe18?source=rss-12acbde2152d------2</link>
            <guid isPermaLink="false">https://medium.com/p/752b724bbe18</guid>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Saad Amir]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 20:58:40 GMT</pubDate>
            <atom:updated>2026-07-07T20:58:40.443Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJwzOvvsFyIput45rbNCTw.png" /></figure><p><em>A junior data scientist’s honest account of testing GRU against XGBoost for B2B reorder prediction — and what the data actually said.</em></p><p>Six weeks into my first data science role, I was convinced I needed a smarter model.</p><p>I was a Junior Data Scientist at Innovo Technologies, building an ML reorder prediction system for a Saudi B2B last-mile water delivery client — 400,000+ customers, 6 million orders, 80+ drivers across KSA. The goal: predict which customers are about to reorder, and when.</p><p>XGBoost was already working. AUC 0.92, recall 93%. But my CEO called it “too static.” So I spent weeks building a GRU sequence model to replace it.</p><p>The GRU lost. Here’s why that was the right outcome.</p><h3>The Setup</h3><p>Our Intelligent Visit module shows dispatchers a queue of overdue B2B customers to call. The ML model answers one question:</p><blockquote><em>“This customer hasn’t ordered in a while. Will they reorder soon — and when?”</em></blockquote><p>Real production data: 6 million orders, 415,000 customers, 2.2 million delivery records. After filtering for customers with enough order history, we built 72,000 labeled training episodes — moments in history where a customer went overdue, and we knew whether they came back.</p><p>XGBoost on tabular features (order frequency, gap trends, quantity changes, inactive streak, preseller visits) hit <strong>AUC 0.92, recall 93%</strong>. Solid. But then came the push.</p><h3>“Isn’t This Just Static Rules?”</h3><p>CEO’s feedback after demo. Fair question.</p><p>XGBoost runs on 33 features <em>we manually calculated</em> — recent_frequency_vs_lifetime, inactive_streak, gap_trend. The model learned which combinations mattered, but we decided what to feed it. New customer behavior we hadn&#39;t thought to engineer? Model misses it.</p><p>GRU reads raw order timelines directly. Feed it the actual sequence — gaps, quantities, values — and it discovers patterns on its own. No manual definitions. No static rules.</p><p>That pitch is compelling. So we built it.</p><h3>The GRU Journey</h3><p>Architecture:</p><ul><li><strong>Input:</strong> last 64 orders per customer as a sequence (gap, qty, value, zone, delivery outcome)</li><li><strong>Model:</strong> 2-layer GRU, hidden size 128, attention pooling</li><li><strong>Label:</strong> same 72,000 overdue episodes as XGBoost</li></ul><p><strong>First results: GRU AUC 0.67. XGBoost: 0.92.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D26qs5-H_eT6J803QuSYHw.png" /></figure><p>We assumed data size. 18,600 customers — maybe GRU needed more. Then real production data arrived. 415,000 customers. Retrained.</p><p><strong>GRU: AUC 0.68.</strong></p><p>Barely moved. We added delivery outcomes. Preseller visit flags. Extended sequences to 128 orders. Tried 180-day history windows. Ran a rigorous “fair retest” — v9 — with everything fixed properly, same holdout, same threshold, 5-seed stability check.</p><p><strong>GRU v9: AUC 0.66. MAE 7.79 days.</strong></p><p>Not improving. Something was structurally wrong.</p><h3>The Actual Problem: CV 2.7</h3><p>A DB audit revealed what we’d missed.</p><p>Label customers had <strong>median 62 orders each</strong> — GRU had plenty of sequence to read. That wasn’t the issue.</p><p>The <strong>coefficient of variation on inter-order gaps was 2.7</strong>.</p><p>CV measures how unpredictable gaps are relative to their average. CV of 1.0 means moderate variation. CV of 2.7 means genuinely chaotic — a customer might order every 3 days for two months, go quiet for 6 weeks, then order 4 times in one week. No consistent rhythm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1Besc-JyCktpNdVmncwPw.png" /></figure><p>GRU is built to find learnable patterns in sequences. When the sequence is genuinely chaotic, there’s nothing to find. The model kept producing similar scores for all customers because it couldn’t differentiate signal from noise.</p><p>XGBoost, meanwhile, was doing what it does best: learning which snapshot features correlated with reordering across 72,000 historical episodes. It doesn’t model the sequence. It asks: “Given these numbers right now, what usually happens?”</p><p>For irregular, unpredictable customer gaps — that’s the right question.</p><h3>What Research Says (That I Should Have Read First)</h3><p>After closing the GRU track, I found the papers that validated everything:</p><p><strong>“Tree-based models remain state-of-the-art on medium-sized data (~10K samples). Deep learning models struggle to learn irregular functions, which are prevalent in tabular data.”</strong> — <em>Why do tree-based models still outperform deep learning on tabular data? (NeurIPS 2022)</em></p><p><strong>“XGBoost outperforms deep models across datasets, including the datasets used in the papers that proposed those deep models.”</strong> — <em>Tabular Data: Deep Learning is Not All You Need (arXiv 2021)</em></p><p>The core issue: GRU has an inductive bias — it assumes sequences contain learnable temporal patterns. When gaps have CV 2.7, that assumption breaks. “How irregular are this customer’s gaps” is itself a feature (gap_std_days) that XGBoost uses directly. GRU tried to learn it from noise. XGBoost was handed it explicitly.</p><h3>The Decision</h3><p>We closed the GRU reorder track for this dataset.</p><p>GRU code stays — it may prove useful later for churn prediction or customer behavior clustering where sequence understanding matters more. But for reorder prediction on this data, the answer was clear.</p><p>XGBoost v7 became our production model with one key upgrade: replacing the fixed 7-day label window with <strong>segment-based dynamic horizons</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXovGQmi_JG1d40d23LNsA.png" /></figure><p>We also added a <strong>days-to-reorder regression output</strong> — model now predicts both a probability <em>and</em> an expected reorder date. No arbitrary “7 days” anymore.</p><p>Final production metrics: <strong>AUC 0.865</strong>, <strong>recall 90%</strong>. Lower AUC than v6 — but it’s solving a harder problem (exact days, not binary classification). That’s expected and fine.</p><h3>What I’d Tell Myself at the Start</h3><p><strong>Don’t chase architecture. Chase the data.</strong></p><p>Before building a sequence model, ask one question: does the data actually have consistent temporal patterns? Calculate CV on your inter-event gaps. If it’s above 1.5, your sequence model is going to struggle.</p><p>GRU was architecturally smarter. But smart architecture on data that doesn’t support it loses to a simple model on well-understood data — every time.</p><p>XGBoost + RFM-style segmentation is the actual industry standard for B2B repurchase prediction. Not because engineers are lazy. Because for irregular tabular data, it works.</p><p>The research was right. The data was right. I just needed six weeks of building the alternative to believe it.</p><h3>Quick Stack Reference</h3><p>Component Detail Platform Innovo Last Mile — NestJS, React, PostgreSQL, Python FastAPI Training data 6M orders, 415K customers, KSA B2B delivery Production model XGBoost v7, scikit-learn, joblib GRU experiment PyTorch, 2-layer GRU, attention pooling Evaluation Customer-level holdout, 5-seed stability, leakage audit</p><p><em>Next up: why intermittent demand forecasting broke our SKU model across 6 versions — and what finally helped.</em></p><p><em>Working on similar problems — B2B reorder prediction, last-mile delivery ML, or the GRU-vs-XGBoost question on your own data? Drop a comment.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=752b724bbe18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Node.js Server Doesn’t Block (Despite Running on One Thread)]]></title>
            <link>https://medium.com/@saadamir1/why-your-node-js-server-doesnt-block-despite-running-on-one-thread-55dae6262ef9?source=rss-12acbde2152d------2</link>
            <guid isPermaLink="false">https://medium.com/p/55dae6262ef9</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Saad Amir]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 21:17:22 GMT</pubDate>
            <atom:updated>2026-02-06T21:34:17.361Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yW3a1ZnemVBc3Wt9kHxlrQ.png" /></figure><p>You write fs.readFile() to load a 500MB log file. Your server keeps handling other requests while the file loads. Wait - JavaScript runs on one thread with one <strong>Call Stack</strong>. It should freeze completely while reading that file, right?</p><p>Here’s what actually happens: Node.js cheats. Well, not really — it delegates. You’ll learn exactly how Node handles async operations without multiple JavaScript threads, why blocking code kills performance, and the one mental model that makes this all click. This is Part 1 of my Event Loop series — concepts that tripped me up during interview prep and come up constantly in technical interviews.</p><h3>JavaScript is Single-Threaded. Node.js is Not.</h3><p>Let’s clear up the confusion: the JavaScript engine (V8) runs on a single thread with one <strong>Call Stack</strong>. It can execute exactly one piece of code at a time. But Node.js — the runtime environment — is not single-threaded. It’s V8 plus <strong>libuv</strong>, a C library with its own thread pool.</p><p>When your JavaScript code hits an async operation like reading a file or querying a database, the Call Stack doesn’t sit there waiting. It hands off that work to libuv’s thread pool (for file I/O, DNS, crypto) or to the operating system (for network I/O, timers). Then it immediately continues to the next line of your code.</p><pre>console.log(&#39;Start&#39;);<br><br>// This blocks - runs on main thread<br>let sum = 0;<br>for (let i = 0; i &lt; 1000000000; i++) {<br>  sum += i;<br>}<br>console.log(&#39;Sync done&#39;);<br><br>// This doesn&#39;t block - delegated to libuv<br>fs.readFile(&#39;huge.txt&#39;, (err, data) =&gt; {<br>  console.log(&#39;File read done&#39;);<br>});<br>console.log(&#39;End&#39;);<br><br>// Output:<br>// Start<br>// Sync done (after ~2 second freeze)<br>// End<br>// File read done (later, whenever file finishes)</pre><p>The synchronous loop blocks everything — no other code can run while it’s calculating. The file read doesn’t block because it gets delegated immediately. This is why async code exists in the first place.</p><h3>How Node Delegates Without Waiting</h3><p>Think of Node’s architecture like a restaurant. The chef (Call Stack) takes orders and cooks quick items immediately. When someone orders something slow-cooking, the chef doesn’t stand there watching the oven. They hand it to the oven station (libuv), take the next order, and check back when it’s ready.</p><p>Here’s the flow: Call Stack executes synchronous code line by line. When it hits an async operation (file I/O, database query, timer), it delegates to the appropriate system. Call Stack continues executing the next line immediately — it doesn’t wait. When the async operation completes, the callback goes into a queue. The <strong>Event Loop</strong> picks up callbacks from the queue when the Call Stack is empty.</p><pre>function fetchUser(id) {<br>  console.log(&#39;Starting database query...&#39;);<br>  <br>  database.query(&#39;SELECT * FROM users WHERE id = ?&#39;, [id], (err, user) =&gt; {<br>    console.log(&#39;Got user:&#39;, user.name); // Runs later<br>  });<br>  <br>  console.log(&#39;Query initiated&#39;); // Runs immediately<br>  return &#39;Request pending&#39;;<br>}<br><br>fetchUser(123);<br><br>// Output:<br>// Starting database query...<br>// Query initiated<br>// (database work happens in background)<br>// Got user: John (appears later when query completes)</pre><p>The key insight: Node doesn’t wait for responses. It registers what to do when the response arrives (the callback), then moves on. While the database is processing your query, Node can handle hundreds of other requests.</p><h3>The Blocking Code Trap</h3><p>Node can handle 10,000+ concurrent connections on a single thread, but ONLY if your code doesn’t block. A <strong>blocking operation</strong> prevents all other code from running because there’s only one Call Stack. While it’s busy with synchronous work, nothing else can execute — not timers, not I/O callbacks, not incoming HTTP requests. Everything waits.</p><p>Common blocking operations that kill performance: synchronous file operations, CPU-intensive calculations, parsing massive JSON objects, cryptographic operations using sync methods. Each one freezes your entire application.</p><pre>const express = require(&#39;express&#39;);<br>const crypto = require(&#39;crypto&#39;);<br>const app = express();<br><br>// ❌ WRONG: Blocks the entire server<br>app.post(&#39;/hash-password&#39;, (req, res) =&gt; {<br>  // This takes ~100ms and freezes ALL other requests during that time<br>  const hash = crypto.pbkdf2Sync(<br>    req.body.password,<br>    &#39;salt&#39;,<br>    100000,<br>    64,<br>    &#39;sha512&#39;<br>  );<br>  res.send({ hash: hash.toString(&#39;hex&#39;) });<br>});<br><br>// ✅ RIGHT: Delegates to thread pool<br>app.post(&#39;/hash-password&#39;, (req, res) =&gt; {<br>  crypto.pbkdf2(<br>    req.body.password,<br>    &#39;salt&#39;,<br>    100000,<br>    64,<br>    &#39;sha512&#39;,<br>    (err, hash) =&gt; {<br>      res.send({ hash: hash.toString(&#39;hex&#39;) });<br>    }<br>  );<br>});</pre><p>The synchronous version seems simpler, but it’s devastating for performance. While hashing one password, your server can’t respond to any other user. With 10 concurrent requests, users wait up to 1 second each. The async version handles all 10 simultaneously because the hashing happens in libuv’s thread pool.</p><h3>Common Mistakes That Block the Event Loop</h3><p>The most common mistake is running heavy computation in the main thread without realizing it blocks everything:</p><pre>app.get(&#39;/calculate&#39;, (req, res) =&gt; {<br>  // ❌ This freezes the server for ~2 seconds<br>  let result = 0;<br>  for (let i = 0; i &lt; 2000000000; i++) {<br>    result += Math.sqrt(i);<br>  }<br>  res.json({ result });<br>});<br><br>// While this runs, ALL other requests wait<br>// Your server becomes completely unresponsive</pre><p>For CPU-intensive work, use Worker Threads or break the computation into smaller chunks that yield control periodically.</p><p>Another trap is using synchronous file methods. They’re tempting because the code looks cleaner, but they freeze your application:</p><pre>// ❌ Blocks - nothing else runs during file read<br>const config = JSON.parse(fs.readFileSync(&#39;config.json&#39;, &#39;utf8&#39;));<br><br>// ✅ Doesn&#39;t block - other code runs while file loads<br>fs.readFile(&#39;config.json&#39;, &#39;utf8&#39;, (err, data) =&gt; {<br>  const config = JSON.parse(data);<br>  // Use config here<br>});</pre><p>The synchronous version might be acceptable during application startup before you start accepting requests. But if it runs during request handling, it blocks every other request.</p><p>One more gotcha: not understanding what libuv actually handles. Libuv’s thread pool handles file I/O, DNS lookups, and some crypto operations. The operating system handles network I/O (HTTP requests, socket connections) and timers. Everything else — your actual JavaScript code — runs on the main thread. If you write a loop that processes 100,000 records, that’s blocking the main thread. Libuv can’t help with that.</p><h3>Key Takeaways</h3><ul><li>JavaScript is single-threaded, but Node.js uses libuv for async I/O operations</li><li>The Call Stack delegates blocking operations and continues executing immediately</li><li>Blocking code (sync methods, heavy loops) freezes your entire server</li><li>Node handles thousands of connections because it never waits — it delegates and moves on</li><li>Async methods let other code run while operations complete in the background</li></ul><p><strong>One-liner to remember:</strong> Node.js is fast not because it’s multi-threaded, but because it delegates waiting to others and never stops working.</p><p>In interviews, you’ll hear: “How does Node handle concurrency with one thread?” This architecture is your answer. Node doesn’t handle multiple operations simultaneously — it handles them concurrently by delegating the waiting.</p><p>Now you understand how Node delegates async work to stay non-blocking. But when those callbacks come back, which one runs first? That’s where microtask and macrotask queues come in — we’ll break down the priority system in Part 2.</p><p>Try this: add console.log statements before and after async operations in your code to trace the execution flow. You&#39;ll see the Call Stack never waits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55dae6262ef9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL WHERE vs HAVING: Why Your GROUP BY Query Returns Nothing (And the One-Word Fix)]]></title>
            <link>https://medium.com/@saadamir1/sql-where-vs-having-why-your-group-by-query-returns-nothing-and-the-one-word-fix-5eeb610a06ad?source=rss-12acbde2152d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eeb610a06ad</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Saad Amir]]></dc:creator>
            <pubDate>Fri, 06 Feb 2026 15:44:02 GMT</pubDate>
            <atom:updated>2026-02-06T15:44:02.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfqWfdIfl0AoFsy3B_8Kog.png" /></figure><p>I once spent three hours debugging a department analytics query. The data was there. The syntax looked perfect. But the result? Empty.</p><p>The bug? I used <strong>WHERE</strong> with <strong>COUNT()</strong>. Changed one word to <strong>HAVING</strong> and it worked instantly.</p><p>If you’ve ever been confused about when to use WHERE vs HAVING, you’re about to learn the mental model that makes it obvious. This is part of my series breaking down concepts that tripped me up during interview prep — starting with the one that costs developers hours of debugging time.</p><h3>The Real Difference: Timing, Not Syntax</h3><p>Most tutorials say “WHERE filters rows, HAVING filters groups.” True, but useless. Here’s what actually matters:</p><p><strong>SQL doesn’t execute in the order you write it.</strong></p><p>You write:</p><pre>SELECT<br>FROM<br>WHERE<br>GROUP BY<br>HAVING<br>ORDER BY<br>LIMIT</pre><p>But SQL engines execute them in a <strong>completely different order</strong>:</p><pre>1. FROM     ← Get the data<br>2. WHERE    ← Filter individual rows<br>3. GROUP BY ← Create groups<br>4. HAVING   ← Filter groups<br>5. SELECT   ← Choose columns<br>6. ORDER BY ← Sort results<br>7. LIMIT    ← Limit results</pre><p><strong>WHERE</strong> runs <strong>before</strong> grouping. <strong>HAVING</strong> runs <strong>after</strong> grouping. This isn’t trivia — it’s why your query breaks.</p><h3>WHERE: Filter First, Then Group</h3><p><strong>WHERE</strong> filters individual rows before any grouping happens.</p><pre>SELECT department, COUNT(*) as total<br>FROM employees<br>WHERE salary &gt; 50000<br>GROUP BY department;</pre><p><strong>What happens:</strong></p><ol><li><strong>FROM:</strong> Load all employees</li><li><strong>WHERE:</strong> Keep only rows where salary &gt; 50000</li><li><strong>GROUP BY:</strong> Group the survivors by department</li><li><strong>SELECT:</strong> Count employees in each group</li></ol><p>If you have 10,000 employees and 3,000 earn over 50k, only those 3,000 get grouped.</p><p><strong>The rule:</strong> WHERE cannot use aggregates (<strong>COUNT</strong>, <strong>SUM</strong>, <strong>AVG</strong>) because groups don’t exist yet.</p><pre>-- This fails<br>WHERE COUNT(*) &gt; 10<br><br>-- This also fails<br>WHERE AVG(salary) &gt; 60000</pre><h3>HAVING: Group First, Then Filter</h3><p><strong>HAVING</strong> filters groups after grouping completes.</p><pre>SELECT department, COUNT(*) as total<br>FROM employees<br>GROUP BY department<br>HAVING COUNT(*) &gt; 10;</pre><p><strong>What happens:</strong></p><ol><li><strong>FROM:</strong> Load all employees</li><li><strong>GROUP BY:</strong> Group by department</li><li><strong>HAVING:</strong> Keep only groups with more than 10 employees</li><li><strong>SELECT:</strong> Show the results</li></ol><p><strong>The rule:</strong> HAVING works with aggregates because groups already exist.</p><h3>Using Both: The Real Power Move</h3><p>You need both when filtering at different stages:</p><pre>SELECT department, COUNT(*) as high_earners<br>FROM employees<br>WHERE salary &gt; 50000<br>GROUP BY department<br>HAVING COUNT(*) &gt; 5;</pre><p><strong>Translation:</strong> “Show me departments that have more than 5 employees earning over 50k.”</p><p>Let’s trace this with real data:</p><p><strong>Original data:</strong> 10 employees across 2 departments <strong>After WHERE (salary &gt; 50k):</strong> 8 employees remain <strong>After GROUP BY:</strong> Sales (4), Engineering (4) <strong>After HAVING (count &gt; 5):</strong> Empty result (no department has 6+)</p><p>Change <strong>HAVING COUNT(*) &gt; 5</strong> to <strong>HAVING COUNT(*) &gt; 3</strong> and both departments appear.</p><h3>The Bug That Wastes Hours</h3><p><strong>Wrong way</strong> (my original bug):</p><pre>SELECT department, COUNT(*)<br>FROM employees<br>WHERE COUNT(*) &gt; 10<br>GROUP BY department;</pre><p>This breaks because aggregates don’t work in WHERE.</p><p><strong>Right way:</strong></p><pre>SELECT department, COUNT(*)<br>FROM employees<br>GROUP BY department<br>HAVING COUNT(*) &gt; 10;</pre><p><strong>Why this mistake happens:</strong> We write queries left-to-right but SQL executes in a different order. Your brain says “filter by count” but WHERE runs before counts exist.</p><h3>Performance Trap: HAVING When You Mean WHERE</h3><p><strong>Slow version:</strong></p><pre>SELECT department, COUNT(*)<br>FROM employees<br>GROUP BY department<br>HAVING department = &#39;Sales&#39;;</pre><p><strong>Fast version:</strong></p><pre>SELECT department, COUNT(*)<br>FROM employees<br>WHERE department = &#39;Sales&#39;<br>GROUP BY department;</pre><p>Both work. The second is <strong>faster</strong> because it processes fewer rows.</p><p><strong>Rule of thumb:</strong> If you’re filtering on a regular column (not an aggregate), use WHERE.</p><h3>Edge Case: HAVING Without GROUP BY</h3><p>This is valid and useful:</p><pre>SELECT COUNT(*) as total<br>FROM employees<br>HAVING COUNT(*) &gt; 100;</pre><p>SQL treats the entire table as one group. If there are 150 employees, you get 150. If there are 80 employees, you get nothing (empty result).</p><p><strong>Use case:</strong> Conditional checks before running expensive operations.</p><h3>Key Takeaways</h3><ul><li><strong>WHERE</strong> filters rows <strong>before grouping</strong> — can’t use COUNT(), SUM(), AVG()</li><li><strong>HAVING</strong> filters groups <strong>after grouping</strong> — requires aggregates or GROUP BY columns</li><li><strong>Use both together</strong> when you need to filter at different stages</li><li><strong>Performance matters:</strong> Use WHERE for non-aggregates (faster)</li><li><strong>Mental model:</strong> WHERE = bouncer at the door, HAVING = manager counting groups inside</li></ul><p><strong>One-liner:</strong> If groups don’t exist yet, you can’t filter by group properties.</p><p>In interviews, they’ll ask you to write a query like “Find departments where more than 5 employees earn over 60k.” Now you know: <strong>WHERE</strong> filters the 60k earners, <strong>HAVING</strong> filters the departments with 5+ people.</p><h3>Try This in Your Code</h3><p>Open your SQL editor and run this:</p><pre>SELECT department, AVG(salary) as avg_sal<br>FROM employees<br>WHERE salary &gt; 30000<br>GROUP BY department<br>HAVING AVG(salary) &gt; 60000;</pre><p>Then swap WHERE and HAVING conditions. Notice how the results change completely? That’s execution order in action.</p><p>Next time, I’m breaking down <strong>subqueries vs JOINs</strong> — when each one is actually faster (spoiler: it’s not what you think).</p><p>Hit a WHERE vs HAVING bug before? Drop a comment with what broke.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eeb610a06ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Modifying a Python Copy Changes the Original]]></title>
            <link>https://medium.com/@saadamir1/python-copies-dont-work-how-you-think-why-your-list-changes-break-everything-0968a548e390?source=rss-12acbde2152d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0968a548e390</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[shallow-vs-deep-copy]]></category>
            <dc:creator><![CDATA[Saad Amir]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 21:39:13 GMT</pubDate>
            <atom:updated>2025-12-11T23:57:50.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1PlPHKBsiBNr02ZBjx7fIw.png" /></figure><p>You modify a copy of a list, and suddenly your original data is corrupted. You’ve triple-checked your code — you made a copy, right? This bug has burned every Python developer at least once, and it stems from a fundamental misunderstanding of how Python stores data in memory.</p><p>Here’s what’s really happening: Python lists don’t store values directly — they store references (pointers) to objects in memory. When you “copy” a list, you’re not copying the objects inside. You’re copying the pointers. This is part of my series breaking down concepts that tripped me up during interview prep, and this one cost me a debugging session I’ll never forget.</p><p>Let’s fix this confusion once and for all.</p><h3>How Python Actually Stores Lists</h3><p>When you create a list in Python, each element is a reference pointing to an object somewhere in memory. Think of it like a row of addresses, not actual houses.</p><pre>original = [1, 2, [3, 4]]<br># Memory: original → [ptr1, ptr2, ptr3]<br>#         ptr1 → 1, ptr2 → 2, ptr3 → [3,4]</pre><p>This distinction doesn’t matter for immutable objects like integers or strings — they can’t change anyway. But for mutable objects like lists or dictionaries, this is where things break.</p><h3>Shallow Copy: Copying Pointers, Not Objects</h3><p>A shallow copy duplicates the list structure but keeps the same references to nested objects.</p><pre>import copy<br><br>original = [1, 2, [3, 4]]<br>shallow = original.copy()  # or list(original) or copy.copy()<br>shallow[0] = 99  # Changes shallow only<br>shallow[2][0] = 99  # CHANGES BOTH!<br>print(original)  # [1, 2, [99, 4]] ← Wait, what?</pre><p>Here’s why: shallow[0] = 99 creates a new integer object and points shallow[0] to it. But shallow[2][0] = 99 modifies the nested list that both original[2] and shallow[2] point to. Same object, two pointers.</p><h3>Deep Copy: Actually Copying Everything</h3><p>A deep copy recursively duplicates all nested objects, creating completely independent data structures.</p><pre>import copy<br><br>original = [1, 2, [3, 4]]<br>deep = copy.deepcopy(original)<br>deep[2][0] = 99<br><br>print(original)  # [1, 2, [3, 4]] ← Safe!<br>print(deep)      # [1, 2, [99, 4]]</pre><p>Now deep[2] points to a different list object in memory. Modifying it leaves original untouched.</p><h3>Mutable vs Immutable: Why Some Copies “Work”</h3><p>Immutable objects (int, str, tuple) can’t be modified in place, so shallow copying appears to work fine.</p><pre>original = [1, 2, 3]<br>shallow = original.copy()<br><br>shallow[0] = 99  # Creates NEW int, doesn&#39;t modify original&#39;s int<br>print(original)  # [1, 2, 3] ← Looks safe</pre><p>You’re not actually safe — you just got lucky because integers are immutable. The moment you add a mutable object, the bug reappears.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bm5rDKGw2nsGWAgz0_OXdw.png" /></figure><h3>Edge Cases &amp; Common Mistakes</h3><p>Mistake 1: Using assignment instead of copying</p><pre># Wrong<br>copy_list = original_list  # Not a copy! Same object, different name<br><br># Right<br>copy_list = original_list.copy()  # Shallow copy</pre><p>Assignment creates another reference to the same list. Modifying either “variable” affects both because there’s only one list.</p><p>Mistake 2: Shallow copying nested structures</p><pre># Wrong - Nested list still shared<br>data = [[1, 2], [3, 4]]<br>copy_data = data.copy()<br>copy_data[0][0] = 99  # Modifies original!<br><br># Right - Use deepcopy for nested structures<br>import copy<br>copy_data = copy.deepcopy(data)</pre><p>Shallow copy only goes one level deep. Any nested mutable objects remain shared.</p><p>Mistake 3: Assuming slicing creates deep copies</p><pre># Wrong assumption<br>original = [[1, 2], [3, 4]]<br>sliced = original[:]  # Shallow copy!<br>sliced[0][0] = 99  # Still modifies original</pre><p>Slicing ([:]) creates a shallow copy, not a deep one. It&#39;s convenient but has the same reference-sharing problem.</p><h3>Key Takeaways</h3><ul><li>Python lists store references (pointers), not values — copying the list doesn’t copy the objects inside</li><li>Shallow copy duplicates the list structure but shares nested objects</li><li>Deep copy recursively duplicates everything, creating fully independent copies</li><li>Immutable objects hide the problem until you add mutable nested data</li><li>Use copy.deepcopy() for nested structures, list.copy() for flat lists with immutables</li></ul><p>The one-liner: If your data has layers, shallow won’t save you.</p><p>This distinction appears constantly in interviews when manipulating 2D arrays, implementing graph algorithms, or working with complex data structures. Interviewers love asking “why did this modify my original list?”</p><h3>Try It Yourself</h3><p>Next time, we’ll explore how Python’s reference system affects function arguments — spoiler: it’s not pass-by-reference or pass-by-value.</p><p>Create a nested list right now and test both copy methods. See the difference firsthand before this bug bites you in production.</p><p>Suggested Tags: Python, Programming, Software-Development, Interview-Prep, Data-Structures</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0968a548e390" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Slicing: The Complete Guide (With Edge Cases You’re Missing)]]></title>
            <link>https://medium.com/@saadamir1/python-slicing-the-complete-guide-with-edge-cases-youre-missing-07e171fb3743?source=rss-12acbde2152d------2</link>
            <guid isPermaLink="false">https://medium.com/p/07e171fb3743</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[shallow-copy]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-slicing]]></category>
            <dc:creator><![CDATA[Saad Amir]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 15:54:39 GMT</pubDate>
            <atom:updated>2025-12-10T15:54:39.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pSeC4WdkpuFMLFjicBDD3Q.png" /></figure><p><em>In my recent article on recursion, we used </em><em>s[1:] to reverse strings. Several readers asked: &quot;What exactly is that syntax doing?&quot; That&#39;s Python slicing—and it&#39;s more powerful (and confusing) than most developers realize.</em></p><p>You’ve probably used my_list[1:5] dozens of times. But do you know what happens with my_list[-3:] or my_list[::-1]? Python slicing has hidden behaviors that trip up even experienced developers.</p><p>I learned this the hard way during a code review when my “simple” slice caused a subtle bug. Let me save you that embarrassment.</p><h3>The Basic Syntax (You Probably Know This)</h3><pre>sequence[start:stop:step]</pre><ul><li><strong>start</strong>: Where to begin (inclusive)</li><li><strong>stop</strong>: Where to end (exclusive)</li><li><strong>step</strong>: How many items to skip</li></ul><p><strong>The golden rule:</strong> stop is always exclusive. my_list[0:3] gives you indices 0, 1, 2—NOT 3.</p><h3>Simple Examples (The Comfort Zone)</h3><pre>text = &quot;ABCDEFGH&quot;<br><br>print(text[0:3])    # &quot;ABC&quot; - indices 0, 1, 2<br>print(text[2:5])    # &quot;CDE&quot; - indices 2, 3, 4<br>print(text[1:6:2])  # &quot;BDF&quot; - indices 1, 3, 5 (every 2nd item)</pre><p>Easy, right? Now let’s get to the stuff that causes bugs.</p><h3>Negative Indices (This Gets Interesting)</h3><p>Negative numbers count from the end:</p><pre>text = &quot;ABCDEFGH&quot;<br>#       01234567  (positive indices)<br>#      -87654321  (negative indices)<br><br>print(text[-1])     # &quot;H&quot; - last character<br>print(text[-3])     # &quot;F&quot; - 3rd from end<br>print(text[-5:-2])  # &quot;DEF&quot; - from -5 to -2 (exclusive)</pre><p><strong>Mental model:</strong> Think of -1 as len(text) - 1, -2 as len(text) - 2, etc.</p><p>But here’s where it gets tricky:</p><pre>print(text[2:-2])   # &quot;CDEF&quot; - from index 2 to 2nd-last (exclusive)<br>print(text[-6:7])   # &quot;CDEFG&quot; - mixing positive and negative works!</pre><h3>Omitting Start, Stop, or Step (The Defaults)</h3><p>When you leave parts blank, Python fills in smart defaults:</p><pre>text = &quot;ABCDEFGH&quot;<br><br>print(text[:4])     # &quot;ABCD&quot; - start defaults to 0<br>print(text[3:])     # &quot;DEFGH&quot; - stop defaults to end<br>print(text[:])      # &quot;ABCDEFGH&quot; - full copy<br>print(text[::2])    # &quot;ACEG&quot; - every 2nd item from start to end</pre><p><strong>Critical insight:</strong> text[:] creates a <strong>shallow copy</strong> of the sequence. This is different from just text.</p><pre>original = [1, 2, 3]<br>copy = original[:]<br>copy[0] = 999<br><br>print(original)  # [1, 2, 3] - unchanged<br>print(copy)      # [999, 2, 3] - modified5</pre><h3>Negative Step (Reversing and More)</h3><p>This is where minds are blown:</p><pre>text = &quot;ABCDEFGH&quot;<br><br>print(text[::-1])   # &quot;HGFEDCBA&quot; - reversed!<br>print(text[::2])    # &quot;ACEG&quot; - every 2nd item forward<br>print(text[::-2])   # &quot;HFDB&quot; - every 2nd item backward</pre><p><strong>With negative step, start and stop logic reverses:</strong></p><pre>text = &quot;ABCDEFGH&quot;<br><br>print(text[6:2:-1])  # &quot;GFED&quot; - from index 6 down to 3 (stop is exclusive)<br>print(text[5::-1])   # &quot;FEDCBA&quot; - from index 5 to start, reversed<br>print(text[:3:-1])   # &quot;HGFE&quot; - from end down to 4 (stop is exclusive)</pre><p><strong>Common mistake:</strong></p><pre>print(text[2:6:-1])  # &quot;&quot; - empty! Start is before stop with negative step</pre><p>When step is negative, start must be AFTER stop, or you get nothing.</p><h3>Edge Cases That Bite You</h3><h3>Edge Case 1: Out-of-Bounds Doesn’t Error</h3><p>Unlike regular indexing, slicing is forgiving:</p><pre>text = &quot;ABCDEFGH&quot;<br><br>print(text[10])      # IndexError!<br>print(text[5:100])   # &quot;FGH&quot; - just goes to end, no error<br>print(text[-100:3])  # &quot;ABC&quot; - starts at beginning if too negative</pre><p><strong>Why this matters:</strong> Your bugs might fail silently.</p><h3>Edge Case 2: Empty Slices</h3><pre>text = &quot;ABCDEFGH&quot;<br><br>print(text[5:2])    # &quot;&quot; - start after stop with positive step<br>print(text[2:2])    # &quot;&quot; - start equals stop<br>print(text[-2:-5])  # &quot;&quot; - start after stop (with positive step)<br>print(text[-2:-5:-1])# &quot;GFE&quot; - NOW it works with negative step</pre><h3>Slicing Different Sequence Types</h3><pre># Strings<br>text = &quot;hello&quot;<br>print(text[1:4])  # &quot;ell&quot;<br><br># Lists<br>nums = [0, 1, 2, 3, 4, 5]<br>print(nums[2:5])  # [2, 3, 4]<br><br># Tuples<br>coords = (10, 20, 30, 40, 50)<br>print(coords[-3:]) # (30, 40, 50)</pre><p><strong>Important:</strong> You can modify list slices but NOT strings (they’re immutable):</p><pre>nums = [0, 1, 2, 3, 4, 5]<br>nums[2:4] = [99, 88]<br>print(nums)  # [0, 1, 99, 88, 4, 5]<br><br>text = &quot;hello&quot;<br># text[1:3] = &quot;ey&quot;  # TypeError! Strings are immutable</pre><h3>Practical Use Cases</h3><p><strong>1. Getting file extensions:</strong></p><pre>filename = &quot;document.pdf&quot;<br>extension = filename[-3:]  # &quot;pdf&quot;</pre><p><strong>2. Reversing efficiently:</strong></p><pre>palindrome = &quot;racecar&quot;<br>if palindrome == palindrome[::-1]:<br>    print(&quot;It&#39;s a palindrome!&quot;)</pre><p><strong>3. Skipping headers in data:</strong></p><pre>lines = [&quot;header1,header2&quot;, &quot;data1,data2&quot;, &quot;data3,data4&quot;]<br>data_only = lines[1:]  # Skip first line</pre><p><strong>4. Getting every Nth item:</strong></p><pre>all_items = [1, 2, 3, 4, 5, 6, 7, 8]<br>every_third = all_items[::3]  # [1, 4, 7]</pre><h3>Interview Challenge</h3><p>Can you predict the output?</p><pre>text = &quot;PYTHON&quot;<br>result = text[5:0:-2]<br>print(result)</pre><p><em>(Try it yourself before scrolling…)</em></p><p>.</p><p>.</p><p>.</p><p><strong>Answer:</strong> &quot;NHY&quot;</p><p><strong>Breakdown:</strong></p><ul><li>Start at index 5 (&quot;N&quot;)</li><li>Go backwards (step = -2) to index 1 (stop = 0 is exclusive)</li><li>Indices: 5 (&quot;N&quot;), 3 (&quot;H&quot;), 1 (&quot;Y&quot;)</li></ul><h3>Common Pitfalls to Avoid</h3><p>❌ <strong>Assuming stop is inclusive</strong></p><pre>text = &quot;ABCDE&quot;<br>print(text[1:3])  # &quot;BC&quot; not &quot;BCD&quot;</pre><p>❌ <strong>Forgetting shallow copy behavior</strong></p><pre>original = [[1, 2], [3, 4]]<br>copy = original[:]<br>copy[0][0] = 999<br>print(original)  # [[999, 2], [3, 4]] - inner lists still shared!</pre><p>❌ <strong>Expecting errors on out-of-bounds</strong></p><pre>text = &quot;ABC&quot;<br>print(text[10:20])  # &quot;&quot; not IndexError</pre><h3>Quick Reference Cheat Sheet</h3><p><strong>text = “ABCDEFGH”</strong></p><p>• text[:] — Full copy → &quot;ABCDEFGH&quot;<br> • text[n:] — From n to end → text[3:] = &quot;DEFGH&quot;<br> • text[:n] — From start to n → text[:3] = &quot;ABC&quot;<br> • text[::n] — Every nth item → text[::2] = &quot;ACEG&quot;<br> • text[::-1] — Reversed → &quot;HGFEDCBA&quot;<br> • text[n:m] — From n to m-1 → text[2:5] = &quot;CDE&quot;<br> • text[-n:] — Last n items → text[-3:] = &quot;FGH&quot;<br> • text[:-n] — All except last n → text[:-2] = &quot;ABCDEF&quot;</p><h3>Key Takeaways</h3><p>✅ stop is always exclusive<br> ✅ Negative indices count from the end<br> ✅ Omitted values have smart defaults<br> ✅ Negative step reverses direction and logic<br> ✅ Out-of-bounds slices don&#39;t raise errors (be careful!)<br> ✅ Slicing creates new objects (shallow copies)</p><h3>Practice Challenge</h3><p>What does this print?</p><pre>data = [10, 20, 30, 40, 50, 60, 70]<br>print(data[-5:-1:2])</pre><p>Try it yourself before running the code!</p><p><strong>Master slicing?</strong> Check out my article on recursion where we use slicing to reverse strings: <a href="https://medium.com/@saadamir1/master-recursion-once-and-for-all-visualizing-string-reversal-step-by-step-python-7212b2c7fee5">Master Recursion Once and For All →</a></p><p><em>Found this helpful? Follow for more Python deep dives that clarify confusing concepts.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07e171fb3743" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Recursion Once and For All: Visualizing String Reversal Step-by-Step (Python)]]></title>
            <link>https://medium.com/@saadamir1/master-recursion-once-and-for-all-visualizing-string-reversal-step-by-step-python-7212b2c7fee5?source=rss-12acbde2152d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7212b2c7fee5</guid>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Saad Amir]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 17:55:50 GMT</pubDate>
            <atom:updated>2025-12-11T15:21:35.439Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ky046S3ltc4-puz9Zi4uUA.png" /></figure><p>Recursion confused me during my first <strong>technical interview</strong>. I knew the theory, but when asked to trace through a recursive function, I froze. If you’ve ever struggled to visualize what’s actually happening inside a recursive call, this guide is for you.</p><h3>What Is Recursion, Really?</h3><p>Recursion is when a function calls itself to solve a smaller version of the same problem. Think of it like Russian nesting dolls — each doll contains a smaller version until you reach the tiniest one.</p><p><strong>Two critical parts every recursive function needs:</strong></p><ol><li><strong>Base case</strong>: The stopping condition (or your function runs forever)</li><li><strong>Recursive case</strong>: Where the function calls itself with a simpler input</li></ol><h3>The Problem: Reverse a String Recursively</h3><p>Let’s reverse the string &quot;hello&quot; using recursion. Here&#39;s the code:</p><pre>def reverse_string(s):<br>    # Base case: empty string or single character<br>    if len(s) &lt;= 1:<br>        return s<br>    <br>    # Recursive case: first char goes to end<br>    return reverse_string(s[1:]) + s[0]<br><br>result = reverse_string(&quot;hello&quot;)<br>print(result)  # Output: &quot;olleh&quot;</pre><p><strong>Wait, what’s </strong><strong>s[1:]?</strong> That&#39;s Python slicing. It means &quot;give me everything from index 1 to the end.&quot; So &quot;hello&quot;[1:] gives us &quot;ello&quot;. Don&#39;t worry about slicing details now—just know it&#39;s grabbing a substring.</p><blockquote><strong><em>🔍 Not familiar with Python slicing?</em></strong><em><br> I created a complete guide covering every edge case and gotcha: </em><a href="https://medium.com/@saadamir1/python-slicing-the-complete-guide-with-edge-cases-youre-missing-07e171fb3743"><em>Python Slicing: The Complete Guide →</em></a></blockquote><h3>How It Actually Works: The Recursion Tree</h3><p>Here’s where most tutorials fail you. Let me show you exactly what happens at each step:</p><pre>reverse_string(&quot;hello&quot;)<br>│<br>├─ reverse_string(&quot;ello&quot;) + &quot;h&quot;<br>│  │<br>│  ├─ reverse_string(&quot;llo&quot;) + &quot;e&quot; + &quot;h&quot;<br>│  │  │<br>│  │  ├─ reverse_string(&quot;lo&quot;) + &quot;l&quot; + &quot;e&quot; + &quot;h&quot;<br>│  │  │  │<br>│  │  │  ├─ reverse_string(&quot;o&quot;) + &quot;l&quot; + &quot;l&quot; + &quot;e&quot; + &quot;h&quot;<br>│  │  │  │  │<br>│  │  │  │  └─ &quot;o&quot; (base case: length is 1)<br>│  │  │  │<br>│  │  │  └─ returns &quot;o&quot; + &quot;l&quot; = &quot;ol&quot;<br>│  │  │<br>│  │  └─ returns &quot;ol&quot; + &quot;l&quot; = &quot;oll&quot;<br>│  │<br>│  └─ returns &quot;oll&quot; + &quot;e&quot; = &quot;olle&quot;<br>│<br>└─ returns &quot;olle&quot; + &quot;h&quot; = &quot;olleh&quot;</pre><h3>Step-by-Step Breakdown</h3><p>Let me walk you through this like I wish someone had explained it to me:</p><p><strong>Call 1: </strong><strong>reverse_string(&quot;hello&quot;)</strong></p><ul><li>Length is 5, not ≤ 1, so we hit the recursive case</li><li>We call reverse_string(&quot;ello&quot;) and will add &quot;h&quot; to whatever it returns</li><li>This call is now <strong>waiting</strong> for the result</li></ul><p><strong>Call 2: </strong><strong>reverse_string(&quot;ello&quot;)</strong></p><ul><li>Length is 4, still not base case</li><li>We call reverse_string(&quot;llo&quot;) and will add &quot;e&quot; later</li><li>This call is also <strong>waiting</strong></li></ul><p><strong>Call 3: </strong><strong>reverse_string(&quot;llo&quot;)</strong></p><ul><li>Length is 3, keep going</li><li>Call reverse_string(&quot;lo&quot;) and remember to add &quot;l&quot;</li></ul><p><strong>Call 4: </strong><strong>reverse_string(&quot;lo&quot;)</strong></p><ul><li>Length is 2, continue</li><li>Call reverse_string(&quot;o&quot;) and remember to add &quot;l&quot;</li></ul><p><strong>Call 5: </strong><strong>reverse_string(&quot;o&quot;)</strong> ⭐ <strong>BASE CASE HIT</strong></p><ul><li>Length is 1!</li><li>Return &quot;o&quot; immediately</li><li>Now the magic happens — all waiting calls start resolving</li></ul><h3>The Return Journey (This Is Key!)</h3><p>Now we unwind back up the tree:</p><pre>Call 5 returns: &quot;o&quot;<br>Call 4 receives &quot;o&quot;, adds &quot;l&quot; → returns &quot;ol&quot;<br>Call 3 receives &quot;ol&quot;, adds &quot;l&quot; → returns &quot;oll&quot;<br>Call 2 receives &quot;oll&quot;, adds &quot;e&quot; → returns &quot;olle&quot;<br>Call 1 receives &quot;olle&quot;, adds &quot;h&quot; → returns &quot;olleh&quot;</pre><p><strong>The crucial insight:</strong> Each function call is frozen in time, waiting for the recursive call to finish. Once the base case returns, they all complete in reverse order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WM06O6nwJwQTf121-655jw.png" /></figure><h3>The Call Stack Visualization</h3><p>Think of the call stack like a stack of plates:</p><pre>[reverse_string(&quot;o&quot;)]           ← Top of stack (executes first)<br>[reverse_string(&quot;lo&quot;)]<br>[reverse_string(&quot;llo&quot;)]<br>[reverse_string(&quot;ello&quot;)]<br>[reverse_string(&quot;hello&quot;)]       ← Bottom (called first)</pre><p>As each function completes, we pop it off the stack and return to the previous one.</p><h3>Common Mistakes to Avoid</h3><p><strong>Mistake 1: Forgetting the base case</strong></p><pre>def reverse_string(s):<br>    return reverse_string(s[1:]) + s[0]  # Infinite recursion!</pre><p>This never stops. It’ll crash with “maximum recursion depth exceeded.”</p><p><strong>Mistake 2: Wrong base case</strong></p><pre>def reverse_string(s):<br>    if len(s) == 0:  # What about length 1?<br>        return s<br>    return reverse_string(s[1:]) + s[0]</pre><p>This works but makes an unnecessary recursive call for single characters.</p><p><strong>Mistake 3: Not understanding what gets returned</strong> The recursive call returns a <strong>complete reversed substring</strong>, not just one character. reverse_string(&quot;ello&quot;) returns the entire string &quot;olle&quot;, not just &quot;o&quot;.</p><h3>Practice: Trace This Yourself</h3><p>Try tracing reverse_string(&quot;cat&quot;) on paper:</p><pre>reverse_string(&quot;cat&quot;)<br>├─ reverse_string(&quot;at&quot;) + &quot;c&quot;<br>│  ├─ reverse_string(&quot;t&quot;) + &quot;a&quot; + &quot;c&quot;<br>│  │  └─ &quot;t&quot; (base case)<br>│  └─ &quot;t&quot; + &quot;a&quot; = &quot;ta&quot;<br>└─ &quot;ta&quot; + &quot;c&quot; = &quot;tac&quot;</pre><p>If you got &quot;tac&quot;, you understand recursion!</p><h3>Why Learn This Pattern?</h3><p>This same pattern appears everywhere:</p><ul><li>Tree traversals</li><li>Divide and conquer algorithms (merge sort, quicksort)</li><li>Dynamic programming problems</li><li>Graph algorithms (DFS)</li></ul><p>Master this visualization technique, and you’ll ace recursion questions in interviews.</p><h3>Does This Work in Other Languages?</h3><p><strong>Yes! The recursion concept is universal.</strong> JavaScript, Java, C++, Go, and virtually all modern languages support recursion with the same base case + recursive case pattern.</p><p>The syntax differs, but the logic and call stack behavior are identical:</p><p><strong>JavaScript equivalent:</strong></p><pre>function reverseString(s) {<br>    if (s.length &lt;= 1) {<br>        return s;<br>    }<br>    return reverseString(s.slice(1)) + s[0];<br>}<br><br>console.log(reverseString(&quot;hello&quot;));  // &quot;olleh&quot;</pre><p><strong>Java equivalent:</strong></p><pre>public String reverseString(String s) {<br>    if (s.length() &lt;= 1) {<br>        return s;<br>    }<br>    return reverseString(s.substring(1)) + s.charAt(0);<br>}</pre><p><strong>C++ equivalent:</strong></p><pre>string reverseString(string s) {<br>    if (s.length() &lt;= 1) {<br>        return s;<br>    }<br>    return reverseString(s.substr(1)) + s[0];<br>}</pre><p><strong>The recursion tree, call stack, and unwinding process work exactly the same way across all these languages.</strong> Once you understand it in one language, you understand it everywhere.</p><h3>Key Takeaways</h3><p>✅ Every recursive function needs a base case and recursive case<br> ✅ The function calls stack up until the base case is hit<br> ✅ Returns happen in reverse order (unwinding the stack)<br> ✅ Each call waits for its recursive call to complete<br> ✅ Visualize the tree to understand the flow<br> ✅ The concept is universal across programming languages</p><h3>What’s Next?</h3><p>Now you understand recursion! Want to optimize this? The iterative version is more efficient. Or dive deeper into Python slicing to understand how s[1:] really works in my next article.</p><p><strong>Found this helpful?</strong> Drop a comment with which recursive problem you’d like me to visualize next. Fibonacci? Factorial? Tree traversal?</p><p><em>Preparing for technical interviews? Follow me for more deep dives into confusing CS concepts.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7212b2c7fee5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Stop! const in JavaScript Doesn't Mean What You Think It Does]]></title>
            <link>https://medium.com/@saadamir1/stop-const-in-javascript-doesnt-mean-what-you-think-it-does-2b5ca873d50b?source=rss-12acbde2152d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b5ca873d50b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Saad Amir]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 20:23:51 GMT</pubDate>
            <atom:updated>2025-11-04T19:41:14.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_fdmz3NyXuyuWygDBwyWQ.png" /></figure><p>If you’re coming from Python or just learning JavaScript, you might think const makes your data immutable. <strong>Spoiler alert: it doesn&#39;t.</strong></p><p>Let me show you why this is one of JavaScript’s sneakiest gotchas.</p><h3>🤔 The Misconception</h3><p>Many developers see this code and think the array is “locked”:</p><pre>const coords = [10, 20];</pre><p>After all, it’s const (constant), right? So the values should be fixed... <strong>right?</strong></p><p><strong>Wrong.</strong> 😬</p><h3>💥 The Surprise</h3><p>Watch what happens:</p><pre>const coords = [10, 20];<br>// ❌ This fails (as expected):<br>coords = [30, 40]; // TypeError: Assignment to constant variable<br>// ✅ But THIS works (wait, what?!):<br>coords[0] = 99;<br>coords.push(50);<br>console.log(coords); // [99, 20, 50]</pre><p><strong>The array changed!</strong> Even though we used const.</p><h3>🧠 What const Actually Does</h3><p>Here’s the truth:</p><blockquote><strong><em>const prevents reassignment, NOT mutation.</em></strong></blockquote><p>Think of it like this:</p><ul><li>const locks the <strong>variable name</strong> to one reference</li><li>It does <strong>NOT</strong> lock the <strong>contents</strong> of objects or arrays</li></ul><pre>const box = [1, 2, 3];<br>// ❌ Can&#39;t point &#39;box&#39; to a new array:<br>box = [4, 5, 6]; // Error<br>// ✅ But can change what&#39;s inside the box:<br>box[0] = 999; // Totally fine</pre><h3>🔒 How to Make It TRULY Immutable</h3><p>If you want real immutability, use <strong>Object.freeze()</strong>:</p><pre>const coords = Object.freeze([10, 20]);<br>coords[0] = 99; // ❌ Silently ignored (no error in non-strict mode)<br>coords.push(50); // ❌ TypeError: Cannot add property<br>console.log(coords); // [10, 20] - unchanged!</pre><p>Now it’s <strong>actually</strong> immutable. ✅</p><h3>🐍 Compare This to Python Tuples</h3><p>In Python, tuples are <strong>truly immutable</strong> by default:</p><p>python</p><pre>coords = (10, 20)<br>coords[0] = 99  # ❌ TypeError: &#39;tuple&#39; object does not support item assignment</pre><p>No extra steps needed. The data is locked from the start.</p><p>JavaScript’s const is more like Python&#39;s variable assignment — it just stops you from reassigning the name, not changing the data.</p><h3>Quick Comparison</h3><p><strong>JavaScript </strong><strong>const:</strong></p><ul><li>Prevents reassignment: Yes ✅</li><li>Prevents mutation: No ❌</li><li>Need Object.freeze for immutability: Yes</li></ul><p><strong>Python </strong><strong>tuple:</strong></p><ul><li>Prevents reassignment: Yes ✅</li><li>Prevents mutation: Yes ✅</li><li>Immutable by default: Yes</li></ul><h3>💡 Key Takeaways</h3><p>✅ <strong>const ≠ immutable</strong> — it only prevents reassignment<br> ✅ <strong>Arrays and objects declared with </strong><strong>const can still be modified</strong><br> ✅ <strong>Use </strong><strong>Object.freeze() for true immutability</strong><br> ✅ <strong>For deep immutability, consider libraries like Immer or Immutable.js</strong></p><h3>🎯 Final Thought</h3><p>Next time you use const, remember:</p><blockquote><strong><em>You’re locking the box, not what’s inside it.</em></strong></blockquote><p>If you want the contents locked too, freeze it. 🧊</p><p><strong>Have you been caught by this before?</strong> Drop a comment below! 👇</p><p><em>Happy coding! 🚀</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b5ca873d50b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I Ditched REST for GraphQL (And You Should Too)]]></title>
            <link>https://medium.com/@saadamir1/why-i-ditched-rest-for-graphql-and-you-should-too-1e4aa372ed56?source=rss-12acbde2152d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e4aa372ed56</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Saad Amir]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 19:01:10 GMT</pubDate>
            <atom:updated>2025-09-18T19:01:10.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OGL1e5zg27UY6K_RsYgPuA.png" /></figure><p>I spent weeks building a solid NestJS REST API with authentication, file uploads, and all the enterprise features. Then I threw it all away and rebuilt it with GraphQL. Here’s why it was the best decision I made.</p><h3>The REST Reality Check</h3><p>My <a href="https://github.com/saadamir1/nestjs-pg-crud">NestJS REST foundation</a> was everything you’d expect from a professional API:</p><pre>GET /api/v1/users?page=2&amp;limit=10<br>GET /api/v1/cities?country=US&amp;page=1<br>GET /api/v1/posts?userId=123&amp;category=tech<br>POST /api/v1/files/upload<br>GET /api/v1/analytics/dashboard</pre><p>Multiple modules, clean endpoints, comprehensive features. But then reality hit.</p><p><strong>Frontend team:</strong> “Can we get user data with their recent posts and city info in one request?” <strong>Me:</strong> “Sure, I’ll create a new endpoint…”</p><p><strong>Frontend team:</strong> “For the dashboard, we need user stats, post counts by category, and file usage metrics.” <strong>Me:</strong> “Another endpoint coming up…”</p><p><strong>Frontend team:</strong> “Mobile needs just basic user info with city name, but desktop needs full user profile with post analytics.” <strong>Me:</strong> “Let me create two more endpoints…”</p><p>Sound familiar?</p><h3>The GraphQL Conversion</h3><p>Instead of building endpoint after endpoint, I took a step back. What if the frontend could ask for exactly what it needs?</p><p>I cloned my REST foundation and started the migration to GraphQL. The difference was immediate:</p><h3>Before (REST):</h3><pre>// Dashboard requires multiple requests<br>const user = await fetch(&#39;/api/v1/users/123&#39;)<br>const posts = await fetch(&#39;/api/v1/posts?userId=123&amp;limit=5&#39;)<br>const city = await fetch(`/api/v1/cities/${user.cityId}`)<br>const analytics = await fetch(&#39;/api/v1/analytics/user/123&#39;)</pre><h3>After (GraphQL):</h3><pre>query DashboardData {<br>  user(id: &quot;123&quot;) {<br>    name<br>    email<br>    city { name country }<br>    recentPosts(limit: 5) { title category }<br>    analytics { totalPosts storageUsed }<br>  }<br>}</pre><p>One request. Exactly the data needed. Type-safe.</p><h3>What Changed Everything</h3><p><strong>1. Frontend Freedom</strong> No more “can you add this field to the API?” requests. Frontend teams could experiment with different data shapes without backend changes.</p><p><strong>2. Type Safety Everywhere</strong> GraphQL’s type system caught bugs during development that would have slipped through in REST. Auto-generated TypeScript types meant frontend and backend stayed in sync.</p><p><strong>3. Better Developer Experience</strong> GraphQL Playground replaced my Swagger docs and provided something better — interactive documentation that was always up-to-date.</p><p><strong>4. Relationship Queries</strong> Complex data relationships that required multiple REST endpoints became simple GraphQL queries. Need users with their cities and recent posts? One query instead of three.</p><h3>The Reality Check</h3><p><strong>The myth:</strong> “GraphQL is just REST with one endpoint.” <strong>The reality:</strong> It’s a completely different approach to API design.</p><p>GraphQL isn’t always the answer:</p><ul><li>Simple CRUD APIs? REST is simpler</li><li>File-heavy APIs? REST handles uploads more naturally</li><li>Public APIs? REST is more familiar to external developers</li></ul><p>But for complex applications with multiple clients and evolving data requirements? GraphQL was a game-changer.</p><h3>The Results</h3><p>My <a href="https://github.com/saadamir1/nestjs-graphql-foundation">GraphQL foundation</a> became the base for all my future projects. Frontend teams became more productive. API evolution became easier. Type safety caught bugs earlier.</p><p><strong>The real benefit wasn’t performance — it was developer experience.</strong></p><h3>Should You Make the Switch?</h3><p>Ask yourself:</p><ul><li>Do you frequently create new endpoints for frontend variations?</li><li>Are you building multiple clients (web, mobile, desktop)?</li><li>Do you value type safety and developer experience?</li></ul><p>If yes, GraphQL is worth exploring.</p><h3>What’s Next?</h3><p>This GraphQL foundation became the base for my <a href="https://github.com/saadamir1/nestjs-graphql-realtime-foundation">real-time features</a>, <a href="https://github.com/saadamir1/nestjs-multitenant-foundation">multi-tenant architecture</a>, and eventually a <a href="https://github.com/saadamir1/chatflow-saas">complete SaaS platform</a>.</p><p><strong>Want the technical details?</strong> I’m writing a detailed breakdown of the exact migration process, code comparisons, and challenges I faced. Stay tuned for the technical deep dive!</p><p><em>Have you made the switch from REST to GraphQL? What’s holding you back? Share your thoughts in the comments.</em></p><p><strong>Tags:</strong> #graphql #rest #nestjs #api #typescript #webdevelopment #nodejs</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e4aa372ed56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My NestJS Journey: From REST API to Complete SaaS Platform]]></title>
            <link>https://medium.com/@saadamir1/my-nestjs-journey-from-rest-api-to-complete-saas-platform-e2f40abdbdbc?source=rss-12acbde2152d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2f40abdbdbc</guid>
            <category><![CDATA[evolution]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Saad Amir]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 15:55:48 GMT</pubDate>
            <atom:updated>2025-09-18T18:11:01.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2npMvxED0EmVwmeLQ__w-w.png" /></figure><p>A few months ago, during my job training, I got the opportunity to explore and practice different Node.js technologies. Instead of just following tutorials, I decided to build something meaningful. What started as a simple NestJS REST API evolved into a complete SaaS foundation with multi-tenancy, real-time features, and Stripe billing. Here’s how it progressed through 5 major iterations.</p><h3>Stage 1: The Professional REST Foundation</h3><p>It all started with building a robust NestJS REST API. I wasn’t looking to reinvent the wheel — I wanted something production-ready from day one.</p><p><strong>What I built:</strong></p><ul><li>JWT authentication with refresh tokens</li><li>Role-based access control</li><li>Password reset via email</li><li>File uploads with Cloudinary</li><li>Audit logging and rate limiting</li></ul><p>This wasn’t just another tutorial project. I included features most developers skip: proper pagination, soft deletes, comprehensive logging, and API versioning. The foundation was solid, but I soon realized REST had limitations.</p><p><a href="https://github.com/saadamir1/nestjs-pg-crud">View the REST Foundation →</a></p><h3>Stage 2: The GraphQL Conversion</h3><p>Working with REST endpoints felt restrictive. Frontend teams constantly needed different data shapes, leading to either over-fetching or multiple API calls.</p><p><strong>The switch to GraphQL changed everything:</strong></p><ul><li>Single endpoint for all operations</li><li>Type-safe queries with Apollo Server</li><li>No more over/under-fetching</li><li>Built-in GraphQL Playground</li></ul><p>I cloned my REST foundation and methodically converted each endpoint to GraphQL resolvers. The migration taught me that GraphQL isn’t just “REST with one endpoint” — it’s a fundamentally different approach to API design.</p><p><strong>Key insight:</strong> GraphQL’s type system caught so many bugs during development that would have slipped through in REST.</p><p><a href="https://github.com/saadamir1/nestjs-graphql-foundation">View the GraphQL Foundation →</a></p><h3>Stage 3: Adding Real-Time Features</h3><p>Static APIs weren’t enough for modern applications. Users expect real-time updates, notifications, and live chat.</p><p><strong>I added the missing piece:</strong></p><ul><li>Socket.IO for WebSocket connections</li><li>GraphQL subscriptions for real-time data</li><li>Live chat system</li><li>Push notifications</li><li>File sharing with real-time updates</li></ul><p>The combination of GraphQL subscriptions and Socket.IO was powerful. GraphQL handled structured real-time data, while Socket.IO managed connection states and room management.</p><p><strong>Lesson learned:</strong> Don’t choose between WebSockets and GraphQL subscriptions — use both for different purposes.</p><p><a href="https://github.com/saadamir1/nestjs-graphql-realtime-foundation">View the Real-Time Foundation →</a></p><h3>Stage 4: Multi-Tenant Architecture</h3><p>Single-tenant applications are limiting. To build a real SaaS, I needed workspace isolation where multiple organizations could use the same codebase securely.</p><p><strong>The multi-tenant transformation:</strong></p><ul><li>Complete workspace isolation</li><li>Tenant-scoped database queries</li><li>Role-based access within workspaces</li><li>Data segregation at every level</li></ul><p>This was the hardest migration. Every database query needed tenant context. Every GraphQL resolver required workspace validation. But the result was a true SaaS foundation.</p><p><strong>Critical insight:</strong> Multi-tenancy isn’t just about adding a workspaceId field—it&#39;s architectural from the ground up.</p><p><a href="https://github.com/saadamir1/nestjs-multitenant-foundation">View the Multi-Tenant Foundation →</a></p><h3>Stage 5: Complete SaaS Platform</h3><p>The final evolution: a production-ready SaaS with everything needed to launch and scale.</p><p><strong>What I added:</strong></p><ul><li>Stripe billing integration</li><li>Subscription management (FREE/PRO/ENTERPRISE)</li><li>Usage limits and enforcement</li><li>Team invitations and onboarding</li><li>Analytics dashboard</li><li>Webhook handling</li><li>Development mode with mock responses</li></ul><p>This became <strong>ChatFlow</strong> — a complete SaaS foundation that any developer can clone and build upon. It includes features that typically take months to implement: billing, multi-tenancy, real-time collaboration, and comprehensive authentication.</p><p><a href="https://github.com/saadamir1/chatflow-saas">View the Complete SaaS Foundation →</a></p><h3>The Tech Stack Evolution</h3><pre>Stage 1: NestJS + REST + PostgreSQL + JWT<br>Stage 2: + GraphQL + Apollo Server<br>Stage 3: + Socket.IO + Real-time subscriptions<br>Stage 4: + Multi-tenant architecture<br>Stage 5: + Stripe + Usage tracking + Complete SaaS features</pre><h3>Key Takeaways</h3><p><strong>1. Evolution beats revolution:</strong> Each stage built upon the previous one. I didn’t rewrite from scratch — I extended and improved.</p><p><strong>2. GraphQL is worth the learning curve:</strong> The type safety and flexibility pay dividends in larger applications.</p><p><strong>3. Real-time is expected:</strong> Modern users expect live updates. Plan for it early.</p><p><strong>4. Multi-tenancy is architectural:</strong> It affects every part of your application. Design for it from the beginning if you’re building SaaS.</p><p><strong>5. Billing is complex:</strong> Stripe integration, webhook handling, and usage tracking took longer than expected.</p><h3>What’s Next?</h3><p>This journey taught me that building SaaS infrastructure is time-consuming but necessary. That’s why I open-sourced the complete ChatFlow foundation — so other developers can skip months of boilerplate and focus on their unique features.</p><p>The foundation includes everything: authentication, billing, real-time features, multi-tenancy, and production-ready deployment. It’s the SaaS starter I wish I had when I began this journey.</p><p><strong>Ready to build your SaaS?</strong> Check out the complete foundation and start building your unique features today.</p><p><em>What challenges have you faced building SaaS applications? Share your experiences in the comments below.</em></p><p><strong>Tags:</strong> #nestjs #graphql #saas #nodejs #typescript #stripe #multitenant #realtime</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2f40abdbdbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full-Stack Web Development: Connecting React Frontend to Express Backend]]></title>
            <link>https://medium.com/@saadamir1/full-stack-web-development-connecting-react-frontend-to-express-backend-8b7c699a7ebf?source=rss-12acbde2152d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b7c699a7ebf</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Saad Amir]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 11:55:32 GMT</pubDate>
            <atom:updated>2025-04-21T20:26:02.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0sQDhqDq_8Av8POaYkC8g.png" /></figure><p>In the world of web development, creating an application that seamlessly connects frontend and backend components is a fundamental skill. This blog post walks through building JotDown, a simple notes application, to demonstrate how to establish this crucial connection between a React frontend and an Express backend.</p><h3>The Challenge</h3><p>Many new developers struggle with the concept of how a frontend application communicates with a backend server. Questions like “How do I send data from my server to my React app?” or “Why isn’t my API working with my frontend?” are common. This guide aims to demystify this process with practical, step-by-step instructions.</p><h3>Project Overview: JotDown Notes App</h3><p>JotDown is a straightforward notes application with two main features:</p><ul><li>View all notes</li><li>Add new notes</li></ul><p>Our architecture consists of:</p><ul><li><strong>Backend (JotDown-api)</strong>: Node.js with Express</li><li><strong>Frontend (JotDown-client)</strong>: React</li><li><strong>Deployment</strong>: Vercel for frontend, Render for backend</li></ul><h3>Complete File Structure</h3><p>Here’s the complete file structure for our project:</p><pre>JotDown/<br>├── JotDown-api/              # Backend code<br>│   ├── node_modules/         # Backend dependencies (generated)<br>│   ├── index.js              # Main server file<br>│   ├── package.json          # Backend dependencies &amp; scripts<br>│   └── .gitignore            # Backend git ignore<br>│<br>└── JotDown-client/           # Frontend code<br>    ├── node_modules/         # Frontend dependencies (generated)<br>    ├── public/               # Public assets<br>    │   ├── index.html        # HTML template<br>    │   ├── favicon.ico       # Favicon<br>    │   └── manifest.json     # Web app manifest<br>    ├── src/                  # React source code<br>    │   ├── App.js            # Main React component<br>    │   ├── index.js          # React entry point<br>    │   ├── App.css           # Styles for App component<br>    │   └── index.css         # Global styles<br>    ├── package.json          # Frontend dependencies &amp; scripts<br>    └── .gitignore            # Frontend git ignore</pre><h3>Step 1: Setting Up the Backend (Express)</h3><p>First, let’s create our backend server:</p><pre>mkdir JotDown-api<br>cd JotDown-api<br>npm init -y<br>npm install express cors nodemon</pre><p>Create an index.js file:</p><pre>const express = require(&#39;express&#39;);<br>const cors = require(&#39;cors&#39;);<br>const app = express();<br>const PORT = process.env.PORT || 5000;<br><br>// Enable CORS<br>app.use(cors());<br><br>// Parse JSON request body<br>app.use(express.json());<br><br>// In-memory notes database<br>let notes = [<br>  { id: 1, text: &quot;Welcome to JotDown!&quot;, createdAt: new Date().toISOString() },<br>  { id: 2, text: &quot;Add your own notes below.&quot;, createdAt: new Date().toISOString() }<br>];<br><br>// GET endpoint to fetch all notes<br>app.get(&#39;/api/notes&#39;, (req, res) =&gt; {<br>  res.json(notes);<br>});<br><br>// POST endpoint to add a new note<br>app.post(&#39;/api/notes&#39;, (req, res) =&gt; {<br>  const { text } = req.body;<br>  <br>  if (!text) {<br>    return res.status(400).json({ error: &#39;Note text is required&#39; });<br>  }<br>  <br>  const newNote = {<br>    id: notes.length &gt; 0 ? Math.max(...notes.map(note =&gt; note.id)) + 1 : 1,<br>    text,<br>    createdAt: new Date().toISOString()<br>  };<br>  <br>  notes.push(newNote);<br>  res.status(201).json(newNote);<br>});<br>// Server health check<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.json({ message: &#39;Notes API is running!&#39; });<br>});<br>app.listen(PORT, () =&gt; {<br>  console.log(`Server running on port ${PORT}`);<br>});</pre><p>Create a .gitignore file for the backend:</p><pre># Dependencies<br>/node_modules<br><br># Environment variables<br>.env<br># Logs<br>logs<br>*.log<br>npm-debug.log*<br># Runtime data<br>pids<br>*.pid<br>*.seed<br># OS files<br>.DS_Store</pre><p>Update .pakage.json to include start scripts:</p><pre>{<br>  &quot;name&quot;: &quot;jotdown-api&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;Backend API for JotDown Notes App&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node index.js&quot;,<br>    &quot;dev&quot;: &quot;nodemon index.js&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;cors&quot;: &quot;^2.8.5&quot;,<br>    &quot;express&quot;: &quot;^4.18.2&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;nodemon&quot;: &quot;^2.0.22&quot;<br>  },<br>  &quot;engines&quot;: {<br>    &quot;node&quot;: &quot;&gt;=14.0.0&quot;<br>  }<br>}</pre><h3>Step 2: Building the Frontend (React)</h3><p>Now, let’s create our React frontend:</p><pre>npx create-react-app JotDown-client<br>cd JotDown-client</pre><p>Create a .gitignore file for the frontend (if not already created by Create React App):</p><pre># Dependencies<br>/node_modules<br>/.pnp<br>.pnp.js<br><br># Testing<br>/coverage<br><br># Production<br>/build<br><br># Misc<br>.DS_Store<br>.env.local<br>.env.development.local<br>.env.test.local<br>.env.production.local<br><br>npm-debug.log*<br>yarn-debug.log*<br>yarn-error.log*</pre><p>Replace the content of src/App.js:</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br><br>function App() {<br>  const [notes, setNotes] = useState([]);<br>  const [newNote, setNewNote] = useState(&#39;&#39;);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError] = useState(null);<br>  <br>  // API URL - change to your deployed backend URL when ready<br>  const API_URL = process.env.REACT_APP_API_URL || &#39;http://localhost:5000&#39;;<br>  <br>  // Fetch notes from backend<br>  useEffect(() =&gt; {<br>    const fetchNotes = async () =&gt; {<br>      try {<br>        const response = await fetch(`${API_URL}/api/notes`);<br>        if (!response.ok) {<br>          throw new Error(&#39;Failed to fetch notes&#39;);<br>        }<br>        const data = await response.json();<br>        setNotes(data);<br>        setLoading(false);<br>      } catch (err) {<br>        setError(err.message);<br>        setLoading(false);<br>      }<br>    };<br>    fetchNotes();<br>  }, [API_URL]);<br>  // Add a new note<br>  const handleAddNote = async (e) =&gt; {<br>    e.preventDefault();<br>    if (!newNote.trim()) return;<br>    try {<br>      const response = await fetch(`${API_URL}/api/notes`, {<br>        method: &#39;POST&#39;,<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        },<br>        body: JSON.stringify({ text: newNote }),<br>      });<br>      if (!response.ok) {<br>        throw new Error(&#39;Failed to add note&#39;);<br>      }<br>      const addedNote = await response.json();<br>      setNotes([...notes, addedNote]);<br>      setNewNote(&#39;&#39;);<br>    } catch (err) {<br>      setError(err.message);<br>    }<br>  };<br>  if (loading) return &lt;div className=&quot;loading&quot;&gt;Loading notes...&lt;/div&gt;;<br>  if (error) return &lt;div className=&quot;error&quot;&gt;Error: {error}&lt;/div&gt;;<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;header&gt;<br>        &lt;h1&gt;JotDown&lt;/h1&gt;<br>        &lt;p&gt;Simple note-taking app&lt;/p&gt;<br>      &lt;/header&gt;<br>      &lt;section className=&quot;add-note&quot;&gt;<br>        &lt;form onSubmit={handleAddNote}&gt;<br>          &lt;input<br>            type=&quot;text&quot;<br>            value={newNote}<br>            onChange={(e) =&gt; setNewNote(e.target.value)}<br>            placeholder=&quot;Enter a new note...&quot;<br>          /&gt;<br>          &lt;button type=&quot;submit&quot;&gt;Add Note&lt;/button&gt;<br>        &lt;/form&gt;<br>      &lt;/section&gt;<br>      &lt;section className=&quot;notes-container&quot;&gt;<br>        &lt;h2&gt;Your Notes&lt;/h2&gt;<br>        {notes.length === 0 ? (<br>          &lt;p&gt;No notes yet. Add your first note above!&lt;/p&gt;<br>        ) : (<br>          &lt;ul className=&quot;notes-list&quot;&gt;<br>            {notes.map((note) =&gt; (<br>              &lt;li key={note.id} className=&quot;note-item&quot;&gt;<br>                &lt;p&gt;{note.text}&lt;/p&gt;<br>                &lt;small&gt;Created: {new Date(note.createdAt).toLocaleString()}&lt;/small&gt;<br>              &lt;/li&gt;<br>            ))}<br>          &lt;/ul&gt;<br>        )}<br>      &lt;/section&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p>Add some styling in src/App.css:</p><pre>.App {<br>  max-width: 800px;<br>  margin: 0 auto;<br>  padding: 20px;<br>}<br>header {<br>  text-align: center;<br>  margin-bottom: 30px;<br>}<br>header h1 {<br>  margin-bottom: 10px;<br>  color: #2c3e50;<br>}<br>.add-note {<br>  margin-bottom: 30px;<br>}<br>form {<br>  display: flex;<br>  gap: 10px;<br>}<br>input {<br>  flex: 1;<br>  padding: 10px;<br>  border: 1px solid #ddd;<br>  border-radius: 4px;<br>  font-size: 16px;<br>}<br>button {<br>  padding: 10px 20px;<br>  background-color: #3498db;<br>  color: white;<br>  border: none;<br>  border-radius: 4px;<br>  cursor: pointer;<br>  font-size: 16px;<br>  transition: background-color 0.3s;<br>}<br>button:hover {<br>  background-color: #2980b9;<br>}<br>.notes-container {<br>  background-color: #f9f9f9;<br>  padding: 20px;<br>  border-radius: 8px;<br>}<br>h2 {<br>  margin-top: 0;<br>  color: #2c3e50;<br>}<br>.notes-list {<br>  list-style: none;<br>  padding: 0;<br>}<br>.note-item {<br>  background-color: white;<br>  padding: 15px;<br>  margin-bottom: 15px;<br>  border-radius: 4px;<br>  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);<br>}<br>.note-item p {<br>  margin: 0 0 10px;<br>  font-size: 18px;<br>}<br>.note-item small {<br>  color: #7f8c8d;<br>}<br>.loading, .error {<br>  text-align: center;<br>  padding: 20px;<br>  font-size: 18px;<br>}<br>.error {<br>  color: #e74c3c;<br>}</pre><p>Ensure that public/index.html has an appropriate title:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;link rel=&quot;icon&quot; href=&quot;%PUBLIC_URL%/favicon.ico&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>    &lt;meta name=&quot;theme-color&quot; content=&quot;#000000&quot; /&gt;<br>    &lt;meta<br>      name=&quot;description&quot;<br>      content=&quot;JotDown - A simple note-taking application&quot;<br>    /&gt;<br>    &lt;title&gt;JotDown&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;noscript&gt;You need to enable JavaScript to run this app.&lt;/noscript&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>Step 3: Setting Up the Proxy for Development</h3><p>To avoid CORS issues during development, modify your frontend package.json:</p><pre>{<br>  &quot;name&quot;: &quot;jotdown-client&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;private&quot;: true,<br>  &quot;dependencies&quot;: {<br>    &quot;react&quot;: &quot;^18.2.0&quot;,<br>    &quot;react-dom&quot;: &quot;^18.2.0&quot;,<br>    &quot;react-scripts&quot;: &quot;5.0.1&quot;<br>  },<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;react-scripts start&quot;,<br>    &quot;build&quot;: &quot;react-scripts build&quot;,<br>    &quot;test&quot;: &quot;react-scripts test&quot;,<br>    &quot;eject&quot;: &quot;react-scripts eject&quot;<br>  },<br>  &quot;eslintConfig&quot;: {<br>    &quot;extends&quot;: [<br>      &quot;react-app&quot;<br>    ]<br>  },<br>  &quot;browserslist&quot;: {<br>    &quot;production&quot;: [<br>      &quot;&gt;0.2%&quot;,<br>      &quot;not dead&quot;,<br>      &quot;not op_mini all&quot;<br>    ],<br>    &quot;development&quot;: [<br>      &quot;last 1 chrome version&quot;,<br>      &quot;last 1 firefox version&quot;,<br>      &quot;last 1 safari version&quot;<br>    ]<br>  },<br>  &quot;proxy&quot;: &quot;http://localhost:5000&quot;<br>}</pre><p>The &quot;proxy&quot;: &quot;http://localhost:5000&quot; line tells React to forward API requests to your backend server during development.</p><h3>Step 4: Running the Application Locally</h3><p>Start the backend:</p><pre>cd JotDown-api<br>npm run dev</pre><p>Start the frontend (in a separate terminal):</p><pre>cd JotDown-client<br>npm start</pre><p>Visit http://localhost:3000 to see your application running!</p><h3>Step 5: Understanding the Connection</h3><p>Now, let’s break down how the backend and frontend connect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUgdxc4QwJK2ZEUb8fiTeg.png" /></figure><h3>1. Backend Exposes API Endpoints</h3><ul><li>/api/notes (GET): Returns all notes</li><li>/api/notes (POST): Creates a new note</li></ul><h3>2. Frontend Makes HTTP Requests</h3><ul><li>useEffect hook fetches notes when the component loads</li><li>handleAddNote function sends new notes to the API</li></ul><h3>3. Frontend Processes API Responses</h3><ul><li>Updates state with fetched notes</li><li>Adds new notes to the existing list</li><li>Handles loading states and errors</li></ul><h3>Key Points About the Connection</h3><ol><li><strong>API URL Configuration</strong>:</li></ol><pre>const API_URL = process.env.REACT_APP_API_URL || &#39;http://localhost:5000&#39;;</pre><p>This line allows for different URLs in development vs. production.</p><p>2. <strong>HTTP Requests with Fetch</strong>:</p><pre>const response = await fetch(`${API_URL}/api/notes`);<br>const data = await response.json();</pre><p>The frontend uses the fetch API to communicate with the backend.</p><p>3. <strong>CORS Handling:</strong></p><pre>app.use(cors());</pre><p>The backend uses the CORS middleware to allow requests from different origins.</p><p>4. <strong>Request/Response Cycle</strong>:</p><ul><li>Frontend sends a request to a specific endpoint</li><li>Backend processes the request and sends a response</li><li>Frontend handles the response data and updates the UI</li></ul><h3>Step 6: Setting Up Git Repositories</h3><h3>Backend Git Setup</h3><pre>cd JotDown-api<br>git init<br>git add .<br>git commit -m &quot;Initial backend setup&quot;</pre><p>Create a repository on GitHub named JotDown-api and connect it:</p><pre>git remote add origin https://github.com/yourusername/JotDown-api.git<br>git push -u origin main</pre><h3>Frontend Git Setup</h3><pre>cd JotDown-client<br>git init<br>git add .<br>git commit -m &quot;Initial frontend setup&quot;</pre><p>Create a repository on GitHub named JotDown-client and connect it:</p><pre>git remote add origin https://github.com/yourusername/JotDown-client.git<br>git push -u origin main</pre><h3>Step 7: Deploying Your Application</h3><h3>Backend Deployment (Render)</h3><ol><li>Create a Render account at <a href="https://render.com/">render.com</a></li><li>Click “New” and select “Web Service”</li><li>Connect your GitHub account and select your JotDown-api repository</li><li>Configure the service:</li></ol><ul><li>Name: jotdown-api</li><li>Runtime: Node</li><li>Build Command: npm install</li><li>Start Command: npm start</li><li>Environment Variables: (you can add any environment variables your app needs)</li></ul><p>5. Click “Create Web Service”</p><p>6. Note the URL provided by Render (e.g., <a href="https://jotdown-api.onrender.com)/">https://jotdown-api.onrender.com)</a></p><h3>Frontend Deployment (Vercel)</h3><ol><li>Create a Vercel account at <a href="https://vercel.com/">vercel.com</a></li><li>Click “Import Project” and select your JotDown-client repository</li><li>Configure the project:</li></ol><ul><li>Framework Preset: Create React App</li><li>Build Command: npm run build</li><li>Output Directory: build</li></ul><p>4. Add environment variable:</p><ul><li>Name: REACT_APP_API_URL</li><li>Value: Your backend URL from Render (e.g., <a href="https://jotdown-api.onrender.com)/">https://jotdown-api.onrender.com)</a></li></ul><p>5. Click “Deploy”</p><blockquote>Explore the live version of JotDown here:<br>🔗 <a href="https://jot-down-client.vercel.app/">https://jot-down-client.vercel.app</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cDlVYy401ZKfvEK1uKW4pA.png" /></figure><h3>Common Challenges and Solutions</h3><h3>1. CORS Errors</h3><p>If you see errors like “Access to fetch at… has been blocked by CORS policy”:</p><ul><li>Ensure the backend has cors middleware correctly configured</li><li>Check that your origins match (in development and production)</li><li>For more control, configure CORS with specific origins:</li></ul><pre>app.use(cors({<br>  origin: [&#39;http://localhost:3000&#39;, &#39;https://your-frontend-url.vercel.app&#39;]<br>}));</pre><h3>2. API Connection Issues</h3><p>If your frontend can’t connect to your backend:</p><ul><li>Verify the backend is running</li><li>Check the API URL is correct</li><li>Look for typos in endpoint paths</li><li>Ensure the proxy is set up correctly in development</li><li>Use browser developer tools to inspect network requests</li></ul><h3>3. State Management</h3><p>If your UI doesn’t update after API calls:</p><ul><li>Confirm you’re properly updating state after successful API calls</li><li>Check the browser console for errors</li><li>Verify the response format matches what your code expects</li></ul><h3>4. Environment Variables</h3><ul><li>In development, environment variables in React must be prefixed with REACT_APP_</li><li>For production, make sure to set the variables in your deployment service</li><li>To test environment variables locally, create a .env file in your frontend root:</li></ul><pre>REACT_APP_API_URL=http://localhost:5000</pre><h3>5. Deployment Issues</h3><ul><li>Check your deployment logs for errors</li><li>Make sure your Node version is supported by your hosting provider</li><li>Verify your start commands are correct</li><li>Ensure you’ve added all necessary environment variables</li></ul><h3>Testing Your Application</h3><p>Here’s how to test if your application is working correctly:</p><ol><li><strong>Backend API Testing</strong>:</li></ol><ul><li>Visit your backend URL directly in a browser (e.g., http://localhost:5000/api/notes or your Render URL)</li><li>You should see a JSON response with your notes</li><li>You can also use tools like Postman to test the POST endpoint</li></ul><p><strong>2. Frontend Testing</strong>:</p><ul><li>Visit your frontend URL</li><li>Add a new note and check if it appears in the list</li><li>Refresh the page to see if notes persist (fetched from the backend)</li><li>Open browser developer tools (F12) and check the Network tab to see API requests</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MnQFbg-tI-hIBioHq-V-Ig.png" /></figure><h3>Next Steps for Improvement</h3><p>Once you’ve got the basic application working, consider these enhancements:</p><ol><li><strong>Add Persistence</strong>:</li></ol><ul><li>Connect the backend to a database like MongoDB or PostgreSQL</li><li>Implement data validation with a library like Joi or Yup</li></ul><p><strong>2. Add More Features</strong>:</p><ul><li>Editing notes</li><li>Deleting notes</li><li>Note categories</li><li>Rich text formatting</li><li>User authentication</li></ul><p><strong>3. Improve Error Handling</strong>:</p><ul><li>More specific error messages</li><li>Toast notifications for success/failure</li><li>Form validation</li></ul><p><strong>4. Optimize Performance</strong>:</p><ul><li>Add loading indicators during API calls</li><li>Implement caching for API responses</li><li>Use pagination for large numbers of notes</li></ul><h3>Conclusion</h3><p>Connecting a React frontend to an Express backend isn’t magic — it’s a systematic process of creating endpoints, making HTTP requests, and handling responses. The JotDown app demonstrates a simple yet effective implementation of this fundamental web development pattern.</p><p>By understanding how these parts fit together, you’re now equipped to build more complex full-stack applications. The principles remain the same even as your applications grow in complexity.</p><p>Remember that proper error handling, environment configuration, and security practices become increasingly important as your applications scale. This tutorial provides a foundation that you can build upon with more advanced features like authentication, databases, and more sophisticated state management.</p><h3>Explore the Code &amp; Get in Touch</h3><p>Want to dive deeper into the implementation? Check out the full source code:</p><ul><li><strong>Backend (Express) Repository</strong>: <a href="https://github.com/saadamir1/JotDown-api">github.com/saadamir1/JotDown-api</a></li><li><strong>Frontend (React) Repository</strong>: <a href="https://github.com/saadamir1/JotDown-client">github.com/saadamir1/JotDown-client</a></li></ul><p><strong>Questions or suggestions?</strong> Feel free to reach out:<br>📧 <strong>Email</strong>: <a href="https://mailto:saadamir070@gmail.com/">saadamir070@gmail.com</a></p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b7c699a7ebf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>